diff --git a/.gitignore b/.gitignore index e42dfdcb021..0dc52799236 100644 --- a/.gitignore +++ b/.gitignore @@ -13,33 +13,6 @@ generated-sources/* generated-code/* *.swp *.swo -*.csproj.user - -/target -/generated-files -/nbactions.xml -*.pyc -__pycache__ -samples/server-generator/scalatra/output -samples/server-generator/node/output/node_modules -samples/server-generator/scalatra/target -samples/server-generator/scalatra/output/.history -samples/client/petstore/qt5cpp/PetStore/moc_* -samples/client/petstore/qt5cpp/PetStore/*.o -samples/client/petstore/objc/PetstoreClient.xcworkspace/xcuserdata -samples/client/petstore/qt5cpp/build-* -samples/client/petstore/qt5cpp/PetStore/PetStore -samples/client/petstore/qt5cpp/PetStore/Makefile -samples/client/petstore/java/hello.txt -samples/client/petstore/android/default/hello.txt -samples/client/petstore/objc/SwaggerClientTests/Build -samples/client/petstore/objc/SwaggerClientTests/Pods -samples/client/petstore/objc/SwaggerClientTests/SwaggerClient.xcworkspace -samples/client/petstore/objc/SwaggerClientTests/Podfile.lock -samples/server/petstore/nodejs/node_modules -samples/client/petstore/csharp/SwaggerClientTest/.vs -samples/client/petstore/csharp/SwaggerClientTest/obj -samples/client/petstore/csharp/SwaggerClientTest/bin target .idea .lib @@ -50,24 +23,6 @@ packages/ .packages .vagrant/ -samples/client/petstore/php/SwaggerClient-php/composer.lock -samples/client/petstore/php/SwaggerClient-php/vendor/ - -samples/client/petstore/silex/SwaggerServer/composer.lock -samples/client/petstore/silex/SwaggerServer/venodr/ - -samples/client/petstore/perl/deep_module_test/ - -samples/client/petstore/python/.projectile -samples/client/petstore/python/.venv/ -samples/client/petstore/python/dev-requirements.txt.log - -samples/client/petstore/objc/SwaggerClientTests/SwaggerClient.xcodeproj/xcuserdata -samples/client/petstore/swift/SwaggerClientTests/SwaggerClient.xcodeproj/xcuserdata -samples/client/petstore/swift/SwaggerClientTests/SwaggerClient.xcworkspace/xcuserdata -samples/client/petstore/swift/SwaggerClientTests/Pods/Pods.xcodeproj/xcuserdata -samples/client/petstore/swift/SwaggerClientTests/Pods/Pods.xcodeproj/xcshareddata/xcschemes - .settings *.mustache~ @@ -76,10 +31,79 @@ samples/client/petstore/swift/SwaggerClientTests/Pods/Pods.xcodeproj/xcshareddat *.xml~ *.t~ +/target +/generated-files +/nbactions.xml + +# scalatra +samples/server-generator/scalatra/output +samples/server-generator/scalatra/target +samples/server-generator/scalatra/output/.history + +# nodejs +samples/server-generator/node/output/node_modules +samples/server/petstore/nodejs/node_modules +samples/server/petstore/nodejs-server/node_modules + +# qt5 cpp +samples/client/petstore/qt5cpp/PetStore/moc_* +samples/client/petstore/qt5cpp/PetStore/*.o +samples/client/petstore/qt5cpp/build-* +samples/client/petstore/qt5cpp/PetStore/PetStore +samples/client/petstore/qt5cpp/PetStore/Makefile + +#Java/Android +**/.gradle/ +samples/client/petstore/java/hello.txt +samples/client/petstore/android/default/hello.txt +samples/client/petstore/android/volley/.gradle/ +samples/client/petstore/android/volley/build/ +samples/client/petstore/java/jersey2/.gradle/ +samples/client/petstore/java/jersey2/build/ +samples/client/petstore/java/okhttp-gson/.gradle/ +samples/client/petstore/java/okhttp-gson/build/ + +#PHP +samples/client/petstore/php/SwaggerClient-php/composer.lock +samples/client/petstore/php/SwaggerClient-php/vendor/ +samples/client/petstore/silex/SwaggerServer/composer.lock +samples/client/petstore/silex/SwaggerServer/venodr/ + +# Perl +samples/client/petstore/perl/deep_module_test/ + +# Objc +samples/client/petstore/objc/PetstoreClient.xcworkspace/xcuserdata +samples/client/petstore/objc/SwaggerClientTests/SwaggerClient.xcodeproj/xcuserdata +samples/client/petstore/objc/SwaggerClientTests/Build +samples/client/petstore/objc/SwaggerClientTests/Pods +samples/client/petstore/objc/SwaggerClientTests/SwaggerClient.xcworkspace +samples/client/petstore/objc/SwaggerClientTests/Podfile.lock + +# Swift +samples/client/petstore/swift/SwaggerClientTests/SwaggerClient.xcodeproj/xcuserdata +samples/client/petstore/swift/SwaggerClientTests/SwaggerClient.xcworkspace/xcuserdata +samples/client/petstore/swift/SwaggerClientTests/Pods/Pods.xcodeproj/xcuserdata +samples/client/petstore/swift/SwaggerClientTests/Pods/Pods.xcodeproj/xcshareddata/xcschemes + +# C# +*.csproj.user +samples/client/petstore/csharp/SwaggerClientTest/.vs +samples/client/petstore/csharp/SwaggerClientTest/obj +samples/client/petstore/csharp/SwaggerClientTest/bin +samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/vendor/ samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/ samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/ -**/.gradle/ +samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/nuget.exe +samples/client/petstore/csharp/SwaggerClientTest/TestResult.xml +samples/client/petstore/csharp/SwaggerClientTest/nuget.exe +samples/client/petstore/csharp/SwaggerClientTest/testrunner/ +# Python +*.pyc +__pycache__ samples/client/petstore/python/dev-requirements.txt.log samples/client/petstore/python/swagger_client.egg-info/SOURCES.txt samples/client/petstore/python/.coverage +samples/client/petstore/python/.projectile +samples/client/petstore/python/.venv/ diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 35294347b00..4cf901c2d3f 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -13,6 +13,7 @@ - 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 ## How to contribute @@ -31,8 +32,10 @@ For a list of variables available in the template, please refer to this [page](h Code change should conform to the programming style guide of the respective langauages: - C#: https://msdn.microsoft.com/en-us/library/vstudio/ff926074.aspx - Java: https://google.github.io/styleguide/javaguide.html -- JavaScript - https://github.com/airbnb/javascript/tree/master/es5 +- JavaScript: https://github.com/airbnb/javascript/tree/master/es5 +- Go: https://github.com/golang/go/wiki/CodeReviewComments - ObjC: https://github.com/NYTimes/objective-c-style-guide +- Perl: http://perldoc.perl.org/perlstyle.html - PHP: https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md - Python: https://www.python.org/dev/peps/pep-0008/ - Ruby: https://github.com/bbatsov/ruby-style-guide diff --git a/README.md b/README.md index 5ba583bf677..1c7ecb5758d 100644 --- a/README.md +++ b/README.md @@ -46,11 +46,13 @@ Check out [Swagger-Spec](https://github.com/OAI/OpenAPI-Specification) for addit - [Scala Scalatra](#scala-scalatra) - [Java JAX-RS (Java JAX-RS (Jersey v1.18)](#java-jax-rs-jersey-v118) - [Java JAX-RS (Apache CXF 2 / 3)](#java-jax-rs-apache-cxf-2--3) + - [Java JAX-RS (Resteasy)](#java-jax-rs-resteasy) - [Java Spring MVC](#java-spring-mvc) - [Haskell Servant](#haskell-servant) - [ASP.NET 5 Web API](#aspnet-5-web-api) - [To build the codegen library](#to-build-the-codegen-library) - [Workflow Integration](#workflow-integration) + - [Github Integration](#github-integration) - [Online Generators](#online-generators) - [Guidelines for Contribution](https://github.com/swagger-api/swagger-codegen/wiki/Guidelines-for-Contribution) - [Companies/Projects using Swagger Codegen](#companiesprojects-using-swagger-codegen) @@ -62,8 +64,8 @@ The OpenAPI Specification has undergone 3 revisions since initial creation in 20 Swagger Codegen Version | Release Date | OpenAPI Spec compatibility | Notes -------------------------- | ------------ | -------------------------- | ----- -2.1.6-SNAPSHOT | | 1.0, 1.1, 1.2, 2.0 | [master](https://github.com/swagger-api/swagger-codegen) -2.1.5 (**current stable**) | 2015-01-06 | 1.0, 1.1, 1.2, 2.0 | [tag v2.1.5](https://github.com/swagger-api/swagger-codegen/tree/v2.1.5) +2.1.7-SNAPSHOT | | 1.0, 1.1, 1.2, 2.0 | [master](https://github.com/swagger-api/swagger-codegen) +2.1.6 (**current stable**) | 2016-04-06 | 1.0, 1.1, 1.2, 2.0 | [tag v2.1.6](https://github.com/swagger-api/swagger-codegen/tree/v2.1.6) 2.0.17 | 2014-08-22 | 1.1, 1.2 | [tag v2.0.17](https://github.com/swagger-api/swagger-codegen/tree/v2.0.17) 1.0.4 | 2012-04-12 | 1.0, 1.1 | [tag v1.0.4](https://github.com/swagger-api/swagger-codegen/tree/swagger-codegen_2.9.1-1.1) @@ -72,7 +74,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.5/swagger-codegen-cli-2.1.5.jar -O swagger-codegen-cli.jar +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 java -jar swagger-codegen-cli.jar help ``` @@ -86,7 +88,7 @@ To build from source, you need the following installed and available in your $PA * [Java 7 or 8](http://java.oracle.com) -* [Apache maven 3.0.3 or greater](http://maven.apache.org/) +* [Apache maven 3.3.3 or greater](http://maven.apache.org/) #### OS X Users Don't forget to install Java 7 or 8. You probably have 1.6. @@ -386,6 +388,7 @@ JavaCXFServerCodegen.java JavaClientCodegen.java JavaInflectorServerCodegen.java JavaJerseyServerCodegen.java +JavaResteasyServerCodegen.java JavascriptClientCodegen.java NodeJSServerCodegen.java ObjcClientCodegen.java @@ -644,6 +647,14 @@ You must register this class into your JAX-RS configuration file: This is no longer necessary if you are using CXF >=v3.x +### Java JAX-RS (Resteasy) + +``` +java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate \ + -i http://petstore.swagger.io/v2/swagger.json \ + -l jaxrs-resteasy \ + -o samples/server/petstore/jaxrs-resteasy +``` ### Java Spring MVC @@ -686,6 +697,26 @@ Note! The templates are included in the library generated. If you want to modi You can use the [swagger-codegen-maven-plugin](modules/swagger-codegen-maven-plugin/README.md) for integrating with your workflow, and generating any codegen target. +## GitHub Integration + +To push the auto-generated SDK to GitHub, we provide `git_push.sh` to streamline the process. For example: + + 1) Create a new repository in GitHub (Ref: https://help.github.com/articles/creating-a-new-repository/) + + 2) Generate the SDK +``` + java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate \ + -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l perl \ + --git-user-id "wing328" \ + --git-repo-id "petstore-perl" \ + --release-note "Github integration demo" \ + -o /var/tmp/perl/petstore +``` + 3) Push the SDK to GitHub +``` +cd /var/tmp/perl/petstore +/bin/sh ./git_push.sh +``` ## Online generators @@ -708,13 +739,18 @@ Here are some companies/projects using Swagger Codegen in production. To add you - [Activehours](https://www.activehours.com/) - [Acunetix](https://www.acunetix.com/) - [Atlassian](https://www.atlassian.com/) +- [beemo](http://www.beemo.eu) - [CloudBoost](https://www.CloudBoost.io/) - [Cupix](http://www.cupix.com) - [DocuSign](https://www.docusign.com) - [Ergon](http://www.ergon.ch/) +- [eureka](http://eure.jp/) - [everystory.us](http://everystory.us) - [Expected Behavior](http://www.expectedbehavior.com/) +- [FH Münster - University of Applied Sciences](http://www.fh-muenster.de) +- [LANDR Audio](https://www.landr.com/) - [LiveAgent](https://www.ladesk.com/) +- [Kuary](https://kuary.com/) - [nViso](http://www.nviso.ch/) - [Okiok](https://www.okiok.com) - [OSDN](https://osdn.jp) diff --git a/bin/go-petstore.sh b/bin/go-petstore.sh index 239f31f0d71..9f192d22234 100755 --- a/bin/go-petstore.sh +++ b/bin/go-petstore.sh @@ -26,6 +26,6 @@ fi # if you've executed sbt assembly previously it will use that instead. export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" -ags="$@ generate -t modules/swagger-codegen/src/main/resources/go -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l go -o samples/client/petstore/go" +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" java $JAVA_OPTS -jar $executable $ags diff --git a/bin/java-petstore.sh b/bin/java-petstore.sh index f842d9ca3b0..17a1b0d6b98 100755 --- a/bin/java-petstore.sh +++ b/bin/java-petstore.sh @@ -26,6 +26,6 @@ fi # if you've executed sbt assembly previously it will use that instead. export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" -ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l java -o samples/client/petstore/java/default" +ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l java -o samples/client/petstore/java/default -DhideGenerationTimestamp=true" java $JAVA_OPTS -jar $executable $ags diff --git a/bin/jaxrs-cxf-petstore-server.sh b/bin/jaxrs-cxf-petstore-server.sh index 8049dde5630..bac9cb1d4eb 100755 --- a/bin/jaxrs-cxf-petstore-server.sh +++ b/bin/jaxrs-cxf-petstore-server.sh @@ -26,6 +26,6 @@ fi # if you've executed sbt assembly previously it will use that instead. export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" -ags="$@ generate -t modules/swagger-codegen/src/main/resources/JavaJaxRS -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l jaxrs-cxf -o samples/server/petstore/jaxrs-cxf" +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-petstore-server.sh b/bin/jaxrs-petstore-server.sh index 2dd4fc03b38..6436c797e87 100755 --- a/bin/jaxrs-petstore-server.sh +++ b/bin/jaxrs-petstore-server.sh @@ -26,6 +26,6 @@ fi # if you've executed sbt assembly previously it will use that instead. export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" -ags="$@ generate -t modules/swagger-codegen/src/main/resources/JavaJaxRS -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l jaxrs -o samples/server/petstore/jaxrs" +ags="$@ generate -t modules/swagger-codegen/src/main/resources/JavaJaxRS -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l jaxrs -o samples/server/petstore/jaxrs -DhideGenerationTimestamp=true" java $JAVA_OPTS -jar $executable $ags diff --git a/bin/jaxrs-resteasy-petstore-server.sh b/bin/jaxrs-resteasy-petstore-server.sh index ca214b53a16..a715ded67f9 100755 --- a/bin/jaxrs-resteasy-petstore-server.sh +++ b/bin/jaxrs-resteasy-petstore-server.sh @@ -26,6 +26,6 @@ fi # if you've executed sbt assembly previously it will use that instead. export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" -ags="$@ generate -t modules/swagger-codegen/src/main/resources/JavaJaxRS -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l jaxrs-resteasy -o samples/server/petstore/jaxrs-resteasy" +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 -DhideGenerationTimestamp=true" java $JAVA_OPTS -jar $executable $ags diff --git a/bin/jersey2-petstore-server.sh b/bin/jersey2-petstore-server.sh new file mode 100755 index 00000000000..d27379fd345 --- /dev/null +++ b/bin/jersey2-petstore-server.sh @@ -0,0 +1,31 @@ +#!/bin/sh + +SCRIPT="$0" + +while [ -h "$SCRIPT" ] ; do + ls=`ls -ld "$SCRIPT"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + SCRIPT="$link" + else + SCRIPT=`dirname "$SCRIPT"`/"$link" + fi +done + +if [ ! -d "${APP_DIR}" ]; then + APP_DIR=`dirname "$SCRIPT"`/.. + APP_DIR=`cd "${APP_DIR}"; pwd` +fi + +executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar" + +if [ ! -f "$executable" ] +then + mvn clean package +fi + +# if you've executed sbt assembly previously it will use that instead. +export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" +ags="$@ generate -t modules/swagger-codegen/src/main/resources/JavaJaxRS -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l jaxrs -o samples/server/petstore/jersey2 --library=jersey2 -DhideGenerationTimestamp=true" + +java $JAVA_OPTS -jar $executable $ags diff --git a/bin/nodejs-petstore-server.sh b/bin/nodejs-petstore-server.sh index 5d797903791..3fff1bdc0c0 100755 --- a/bin/nodejs-petstore-server.sh +++ b/bin/nodejs-petstore-server.sh @@ -26,6 +26,6 @@ fi # if you've executed sbt assembly previously it will use that instead. export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" -ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l nodejs -o samples/server/petstore/nodejs" +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/sinatra-petstore-server.sh b/bin/sinatra-petstore-server.sh index 4f7e19cee39..7c99e9a068a 100755 --- a/bin/sinatra-petstore-server.sh +++ b/bin/sinatra-petstore-server.sh @@ -26,6 +26,6 @@ fi # if you've executed sbt assembly previously it will use that instead. export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" -ags="$@ generate -t modules/swagger-codegen/src/main/resources/sinatra -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l sinatra -o samples/server/petstore/sinatra" +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/modules/swagger-codegen-cli/pom.xml b/modules/swagger-codegen-cli/pom.xml index c118a6325ef..90a14b16deb 100644 --- a/modules/swagger-codegen-cli/pom.xml +++ b/modules/swagger-codegen-cli/pom.xml @@ -3,7 +3,7 @@ io.swagger swagger-codegen-project - 2.1.6-SNAPSHOT + 2.1.6 ../.. 4.0.0 diff --git a/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/Generate.java b/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/Generate.java index 51fd246484a..8c7beab502b 100644 --- a/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/Generate.java +++ b/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/Generate.java @@ -105,6 +105,18 @@ public class Generate implements Runnable { @Option(name = {"--library"}, title = "library", description = CodegenConstants.LIBRARY_DESC) private String library; + + @Option(name = {"--git-user-id"}, title = "git user id", description = CodegenConstants.GIT_USER_ID_DESC) + private String gitUserId; + + @Option(name = {"--git-repo-id"}, title = "git repo id", description = CodegenConstants.GIT_REPO_ID_DESC) + private String gitRepoId; + + @Option(name = {"--release-note"}, title = "release note", description = CodegenConstants.RELEASE_NOTE_DESC) + private String releaseNote; + + @Option(name = {"--http-user-agent"}, title = "http user agent", description = CodegenConstants.HTTP_USER_AGENT_DESC) + private String httpUserAgent; @Override public void run() { @@ -183,6 +195,22 @@ public class Generate implements Runnable { configurator.setLibrary(library); } + if (isNotEmpty(gitUserId)) { + configurator.setGitUserId(gitUserId); + } + + if (isNotEmpty(gitRepoId)) { + configurator.setGitRepoId(gitRepoId); + } + + if (isNotEmpty(releaseNote)) { + configurator.setReleaseNote(releaseNote); + } + + if (isNotEmpty(httpUserAgent)) { + configurator.setHttpUserAgent(httpUserAgent); + } + applySystemPropertiesKvp(systemProperties, configurator); applyInstantiationTypesKvp(instantiationTypes, configurator); applyImportMappingsKvp(importMappings, configurator); diff --git a/modules/swagger-codegen-maven-plugin/pom.xml b/modules/swagger-codegen-maven-plugin/pom.xml index 52cf252d309..b45e0d97874 100644 --- a/modules/swagger-codegen-maven-plugin/pom.xml +++ b/modules/swagger-codegen-maven-plugin/pom.xml @@ -6,7 +6,7 @@ io.swagger swagger-codegen-project - 2.1.6-SNAPSHOT + 2.1.6 ../.. swagger-codegen-maven-plugin diff --git a/modules/swagger-codegen/pom.xml b/modules/swagger-codegen/pom.xml index a5c4eedd740..23f5aaed0d7 100644 --- a/modules/swagger-codegen/pom.xml +++ b/modules/swagger-codegen/pom.xml @@ -3,7 +3,7 @@ io.swagger swagger-codegen-project - 2.1.6-SNAPSHOT + 2.1.6 ../.. 4.0.0 diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/AbstractGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/AbstractGenerator.java index cadd7a1d85f..1d92c923c5c 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/AbstractGenerator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/AbstractGenerator.java @@ -69,6 +69,7 @@ public abstract class AbstractGenerator { * * @param config Codegen config * @param templateFile Template file + * @return String Full template file path */ public String getFullTemplateFile(CodegenConfig config, String templateFile) { String library = config.getLibrary(); 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 6809c4970d2..3dc90472247 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 @@ -29,6 +29,8 @@ public interface CodegenConfig { String apiTestFileFolder(); + String apiDocFileFolder(); + String fileSuffix(); String outputFolder(); @@ -41,6 +43,8 @@ public interface CodegenConfig { String modelTestFileFolder(); + String modelDocFileFolder(); + String modelPackage(); String toApiName(String name); @@ -99,6 +103,10 @@ public interface CodegenConfig { Map modelTestTemplateFiles(); + Map apiDocTemplateFiles(); + + Map modelDocTemplateFiles(); + Set languageSpecificPrimitives(); void preprocessSwagger(Swagger swagger); @@ -115,6 +123,10 @@ public interface CodegenConfig { String toModelTestFilename(String name); + String toApiDocFilename(String name); + + String toModelDocFilename(String name); + String toModelImport(String name); String toApiImport(String name); @@ -137,6 +149,8 @@ public interface CodegenConfig { String apiTestFilename(String templateName, String tag); + String apiDocFilename(String templateName, String tag); + boolean shouldOverwrite(String filename); boolean isSkipOverwrite(); @@ -153,4 +167,21 @@ public interface CodegenConfig { * @return libray template */ String getLibrary(); + + void setGitUserId(String gitUserId); + + String getGitUserId(); + + void setGitRepoId(String gitRepoId); + + String getGitRepoId(); + + void setReleaseNote(String releaseNote); + + String getReleaseNote(); + + void setHttpUserAgent(String httpUserAgent); + + String getHttpUserAgent(); + } 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 d02bc60539a..1d97fe829b8 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 @@ -91,4 +91,16 @@ public class CodegenConstants { public static final String OPTIONAL_EMIT_DEFAULT_VALUES = "optionalEmitDefaultValues"; public static final String OPTIONAL_EMIT_DEFAULT_VALUES_DESC = "Set DataMember's EmitDefaultValue, default false."; + public static final String GIT_USER_ID = "gitUserId"; + public static final String GIT_USER_ID_DESC = "Git user ID, e.g. swagger-api."; + + public static final String GIT_REPO_ID = "gitRepoId"; + public static final String GIT_REPO_ID_DESC = "Git repo ID, e.g. swagger-codegen."; + + public static final String RELEASE_NOTE = "releaseNote"; + public static final String RELEASE_NOTE_DESC = "Release note, default to 'Minor update'."; + + public static final String HTTP_USER_AGENT = "httpUserAgent"; + public static final String HTTP_USER_AGENT_DESC = "HTTP user agent, e.g. codegen_csharp_api_client, default to 'Swagger-Codegen/{packageVersion}}/{language}'"; + } 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 6fd620fc7f7..a7866e5675a 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 @@ -6,20 +6,35 @@ import java.util.*; public class CodegenModel { public String parent, parentSchema; + public List interfaces; + + // References to parent and interface CodegenModels. Only set when code generator supports inheritance. + public CodegenModel parentModel; + public List interfaceModels; + public String name, classname, description, classVarName, modelJson, dataType; public String classFilename; // store the class file name, mainly used for import public String unescapedDescription; public String discriminator; public String defaultValue; public List vars = new ArrayList(); + public List allVars; public List allowableValues; - // list of all required parameters - public Set mandatory = new HashSet(); - + // Sorted sets of required parameters. + public Set mandatory = new TreeSet(); + public Set allMandatory; + public Set imports = new TreeSet(); public Boolean hasVars, emptyVars, hasMoreModels, hasEnums, isEnum; public ExternalDocs externalDocs; public Map vendorExtensions; + + { + // By default these are the same collections. Where the code generator supports inheritance, composed models + // store the complete closure of owned and inherited properties in allVars and allMandatory. + allVars = vars; + allMandatory = mandatory; + } } 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 956e906b44f..59c5057ac29 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 @@ -15,7 +15,7 @@ public class CodegenOperation { isListContainer, isMultipart, hasMore = Boolean.TRUE, isResponseBinary = Boolean.FALSE, hasReference = Boolean.FALSE; public String path, operationId, returnType, httpMethod, returnBaseType, - returnContainer, summary, notes, baseName, defaultResponse; + returnContainer, summary, notes, baseName, defaultResponse, discriminator; public List> consumes, produces; public CodegenParameter bodyParam; public List allParams = new ArrayList(); @@ -32,6 +32,7 @@ public class CodegenOperation { public ExternalDocs externalDocs; public Map vendorExtensions; public String nickname; // legacy support + public String operationIdLowerCase; // for mardown documentation /** * Check if there's at least one parameter diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenParameter.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenParameter.java index 4a8c34e374f..d386b4c4dca 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenParameter.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenParameter.java @@ -8,8 +8,9 @@ import java.util.List; public class CodegenParameter { public Boolean isFormParam, isQueryParam, isPathParam, isHeaderParam, isCookieParam, isBodyParam, hasMore, isContainer, - secondaryParam, isCollectionFormatMulti; + secondaryParam, isCollectionFormatMulti, isPrimitiveType; public String baseName, paramName, dataType, datatypeWithEnum, collectionFormat, description, baseType, defaultValue; + public String example; // example value (x-example) public String jsonSchema; public Boolean isString, isInteger, isLong, isFloat, isDouble, isByteArray, isBinary, isBoolean, isDate, isDateTime; public Boolean isListContainer, isMapContainer; @@ -107,6 +108,7 @@ public class CodegenParameter { output.multipleOf = this.multipleOf; output.jsonSchema = this.jsonSchema; output.defaultValue = this.defaultValue; + output.example = this.example; output.isEnum = this.isEnum; if (this._enum != null) { output._enum = new ArrayList(this._enum); 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 0091204a0ab..a7045738cc3 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 @@ -32,6 +32,7 @@ public class CodegenProperty { public Boolean exclusiveMinimum; public Boolean exclusiveMaximum; public Boolean hasMore, required, secondaryParam; + public Boolean hasMoreNonReadOnly; // for model constructor, true if next properyt is not readonly public Boolean isPrimitiveType, isContainer, isNotContainer; public Boolean isString, isInteger, isLong, isFloat, isDouble, isByteArray, isBinary, isBoolean, isDate, isDateTime; public Boolean isListContainer, isMapContainer; @@ -63,6 +64,7 @@ public class CodegenProperty { result = prime * result + ((exclusiveMinimum == null) ? 0 : exclusiveMinimum.hashCode()); result = prime * result + ((getter == null) ? 0 : getter.hashCode()); result = prime * result + ((hasMore == null) ? 0 : hasMore.hashCode()); + result = prime * result + ((hasMoreNonReadOnly == null) ? 0 : hasMoreNonReadOnly.hashCode()); result = prime * result + ((isContainer == null) ? 0 : isContainer.hashCode()); result = prime * result + (isEnum ? 1231 : 1237); result = prime * result + ((isNotContainer == null) ? 0 : isNotContainer.hashCode()); 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 071f6220cff..9cd719dbe87 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,52 +2,22 @@ package io.swagger.codegen; import com.google.common.base.Function; import com.google.common.collect.Lists; - import io.swagger.codegen.examples.ExampleGenerator; -import io.swagger.models.ArrayModel; -import io.swagger.models.ComposedModel; -import io.swagger.models.Model; -import io.swagger.models.ModelImpl; -import io.swagger.models.Operation; -import io.swagger.models.RefModel; -import io.swagger.models.Response; -import io.swagger.models.Swagger; -import io.swagger.models.auth.ApiKeyAuthDefinition; -import io.swagger.models.auth.BasicAuthDefinition; -import io.swagger.models.auth.In; -import io.swagger.models.auth.OAuth2Definition; -import io.swagger.models.auth.SecuritySchemeDefinition; -import io.swagger.models.parameters.BodyParameter; -import io.swagger.models.parameters.CookieParameter; -import io.swagger.models.parameters.FormParameter; -import io.swagger.models.parameters.HeaderParameter; -import io.swagger.models.parameters.Parameter; -import io.swagger.models.parameters.PathParameter; -import io.swagger.models.parameters.QueryParameter; -import io.swagger.models.parameters.SerializableParameter; +import io.swagger.models.*; +import io.swagger.models.auth.*; +import io.swagger.models.parameters.*; import io.swagger.models.properties.*; import io.swagger.models.properties.PropertyBuilder.PropertyId; import io.swagger.util.Json; - +import org.apache.commons.lang.StringEscapeUtils; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nullable; - import java.io.File; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; +import java.util.*; +import java.util.Map.Entry; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -69,6 +39,8 @@ public class DefaultCodegen { protected Map modelTemplateFiles = new HashMap(); protected Map apiTestTemplateFiles = new HashMap(); protected Map modelTestTemplateFiles = new HashMap(); + protected Map apiDocTemplateFiles = new HashMap(); + protected Map modelDocTemplateFiles = new HashMap(); protected String templateDir; protected String embeddedTemplateDir; protected Map additionalProperties = new HashMap(); @@ -81,6 +53,8 @@ public class DefaultCodegen { protected String library; protected Boolean sortParamsByRequiredFlag = true; protected Boolean ensureUniqueParams = true; + protected String gitUserId, gitRepoId, releaseNote; + protected String httpUserAgent; public List cliOptions() { return cliOptions; @@ -116,11 +90,40 @@ public class DefaultCodegen { if(additionalProperties.containsKey(CodegenConstants.MODEL_NAME_SUFFIX)){ this.setModelNameSuffix((String) additionalProperties.get(CodegenConstants.MODEL_NAME_SUFFIX)); } + } // override with any special post-processing for all models - @SuppressWarnings("static-method") + @SuppressWarnings({ "static-method", "unchecked" }) public Map postProcessAllModels(Map objs) { + if (supportsInheritance) { + // Index all CodegenModels by name. + Map allModels = new HashMap(); + for (Entry entry : objs.entrySet()) { + String modelName = entry.getKey(); + Map inner = (Map) entry.getValue(); + List> models = (List>) inner.get("models"); + for (Map mo : models) { + CodegenModel cm = (CodegenModel) mo.get("model"); + allModels.put(modelName, cm); + } + } + // Fix up all parent and interface CodegenModel references. + for (CodegenModel cm : allModels.values()) { + if (cm.parent != null) { + cm.parentModel = allModels.get(cm.parent); + } + if (cm.interfaces != null && !cm.interfaces.isEmpty()) { + cm.interfaceModels = new ArrayList(cm.interfaces.size()); + for (String intf : cm.interfaces) { + CodegenModel intfModel = allModels.get(intf); + if (intfModel != null) { + cm.interfaceModels.add(intfModel); + } + } + } + } + } return objs; } @@ -167,11 +170,7 @@ public class DefaultCodegen { @SuppressWarnings("static-method") public String escapeText(String input) { if (input != null) { - input = input.trim(); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. - String output = input.replaceAll("\n", "\\\\n"); - output = output.replace("\r", "\\r"); - output = output.replace("\"", "\\\""); - return output; + return StringEscapeUtils.escapeJava(input).replace("\\/", "/"); } return input; } @@ -228,6 +227,14 @@ public class DefaultCodegen { } } + public Map apiDocTemplateFiles() { + return apiDocTemplateFiles; + } + + public Map modelDocTemplateFiles() { + return modelDocTemplateFiles; + } + public Map apiTestTemplateFiles() { return apiTestTemplateFiles; } @@ -260,6 +267,14 @@ public class DefaultCodegen { return outputFolder + "/" + testPackage().replace('.', '/'); } + public String apiDocFileFolder() { + return outputFolder; + } + + public String modelDocFileFolder() { + return outputFolder; + } + public Map additionalProperties() { return additionalProperties; } @@ -322,6 +337,16 @@ public class DefaultCodegen { return toApiName(name); } + /** + * Return the file name of the Api Documentation + * + * @param name the file name of the Api + * @return the file name of the Api + */ + public String toApiDocFilename(String name) { + return toApiName(name); + } + /** * Return the file name of the Api Test * @@ -362,6 +387,16 @@ public class DefaultCodegen { return initialCaps(name) + "Test"; } + /** + * Return the capitalized file name of the model documentation + * + * @param name the model name + * @return the file name of the model + */ + public String toModelDocFilename(String name) { + return initialCaps(name); + } + /** * Return the operation ID (method name) * @@ -614,13 +649,21 @@ public class DefaultCodegen { } } + /** + * Return the example value of the parameter. + * + * @param p Swagger property object + */ + public void setParameterExampleValue(CodegenParameter p) { + + } + /** * Return the example value of the property * * @param p Swagger property object * @return string presentation of the example value of the property */ - @SuppressWarnings("static-method") public String toExampleValue(Property p) { if(p.getExample() != null) { return p.getExample().toString(); @@ -896,8 +939,18 @@ public class DefaultCodegen { // TODO } else if (model instanceof ComposedModel) { final ComposedModel composed = (ComposedModel) model; - Map properties = new HashMap(); + Map properties = new LinkedHashMap(); List required = new ArrayList(); + Map allProperties; + List allRequired; + if (supportsInheritance) { + allProperties = new LinkedHashMap(); + allRequired = new ArrayList(); + m.allVars = new ArrayList(); + } else { + allProperties = null; + allRequired = null; + } // parent model final RefModel parent = (RefModel) composed.getParent(); if (parent != null) { @@ -905,31 +958,29 @@ public class DefaultCodegen { m.parentSchema = parentRef; m.parent = toModelName(parent.getSimpleRef()); addImport(m, m.parent); - if (!supportsInheritance && allDefinitions != null) { + if (allDefinitions != null) { final Model parentModel = allDefinitions.get(m.parentSchema); - if (parentModel instanceof ModelImpl) { - final ModelImpl _parent = (ModelImpl) parentModel; - if (_parent.getProperties() != null) { - properties.putAll(_parent.getProperties()); - } - if (_parent.getRequired() != null) { - required.addAll(_parent.getRequired()); - } + if (supportsInheritance) { + addProperties(allProperties, allRequired, parentModel, allDefinitions); + } else { + addProperties(properties, required, parentModel, allDefinitions); } } } // interfaces (intermediate models) - if (allDefinitions != null && composed.getInterfaces() != null) { + if (composed.getInterfaces() != null) { + if (m.interfaces == null) + m.interfaces = new ArrayList(); for (RefModel _interface : composed.getInterfaces()) { final String interfaceRef = toModelName(_interface.getSimpleRef()); - final Model interfaceModel = allDefinitions.get(interfaceRef); - if (interfaceModel instanceof ModelImpl) { - final ModelImpl _interfaceModel = (ModelImpl) interfaceModel; - if (_interfaceModel.getProperties() != null) { - properties.putAll(_interfaceModel.getProperties()); - } - if (_interfaceModel.getRequired() != null) { - required.addAll(_interfaceModel.getRequired()); + m.interfaces.add(interfaceRef); + addImport(m, interfaceRef); + if (allDefinitions != null) { + final Model interfaceModel = allDefinitions.get(interfaceRef); + if (supportsInheritance) { + addProperties(allProperties, allRequired, interfaceModel, allDefinitions); + } else { + addProperties(properties, required, interfaceModel, allDefinitions); } } } @@ -941,15 +992,12 @@ public class DefaultCodegen { child = allDefinitions.get(childRef); } if (child != null && child instanceof ModelImpl) { - final ModelImpl _child = (ModelImpl) child; - if (_child.getProperties() != null) { - properties.putAll(_child.getProperties()); - } - if (_child.getRequired() != null) { - required.addAll(_child.getRequired()); + addProperties(properties, required, child, allDefinitions); + if (supportsInheritance) { + addProperties(allProperties, allRequired, child, allDefinitions); } } - addVars(m, properties, required); + addVars(m, properties, required, allProperties, allRequired); } else { ModelImpl impl = (ModelImpl) model; if(impl.getEnum() != null && impl.getEnum().size() > 0) { @@ -965,7 +1013,7 @@ public class DefaultCodegen { addVars(m, impl.getProperties(), impl.getRequired()); } - if(m.vars != null) { + if (m.vars != null) { for(CodegenProperty prop : m.vars) { postProcessModelProperty(m, prop); } @@ -973,6 +1021,28 @@ public class DefaultCodegen { return m; } + protected void addProperties(Map properties, List required, Model model, + Map allDefinitions) { + + if (model instanceof ModelImpl) { + ModelImpl mi = (ModelImpl) model; + if (mi.getProperties() != null) { + properties.putAll(mi.getProperties()); + } + if (mi.getRequired() != null) { + required.addAll(mi.getRequired()); + } + } else if (model instanceof RefModel) { + String interfaceRef = toModelName(((RefModel) model).getSimpleRef()); + Model interfaceModel = allDefinitions.get(interfaceRef); + addProperties(properties, required, interfaceModel, allDefinitions); + } else if (model instanceof ComposedModel) { + for (Model component :((ComposedModel) model).getAllOf()) { + addProperties(properties, required, component, allDefinitions); + } + } + } + /** * Camelize the method name of the getter and setter * @@ -1214,6 +1284,7 @@ public class DefaultCodegen { property.containerType = "map"; MapProperty ap = (MapProperty) p; CodegenProperty cp = fromProperty("inner", ap.getAdditionalProperties()); + property.items = cp; property.baseType = getSwaggerType(p); if (!languageSpecificPrimitives.contains(cp.baseType)) { @@ -1402,6 +1473,16 @@ public class DefaultCodegen { op.defaultResponse = toDefaultValue(responseProperty); op.returnType = cm.datatype; op.hasReference = definitions != null && definitions.containsKey(op.returnBaseType); + + // lookup discriminator + if (definitions != null) { + Model m = definitions.get(op.returnBaseType); + if (m != null) { + CodegenModel cmod = fromModel(op.returnBaseType, m, definitions); + op.discriminator = cmod.discriminator; + } + } + if (cm.isContainer != null) { op.returnContainer = cm.containerType; if ("map".equals(cm.containerType)) { @@ -1452,6 +1533,14 @@ public class DefaultCodegen { } } } + + // set isPrimitiveType and baseType for allParams + /*if (languageSpecificPrimitives.contains(p.baseType)) { + p.isPrimitiveType = true; + p.baseType = getSwaggerType(p); + }*/ + + allParams.add(p); if (param instanceof QueryParameter) { p.isQueryParam = new Boolean(true); @@ -1518,7 +1607,6 @@ public class DefaultCodegen { // legacy support op.nickname = op.operationId; - if (op.allParams.size() > 0) { op.hasParams = true; } @@ -1723,7 +1811,9 @@ public class DefaultCodegen { prop.setRequired(bp.getRequired()); CodegenProperty cp = fromProperty("property", prop); if (cp != null) { + p.baseType = cp.baseType; p.dataType = cp.datatype; + p.isPrimitiveType = cp.isPrimitiveType; p.isBinary = cp.datatype.toLowerCase().startsWith("byte"); } @@ -1743,6 +1833,8 @@ public class DefaultCodegen { } imports.add(cp.baseType); p.dataType = cp.datatype; + p.baseType = cp.complexType; + p.isPrimitiveType = cp.isPrimitiveType; p.isContainer = true; p.isListContainer = true; @@ -1763,11 +1855,47 @@ public class DefaultCodegen { name = getTypeDeclaration(name); } p.dataType = name; + p.baseType = name; } } p.paramName = toParamName(bp.getName()); } + // set the example value + // if not specified in x-example, generate a default value + if (p.vendorExtensions.containsKey("x-example")) { + p.example = (String) p.vendorExtensions.get("x-example"); + } else if (Boolean.TRUE.equals(p.isString)) { + p.example = p.paramName + "_example"; + } else if (Boolean.TRUE.equals(p.isBoolean)) { + p.example = new String("true"); + } else if (Boolean.TRUE.equals(p.isLong)) { + p.example = new String("789"); + } else if (Boolean.TRUE.equals(p.isInteger)) { + p.example = new String("56"); + } else if (Boolean.TRUE.equals(p.isFloat)) { + p.example = new String("3.4"); + } else if (Boolean.TRUE.equals(p.isDouble)) { + p.example = new String("1.2"); + } else if (Boolean.TRUE.equals(p.isBinary)) { + p.example = new String("BINARY_DATA_HERE"); + } else if (Boolean.TRUE.equals(p.isByteArray)) { + p.example = new String("B"); + } else if (Boolean.TRUE.equals(p.isDate)) { + p.example = new String("2013-10-20"); + } else if (Boolean.TRUE.equals(p.isDateTime)) { + p.example = new String("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"); + } + + // set the parameter excample value + // should be overridden by lang codegen + setParameterExampleValue(p); + postProcessParameter(p); return p; } @@ -1978,6 +2106,7 @@ public class DefaultCodegen { LOGGER.warn("generated unique operationId `" + uniqueName + "`"); } co.operationId = uniqueName; + co.operationIdLowerCase = uniqueName.toLowerCase(); opList.add(co); co.baseName = tag; } @@ -2060,45 +2189,74 @@ public class DefaultCodegen { } } - private void addVars(CodegenModel m, Map properties, Collection required) { - if (properties != null && properties.size() > 0) { + private void addVars(CodegenModel m, Map properties, List required) { + addVars(m, properties, required, null, null); + } + + private void addVars(CodegenModel m, Map properties, List required, + Map allProperties, List allRequired) { + + if (properties != null && !properties.isEmpty()) { m.hasVars = true; m.hasEnums = false; - final int totalCount = properties.size(); - final Set mandatory = required == null ? Collections.emptySet() : new HashSet(required); - int count = 0; - for (Map.Entry entry : properties.entrySet()) { - final String key = entry.getKey(); - final Property prop = entry.getValue(); - if (prop == null) { - LOGGER.warn("null property for " + key); - } else { - final CodegenProperty cp = fromProperty(key, prop); - cp.required = mandatory.contains(key) ? true : null; - if (cp.isEnum) { - m.hasEnums = true; - } - count += 1; - if (count != totalCount) { - cp.hasMore = true; - } - if (cp.isContainer != null) { - addImport(m, typeMapping.get("array")); - } - addImport(m, cp.baseType); - addImport(m, cp.complexType); - m.vars.add(cp); - } - } - - m.mandatory = mandatory; + Set mandatory = required == null ? Collections. emptySet() + : new TreeSet(required); + addVars(m, m.vars, properties, mandatory); + m.allMandatory = m.mandatory = mandatory; } else { m.emptyVars = true; m.hasVars = false; m.hasEnums = false; } + + if (allProperties != null) { + Set allMandatory = allRequired == null ? Collections. emptySet() + : new TreeSet(allRequired); + addVars(m, m.allVars, allProperties, allMandatory); + m.allMandatory = allMandatory; + } + } + + private void addVars(CodegenModel m, List vars, Map properties, Set mandatory) { + // convert set to list so that we can access the next entry in the loop + List> propertyList = new ArrayList>(properties.entrySet()); + final int totalCount = propertyList.size(); + for (int i = 0; i < totalCount; i++) { + Map.Entry entry = propertyList.get(i); + + final String key = entry.getKey(); + final Property prop = entry.getValue(); + + if (prop == null) { + LOGGER.warn("null property for " + key); + } else { + final CodegenProperty cp = fromProperty(key, prop); + cp.required = mandatory.contains(key) ? true : null; + if (cp.isEnum) { + // FIXME: if supporting inheritance, when called a second time for allProperties it is possible for + // m.hasEnums to be set incorrectly if allProperties has enumerations but properties does not. + m.hasEnums = true; + } + + if (i+1 != totalCount) { + cp.hasMore = true; + // check the next entry to see if it's read only + if (!Boolean.TRUE.equals(propertyList.get(i+1).getValue().getReadOnly())) { + cp.hasMoreNonReadOnly = true; // next entry is not ready only + } + } + + if (cp.isContainer != null) { + addImport(m, typeMapping.get("array")); + } + + addImport(m, cp.baseType); + addImport(m, cp.complexType); + vars.add(cp); + } + } } /** @@ -2196,6 +2354,19 @@ public class DefaultCodegen { return apiFileFolder() + '/' + toApiFilename(tag) + suffix; } + /** + * Return the full path and API documentation file + * + * @param templateName template name + * @param tag tag + * + * @return the API documentation file name with full path + */ + public String apiDocFilename(String templateName, String tag) { + String suffix = apiDocTemplateFiles().get(templateName); + return apiDocFileFolder() + '/' + toApiDocFilename(tag) + suffix; + } + /** * Return the full path and API test file * @@ -2230,6 +2401,11 @@ public class DefaultCodegen { return supportedLibraries; } + /** + * Set library template (sub-template). + * + * @param library Library template + */ public void setLibrary(String library) { if (library != null && !supportedLibraries.containsKey(library)) throw new RuntimeException("unknown library: " + library); @@ -2245,6 +2421,78 @@ public class DefaultCodegen { return library; } + /** + * Set Git user ID. + * + * @param gitUserId Git user ID + */ + public void setGitUserId(String gitUserId) { + this.gitUserId = gitUserId; + } + + /** + * Git user ID + * + * @return Git user ID + */ + public String getGitUserId() { + return gitUserId; + } + + /** + * Set Git repo ID. + * + * @param gitRepoId Git repo ID + */ + public void setGitRepoId(String gitRepoId) { + this.gitRepoId = gitRepoId; + } + + /** + * Git repo ID + * + * @return Git repo ID + */ + public String getGitRepoId() { + return gitRepoId; + } + + /** + * Set release note. + * + * @param releaseNote Release note + */ + public void setReleaseNote(String releaseNote) { + this.releaseNote = releaseNote; + } + + /** + * Release note + * + * @return Release note + */ + public String getReleaseNote() { + return releaseNote; + } + + /** + * Set HTTP user agent. + * + * @param httpUserAgent HTTP user agent + */ + public void setHttpUserAgent(String httpUserAgent) { + this.httpUserAgent = httpUserAgent; + } + + /** + * HTTP user agent + * + * @return HTTP user agent + */ + public String getHttpUserAgent() { + return httpUserAgent; + } + @SuppressWarnings("static-method") protected CliOption buildLibraryCliOption(Map supportedLibraries) { StringBuilder sb = new StringBuilder("library template (sub-template) to use:"); @@ -2361,24 +2609,34 @@ public class DefaultCodegen { if (Boolean.TRUE.equals(property.isString)) { parameter.isString = true; + parameter.isPrimitiveType = true; } else if (Boolean.TRUE.equals(property.isBoolean)) { parameter.isBoolean = true; + parameter.isPrimitiveType = true; } else if (Boolean.TRUE.equals(property.isLong)) { parameter.isLong = true; + parameter.isPrimitiveType = true; } else if (Boolean.TRUE.equals(property.isInteger)) { parameter.isInteger = true; + parameter.isPrimitiveType = true; } else if (Boolean.TRUE.equals(property.isDouble)) { parameter.isDouble = true; + parameter.isPrimitiveType = true; } else if (Boolean.TRUE.equals(property.isFloat)) { parameter.isFloat = true; + parameter.isPrimitiveType = true; } else if (Boolean.TRUE.equals(property.isByteArray)) { parameter.isByteArray = true; + parameter.isPrimitiveType = true; } else if (Boolean.TRUE.equals(property.isBinary)) { parameter.isByteArray = true; + parameter.isPrimitiveType = true; } else if (Boolean.TRUE.equals(property.isDate)) { parameter.isDate = true; + parameter.isPrimitiveType = true; } else if (Boolean.TRUE.equals(property.isDateTime)) { parameter.isDateTime = true; + parameter.isPrimitiveType = true; } else { LOGGER.debug("Property type is not primitive: " + property.datatype); } 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 c966cf6ba66..aebf7e50de5 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 @@ -8,6 +8,7 @@ import io.swagger.models.auth.SecuritySchemeDefinition; import io.swagger.models.parameters.Parameter; import io.swagger.util.Json; import org.apache.commons.io.IOUtils; +import org.apache.commons.lang3.ObjectUtils; import org.joda.time.DateTime; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -167,26 +168,63 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { List allModels = new ArrayList(); // models - Map definitions = swagger.getDefinitions(); + final Map definitions = swagger.getDefinitions(); if (definitions != null) { - List sortedModelKeys = sortModelsByInheritance(definitions); + Set modelKeys = definitions.keySet(); if(generateModels) { if(modelsToGenerate != null && modelsToGenerate.size() > 0) { - List updatedKeys = new ArrayList(); - for(String m : sortedModelKeys) { + Set updatedKeys = new HashSet(); + for(String m : modelKeys) { if(modelsToGenerate.contains(m)) { updatedKeys.add(m); } } - sortedModelKeys = updatedKeys; + modelKeys = updatedKeys; } // store all processed models - Map allProcessedModels = new HashMap(); + Map allProcessedModels = new TreeMap(new Comparator() { + @Override + public int compare(String o1, String o2) { + Model model1 = definitions.get(o1); + Model model2 = definitions.get(o2); + + int model1InheritanceDepth = getInheritanceDepth(model1); + int model2InheritanceDepth = getInheritanceDepth(model2); + + if (model1InheritanceDepth == model2InheritanceDepth) { + return ObjectUtils.compare(config.toModelName(o1), config.toModelName(o2)); + } else if (model1InheritanceDepth > model2InheritanceDepth) { + return 1; + } else { + return -1; + } + } + + private int getInheritanceDepth(Model model) { + int inheritanceDepth = 0; + Model parent = getParent(model); + + while (parent != null) { + inheritanceDepth++; + parent = getParent(parent); + } + + return inheritanceDepth; + } + + private Model getParent(Model model) { + if (model instanceof ComposedModel) { + return definitions.get(((ComposedModel) model).getParent().getReference()); + } + + return null; + } + }); // process models only - for (String name : sortedModelKeys) { + for (String name : modelKeys) { try { //don't generate models that have an import mapping if(config.importMapping().containsKey(name)) { @@ -197,6 +235,7 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { Map modelMap = new HashMap(); modelMap.put(name, model); Map models = processModels(config, modelMap, definitions); + models.put("classname", config.toModelName(name)); models.putAll(config.additionalProperties()); allProcessedModels.put(name, models); @@ -263,6 +302,28 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { writeToFile(filename, tmpl.execute(models)); files.add(new File(filename)); } + + // to generate model documentation files + for (String templateName : config.modelDocTemplateFiles().keySet()) { + String suffix = config.modelDocTemplateFiles().get(templateName); + String filename = config.modelDocFileFolder() + File.separator + config.toModelDocFilename(name) + suffix; + if (!config.shouldOverwrite(filename)) { + continue; + } + String templateFile = getFullTemplateFile(config, templateName); + String template = readTemplate(templateFile); + Template tmpl = Mustache.compiler() + .withLoader(new Mustache.TemplateLoader() { + @Override + public Reader getTemplate(String name) { + return getTemplateReader(getFullTemplateFile(config, name + ".mustache")); + } + }) + .defaultValue("") + .compile(template); + writeToFile(filename, tmpl.execute(models)); + files.add(new File(filename)); + } } catch (Exception e) { throw new RuntimeException("Could not generate model '" + name + "'", e); } @@ -289,6 +350,12 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { for (String tag : paths.keySet()) { try { List ops = paths.get(tag); + Collections.sort(ops, new Comparator() { + @Override + public int compare(CodegenOperation one, CodegenOperation another) { + return ObjectUtils.compare(one.operationId, another.operationId); + } + }); Map operation = processOperations(config, tag, ops); operation.put("basePath", basePath); @@ -368,11 +435,35 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { files.add(new File(filename)); } + // to generate api documentation files + for (String templateName : config.apiDocTemplateFiles().keySet()) { + String filename = config.apiDocFilename(templateName, tag); + if (!config.shouldOverwrite(filename) && new File(filename).exists()) { + continue; + } + + String templateFile = getFullTemplateFile(config, templateName); + String template = readTemplate(templateFile); + Template tmpl = Mustache.compiler() + .withLoader(new Mustache.TemplateLoader() { + @Override + public Reader getTemplate(String name) { + return getTemplateReader(getFullTemplateFile(config, name + ".mustache")); + } + }) + .defaultValue("") + .compile(template); + + writeToFile(filename, tmpl.execute(operation)); + files.add(new File(filename)); + } + } catch (Exception e) { throw new RuntimeException("Could not generate api file for '" + tag + "'", e); } } } + if (System.getProperty("debugOperations") != null) { LOGGER.info("############ Operation info ############"); Json.prettyPrint(allOperations); @@ -513,54 +604,8 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { } } - private static List sortModelsByInheritance(final Map definitions) { - List sortedModelKeys = new ArrayList(definitions.keySet()); - Comparator cmp = new Comparator() { - @Override - public int compare(String o1, String o2) { - Model model1 = definitions.get(o1); - Model model2 = definitions.get(o2); - - int model1InheritanceDepth = getInheritanceDepth(model1); - int model2InheritanceDepth = getInheritanceDepth(model2); - - if (model1InheritanceDepth == model2InheritanceDepth) { - return 0; - } else if (model1InheritanceDepth > model2InheritanceDepth) { - return 1; - } else { - return -1; - } - } - - private int getInheritanceDepth(Model model) { - int inheritanceDepth = 0; - Model parent = getParent(model); - - while (parent != null) { - inheritanceDepth++; - parent = getParent(parent); - } - - return inheritanceDepth; - } - - private Model getParent(Model model) { - if (model instanceof ComposedModel) { - return definitions.get(((ComposedModel) model).getParent().getReference()); - } - - return null; - } - }; - - Collections.sort(sortedModelKeys, cmp); - - return sortedModelKeys; - } - public Map> processPaths(Map paths) { - Map> ops = new HashMap>(); + Map> ops = new TreeMap>(); for (String resourcePath : paths.keySet()) { Path path = paths.get(resourcePath); 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 7c73b2cb6b0..98c57ab341a 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 @@ -60,6 +60,10 @@ public class CodegenConfigurator { private Map additionalProperties = new HashMap(); private Map importMappings = new HashMap(); private Set languageSpecificPrimitives = new HashSet(); + private String gitUserId="YOUR_GIT_USR_ID"; + private String gitRepoId="YOUR_GIT_REPO_ID"; + private String releaseNote="Minor update"; + private String httpUserAgent; private final Map dynamicProperties = new HashMap(); //the map that holds the JsonAnySetter/JsonAnyGetter values @@ -295,6 +299,42 @@ public class CodegenConfigurator { return this; } + public String getGitUserId() { + return gitUserId; + } + + public CodegenConfigurator setGitUserId(String gitUserId) { + this.gitUserId = gitUserId; + return this; + } + + public String getGitRepoId() { + return gitRepoId; + } + + public CodegenConfigurator setGitRepoId(String gitRepoId) { + this.gitRepoId = gitRepoId; + return this; + } + + public String getReleaseNote() { + return releaseNote; + } + + public CodegenConfigurator setReleaseNote(String releaseNote) { + this.releaseNote = releaseNote; + return this; + } + + public String getHttpUserAgent() { + return httpUserAgent; + } + + public CodegenConfigurator setHttpUserAgent(String httpUserAgent) { + this.httpUserAgent= httpUserAgent; + return this; + } + public ClientOptInput toClientOptInput() { Validate.notEmpty(lang, "language must be specified"); @@ -322,6 +362,10 @@ public class CodegenConfigurator { checkAndSetAdditionalProperty(templateDir, toAbsolutePathStr(templateDir), CodegenConstants.TEMPLATE_DIR); checkAndSetAdditionalProperty(modelNamePrefix, CodegenConstants.MODEL_NAME_PREFIX); checkAndSetAdditionalProperty(modelNameSuffix, CodegenConstants.MODEL_NAME_SUFFIX); + checkAndSetAdditionalProperty(gitUserId, CodegenConstants.GIT_USER_ID); + checkAndSetAdditionalProperty(gitRepoId, CodegenConstants.GIT_REPO_ID); + checkAndSetAdditionalProperty(releaseNote, CodegenConstants.RELEASE_NOTE); + checkAndSetAdditionalProperty(httpUserAgent, CodegenConstants.HTTP_USER_AGENT); handleDynamicProperties(config); 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 5b161bac21d..76c0d1277b1 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 @@ -101,6 +101,7 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co typeMapping = new HashMap(); typeMapping.put("string", "string"); typeMapping.put("binary", "byte[]"); + typeMapping.put("bytearray", "byte[]"); typeMapping.put("boolean", "bool?"); typeMapping.put("integer", "int?"); typeMapping.put("float", "float?"); @@ -435,7 +436,7 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co } else if (p instanceof FloatProperty) { FloatProperty dp = (FloatProperty) p; if (dp.getDefault() != null) { - return dp.getDefault().toString(); + return String.format("%1$sF", dp.getDefault()); } } else if (p instanceof IntegerProperty) { IntegerProperty dp = (IntegerProperty) p; @@ -500,6 +501,12 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co 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) + } + // camelize the model name // phone_number => PhoneNumber return camelize(name); 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 07c1f19c9a8..4069dded643 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 @@ -1,6 +1,7 @@ package io.swagger.codegen.languages; import io.swagger.codegen.CodegenOperation; +import io.swagger.codegen.CodegenParameter; import io.swagger.codegen.CodegenResponse; import io.swagger.codegen.CodegenType; import io.swagger.models.Operation; @@ -95,6 +96,25 @@ public abstract class AbstractJavaJAXRSServerCodegen extends JavaClientCodegen @SuppressWarnings("unchecked") List ops = (List) operations.get("operation"); for ( CodegenOperation operation : ops ) { + boolean isMultipartPost = false; + List> consumes = operation.consumes; + if(consumes != null) { + for(Map consume : consumes) { + String mt = consume.get("mediaType"); + if(mt != null) { + if(mt.startsWith("multipart/form-data")) { + isMultipartPost = true; + } + } + } + } + + for(CodegenParameter parameter : operation.allParams) { + if(isMultipartPost) { + parameter.vendorExtensions.put("x-multipart", "true"); + } + } + List responses = operation.responses; if ( responses != null ) { for ( CodegenResponse resp : responses ) { 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 941bf77f667..5389c509d76 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 @@ -139,6 +139,13 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp return modelName; } + // model name starts with number + if (name.matches("^\\d.*")) { + String modelName = camelize("model_" + name); // e.g. 200Response => Model200Response (after camelize) + LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + modelName); + return modelName; + } + // camelize the model name // phone_number => PhoneNumber return camelize(name); 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 e165f491eb3..c0bead5c695 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 @@ -157,6 +157,9 @@ public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfi @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'. + // 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'. @@ -205,6 +208,13 @@ public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfi return modelName; } + // model name starts with number + if (name.matches("^\\d.*")) { + String modelName = "Model" + name; // e.g. 200Response => Model200Response (after camelize) + LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + modelName); + return modelName; + } + return name; } @@ -302,6 +312,8 @@ public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfi (sourceFolder + File.separator + invokerPackage).replace(".", File.separator), "ApiException.java")); supportingFiles.add(new SupportingFile("Pair.mustache", (sourceFolder + File.separator + invokerPackage).replace(".", File.separator), "Pair.java")); + supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); + supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore")); } private void addSupportingFilesForVolley() { 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 89f5806236d..0db384adf8b 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 @@ -34,6 +34,7 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen { private static final Logger LOGGER = LoggerFactory.getLogger(CSharpClientCodegen.class); private static final String NET45 = "v4.5"; private static final String NET35 = "v3.5"; + private static final String DATA_TYPE_WITH_ENUM_EXTENSION = "plainDatatypeWithEnum"; protected String packageGuid = "{" + java.util.UUID.randomUUID().toString().toUpperCase() + "}"; protected String packageTitle = "Swagger Library"; @@ -209,6 +210,9 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen { supportingFiles.add(new SupportingFile("compile-mono.sh.mustache", "", "compile-mono.sh")); supportingFiles.add(new SupportingFile("packages.config.mustache", "vendor" + java.io.File.separator, "packages.config")); supportingFiles.add(new SupportingFile("README.md", "", "README.md")); + supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); + supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore")); + if (optionalAssemblyInfoFlag) { supportingFiles.add(new SupportingFile("AssemblyInfo.mustache", packageFolder + File.separator + "Properties", "AssemblyInfo.cs")); @@ -285,19 +289,21 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen { } @Override - public Map postProcessModels(Map objs) { + public Map postProcessModels(Map objMap) { + Map objs = super.postProcessModels(objMap); + List models = (List) objs.get("models"); for (Object _mo : models) { Map mo = (Map) _mo; CodegenModel cm = (CodegenModel) mo.get("model"); for (CodegenProperty var : cm.vars) { Map allowableValues = var.allowableValues; - + // handle ArrayProperty if (var.items != null) { allowableValues = var.items.allowableValues; } - + if (allowableValues == null) { continue; } @@ -328,23 +334,27 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen { } allowableValues.put("enumVars", enumVars); // handle default value for enum, e.g. available => StatusEnum.AVAILABLE + + // HACK: strip ? from enum + if (var.datatypeWithEnum != null) { + var.vendorExtensions.put(DATA_TYPE_WITH_ENUM_EXTENSION, var.datatypeWithEnum.substring(0, var.datatypeWithEnum.length() - 1)); + } + if (var.defaultValue != null) { String enumName = null; + for (Map enumVar : enumVars) { - if (var.defaultValue.equals(enumVar.get("value"))) { + + if (var.defaultValue.replace("\"", "").equals(enumVar.get("value"))) { enumName = enumVar.get("name"); break; } } - if (enumName != null) { - var.defaultValue = var.datatypeWithEnum + "." + enumName; + if (enumName != null && var.vendorExtensions.containsKey(DATA_TYPE_WITH_ENUM_EXTENSION)) { + var.defaultValue = var.vendorExtensions.get(DATA_TYPE_WITH_ENUM_EXTENSION) + "." + enumName; } } - // HACK: strip ? from enum - if (var.datatypeWithEnum != null) { - var.vendorExtensions.put("plainDatatypeWithEnum", var.datatypeWithEnum.substring(0, var.datatypeWithEnum.length() - 1)); - } } } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ClojureClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ClojureClientCodegen.java index bf55e573644..2c60a30754b 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ClojureClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ClojureClientCodegen.java @@ -143,6 +143,8 @@ public class ClojureClientCodegen extends DefaultCodegen implements CodegenConfi final String baseNamespaceFolder = sourceFolder + File.separator + namespaceToFolder(baseNamespace); supportingFiles.add(new SupportingFile("project.mustache", "", "project.clj")); supportingFiles.add(new SupportingFile("core.mustache", baseNamespaceFolder, "core.clj")); + supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); + supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore")); } @Override 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 f32731b4754..70b98676ab3 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 @@ -52,9 +52,8 @@ public class DartClientCodegen extends DefaultCodegen implements CodegenConfig { Arrays.asList( "String", "bool", - "num", "int", - "float") + "double") ); instantiationTypes.put("array", "List"); instantiationTypes.put("map", "Map"); @@ -66,11 +65,11 @@ public class DartClientCodegen extends DefaultCodegen implements CodegenConfig { typeMapping.put("boolean", "bool"); typeMapping.put("string", "String"); typeMapping.put("int", "int"); - typeMapping.put("float", "num"); + typeMapping.put("float", "double"); typeMapping.put("long", "int"); typeMapping.put("short", "int"); typeMapping.put("char", "String"); - typeMapping.put("double", "num"); + typeMapping.put("double", "double"); typeMapping.put("object", "Object"); typeMapping.put("integer", "int"); typeMapping.put("Date", "DateTime"); @@ -150,6 +149,9 @@ public class DartClientCodegen extends DefaultCodegen implements CodegenConfig { supportingFiles.add(new SupportingFile("auth/http_basic_auth.mustache", authFolder, "http_basic_auth.dart")); supportingFiles.add(new SupportingFile("auth/api_key_auth.mustache", authFolder, "api_key_auth.dart")); supportingFiles.add(new SupportingFile("auth/oauth.mustache", authFolder, "oauth.dart")); + supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); + supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore")); + } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FlashClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FlashClientCodegen.java index f68f57d38ac..b5699a93a34 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 @@ -153,6 +153,8 @@ public class FlashClientCodegen extends DefaultCodegen implements CodegenConfig + 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) { 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 9f2f527dadd..234bda9adb7 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 @@ -129,6 +129,9 @@ public class GoClientCodegen extends DefaultCodegen implements CodegenConfig { apiPackage = packageName; 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("configuration.mustache", packageName, "Configuration.go")); } @Override diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaClientCodegen.java index 03a0aa36392..380a1eee2a1 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 @@ -42,6 +42,8 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { protected Boolean serializableModel = false; protected boolean serializeBigDecimalAsString = false; protected boolean useRxJava = false; + protected boolean hideGenerationTimestamp = false; + public JavaClientCodegen() { super(); @@ -99,6 +101,7 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { .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(USE_RX_JAVA, "Whether to use the RxJava adapter with the retrofit2 library.")); + cliOptions.add(new CliOption("hideGenerationTimestamp", "hides the timestamp when files were generated")); supportedLibraries.put(DEFAULT_LIBRARY, "HTTP client: Jersey client 1.18. JSON processing: Jackson 2.4.2"); supportedLibraries.put("feign", "HTTP client: Netflix Feign 8.1.1"); @@ -301,6 +304,10 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { importMapping.put("LocalDate", "java.time.LocalDate"); importMapping.put("LocalDateTime", "java.time.LocalDateTime"); } + + supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); + supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore")); + } private boolean usesAnyRetrofitLibrary() { @@ -393,6 +400,13 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { 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; } @@ -525,7 +539,9 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { @Override public CodegenModel fromModel(String name, Model model, Map allDefinitions) { CodegenModel codegenModel = super.fromModel(name, model, allDefinitions); - + if(codegenModel.description != null) { + codegenModel.imports.add("ApiModel"); + } if (allDefinitions != null && codegenModel != null && codegenModel.parentSchema != null && codegenModel.hasEnums) { final Model parentModel = allDefinitions.get(codegenModel.parentSchema); final CodegenModel parentCodegenModel = super.fromModel(codegenModel.parent, parentModel); @@ -584,6 +600,7 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { for (Object _mo : models) { Map mo = (Map) _mo; CodegenModel cm = (CodegenModel) mo.get("model"); + for (CodegenProperty var : cm.vars) { Map allowableValues = var.allowableValues; 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 78f3653671b..24f7fddc524 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 @@ -83,21 +83,6 @@ public class JavaInflectorServerCodegen extends JavaClientCodegen { (sourceFolder + '/' + invokerPackage).replace(".", "/"), "StringUtil.java")); } - @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 getTypeDeclaration(inner); - } - return super.getTypeDeclaration(p); - } - @Override public void addOperationToGroup(String tag, String resourcePath, Operation operation, CodegenOperation co, Map> operations) { String basePath = resourcePath; 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 32da243f7b4..3b3a6dbc280 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaJerseyServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaJerseyServerCodegen.java @@ -6,11 +6,8 @@ import io.swagger.models.Operation; import java.io.File; import java.util.*; -public class JavaJerseyServerCodegen extends AbstractJavaJAXRSServerCodegen -{ - - public JavaJerseyServerCodegen() - { +public class JavaJerseyServerCodegen extends AbstractJavaJAXRSServerCodegen { + public JavaJerseyServerCodegen() { super(); sourceFolder = "src/gen/java"; @@ -43,6 +40,7 @@ public class JavaJerseyServerCodegen extends AbstractJavaJAXRSServerCodegen Map supportedLibraries = new LinkedHashMap(); supportedLibraries.put(DEFAULT_LIBRARY, "Jersey core 1.18.1"); + supportedLibraries.put("jersey2", "Jersey core 2.x"); library.setEnum(supportedLibraries); cliOptions.add(library); @@ -85,6 +83,9 @@ public class JavaJerseyServerCodegen extends AbstractJavaJAXRSServerCodegen supportingFiles.add(new SupportingFile("ApiOriginFilter.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "ApiOriginFilter.java")); 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")); + 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")); @@ -92,6 +93,24 @@ public class JavaJerseyServerCodegen extends AbstractJavaJAXRSServerCodegen setDateLibrary(additionalProperties.get("dateLibrary").toString()); additionalProperties.put(dateLibrary, "true"); } + if(DEFAULT_LIBRARY.equals(library) || library == null) { + if(templateDir.startsWith(JAXRS_TEMPLATE_DIRECTORY_NAME)) { + // set to the default location + templateDir = JAXRS_TEMPLATE_DIRECTORY_NAME + File.separator + "jersey1_18"; + } + else { + templateDir += File.separator + "jersey1_18"; + } + } + if("jersey2".equals(library)) { + if(templateDir.startsWith(JAXRS_TEMPLATE_DIRECTORY_NAME)) { + // set to the default location + templateDir = JAXRS_TEMPLATE_DIRECTORY_NAME + File.separator + "jersey2"; + } + else { + templateDir += File.separator + "jersey2"; + } + } if ( "joda".equals(dateLibrary) ) { supportingFiles.add(new SupportingFile("JodaDateTimeProvider.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "JodaDateTimeProvider.java")); @@ -128,5 +147,9 @@ public class JavaJerseyServerCodegen extends AbstractJavaJAXRSServerCodegen } opList.add(co); co.baseName = basePath; - } + } + + public void hideGenerationTimestamp(boolean hideGenerationTimestamp) { + this.hideGenerationTimestamp = hideGenerationTimestamp; + } } 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 9e9ec3100a9..d9c93e4f69e 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 @@ -47,23 +47,29 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo @SuppressWarnings("hiding") private static final Logger LOGGER = LoggerFactory.getLogger(JavascriptClientCodegen.class); - private static final String PROJECT_NAME = "projectName"; - private static final String MODULE_NAME = "moduleName"; - private static final String PROJECT_DESCRIPTION = "projectDescription"; - private static final String PROJECT_VERSION = "projectVersion"; - private static final String PROJECT_LICENSE_NAME = "projectLicenseName"; - private static final String USE_PROMISES = "usePromises"; - private static final String OMIT_MODEL_METHODS = "omitModelMethods"; + public static final String PROJECT_NAME = "projectName"; + public static final String MODULE_NAME = "moduleName"; + public static final String PROJECT_DESCRIPTION = "projectDescription"; + public static final String PROJECT_VERSION = "projectVersion"; + public static final String PROJECT_LICENSE_NAME = "projectLicenseName"; + public static final String USE_PROMISES = "usePromises"; + public static final String USE_INHERITANCE = "useInheritance"; + public static final String EMIT_MODEL_METHODS = "emitModelMethods"; + public static final String EMIT_JS_DOC = "emitJSDoc"; protected String projectName; protected String moduleName; protected String projectDescription; protected String projectVersion; + protected String projectLicenseName; protected String sourceFolder = "src"; protected String localVariablePrefix = ""; - protected boolean usePromises = false; - protected boolean omitModelMethods = false; + protected boolean usePromises; + protected boolean emitModelMethods; + protected boolean emitJSDoc = true; + protected String apiDocPath = "docs/"; + protected String modelDocPath = "docs/"; public JavascriptClientCodegen() { super(); @@ -73,6 +79,8 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo templateDir = "Javascript"; apiPackage = "api"; modelPackage = "model"; + modelDocTemplateFiles.put("model_doc.mustache", ".md"); + apiDocTemplateFiles.put("api_doc.mustache", ".md"); // reference: http://www.w3schools.com/js/js_reserved.asp setReservedWordsLowerCase( @@ -101,8 +109,36 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo ); defaultIncludes = new HashSet(languageSpecificPrimitives); + instantiationTypes.put("array", "Array"); + instantiationTypes.put("list", "Array"); + instantiationTypes.put("map", "Object"); + typeMapping.clear(); + typeMapping.put("array", "Array"); + typeMapping.put("map", "Object"); + typeMapping.put("List", "Array"); + typeMapping.put("boolean", "Boolean"); + typeMapping.put("string", "String"); + typeMapping.put("int", "Integer"); // Huh? What is JS Integer? + 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("char", "String"); + typeMapping.put("double", "Number"); + typeMapping.put("object", "Object"); + typeMapping.put("integer", "Integer"); + // 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"); + + importMapping.clear(); + cliOptions.add(new CliOption(CodegenConstants.SOURCE_FOLDER, CodegenConstants.SOURCE_FOLDER_DESC).defaultValue("src")); cliOptions.add(new CliOption(CodegenConstants.LOCAL_VARIABLE_PREFIX, CodegenConstants.LOCAL_VARIABLE_PREFIX_DESC)); + cliOptions.add(new CliOption(CodegenConstants.API_PACKAGE, CodegenConstants.API_PACKAGE_DESC)); + cliOptions.add(new CliOption(CodegenConstants.MODEL_PACKAGE, CodegenConstants.MODEL_PACKAGE_DESC)); cliOptions.add(new CliOption(PROJECT_NAME, "name of the project (Default: generated from info.title or \"swagger-js-client\")")); cliOptions.add(new CliOption(MODULE_NAME, @@ -116,9 +152,15 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo cliOptions.add(new CliOption(USE_PROMISES, "use Promises as return values from the client API, instead of superagent callbacks") .defaultValue(Boolean.FALSE.toString())); - cliOptions.add(new CliOption(OMIT_MODEL_METHODS, - "omits generation of getters and setters for model classes") + cliOptions.add(new CliOption(EMIT_MODEL_METHODS, + "generate getters and setters for model properties") .defaultValue(Boolean.FALSE.toString())); + cliOptions.add(new CliOption(EMIT_JS_DOC, + "generate JSDoc comments") + .defaultValue(Boolean.TRUE.toString())); + cliOptions.add(new CliOption(USE_INHERITANCE, + "use JavaScript prototype chains & delegation for inheritance") + .defaultValue(Boolean.TRUE.toString())); } @Override @@ -140,59 +182,47 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo public void processOpts() { super.processOpts(); - typeMapping = new HashMap(); - typeMapping.put("array", "Array"); - typeMapping.put("List", "Array"); - typeMapping.put("map", "Object"); - typeMapping.put("object", "Object"); - typeMapping.put("boolean", "Boolean"); - typeMapping.put("char", "String"); - typeMapping.put("string", "String"); - typeMapping.put("short", "Integer"); - typeMapping.put("int", "Integer"); - typeMapping.put("integer", "Integer"); - typeMapping.put("long", "Integer"); - typeMapping.put("float", "Number"); - typeMapping.put("double", "Number"); - typeMapping.put("number", "Number"); - typeMapping.put("DateTime", "Date"); - typeMapping.put("Date", "Date"); - typeMapping.put("file", "File"); - // binary not supported in JavaScript client right now, using String as a workaround - typeMapping.put("binary", "String"); - - importMapping.clear(); + if (additionalProperties.containsKey(PROJECT_NAME)) { + setProjectName(((String) additionalProperties.get(PROJECT_NAME))); + } + if (additionalProperties.containsKey(MODULE_NAME)) { + setModuleName(((String) additionalProperties.get(MODULE_NAME))); + } + if (additionalProperties.containsKey(PROJECT_DESCRIPTION)) { + setProjectDescription(((String) additionalProperties.get(PROJECT_DESCRIPTION))); + } + if (additionalProperties.containsKey(PROJECT_VERSION)) { + setProjectVersion(((String) additionalProperties.get(PROJECT_VERSION))); + } + if (additionalProperties.containsKey(PROJECT_LICENSE_NAME)) { + setProjectLicenseName(((String) additionalProperties.get(PROJECT_LICENSE_NAME))); + } + if (additionalProperties.containsKey(CodegenConstants.LOCAL_VARIABLE_PREFIX)) { + setLocalVariablePrefix((String) additionalProperties.get(CodegenConstants.LOCAL_VARIABLE_PREFIX)); + } + if (additionalProperties.containsKey(CodegenConstants.SOURCE_FOLDER)) { + setSourceFolder((String) additionalProperties.get(CodegenConstants.SOURCE_FOLDER)); + } + if (additionalProperties.containsKey(USE_PROMISES)) { + setUsePromises(Boolean.parseBoolean((String)additionalProperties.get(USE_PROMISES))); + } + if (additionalProperties.containsKey(USE_INHERITANCE)) { + setUseInheritance(Boolean.parseBoolean((String)additionalProperties.get(USE_INHERITANCE))); + } else { + supportsInheritance = true; + } + if (additionalProperties.containsKey(EMIT_MODEL_METHODS)) { + setEmitModelMethods(Boolean.parseBoolean((String)additionalProperties.get(EMIT_MODEL_METHODS))); + } + if (additionalProperties.containsKey(EMIT_JS_DOC)) { + setEmitJSDoc(Boolean.parseBoolean((String)additionalProperties.get(EMIT_JS_DOC))); + } } @Override public void preprocessSwagger(Swagger swagger) { super.preprocessSwagger(swagger); - if (additionalProperties.containsKey(PROJECT_NAME)) { - projectName = ((String) additionalProperties.get(PROJECT_NAME)); - } - if (additionalProperties.containsKey(MODULE_NAME)) { - moduleName = ((String) additionalProperties.get(MODULE_NAME)); - } - if (additionalProperties.containsKey(PROJECT_DESCRIPTION)) { - projectDescription = ((String) additionalProperties.get(PROJECT_DESCRIPTION)); - } - if (additionalProperties.containsKey(PROJECT_VERSION)) { - projectVersion = ((String) additionalProperties.get(PROJECT_VERSION)); - } - if (additionalProperties.containsKey(CodegenConstants.LOCAL_VARIABLE_PREFIX)) { - localVariablePrefix = (String) additionalProperties.get(CodegenConstants.LOCAL_VARIABLE_PREFIX); - } - if (additionalProperties.containsKey(CodegenConstants.SOURCE_FOLDER)) { - sourceFolder = (String) additionalProperties.get(CodegenConstants.SOURCE_FOLDER); - } - if (additionalProperties.containsKey(USE_PROMISES)) { - usePromises = Boolean.parseBoolean((String)additionalProperties.get(USE_PROMISES)); - } - if (additionalProperties.containsKey(OMIT_MODEL_METHODS)) { - omitModelMethods = Boolean.parseBoolean((String)additionalProperties.get(OMIT_MODEL_METHODS)); - } - if (swagger.getInfo() != null) { Info info = swagger.getInfo(); if (StringUtils.isBlank(projectName) && info.getTitle() != null) { @@ -207,9 +237,10 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo // when projectDescription is not specified, use info.description projectDescription = info.getDescription(); } - if (info.getLicense() != null) { - License license = info.getLicense(); - if (additionalProperties.get(PROJECT_LICENSE_NAME) == null) { + if (additionalProperties.get(PROJECT_LICENSE_NAME) == null) { + // when projectLicense is not specified, use info.license + if (info.getLicense() != null) { + License license = info.getLicense(); additionalProperties.put(PROJECT_LICENSE_NAME, license.getName()); } } @@ -233,14 +264,24 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo additionalProperties.put(MODULE_NAME, moduleName); additionalProperties.put(PROJECT_DESCRIPTION, escapeText(projectDescription)); additionalProperties.put(PROJECT_VERSION, projectVersion); + additionalProperties.put(CodegenConstants.API_PACKAGE, apiPackage); additionalProperties.put(CodegenConstants.LOCAL_VARIABLE_PREFIX, localVariablePrefix); + additionalProperties.put(CodegenConstants.MODEL_PACKAGE, modelPackage); additionalProperties.put(CodegenConstants.SOURCE_FOLDER, sourceFolder); additionalProperties.put(USE_PROMISES, usePromises); - additionalProperties.put(OMIT_MODEL_METHODS, omitModelMethods); + additionalProperties.put(USE_INHERITANCE, supportsInheritance); + additionalProperties.put(EMIT_MODEL_METHODS, emitModelMethods); + additionalProperties.put(EMIT_JS_DOC, emitJSDoc); + + // make api and model doc path available in mustache template + additionalProperties.put("apiDocPath", apiDocPath); + additionalProperties.put("modelDocPath", modelDocPath); supportingFiles.add(new SupportingFile("package.mustache", "", "package.json")); supportingFiles.add(new SupportingFile("index.mustache", sourceFolder, "index.js")); supportingFiles.add(new SupportingFile("ApiClient.mustache", sourceFolder, "ApiClient.js")); + supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); + supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); } @Override @@ -250,12 +291,76 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo @Override public String apiFileFolder() { - return outputFolder + "/" + sourceFolder + "/" + apiPackage().replace('.', File.separatorChar); + return outputFolder + '/' + sourceFolder + '/' + apiPackage().replace('.', '/'); } @Override public String modelFileFolder() { - return outputFolder + "/" + sourceFolder + "/" + modelPackage().replace('.', File.separatorChar); + return outputFolder + '/' + sourceFolder + '/' + modelPackage().replace('.', '/'); + } + + public void setSourceFolder(String sourceFolder) { + this.sourceFolder = sourceFolder; + } + + public void setProjectName(String projectName) { + this.projectName = projectName; + } + + public void setLocalVariablePrefix(String localVariablePrefix) { + this.localVariablePrefix = localVariablePrefix; + } + + public void setModuleName(String moduleName) { + this.moduleName = moduleName; + } + + public void setProjectDescription(String projectDescription) { + this.projectDescription = projectDescription; + } + + public void setProjectVersion(String projectVersion) { + this.projectVersion = projectVersion; + } + + public void setProjectLicenseName(String projectLicenseName) { + this.projectLicenseName = projectLicenseName; + } + + public void setUsePromises(boolean usePromises) { + this.usePromises = usePromises; + } + + public void setUseInheritance(boolean useInheritance) { + this.supportsInheritance = useInheritance; + } + + public void setEmitModelMethods(boolean emitModelMethods) { + this.emitModelMethods = emitModelMethods; + } + + public void setEmitJSDoc(boolean emitJSDoc) { + this.emitJSDoc = emitJSDoc; + } + + @Override + public String apiDocFileFolder() { + return (outputFolder + "/" + apiDocPath).replace('/', File.separatorChar); + } + + @Override + public String modelDocFileFolder() { + return (outputFolder + "/" + modelDocPath).replace('/', File.separatorChar); + } + + @Override + public String toApiDocFilename(String name) { + return toApiName(name); + } + + @Override + public String toModelDocFilename(String name) { + return toModelName(name); } @Override @@ -313,6 +418,13 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo return modelName; } + // model name starts with number + if (name.matches("^\\d.*")) { + String modelName = "Model" + name; // e.g. 200Response => Model200Response (after camelize) + LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + modelName); + return modelName; + } + return name; } @@ -397,6 +509,84 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo } } + @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; + } + + typeMapping.put("array", "Array"); + typeMapping.put("List", "Array"); + typeMapping.put("map", "Object"); + typeMapping.put("object", "Object"); + typeMapping.put("boolean", "Boolean"); + typeMapping.put("char", "String"); + typeMapping.put("string", "String"); + typeMapping.put("short", "Integer"); + typeMapping.put("int", "Integer"); + typeMapping.put("integer", "Integer"); + typeMapping.put("long", "Integer"); + typeMapping.put("float", "Number"); + typeMapping.put("double", "Number"); + typeMapping.put("number", "Number"); + typeMapping.put("DateTime", "Date"); + typeMapping.put("Date", "Date"); + typeMapping.put("file", "File"); + // binary not supported in JavaScript client right now, using String as a workaround + typeMapping.put("binary", "String"); + + if ("String".equals(type)) { + if (example == null) { + example = p.paramName + "_example"; + } + example = "\"" + escapeText(example) + "\""; + } else if ("Integer".equals(type)) { + if (example == null) { + example = "56"; + } + } else if ("Number".equals(type)) { + if (example == null) { + example = "3.4"; + } + } else if ("Boolean".equals(type)) { + if (example == null) { + example = "true"; + } + } else if ("File".equals(type)) { + if (example == null) { + example = "/path/to/file"; + } + example = "\"" + escapeText(example) + "\""; + } else if ("Date".equals(type)) { + if (example == null) { + example = "2013-10-20T19:20:30+01:00"; + } + example = "new Date(\"" + escapeText(example) + "\")"; + } else if (!languageSpecificPrimitives.contains(type)) { + // type is a model class, e.g. User + example = "new " + moduleName + "." + type + "()"; + } + + 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; + } + /** * Normalize type by wrapping primitive types with single quotes. * @@ -450,6 +640,32 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo if (op.returnType != null) { op.returnType = normalizeType(op.returnType); } + + // 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; } @@ -466,6 +682,92 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo return codegenModel; } + private String trimBrackets(String s) { + if (s != null) { + int beginIdx = s.charAt(0) == '[' ? 1 : 0; + int endIdx = s.length(); + if (s.charAt(endIdx - 1) == ']') + endIdx--; + return s.substring(beginIdx, endIdx); + } + return null; + } + + private String getModelledType(String dataType) { + return "module:" + (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)) { + if (cp.containerType.equals("array")) + return "Array.<" + getJSDocType(cm, cp.items) + ">"; + else if (cp.containerType.equals("map")) + return "Object."; + } + String dataType = trimBrackets(cp.datatypeWithEnum); + if (cp.isEnum) { + dataType = cm.classname + '.' + dataType; + } + if (isModelledType(cp)) + dataType = getModelledType(dataType); + return dataType; + } + + private boolean isModelledType(CodegenProperty cp) { + // N.B. enums count as modelled types, file is not modelled (SuperAgent uses some 3rd party library). + 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); + if (isModelledType(cp)) + dataType = getModelledType(dataType); + if (Boolean.TRUE.equals(cp.isListContainer)) { + return "Array.<" + dataType + ">"; + } else if (Boolean.TRUE.equals(cp.isMapContainer)) { + return "Object."; + } + return dataType; + } + + private boolean isModelledType(CodegenParameter cp) { + // N.B. enums count as modelled types, file is not modelled (SuperAgent uses some 3rd party library). + 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); + if (returnType != null) { + if (isModelledType(co)) + returnType = getModelledType(returnType); + if (Boolean.TRUE.equals(co.isListContainer)) { + return "Array.<" + returnType + ">"; + } else if (Boolean.TRUE.equals(co.isMapContainer)) { + return "Object."; + } + } + return returnType; + } + + private boolean isModelledType(CodegenOperation co) { + // This seems to be the only way to tell whether an operation return type is modelled. + return !Boolean.TRUE.equals(co.returnTypeIsPrimitive); + } + + @SuppressWarnings("unchecked") @Override public Map postProcessOperations(Map objs) { // Generate and store argument list string of each operation into @@ -474,7 +776,7 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo if (operations != null) { List ops = (List) operations.get("operation"); for (CodegenOperation operation : ops) { - List argList = new ArrayList(); + List argList = new ArrayList(); boolean hasOptionalParams = false; for (CodegenParameter p : operation.allParams) { if (p.required != null && p.required) { @@ -490,20 +792,46 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo argList.add("callback"); } operation.vendorExtensions.put("x-codegen-argList", StringUtils.join(argList, ", ")); + + // Store JSDoc type specification into vendor-extension: x-jsdoc-type. + for (CodegenParameter cp : operation.allParams) { + String jsdocType = getJSDocTypeWithBraces(cp); + cp.vendorExtensions.put("x-jsdoc-type", jsdocType); + } + String jsdocType = getJSDocTypeWithBraces(operation); + operation.vendorExtensions.put("x-jsdoc-type", jsdocType); } } return objs; } + @SuppressWarnings("unchecked") @Override public Map postProcessModels(Map objs) { List models = (List) objs.get("models"); for (Object _mo : models) { Map mo = (Map) _mo; CodegenModel cm = (CodegenModel) mo.get("model"); + + // Collect each model's required property names in *document order*. + // 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; + cm.vendorExtensions.put("x-required", required); + cm.vendorExtensions.put("x-all-required", allRequired); + for (CodegenProperty var : cm.vars) { Map allowableValues = var.allowableValues; + // Add JSDoc @type value for this property. + String jsDocType = getJSDocTypeWithBraces(cm, var); + var.vendorExtensions.put("x-jsdoc-type", jsDocType); + + if (Boolean.TRUE.equals(var.required)) { + required.add(var.name); + } + // handle ArrayProperty if (var.items != null) { allowableValues = var.items.allowableValues; @@ -538,6 +866,15 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo } allowableValues.put("enumVars", enumVars); } + + if (supportsInheritance) { + for (CodegenProperty var : cm.allVars) { + if (Boolean.TRUE.equals(var.required)) { + allRequired.add(var.name); + } + } + } + // set vendor-extension: x-codegen-hasMoreRequired CodegenProperty lastRequired = null; for (CodegenProperty var : cm.vars) { 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 da1b8455a5d..bf1cdcbb900 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 @@ -123,7 +123,7 @@ public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig */ @Override public String getName() { - return "nodejs"; + return "nodejs-server"; } /** @@ -278,7 +278,9 @@ public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig if(operation.getOperationId() == null) { operation.setOperationId(getOrGenerateOperationId(operation, pathname, method.toString())); } - operation.getVendorExtensions().put("x-swagger-router-controller", toApiName(tag)); + if(operation.getVendorExtensions().get("x-swagger-router-controller") == null) { + operation.getVendorExtensions().put("x-swagger-router-controller", sanitizeTag(tag)); + } } } } 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 e535dc8892d..21e319f6ec9 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 @@ -4,6 +4,7 @@ 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; @@ -36,6 +37,8 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { protected String license = "MIT"; protected String gitRepoURL = "https://github.com/swagger-api/swagger-codegen"; protected String[] specialWords = {"new", "copy"}; + protected String apiDocPath = "docs/"; + protected String modelDocPath = "docs/"; public ObjcClientCodegen() { super(); @@ -46,6 +49,8 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { apiTemplateFiles.put("api-header.mustache", ".h"); apiTemplateFiles.put("api-body.mustache", ".m"); embeddedTemplateDir = templateDir = "objc"; + modelDocTemplateFiles.put("model_doc.mustache", ".md"); + apiDocTemplateFiles.put("api_doc.mustache", ".md"); defaultIncludes.clear(); defaultIncludes.add("bool"); @@ -90,7 +95,7 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { //TODO binary should be mapped to byte array // mapped to String as a workaround typeMapping.put("binary", "NSString"); - + typeMapping.put("ByteArray", "NSString"); // ref: http://www.tutorialspoint.com/objective_c/objective_c_basic_syntax.htm setReservedWordsLowerCase( @@ -199,6 +204,10 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { additionalProperties.put(GIT_REPO_URL, gitRepoURL); additionalProperties.put(LICENSE, license); + // make api and model doc path available in mustache template + additionalProperties.put("apiDocPath", apiDocPath); + additionalProperties.put("modelDocPath", modelDocPath); + String swaggerFolder = podName; modelPackage = swaggerFolder; @@ -220,6 +229,10 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { supportingFiles.add(new SupportingFile("Configuration-header.mustache", swaggerFolder, classPrefix + "Configuration.h")); supportingFiles.add(new SupportingFile("podspec.mustache", "", podName + ".podspec")); supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); + supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); + supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore")); + + } @Override @@ -320,6 +333,14 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { type = "model_" + type; // e.g. return => ModelReturn (after camelize) } + // model name starts with number + /* no need for the fix below as objc model starts with prefix (e.g. SWG) + if (type.matches("^\\d.*")) { + LOGGER.warn(type + " (model name starts with number) cannot be used as model name. Renamed to " + camelize("model_" + type)); + type = "model_" + type; // e.g. 200Response => Model200Response (after camelize) + } + */ + return toModelNameWithoutReservedWordCheck(type); } @@ -376,6 +397,26 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { return name; } + @Override + public String apiDocFileFolder() { + return (outputFolder + "/" + apiDocPath).replace("/", File.separator); + } + + @Override + public String modelDocFileFolder() { + return (outputFolder + "/" + modelDocPath).replace("/", File.separator); + } + + @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(); @@ -550,4 +591,75 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { 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 ("NSString*".equalsIgnoreCase(type)) { + if (example == null) { + example = p.paramName + "_example"; + } + example = "@\"" + escapeText(example) + "\""; + } else if ("NSNumber*".equals(type)) { + if (example == null) { + example = "56"; + } + example = "@" + example; + /* OBJC uses NSNumber to represent both int, long, double and float + } 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 ("NSURL*".equalsIgnoreCase(type)) { + if (example == null) { + example = "/path/to/file"; + } + //[NSURL fileURLWithPath:@"path/to/file"] + example = "[NSURL fileURLWithPath:@\"" + escapeText(example) + "\"]"; + /*} else if ("NSDate".equalsIgnoreCase(type)) { + if (example == null) { + example = "2013-10-20"; + } + example = "'" + escapeText(example) + "'";*/ + } else if ("NSDate*".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 + type = type.replace("*", ""); + // e.g. [[SWGPet alloc] init + example = "[[" + type + " alloc] init]"; + } 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; + } + + } 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 740f9ac2b21..f264a86b6a5 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 @@ -1,6 +1,7 @@ package io.swagger.codegen.languages; import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.CodegenParameter; import io.swagger.codegen.CodegenType; import io.swagger.codegen.DefaultCodegen; import io.swagger.codegen.SupportingFile; @@ -9,6 +10,17 @@ import io.swagger.codegen.CliOption; import io.swagger.models.properties.ArrayProperty; import io.swagger.models.properties.MapProperty; import io.swagger.models.properties.Property; +import io.swagger.models.properties.StringProperty; +import io.swagger.models.properties.LongProperty; +import io.swagger.models.properties.IntegerProperty; +import io.swagger.models.properties.FloatProperty; +import io.swagger.models.properties.DoubleProperty; +import io.swagger.models.properties.BooleanProperty; +import io.swagger.models.properties.BinaryProperty; +import io.swagger.models.properties.ByteArrayProperty; +import io.swagger.models.properties.DateTimeProperty; +import io.swagger.models.properties.DateProperty; + import java.io.File; import java.util.Arrays; @@ -23,6 +35,8 @@ public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig { protected String moduleName = "WWW::SwaggerClient"; protected String modulePathPart = moduleName.replaceAll("::", Matcher.quoteReplacement(File.separator)); protected String moduleVersion = "1.0.0"; + protected String apiDocPath = "docs/"; + protected String modelDocPath = "docs/"; protected static int emptyFunctionNameCounter = 0; @@ -34,6 +48,8 @@ public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig { apiTemplateFiles.put("api.mustache", ".pm"); modelTestTemplateFiles.put("object_test.mustache", ".t"); apiTestTemplateFiles.put("api_test.mustache", ".t"); + modelDocTemplateFiles.put("object_doc.mustache", ".md"); + apiDocTemplateFiles.put("api_doc.mustache", ".md"); embeddedTemplateDir = templateDir = "perl"; @@ -108,6 +124,10 @@ public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig { additionalProperties.put(MODULE_NAME, moduleName); } + // make api and model doc path available in mustache template + additionalProperties.put("apiDocPath", apiDocPath); + additionalProperties.put("modelDocPath", modelDocPath); + supportingFiles.add(new SupportingFile("ApiClient.mustache", ("lib/" + modulePathPart).replace('/', File.separatorChar), "ApiClient.pm")); supportingFiles.add(new SupportingFile("Configuration.mustache", ("lib/" + modulePathPart).replace('/', File.separatorChar), "Configuration.pm")); supportingFiles.add(new SupportingFile("ApiFactory.mustache", ("lib/" + modulePathPart).replace('/', File.separatorChar), "ApiFactory.pm")); @@ -115,6 +135,8 @@ public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig { supportingFiles.add(new SupportingFile("AutoDoc.mustache", ("lib/" + modulePathPart + "/Role").replace('/', File.separatorChar), "AutoDoc.pm")); supportingFiles.add(new SupportingFile("autodoc.script.mustache", "bin", "autodoc")); supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); + supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore")); + supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); } @Override @@ -147,7 +169,6 @@ public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig { return (outputFolder + "/lib/" + modulePathPart + modelPackage()).replace('/', File.separatorChar); } - @Override public String apiTestFileFolder() { return (outputFolder + "/t").replace('/', File.separatorChar); @@ -158,6 +179,16 @@ public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig { return (outputFolder + "/t").replace('/', File.separatorChar); } + @Override + public String apiDocFileFolder() { + return (outputFolder + "/" + apiDocPath).replace('/', File.separatorChar); + } + + @Override + public String modelDocFileFolder() { + return (outputFolder + "/" + modelDocPath).replace('/', File.separatorChar); + } + @Override public String getTypeDeclaration(Property p) { if (p instanceof ArrayProperty) { @@ -192,7 +223,43 @@ public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig { @Override public String toDefaultValue(Property p) { - return "null"; + 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) { + 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; } @@ -226,6 +293,12 @@ public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig { name = "model_" + name; } + // model name starts with number + if (name.matches("^\\d.*")) { + LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + camelize("model_" + name)); + name = "model_" + name; // e.g. 200Response => Model200Response (after camelize) + } + // add prefix/suffic to model name if (!StringUtils.isEmpty(modelNamePrefix)) { name = modelNamePrefix + "_" + name; @@ -251,11 +324,21 @@ public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig { return toModelFilename(name) + "Test"; } + @Override + public String toModelDocFilename(String name) { + return toModelFilename(name); + } + @Override public String toApiTestFilename(String name) { return toApiFilename(name) + "Test"; } + @Override + public String toApiDocFilename(String name) { + return toApiFilename(name); + } + @Override public String toApiFilename(String name) { // replace - with _ e.g. created-at => created_at @@ -303,4 +386,20 @@ public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig { public void setModuleVersion(String moduleVersion) { this.moduleVersion = moduleVersion; } + + @Override + public void setParameterExampleValue(CodegenParameter p) { + if (Boolean.TRUE.equals(p.isString) || Boolean.TRUE.equals(p.isBinary) || + Boolean.TRUE.equals(p.isByteArray) || Boolean.TRUE.equals(p.isFile)) { + p.example = "'" + p.example + "'"; + } else if (Boolean.TRUE.equals(p.isBoolean)) { + if (Boolean.parseBoolean(p.example)) + p.example = new String("1"); + else + p.example = new String("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 0fbbf5d3c6c..33d5875de6e 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java @@ -3,6 +3,7 @@ package io.swagger.codegen.languages; import io.swagger.codegen.CliOption; import io.swagger.codegen.CodegenConfig; import io.swagger.codegen.CodegenConstants; +import io.swagger.codegen.CodegenParameter; import io.swagger.codegen.CodegenType; import io.swagger.codegen.DefaultCodegen; import io.swagger.codegen.SupportingFile; @@ -35,10 +36,13 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { protected String artifactVersion = "1.0.0"; protected String srcBasePath = "lib"; protected String variableNamingConvention= "snake_case"; + protected String apiDocPath = "docs/"; + protected String modelDocPath = "docs/"; public PhpClientCodegen() { super(); + supportsInheritance = true; outputFolder = "generated-code" + File.separator + "php"; modelTemplateFiles.put("model.mustache", ".php"); apiTemplateFiles.put("api.mustache", ".php"); @@ -49,6 +53,9 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { modelPackage = invokerPackage + "\\Model"; testPackage = invokerPackage + "\\Tests"; + modelDocTemplateFiles.put("model_doc.mustache", ".md"); + apiDocTemplateFiles.put("api_doc.mustache", ".md"); + setReservedWordsLowerCase( Arrays.asList( // local variables used in api methods (endpoints) @@ -89,6 +96,7 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { 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"); @@ -110,8 +118,8 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { 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")); - 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")); + 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(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.ARTIFACT_VERSION, "The version to use in the composer package version field. e.g. 1.2.3")); } @@ -217,6 +225,10 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { additionalProperties.put("escapedInvokerPackage", invokerPackage.replace("\\", "\\\\")); + // make api and model doc path available in mustache template + additionalProperties.put("apiDocPath", apiDocPath); + additionalProperties.put("modelDocPath", modelDocPath); + supportingFiles.add(new SupportingFile("configuration.mustache", toPackagePath(invokerPackage, srcBasePath), "Configuration.php")); supportingFiles.add(new SupportingFile("ApiClient.mustache", toPackagePath(invokerPackage, srcBasePath), "ApiClient.php")); supportingFiles.add(new SupportingFile("ApiException.mustache", toPackagePath(invokerPackage, srcBasePath), "ApiException.php")); @@ -225,6 +237,8 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { supportingFiles.add(new SupportingFile("autoload.mustache", getPackagePath(), "autoload.php")); supportingFiles.add(new SupportingFile("README.mustache", getPackagePath(), "README.md")); supportingFiles.add(new SupportingFile(".travis.yml", getPackagePath(), ".travis.yml")); + supportingFiles.add(new SupportingFile("git_push.sh.mustache", getPackagePath(), "git_push.sh")); + } @Override @@ -252,6 +266,28 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { return (outputFolder + "/" + toPackagePath(testPackage, srcBasePath)); } + @Override + public String apiDocFileFolder() { + //return (outputFolder + "/" + apiDocPath).replace('/', File.separatorChar); + return (outputFolder + "/" + getPackagePath() + "/" + apiDocPath); + } + + @Override + public String modelDocFileFolder() { + //return (outputFolder + "/" + modelDocPath).replace('/', File.separatorChar); + 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) { @@ -373,6 +409,12 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { 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; @@ -458,4 +500,69 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { 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; + } + } 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 52ea0ce20e4..6091b36b90a 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 @@ -3,6 +3,7 @@ package io.swagger.codegen.languages; import io.swagger.codegen.CliOption; import io.swagger.codegen.CodegenConfig; import io.swagger.codegen.CodegenConstants; +import io.swagger.codegen.CodegenParameter; import io.swagger.codegen.CodegenType; import io.swagger.codegen.DefaultCodegen; import io.swagger.codegen.SupportingFile; @@ -17,6 +18,8 @@ import org.apache.commons.lang.StringUtils; public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig { protected String packageName; protected String packageVersion; + protected String apiDocPath = "docs/"; + protected String modelDocPath = "docs/"; public PythonClientCodegen() { super(); @@ -28,6 +31,9 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig apiTemplateFiles.put("api.mustache", ".py"); embeddedTemplateDir = templateDir = "python"; + modelDocTemplateFiles.put("model_doc.mustache", ".md"); + apiDocTemplateFiles.put("api_doc.mustache", ".md"); + languageSpecificPrimitives.clear(); languageSpecificPrimitives.add("int"); languageSpecificPrimitives.add("float"); @@ -36,6 +42,7 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig languageSpecificPrimitives.add("str"); languageSpecificPrimitives.add("datetime"); languageSpecificPrimitives.add("date"); + languageSpecificPrimitives.add("object"); typeMapping.clear(); typeMapping.put("integer", "int"); @@ -97,6 +104,10 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig 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"; @@ -110,6 +121,8 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig supportingFiles.add(new SupportingFile("__init__package.mustache", swaggerFolder, "__init__.py")); supportingFiles.add(new SupportingFile("__init__model.mustache", modelPackage, "__init__.py")); supportingFiles.add(new SupportingFile("__init__api.mustache", apiPackage, "__init__.py")); + supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); + supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore")); } private static String dropDots(String str) { @@ -136,6 +149,27 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig 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); @@ -222,6 +256,12 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig 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; } @@ -247,6 +287,12 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig 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; } @@ -374,4 +420,70 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig 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; + } + + } 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 667fdad1a23..2eedc14ed27 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 @@ -3,15 +3,21 @@ 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.CodegenType; import io.swagger.codegen.DefaultCodegen; import io.swagger.codegen.SupportingFile; +import io.swagger.models.Model; +import io.swagger.models.Operation; +import io.swagger.models.Swagger; import io.swagger.models.properties.*; import java.io.File; import java.util.Arrays; import java.util.HashSet; import java.util.Iterator; +import java.util.Map; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; @@ -40,6 +46,8 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { protected String gemDescription = "This gem maps to a swagger API"; protected String gemAuthor = ""; protected String gemAuthorEmail = ""; + protected String apiDocPath = "docs/"; + protected String modelDocPath = "docs/"; protected static int emptyMethodNameCounter = 0; @@ -50,6 +58,8 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { outputFolder = "generated-code" + File.separator + "ruby"; modelTemplateFiles.put("model.mustache", ".rb"); apiTemplateFiles.put("api.mustache", ".rb"); + modelDocTemplateFiles.put("model_doc.mustache", ".md"); + apiDocTemplateFiles.put("api_doc.mustache", ".md"); embeddedTemplateDir = templateDir = "ruby"; modelTestTemplateFiles.put("model_test.mustache", ".rb"); @@ -194,6 +204,9 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { setGemAuthorEmail((String) additionalProperties.get(GEM_AUTHOR_EMAIL)); } + // make api and model doc path available in mustache template + additionalProperties.put("apiDocPath", apiDocPath); + additionalProperties.put("modelDocPath", modelDocPath); // use constant model/api package (folder path) setModelPackage("models"); @@ -206,8 +219,40 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { supportingFiles.add(new SupportingFile("api_error.mustache", gemFolder, "api_error.rb")); supportingFiles.add(new SupportingFile("configuration.mustache", gemFolder, "configuration.rb")); supportingFiles.add(new SupportingFile("version.mustache", gemFolder, "version.rb")); + 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")); } + @Override + public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, Map definitions, Swagger swagger) { + CodegenOperation op = super.fromOperation(path, httpMethod, operation, definitions, swagger); + // Set vendor-extension to be used in template: + // x-codegen-hasMoreRequired + // x-codegen-hasMoreOptional + // x-codegen-hasRequiredParams + CodegenParameter lastRequired = null; + CodegenParameter lastOptional = null; + for (CodegenParameter p : op.allParams) { + if (p.required != 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; + } @Override public CodegenType getTag() { @@ -271,6 +316,16 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { return outputFolder + File.separator + specFolder + File.separator + modelPackage.replace("/", File.separator); } + @Override + public String apiDocFileFolder() { + return (outputFolder + "/" + apiDocPath).replace('/', File.separatorChar); + } + + @Override + public String modelDocFileFolder() { + return (outputFolder + "/" + modelDocPath).replace('/', File.separatorChar); + } + @Override public String getTypeDeclaration(Property p) { if (p instanceof ArrayProperty) { @@ -328,7 +383,7 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { String type = null; if (typeMapping.containsKey(swaggerType)) { type = typeMapping.get(swaggerType); - if (languageSpecificPrimitives.contains(type)) { + if (languageSpecificPrimitives.contains(type)) { return type; } } else { @@ -386,6 +441,12 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { return modelName; } + // model name starts with number + if (name.matches("^\\d.*")) { + LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + camelize("model_" + name)); + name = "model_" + name; // e.g. 200Response => Model200Response (after camelize) + } + // camelize the model name // phone_number => PhoneNumber return camelize(name); @@ -409,11 +470,22 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { return filename; } + // model name starts with number + if (name.matches("^\\d.*")) { + LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + underscore("model_" + name)); + name = "model_" + name; // e.g. 200Response => model_200_response + } + // underscore the model file name // PhoneNumber.rb => phone_number.rb return underscore(name); } + @Override + public String toModelDocFilename(String name) { + return toModelName(name); + } + @Override public String toApiFilename(String name) { // replace - with _ e.g. created-at => created_at @@ -423,6 +495,11 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { return underscore(name) + "_api"; } + @Override + public String toApiDocFilename(String name) { + return toApiName(name); + } + @Override public String toApiTestFilename(String name) { return toApiFilename(name) + "_spec"; @@ -466,6 +543,69 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { return gemName + "/" + apiPackage() + "/" + toApiFilename(name); } + @Override + public void setParameterExampleValue(CodegenParameter p) { + String example; + + if (p.defaultValue == null) { + example = p.example; + } else { + example = p.defaultValue; + } + + String type = p.baseType; + if (type == null) { + type = p.dataType; + } + + if ("String".equals(type)) { + if (example == null) { + example = p.paramName + "_example"; + } + example = "\"" + escapeText(example) + "\""; + } else if ("Integer".equals(type)) { + if (example == null) { + example = "56"; + } + } else if ("Float".equals(type)) { + if (example == null) { + example = "3.4"; + } + } else if ("BOOLEAN".equals(type)) { + if (example == null) { + example = "true"; + } + } else if ("File".equals(type)) { + if (example == null) { + example = "/path/to/file"; + } + example = "File.new(\"" + escapeText(example) + "\")"; + } else if ("Date".equals(type)) { + if (example == null) { + example = "2013-10-20"; + } + example = "Date.parse(\"" + escapeText(example) + "\")"; + } else if ("DateTime".equals(type)) { + if (example == null) { + example = "2013-10-20T19:20:30+01:00"; + } + example = "DateTime.parse(\"" + escapeText(example) + "\")"; + } else if (!languageSpecificPrimitives.contains(type)) { + // type is a model class, e.g. User + example = moduleName + "::" + type + ".new"; + } + + if (example == null) { + example = "nil"; + } else if (Boolean.TRUE.equals(p.isListContainer)) { + example = "[" + example + "]"; + } else if (Boolean.TRUE.equals(p.isMapContainer)) { + example = "{'key' => " + example + "}"; + } + + p.example = example; + } + public void setGemName(String gemName) { this.gemName = gemName; } 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 51d9614728c..993ef095441 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 @@ -72,6 +72,8 @@ public class ScalaClientCodegen extends DefaultCodegen implements CodegenConfig supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml")); supportingFiles.add(new SupportingFile("apiInvoker.mustache", (sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "ApiInvoker.scala")); + supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); + supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore")); importMapping.remove("List"); importMapping.remove("Set"); @@ -110,6 +112,7 @@ public class ScalaClientCodegen extends DefaultCodegen implements CodegenConfig "Long", "Float", "Object", + "Any", "List", "Map") ); @@ -255,4 +258,67 @@ public class ScalaClientCodegen extends DefaultCodegen implements CodegenConfig 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); + } + } 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 16d332e4489..0725d36eec8 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 @@ -74,6 +74,8 @@ public class SwiftCodegen extends DefaultCodegen implements CodegenConfig { languageSpecificPrimitives = new HashSet( Arrays.asList( "Int", + "Int32", + "Int64", "Float", "Double", "Bool", @@ -115,10 +117,10 @@ public class SwiftCodegen extends DefaultCodegen implements CodegenConfig { typeMapping.put("string", "String"); typeMapping.put("char", "Character"); typeMapping.put("short", "Int"); - typeMapping.put("int", "Int"); - typeMapping.put("long", "Int"); - typeMapping.put("integer", "Int"); - typeMapping.put("Integer", "Int"); + typeMapping.put("int", "Int32"); + typeMapping.put("long", "Int64"); + typeMapping.put("integer", "Int32"); + typeMapping.put("Integer", "Int32"); typeMapping.put("float", "Float"); typeMapping.put("number", "Double"); typeMapping.put("double", "Double"); @@ -195,6 +197,9 @@ public class SwiftCodegen extends DefaultCodegen implements CodegenConfig { supportingFiles.add(new SupportingFile("Extensions.mustache", sourceFolder, "Extensions.swift")); supportingFiles.add(new SupportingFile("Models.mustache", sourceFolder, "Models.swift")); supportingFiles.add(new SupportingFile("APIs.mustache", sourceFolder, "APIs.swift")); + supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); + supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore")); + } @Override @@ -268,6 +273,13 @@ public class SwiftCodegen extends DefaultCodegen implements CodegenConfig { return modelName; } + // model name starts with number + if (name.matches("^\\d.*")) { + String modelName = "Model" + name; // e.g. 200Response => Model200Response (after camelize) + LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + modelName); + return modelName; + } + return name; } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptAngularClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptAngularClientCodegen.java index 1e1acd65c08..6237331cf80 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptAngularClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptAngularClientCodegen.java @@ -19,6 +19,10 @@ public class TypeScriptAngularClientCodegen extends AbstractTypeScriptClientCode public void processOpts() { super.processOpts(); supportingFiles.add(new SupportingFile("api.d.mustache", apiPackage().replace('.', File.separatorChar), "api.d.ts")); + supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); + //supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore")); + + } public TypeScriptAngularClientCodegen() { 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 77371a7fb58..e590a60b323 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 @@ -18,6 +18,8 @@ public class TypeScriptNodeClientCodegen extends AbstractTypeScriptClientCodegen public void processOpts() { super.processOpts(); supportingFiles.add(new SupportingFile("api.mustache", null, "api.ts")); + supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); + //supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore")); } public TypeScriptNodeClientCodegen() { diff --git a/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache index 79da18933aa..4c79216bc55 100644 --- a/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache @@ -71,7 +71,7 @@ public class ApiClient { dateFormat = ApiClient.buildDefaultDateFormat(); // Set default User-Agent. - setUserAgent("Java-Swagger"); + setUserAgent("{{#httpUserAgent}}{{{.}}}{{/httpUserAgent}}{{^httpUserAgent}}Swagger-Codegen/{{{artifactVersion}}}/java{{/httpUserAgent}}"); // Setup authentications (key: authentication name, value: authentication). authentications = new HashMap();{{#authMethods}}{{#isBasic}} diff --git a/modules/swagger-codegen/src/main/resources/Java/api.mustache b/modules/swagger-codegen/src/main/resources/Java/api.mustache index af10f614e32..0487cd8ef98 100644 --- a/modules/swagger-codegen/src/main/resources/Java/api.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/api.mustache @@ -42,7 +42,7 @@ public class {{classname}} { /** * {{summary}} * {{notes}}{{#allParams}} - * @param {{paramName}} {{description}}{{/allParams}}{{#returnType}} + * @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}{{/allParams}}{{#returnType}} * @return {{{returnType}}}{{/returnType}} * @throws ApiException if fails to make API call */ diff --git a/modules/swagger-codegen/src/main/resources/Java/generatedAnnotation.mustache b/modules/swagger-codegen/src/main/resources/Java/generatedAnnotation.mustache index 49110fc1ad9..a47b6faa85b 100644 --- a/modules/swagger-codegen/src/main/resources/Java/generatedAnnotation.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/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/Java/git_push.sh.mustache b/modules/swagger-codegen/src/main/resources/Java/git_push.sh.mustache new file mode 100755 index 00000000000..e153ce23ecf --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/git_push.sh.mustache @@ -0,0 +1,52 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 swagger-petstore-perl "minor update" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 + +if [ "$git_user_id" = "" ]; then + git_user_id="{{{gitUserId}}}" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="{{{gitRepoId}}}" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="{{{releaseNote}}}" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=`git remote` +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git crediential in your environment." + git remote add origin https://github.com/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:${GIT_TOKEN}@github.com/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://github.com/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' + diff --git a/modules/swagger-codegen/src/main/resources/Java/gitignore.mustache b/modules/swagger-codegen/src/main/resources/Java/gitignore.mustache new file mode 100644 index 00000000000..32858aad3c3 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/gitignore.mustache @@ -0,0 +1,12 @@ +*.class + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.ear + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/feign/api.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/api.mustache index a941843a5eb..fae7a93303d 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 @@ -20,7 +20,7 @@ public interface {{classname}} extends ApiClient.Api { /** * {{summary}} * {{notes}} -{{#allParams}} * @param {{paramName}} {{description}} +{{#allParams}} * @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}} {{/allParams}} * @return {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} */ @RequestLine("{{httpMethod}} {{{path}}}{{#hasQueryParams}}?{{/hasQueryParams}}{{#queryParams}}{{baseName}}={{=<% %>=}}{<%paramName%>}<%={{ }}=%>{{#hasMore}}&{{/hasMore}}{{/queryParams}}") 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 d0121e752dc..5ff827ff40c 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 @@ -110,7 +110,7 @@ io.swagger swagger-annotations - ${swagger-annotations-version} + ${swagger-core-version} @@ -179,7 +179,7 @@ - 1.5.0 + 1.5.8 8.1.1 2.6.3 2.5 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 66acc3811d2..58bab66e13d 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 @@ -80,7 +80,7 @@ public class ApiClient { this.json.setDateFormat((DateFormat) dateFormat.clone()); // Set default User-Agent. - setUserAgent("Java-Swagger"); + setUserAgent("{{#httpUserAgent}}{{{.}}}{{/httpUserAgent}}{{^httpUserAgent}}Swagger-Codegen/{{{artifactVersion}}}/java{{/httpUserAgent}}"); // Setup authentications (key: authentication name, value: authentication). authentications = new HashMap();{{#authMethods}}{{#isBasic}} diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/api.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/api.mustache index cd10de1364d..6c980b727fa 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/api.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/api.mustache @@ -42,7 +42,7 @@ public class {{classname}} { /** * {{summary}} * {{notes}}{{#allParams}} - * @param {{paramName}} {{description}}{{/allParams}}{{#returnType}} + * @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}{{/allParams}}{{#returnType}} * @return {{{returnType}}}{{/returnType}} * @throws ApiException if fails to make API call */ 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 be6b9b66cef..13fab8b0ed2 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 @@ -131,7 +131,7 @@ io.swagger swagger-annotations - ${swagger-annotations-version} + ${swagger-core-version} @@ -194,7 +194,7 @@ - 1.5.0 + 1.5.8 2.22 2.4.2 2.3 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 34b0e4b33b2..4c8e304ed97 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 @@ -141,7 +141,7 @@ public class ApiClient { this.lenientDatetimeFormat = true; // Set default User-Agent. - setUserAgent("Java-Swagger"); + setUserAgent("{{#httpUserAgent}}{{{.}}}{{/httpUserAgent}}{{^httpUserAgent}}Swagger-Codegen/{{{artifactVersion}}}/java{{/httpUserAgent}}"); // Setup authentications (key: authentication name, value: authentication). authentications = new HashMap();{{#authMethods}}{{#isBasic}} 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 70559ac281c..6c46a9aed9a 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 @@ -106,7 +106,7 @@ public class {{classname}} { /** * {{summary}} * {{notes}}{{#allParams}} - * @param {{paramName}} {{description}}{{/allParams}}{{#returnType}} + * @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}{{/allParams}}{{#returnType}} * @return {{{returnType}}}{{/returnType}} * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ @@ -118,7 +118,7 @@ public class {{classname}} { /** * {{summary}} * {{notes}}{{#allParams}} - * @param {{paramName}} {{description}}{{/allParams}} + * @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}{{/allParams}} * @return ApiResponse<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ @@ -131,7 +131,7 @@ public class {{classname}} { /** * {{summary}} (asynchronously) * {{notes}}{{#allParams}} - * @param {{paramName}} {{description}}{{/allParams}} + * @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}{{/allParams}} * @param callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/model.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/model.mustache index f469a1346ae..0b544b9e06c 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/model.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/model.mustache @@ -13,7 +13,7 @@ import com.google.gson.annotations.SerializedName; /** * {{description}} **/{{/description}} -@ApiModel(description = "{{{description}}}") +{{#description}}@ApiModel(description = "{{{description}}}"){{/description}} public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#serializableModel}}implements Serializable{{/serializableModel}} { {{#vars}}{{#isEnum}} 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 8339c894895..d457749d19a 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 @@ -132,7 +132,7 @@ io.swagger swagger-annotations - ${swagger-annotations-version} + ${swagger-core-version} com.squareup.okhttp @@ -159,7 +159,7 @@ - 1.5.0 + 1.5.8 2.7.2 2.3.1 1.0.0 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 94be4298250..aa84768b47a 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 @@ -23,7 +23,7 @@ public interface {{classname}} { * {{summary}} * Sync method * {{notes}} -{{#allParams}} * @param {{paramName}} {{description}} +{{#allParams}} * @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}} {{/allParams}} * @return {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} */ {{#formParams}}{{#-first}} @@ -36,7 +36,7 @@ public interface {{classname}} { /** * {{summary}} * Async method -{{#allParams}} * @param {{paramName}} {{description}} +{{#allParams}} * @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}} {{/allParams}} * @param cb callback method * @return void */ diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/model.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/model.mustache index 07ac2095f98..779a56fedb7 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/model.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/model.mustache @@ -13,7 +13,7 @@ import com.google.gson.annotations.SerializedName; /** * {{description}} **/{{/description}} -@ApiModel(description = "{{{description}}}") +{{#description}}@ApiModel(description = "{{{description}}}"){{/description}} public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#serializableModel}}implements Serializable{{/serializableModel}} { {{#vars}}{{#isEnum}} 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 651c9bd6a64..2370cf4a211 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 @@ -110,7 +110,7 @@ io.swagger swagger-annotations - ${swagger-annotations-version} + ${swagger-core-version} com.squareup.retrofit @@ -137,7 +137,7 @@ - 1.5.0 + 1.5.8 1.9.0 2.4.0 1.0.0 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 91a88c5476c..ad5f02c49e4 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 @@ -12,8 +12,9 @@ import org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuil import retrofit2.Converter; import retrofit2.Retrofit; -import retrofit2.converter.gson.GsonConverterFactory; {{#useRxJava}}import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;{{/useRxJava}} +import retrofit2.converter.gson.GsonConverterFactory; +import retrofit2.converter.scalars.ScalarsConverterFactory; import com.google.gson.Gson; import com.google.gson.GsonBuilder; @@ -120,6 +121,7 @@ public class ApiClient { .baseUrl(baseUrl) .client(okClient) {{#useRxJava}}.addCallAdapterFactory(RxJavaCallAdapterFactory.create()){{/useRxJava}} + .addConverterFactory(ScalarsConverterFactory.create()) .addConverterFactory(GsonCustomConverterFactory.create(gson)); } 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 51a24a9777a..9bd835a4a36 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 @@ -24,7 +24,7 @@ public interface {{classname}} { /** * {{summary}} * {{notes}} -{{#allParams}} * @param {{paramName}} {{description}} +{{#allParams}} * @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}} {{/allParams}} * @return Call<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Object{{/returnType}}> */ {{#formParams}}{{#-first}} diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/build.gradle.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/build.gradle.mustache index 17dfef0f2d9..9f34c16afc5 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/build.gradle.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/build.gradle.mustache @@ -46,6 +46,10 @@ if(hasProperty('target') && target == 'android') { } } } + + dependencies { + provided 'javax.annotation:jsr250-api:1.0' + } } afterEvaluate { @@ -103,6 +107,7 @@ ext { dependencies { compile "com.squareup.retrofit2:retrofit:$retrofit_version" + compile "com.squareup.retrofit2:converter-scalars:$retrofit_version" compile "com.squareup.retrofit2:converter-gson:$retrofit_version" {{#useRxJava}} compile "com.squareup.retrofit2:adapter-rxjava:$retrofit_version" diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/model.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/model.mustache index 07ac2095f98..779a56fedb7 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/model.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/model.mustache @@ -13,7 +13,7 @@ import com.google.gson.annotations.SerializedName; /** * {{description}} **/{{/description}} -@ApiModel(description = "{{{description}}}") +{{#description}}@ApiModel(description = "{{{description}}}"){{/description}} public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#serializableModel}}implements Serializable{{/serializableModel}} { {{#vars}}{{#isEnum}} 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 0cb14c49304..a76fb3b9547 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 @@ -111,45 +111,38 @@ io.swagger swagger-annotations - ${swagger-annotations-version} + ${swagger-core-version} com.squareup.retrofit2 retrofit ${retrofit-version} + + com.squareup.retrofit2 + converter-scalars + ${retrofit-version} + com.squareup.retrofit2 converter-gson ${retrofit-version} - - com.google.code.gson - gson - ${gson-version} - org.apache.oltu.oauth2 org.apache.oltu.oauth2.client ${oltu-version} + {{#useRxJava}} + + io.reactivex + rxjava + ${rxjava-version} - - com.squareup.okhttp3 - okhttp - ${okhttp-version} - - {{#useRxJava}} - - io.reactivex - rxjava - ${rxjava-version} - - - com.squareup.retrofit2 - adapter-rxjava - ${retrofit-version} - - {{/useRxJava}} + + com.squareup.retrofit2 + adapter-rxjava + ${retrofit-version} + {{/useRxJava}} @@ -160,11 +153,9 @@ - 1.5.0 - 2.0.0-beta4 - {{#useRxJava}}1.0.16{{/useRxJava}} - 3.0.1 - 2.4 + 1.5.8 + 2.0.0-beta4{{#useRxJava}} + 1.0.16{{/useRxJava}} 1.0.0 1.0.0 4.12 diff --git a/modules/swagger-codegen/src/main/resources/Java/pom.mustache b/modules/swagger-codegen/src/main/resources/Java/pom.mustache index f2c20a96740..f0dd8c213b0 100644 --- a/modules/swagger-codegen/src/main/resources/Java/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/pom.mustache @@ -64,6 +64,7 @@ org.codehaus.mojo build-helper-maven-plugin + 1.10 add_sources @@ -141,7 +142,7 @@ com.fasterxml.jackson.jaxrs jackson-jaxrs-json-provider ${jackson-version} - + com.fasterxml.jackson.datatype jackson-datatype-joda @@ -169,7 +170,8 @@ - 1.5.4 + UTF-8 + 1.5.8 1.18 2.4.2 2.3 diff --git a/modules/swagger-codegen/src/main/resources/JavaInflector/inflector.mustache b/modules/swagger-codegen/src/main/resources/JavaInflector/inflector.mustache index c61fa2054b8..87fc5581316 100644 --- a/modules/swagger-codegen/src/main/resources/JavaInflector/inflector.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaInflector/inflector.mustache @@ -2,8 +2,11 @@ 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 diff --git a/modules/swagger-codegen/src/main/resources/JavaInflector/pom.mustache b/modules/swagger-codegen/src/main/resources/JavaInflector/pom.mustache index 8cb21465b33..a46b1960a67 100644 --- a/modules/swagger-codegen/src/main/resources/JavaInflector/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaInflector/pom.mustache @@ -19,6 +19,25 @@ target ${project.artifactId}-${project.version} + + org.codehaus.mojo + build-helper-maven-plugin + 1.10 + + + add-source + generate-sources + + add-source + + + + src/gen/java + + + + + maven-dependency-plugin @@ -78,12 +97,21 @@ io.swagger swagger-inflector - 1.0.2 + ${swagger-inflector-version} + + + sonatype-snapshots + https://oss.sonatype.org/content/repositories/snapshots + + true + + + 1.0.0 - 1.5.7 + 1.0.4 9.2.9.v20150224 1.0.1 4.8.2 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 57df497e533..346a7a7d0a1 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/api.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/api.mustache @@ -6,6 +6,8 @@ package {{package}}; import javax.ws.rs.*; import javax.ws.rs.core.Response; +import org.apache.cxf.jaxrs.ext.multipart.*; + @Path("/") public interface {{classname}} { {{#operations}} diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/api.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/api.mustache index d98446fdf1b..16f46ce0534 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/api.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/api.mustache @@ -46,10 +46,10 @@ public class {{classname}} { {{/hasMore}}{{/authMethods}} }{{/hasAuthMethods}}, tags={ {{#vendorExtensions.x-tags}}"{{tag}}"{{#hasMore}}, {{/hasMore}}{{/vendorExtensions.x-tags}} }) @io.swagger.annotations.ApiResponses(value = { {{#responses}} - @io.swagger.annotations.ApiResponse(code = {{{code}}}, message = "{{{message}}}", response = {{{returnType}}}.class{{#returnContainer}}, responseContainer = "{{{returnContainer}}}"{{/returnContainer}}){{#hasMore}}, - {{/hasMore}}{{/responses}} }) - - public Response {{nickname}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}},{{/allParams}}@Context SecurityContext securityContext) + @io.swagger.annotations.ApiResponse(code = {{{code}}}, message = "{{{message}}}", response = {{{returnType}}}.class{{#returnContainer}}, responseContainer = "{{{returnContainer}}}"{{/returnContainer}}){{#hasMore}},{{/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); } diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/bootstrap.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/bootstrap.mustache new file mode 100644 index 00000000000..f7e8efff419 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/bootstrap.mustache @@ -0,0 +1,31 @@ +package {{apiPackage}}; + +import io.swagger.jaxrs.config.SwaggerContextService; +import io.swagger.models.*; + +import io.swagger.models.auth.*; + +import javax.servlet.http.HttpServlet; +import javax.servlet.ServletContext; +import javax.servlet.ServletConfig; +import javax.servlet.ServletException; + +public class Bootstrap extends HttpServlet { + @Override + public void init(ServletConfig config) throws ServletException { + Info info = new Info() + .title("{{title}}") + .description("{{{appDescription}}}") + .termsOfService("{{termsOfService}}") + .contact(new Contact() + .email("{{infoEmail}}")) + .license(new License() + .name("{{licenseInfo}}") + .url("{{licenseUrl}}")); + + ServletContext context = config.getServletContext(); + Swagger swagger = new Swagger().info(info); + + new SwaggerContextService().withServletConfig(config).updateSwagger(swagger); + } +} diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/formParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/formParams.mustache index 632d39cf23e..3fe8f19d3de 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/formParams.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/formParams.mustache @@ -1,2 +1,2 @@ -{{#isFormParam}}{{#notFile}}@ApiParam(value = "{{{description}}}"{{#required}}, required=true{{/required}}{{#allowableValues}}, {{> allowableValues }}{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}})@FormParam("{{paramName}}") {{{dataType}}} {{paramName}}{{/notFile}}{{#isFile}} @FormDataParam("file") InputStream inputStream, - @FormDataParam("file") FormDataContentDisposition fileDetail{{/isFile}}{{/isFormParam}} \ No newline at end of file +{{#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, + @FormDataParam("file") FormDataContentDisposition fileDetail{{/isFile}}{{/isFormParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/generatedAnnotation.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/generatedAnnotation.mustache index 49110fc1ad9..a47b6faa85b 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/generatedAnnotation.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/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/jersey1_18/jacksonJsonProvider.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/jacksonJsonProvider.mustache new file mode 100644 index 00000000000..5efcb449bb5 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/jacksonJsonProvider.mustache @@ -0,0 +1,19 @@ +package {{apiPackage}}; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider; +import io.swagger.util.Json; + +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.ext.Provider; + +@Provider +@Produces({MediaType.APPLICATION_JSON}) +public class JacksonJsonProvider extends JacksonJaxbJsonProvider { + private static ObjectMapper commonMapper = Json.mapper(); + + public JacksonJsonProvider() { + super.setMapper(commonMapper); + } +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/pom.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/pom.mustache index 14bbfaecb99..180450ce73f 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/pom.mustache @@ -168,7 +168,7 @@ - 1.5.7 + 1.5.8 9.2.9.v20150224 1.18.1 1.6.3 diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/queryParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/queryParams.mustache index 88da16ecf38..9055e6f16dc 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/queryParams.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/queryParams.mustache @@ -1 +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}} +{{#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/jersey2/ApiException.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/ApiException.mustache new file mode 100644 index 00000000000..f6161147700 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/ApiException.mustache @@ -0,0 +1,10 @@ +package {{apiPackage}}; + +{{>generatedAnnotation}} +public class ApiException extends Exception{ + private int code; + public ApiException (int code, String msg) { + super(msg); + this.code = code; + } +} diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/ApiOriginFilter.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/ApiOriginFilter.mustache new file mode 100644 index 00000000000..b8af270a05a --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/ApiOriginFilter.mustache @@ -0,0 +1,22 @@ +package {{apiPackage}}; + +import java.io.IOException; + +import javax.servlet.*; +import javax.servlet.http.HttpServletResponse; + +{{>generatedAnnotation}} +public class ApiOriginFilter implements javax.servlet.Filter { + public void doFilter(ServletRequest request, ServletResponse response, + FilterChain chain) throws IOException, ServletException { + HttpServletResponse res = (HttpServletResponse) response; + res.addHeader("Access-Control-Allow-Origin", "*"); + res.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT"); + res.addHeader("Access-Control-Allow-Headers", "Content-Type"); + chain.doFilter(request, response); + } + + public void destroy() {} + + public void init(FilterConfig filterConfig) throws ServletException {} +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/ApiResponseMessage.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/ApiResponseMessage.mustache new file mode 100644 index 00000000000..c883e16b5e6 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/ApiResponseMessage.mustache @@ -0,0 +1,69 @@ +package {{apiPackage}}; + +import javax.xml.bind.annotation.XmlTransient; + +@javax.xml.bind.annotation.XmlRootElement +{{>generatedAnnotation}} +public class ApiResponseMessage { + public static final int ERROR = 1; + public static final int WARNING = 2; + public static final int INFO = 3; + public static final int OK = 4; + public static final int TOO_BUSY = 5; + + int code; + String type; + String message; + + public ApiResponseMessage(){} + + public ApiResponseMessage(int code, String message){ + this.code = code; + switch(code){ + case ERROR: + setType("error"); + break; + case WARNING: + setType("warning"); + break; + case INFO: + setType("info"); + break; + case OK: + setType("ok"); + break; + case TOO_BUSY: + setType("too busy"); + break; + default: + setType("unknown"); + break; + } + this.message = message; + } + + @XmlTransient + public int getCode() { + return code; + } + + public void setCode(int code) { + this.code = code; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } +} diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/JodaDateTimeProvider.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/JodaDateTimeProvider.mustache new file mode 100644 index 00000000000..f9421790983 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/JodaDateTimeProvider.mustache @@ -0,0 +1,44 @@ +package {{apiPackage}}; + +import com.sun.jersey.core.spi.component.ComponentContext; +import com.sun.jersey.spi.inject.Injectable; +import com.sun.jersey.spi.inject.PerRequestTypeInjectableProvider; + +import javax.ws.rs.QueryParam; +import javax.ws.rs.WebApplicationException; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.Response.Status; +import javax.ws.rs.core.UriInfo; +import javax.ws.rs.ext.Provider; +import org.joda.time.DateTime; +import java.util.List; + +@Provider +public class JodaDateTimeProvider extends PerRequestTypeInjectableProvider { + private final UriInfo uriInfo; + + public JodaDateTimeProvider(@Context UriInfo uriInfo) { + super(DateTime.class); + this.uriInfo = uriInfo; + } + + @Override + public Injectable getInjectable(final ComponentContext cc, final QueryParam a) { + return new Injectable() { + @Override + public DateTime getValue() { + final List values = uriInfo.getQueryParameters().get(a.value()); + + if (values == null || values.isEmpty()) + return null; + if (values.size() > 1) { + throw new WebApplicationException(Response.status(Status.BAD_REQUEST). + entity(a.value() + " cannot contain multiple values").build()); + } + + return DateTime.parse(values.get(0)); + } + }; + } +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/JodaLocalDateProvider.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/JodaLocalDateProvider.mustache new file mode 100644 index 00000000000..7bd4027e63d --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/JodaLocalDateProvider.mustache @@ -0,0 +1,44 @@ +package {{apiPackage}}; + +import com.sun.jersey.core.spi.component.ComponentContext; +import com.sun.jersey.spi.inject.Injectable; +import com.sun.jersey.spi.inject.PerRequestTypeInjectableProvider; + +import javax.ws.rs.QueryParam; +import javax.ws.rs.WebApplicationException; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.Response.Status; +import javax.ws.rs.core.UriInfo; +import javax.ws.rs.ext.Provider; +import org.joda.time.LocalDate; +import java.util.List; + +@Provider +public class JodaLocalDateProvider extends PerRequestTypeInjectableProvider { + private final UriInfo uriInfo; + + public JodaLocalDateProvider(@Context UriInfo uriInfo) { + super(LocalDate.class); + this.uriInfo = uriInfo; + } + + @Override + public Injectable getInjectable(final ComponentContext cc, final QueryParam a) { + return new Injectable() { + @Override + public LocalDate getValue() { + final List values = uriInfo.getQueryParameters().get(a.value()); + + if (values == null || values.isEmpty()) + return null; + if (values.size() > 1) { + throw new WebApplicationException(Response.status(Status.BAD_REQUEST). + entity(a.value() + " cannot contain multiple values").build()); + } + + return LocalDate.parse(values.get(0)); + } + }; + } +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/LocalDateProvider.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/LocalDateProvider.mustache new file mode 100644 index 00000000000..8c4cd4cbd15 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/LocalDateProvider.mustache @@ -0,0 +1,44 @@ +package {{apiPackage}}; + +import com.sun.jersey.core.spi.component.ComponentContext; +import com.sun.jersey.spi.inject.Injectable; +import com.sun.jersey.spi.inject.PerRequestTypeInjectableProvider; + +import javax.ws.rs.QueryParam; +import javax.ws.rs.WebApplicationException; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.Response.Status; +import javax.ws.rs.core.UriInfo; +import javax.ws.rs.ext.Provider; +import java.time.LocalDate; +import java.util.List; + +@Provider +public class LocalDateProvider extends PerRequestTypeInjectableProvider { + private final UriInfo uriInfo; + + public LocalDateProvider(@Context UriInfo uriInfo) { + super(LocalDate.class); + this.uriInfo = uriInfo; + } + + @Override + public Injectable getInjectable(final ComponentContext cc, final QueryParam a) { + return new Injectable() { + @Override + public LocalDate getValue() { + final List values = uriInfo.getQueryParameters().get(a.value()); + + if (values == null || values.isEmpty()) + return null; + if (values.size() > 1) { + throw new WebApplicationException(Response.status(Status.BAD_REQUEST). + entity(a.value() + " cannot contain multiple values").build()); + } + + return LocalDate.parse(values.get(0)); + } + }; + } +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/LocalDateTimeProvider.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/LocalDateTimeProvider.mustache new file mode 100644 index 00000000000..93bb6f19d50 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/LocalDateTimeProvider.mustache @@ -0,0 +1,44 @@ +package {{apiPackage}}; + +import com.sun.jersey.core.spi.component.ComponentContext; +import com.sun.jersey.spi.inject.Injectable; +import com.sun.jersey.spi.inject.PerRequestTypeInjectableProvider; + +import javax.ws.rs.QueryParam; +import javax.ws.rs.WebApplicationException; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.Response.Status; +import javax.ws.rs.core.UriInfo; +import javax.ws.rs.ext.Provider; +import java.time.LocalDateTime; +import java.util.List; + +@Provider +public class LocalDateTimeProvider extends PerRequestTypeInjectableProvider { + private final UriInfo uriInfo; + + public LocalDateTimeProvider(@Context UriInfo uriInfo) { + super(LocalDateTime.class); + this.uriInfo = uriInfo; + } + + @Override + public Injectable getInjectable(final ComponentContext cc, final QueryParam a) { + return new Injectable() { + @Override + public LocalDateTime getValue() { + final List values = uriInfo.getQueryParameters().get(a.value()); + + if (values == null || values.isEmpty()) + return null; + if (values.size() > 1) { + throw new WebApplicationException(Response.status(Status.BAD_REQUEST). + entity(a.value() + " cannot contain multiple values").build()); + } + + return LocalDateTime.parse(values.get(0)); + } + }; + } +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/NotFoundException.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/NotFoundException.mustache new file mode 100644 index 00000000000..40c25c5ea5c --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/NotFoundException.mustache @@ -0,0 +1,10 @@ +package {{apiPackage}}; + +{{>generatedAnnotation}} +public class NotFoundException extends ApiException { + private int code; + public NotFoundException (int code, String msg) { + super(code, msg); + this.code = code; + } +} diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/README.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/README.mustache new file mode 100644 index 00000000000..808f690a496 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/README.mustache @@ -0,0 +1,23 @@ +# Swagger Jersey 2 generated server + +## Overview +This server was generated by the [swagger-codegen](https://github.com/swagger-api/swagger-codegen) project. By using the +[OpenAPI-Spec](https://github.com/swagger-api/swagger-core/wiki) from a remote server, you can easily generate a server stub. This +is an example of building a swagger-enabled JAX-RS server. + +This example uses the [JAX-RS](https://jax-rs-spec.java.net/) framework. + +To run the server, please execute the following: + +``` +mvn clean package jetty:run +``` + +You can then view the swagger listing here: + +``` +http://localhost:{{serverPort}}{{contextPath}}/swagger.json +``` + +Note that if you have configured the `host` to be something other than localhost, the calls through +swagger-ui will be directed to that host and not localhost! \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/StringUtil.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/StringUtil.mustache new file mode 100644 index 00000000000..073966b0c21 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/StringUtil.mustache @@ -0,0 +1,42 @@ +package {{invokerPackage}}; + +{{>generatedAnnotation}} +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/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/allowableValues.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/allowableValues.mustache new file mode 100644 index 00000000000..a48256d027a --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/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/jersey2/api.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/api.mustache new file mode 100644 index 00000000000..4200f4aca6e --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/api.mustache @@ -0,0 +1,55 @@ +package {{package}}; + +import {{modelPackage}}.*; +import {{package}}.{{classname}}Service; +import {{package}}.factories.{{classname}}ServiceFactory; + +import io.swagger.annotations.ApiParam; + +{{#imports}}import {{import}}; +{{/imports}} + +import java.util.List; +import {{package}}.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("/{{baseName}}") +{{#hasConsumes}}@Consumes({ {{#consumes}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} }){{/hasConsumes}} +{{#hasProduces}}@Produces({ {{#produces}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }){{/hasProduces}} +@io.swagger.annotations.Api(description = "the {{baseName}} API") +{{>generatedAnnotation}} +{{#operations}} +public class {{classname}} { + private final {{classname}}Service delegate = {{classname}}ServiceFactory.get{{classname}}(); + +{{#operation}} + @{{httpMethod}} + {{#subresourceOperation}}@Path("{{path}}"){{/subresourceOperation}} + {{#hasConsumes}}@Consumes({ {{#consumes}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} }){{/hasConsumes}} + {{#hasProduces}}@Produces({ {{#produces}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }){{/hasProduces}} + @io.swagger.annotations.ApiOperation(value = "{{{summary}}}", notes = "{{{notes}}}", response = {{{returnType}}}.class{{#returnContainer}}, responseContainer = "{{{returnContainer}}}"{{/returnContainer}}{{#hasAuthMethods}}, authorizations = { + {{#authMethods}}@io.swagger.annotations.Authorization(value = "{{name}}"{{#isOAuth}}, scopes = { + {{#scopes}}@io.swagger.annotations.AuthorizationScope(scope = "{{scope}}", description = "{{description}}"){{#hasMore}}, + {{/hasMore}}{{/scopes}} + }{{/isOAuth}}){{#hasMore}}, + {{/hasMore}}{{/authMethods}} + }{{/hasAuthMethods}}, tags={ {{#vendorExtensions.x-tags}}"{{tag}}",{{/vendorExtensions.x-tags}} }) + @io.swagger.annotations.ApiResponses(value = { {{#responses}} + @io.swagger.annotations.ApiResponse(code = {{{code}}}, message = "{{{message}}}", response = {{{returnType}}}.class{{#returnContainer}}, responseContainer = "{{{returnContainer}}}"{{/returnContainer}}){{#hasMore}}, + {{/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); + } +{{/operation}} +} +{{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/apiService.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/apiService.mustache new file mode 100644 index 00000000000..50e00e24497 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/apiService.mustache @@ -0,0 +1,26 @@ +package {{package}}; + +import {{package}}.*; +import {{modelPackage}}.*; + +import org.glassfish.jersey.media.multipart.FormDataContentDisposition; + +{{#imports}}import {{import}}; +{{/imports}} + +import java.util.List; +import {{package}}.NotFoundException; + +import java.io.InputStream; + +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; + +{{>generatedAnnotation}} +{{#operations}} +public abstract class {{classname}}Service { + {{#operation}} + public abstract Response {{nickname}}({{#allParams}}{{>serviceQueryParams}}{{>servicePathParams}}{{>serviceHeaderParams}}{{>serviceBodyParams}}{{>serviceFormParams}},{{/allParams}}SecurityContext securityContext) throws NotFoundException; + {{/operation}} +} +{{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/apiServiceFactory.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/apiServiceFactory.mustache new file mode 100644 index 00000000000..0f321034999 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/apiServiceFactory.mustache @@ -0,0 +1,13 @@ +package {{package}}.factories; + +import {{package}}.{{classname}}Service; +import {{package}}.impl.{{classname}}ServiceImpl; + +{{>generatedAnnotation}} +public class {{classname}}ServiceFactory { + private final static {{classname}}Service service = new {{classname}}ServiceImpl(); + + public static {{classname}}Service get{{classname}}() { + return service; + } +} diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/apiServiceImpl.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/apiServiceImpl.mustache new file mode 100644 index 00000000000..3d3f4c6cbf7 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/apiServiceImpl.mustache @@ -0,0 +1,30 @@ +package {{package}}.impl; + +import {{package}}.*; +import {{modelPackage}}.*; + +{{#imports}}import {{import}}; +{{/imports}} + +import java.util.List; +import {{package}}.NotFoundException; + +import java.io.InputStream; + +import org.glassfish.jersey.media.multipart.FormDataContentDisposition; + +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; + +{{>generatedAnnotation}} +{{#operations}} +public class {{classname}}ServiceImpl extends {{classname}}Service { + {{#operation}} + @Override + public Response {{nickname}}({{#allParams}}{{>serviceQueryParams}}{{>servicePathParams}}{{>serviceHeaderParams}}{{>serviceBodyParams}}{{>serviceFormParams}}, {{/allParams}}SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + {{/operation}} +} +{{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/bodyParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/bodyParams.mustache new file mode 100644 index 00000000000..2b28441d3d0 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/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/jersey2/bootstrap.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/bootstrap.mustache new file mode 100644 index 00000000000..f7e8efff419 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/bootstrap.mustache @@ -0,0 +1,31 @@ +package {{apiPackage}}; + +import io.swagger.jaxrs.config.SwaggerContextService; +import io.swagger.models.*; + +import io.swagger.models.auth.*; + +import javax.servlet.http.HttpServlet; +import javax.servlet.ServletContext; +import javax.servlet.ServletConfig; +import javax.servlet.ServletException; + +public class Bootstrap extends HttpServlet { + @Override + public void init(ServletConfig config) throws ServletException { + Info info = new Info() + .title("{{title}}") + .description("{{{appDescription}}}") + .termsOfService("{{termsOfService}}") + .contact(new Contact() + .email("{{infoEmail}}")) + .license(new License() + .name("{{licenseInfo}}") + .url("{{licenseUrl}}")); + + ServletContext context = config.getServletContext(); + Swagger swagger = new Swagger().info(info); + + new SwaggerContextService().withServletConfig(config).updateSwagger(swagger); + } +} diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/enumClass.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/enumClass.mustache new file mode 100644 index 00000000000..6010e26704f --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/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/JavaJaxRS/jersey2/enumOuterClass.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/enumOuterClass.mustache new file mode 100644 index 00000000000..7aea7b92f22 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/enumOuterClass.mustache @@ -0,0 +1,3 @@ +public enum {{classname}} { + {{#allowableValues}}{{.}}{{^-last}}, {{/-last}}{{/allowableValues}} +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/formParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/formParams.mustache new file mode 100644 index 00000000000..993d47bb562 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/formParams.mustache @@ -0,0 +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 diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/generatedAnnotation.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/generatedAnnotation.mustache new file mode 100644 index 00000000000..a47b6faa85b --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/generatedAnnotation.mustache @@ -0,0 +1 @@ +{{^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/jersey2/headerParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/headerParams.mustache new file mode 100644 index 00000000000..1360d796826 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/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/jersey2/jacksonJsonProvider.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/jacksonJsonProvider.mustache new file mode 100644 index 00000000000..5efcb449bb5 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/jacksonJsonProvider.mustache @@ -0,0 +1,19 @@ +package {{apiPackage}}; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider; +import io.swagger.util.Json; + +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.ext.Provider; + +@Provider +@Produces({MediaType.APPLICATION_JSON}) +public class JacksonJsonProvider extends JacksonJaxbJsonProvider { + private static ObjectMapper commonMapper = Json.mapper(); + + public JacksonJsonProvider() { + super.setMapper(commonMapper); + } +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/model.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/model.mustache new file mode 100644 index 00000000000..b9512d2b83c --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/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/JavaJaxRS/jersey2/pathParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/pathParams.mustache new file mode 100644 index 00000000000..8d80210b4b4 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/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/jersey2/pojo.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/pojo.mustache new file mode 100644 index 00000000000..58bfed16381 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/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/JavaJaxRS/jersey2/pom.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/pom.mustache new file mode 100644 index 00000000000..a2f59b53fe7 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/pom.mustache @@ -0,0 +1,145 @@ + + 4.0.0 + {{groupId}} + {{artifactId}} + jar + {{artifactId}} + {{artifactVersion}} + + src/main/java + + + org.apache.maven.plugins + maven-war-plugin + 2.1.1 + + + maven-failsafe-plugin + 2.6 + + + + integration-test + verify + + + + + + org.eclipse.jetty + jetty-maven-plugin + ${jetty-version} + + + / + + target/${project.artifactId}-${project.version} + 8079 + stopit + + {{serverPort}} + 60000 + + + + + start-jetty + pre-integration-test + + start + + + 0 + true + + + + stop-jetty + post-integration-test + + stop + + + + + + org.codehaus.mojo + build-helper-maven-plugin + 1.9.1 + + + add-source + generate-sources + + add-source + + + + src/gen/java + + + + + + + + + + io.swagger + swagger-jersey2-jaxrs + compile + ${swagger-core-version} + + + ch.qos.logback + logback-classic + ${logback-version} + compile + + + ch.qos.logback + logback-core + ${logback-version} + compile + + + junit + junit + ${junit-version} + test + + + javax.servlet + servlet-api + ${servlet-api-version} + + + org.glassfish.jersey.containers + jersey-container-servlet-core + ${jersey2-version} + + + org.glassfish.jersey.media + jersey-media-multipart + ${jersey2-version} + + + + + sonatype-snapshots + https://oss.sonatype.org/content/repositories/snapshots + + true + + + + + 1.5.8 + 9.2.9.v20150224 + 2.6 + 1.6.3 + 4.8.1 + 1.0.1 + 2.5 + + \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/project/build.properties b/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/project/build.properties new file mode 100644 index 00000000000..a8c2f849be3 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/project/build.properties @@ -0,0 +1 @@ +sbt.version=0.12.0 diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/project/plugins.sbt b/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/project/plugins.sbt new file mode 100644 index 00000000000..713b7f3e993 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/project/plugins.sbt @@ -0,0 +1,9 @@ +addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "0.8.4") + +libraryDependencies <+= sbtVersion(v => v match { + case "0.11.0" => "com.github.siasia" %% "xsbt-web-plugin" % "0.11.0-0.2.8" + case "0.11.1" => "com.github.siasia" %% "xsbt-web-plugin" % "0.11.1-0.2.10" + case "0.11.2" => "com.github.siasia" %% "xsbt-web-plugin" % "0.11.2-0.2.11" + case "0.11.3" => "com.github.siasia" %% "xsbt-web-plugin" % "0.11.3-0.2.11.1" + case x if (x.startsWith("0.12")) => "com.github.siasia" %% "xsbt-web-plugin" % "0.12.0-0.2.11.1" +}) \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/queryParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/queryParams.mustache new file mode 100644 index 00000000000..9055e6f16dc --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/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/jersey2/returnTypes.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/returnTypes.mustache new file mode 100644 index 00000000000..c8f7a56938a --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/returnTypes.mustache @@ -0,0 +1 @@ +{{#returnContainer}}{{#isMapContainer}}Map{{/isMapContainer}}{{#isListContainer}}List<{{{returnType}}}>{{/isListContainer}}{{/returnContainer}}{{^returnContainer}}{{{returnType}}}{{/returnContainer}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/serviceBodyParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/serviceBodyParams.mustache new file mode 100644 index 00000000000..c7d1abfe527 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/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/jersey2/serviceFormParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/serviceFormParams.mustache new file mode 100644 index 00000000000..759335ba9ce --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/serviceFormParams.mustache @@ -0,0 +1 @@ +{{#isFormParam}}{{#notFile}}{{{dataType}}} {{paramName}}{{/notFile}}{{#isFile}}InputStream inputStream, FormDataContentDisposition fileDetail{{/isFile}}{{/isFormParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/serviceHeaderParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/serviceHeaderParams.mustache new file mode 100644 index 00000000000..bd03573d196 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/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/jersey2/servicePathParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/servicePathParams.mustache new file mode 100644 index 00000000000..6829cf8c7a6 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/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/jersey2/serviceQueryParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/serviceQueryParams.mustache new file mode 100644 index 00000000000..ff79730471d --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/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/jersey2/web.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/web.mustache new file mode 100644 index 00000000000..520456fb128 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/web.mustache @@ -0,0 +1,63 @@ + + + + + jersey + org.glassfish.jersey.servlet.ServletContainer + + jersey.config.server.provider.packages + + io.swagger.jaxrs.listing, + io.swagger.sample.resource, + {{apiPackage}} + + + + jersey.config.server.provider.classnames + org.glassfish.jersey.media.multipart.MultiPartFeature + + + jersey.config.server.wadl.disableWadl + true + + 1 + + + + Jersey2Config + io.swagger.jersey.config.JerseyJaxrsConfig + + api.version + 1.0.0 + + + swagger.api.title + {{{title}}} + + + swagger.api.basepath + {{basePath}} + + + 2 + + + Bootstrap + {{apiPackage}}.Bootstrap + 2 + + + jersey + {{contextPath}}/* + + + ApiOriginFilter + {{apiPackage}}.ApiOriginFilter + + + ApiOriginFilter + /* + + diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/LocalDateTimeProvider.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/LocalDateTimeProvider.mustache index 591b410b275..5ee7f06bf8e 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/LocalDateTimeProvider.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/LocalDateTimeProvider.mustache @@ -14,7 +14,7 @@ public class LocalDateTimeProvider implements ParamConverterProvider { @Override public LocalDateTime fromString(String string) { - LocalDate localDateTime = LocalDateTime.parse(string); + LocalDateTime localDateTime = LocalDateTime.parse(string); return localDateTime; } 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 b9512d2b83c..85d815a79c6 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/model.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/model.mustache @@ -1,6 +1,7 @@ package {{package}}; import java.util.Objects; +import java.util.ArrayList; {{#imports}}import {{import}}; {{/imports}} 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 ad4c4e7655f..3373c53b2ce 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/pom.mustache @@ -145,7 +145,7 @@ - 1.5.7 + 1.5.8 9.2.9.v20150224 3.0.11.Final 1.6.3 diff --git a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/pom-j8-async.mustache b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/pom-j8-async.mustache index dc18ee3b7fd..257a4611db5 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/pom-j8-async.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/pom-j8-async.mustache @@ -159,7 +159,7 @@ - 1.5.7 + 1.5.8 9.2.9.v20150224 1.13 1.6.3 diff --git a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/pom.mustache b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/pom.mustache index 4d5bceecc68..8cb969102e1 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/pom.mustache @@ -118,7 +118,7 @@ - 1.5.7 + 1.5.8 9.2.9.v20150224 1.13 1.6.3 diff --git a/modules/swagger-codegen/src/main/resources/Javascript/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Javascript/ApiClient.mustache index b8311bd9709..25f5474523f 100644 --- a/modules/swagger-codegen/src/main/resources/Javascript/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/Javascript/ApiClient.mustache @@ -15,46 +15,74 @@ }(this, function(superagent) { 'use strict'; - var ApiClient = function ApiClient() { - /** - * The base path to put in front of every API call's (relative) path. +{{#emitJSDoc}} /** + * @module ApiClient + * @version {{projectVersion}} + */ + + /** + * Manages low level client-server communications, parameter marshalling, etc. There should not be any need for an + * application to use this class directly - the *Api and model classes provide the public API for the service. The + * contents of this file should be regarded as internal but are documented for completeness. + * @alias module:ApiClient + * @class + */ +{{/emitJSDoc}} var exports = function() { +{{#emitJSDoc}} /** + * The base URL against which to resolve every API call's (relative) path. + * @type {String} + * @default {{basePath}} */ - this.basePath = '{{basePath}}'.replace(/\/+$/, ''); -{{=< >=}} - this.authentications = {<#authMethods><#isBasic> +{{/emitJSDoc}} this.basePath = '{{basePath}}'.replace(/\/+$/, ''); + +{{#emitJSDoc}} /** + * 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: 'apiKey', 'in': <#isKeyInHeader>'header'<^isKeyInHeader>'query', name: ''}<#isOAuth> '': {type: 'oauth2'}<#hasMore>, }; <={{ }}=> - /** +{{#emitJSDoc}} /** * The default HTTP headers to be included for all API calls. + * @type {Array.} + * @default {} */ - this.defaultHeaders = {}; +{{/emitJSDoc}} this.defaultHeaders = {}; /** * The default HTTP timeout for all API calls. + * @type {Number} + * @default 60000 */ this.timeout = 60000; }; - ApiClient.prototype.paramToString = function paramToString(param) { - if (param == null) { - // return empty string for null and undefined +{{#emitJSDoc}} /** + * Returns a string representation for an actual parameter. + * @param param The actual parameter. + * @returns {String} The string representation of param. + */ +{{/emitJSDoc}} exports.prototype.paramToString = function(param) { + if (param == undefined || param == null) { return ''; - } else if (param instanceof Date) { - return param.toJSON(); - } else { - return param.toString(); } + if (param instanceof Date) { + return param.toJSON(); + } + return param.toString(); }; - /** - * Build full URL by appending the given path to base path and replacing - * path parameter placeholders with parameter values. +{{#emitJSDoc}} /** + * Builds full URL by appending the given path to the base URL and replacing path parameter place-holders with parameter values. * NOTE: query parameters are not handled here. + * @param {String} path The path to append to the base URL. + * @param {Object} pathParams The parameter values to append. + * @returns {String} The encoded path with parameter values substituted. */ - ApiClient.prototype.buildUrl = function buildUrl(path, pathParams) { +{{/emitJSDoc}} exports.prototype.buildUrl = function(path, pathParams) { if (!path.match(/^\//)) { path = '/' + path; } @@ -72,35 +100,41 @@ return url; }; - /** - * Check if the given MIME is a JSON MIME. - * JSON MIME examples: - * application/json - * application/json; charset=UTF8 - * APPLICATION/JSON +{{#emitJSDoc}} /** + * Checks whether the given content type represents JSON.
+ * JSON content type examples:
+ *
    + *
  • application/json
  • + *
  • application/json; charset=UTF8
  • + *
  • APPLICATION/JSON
  • + *
+ * @param {String} contentType The MIME content type to check. + * @returns {Boolean} true if contentType represents JSON, otherwise false. */ - ApiClient.prototype.isJsonMime = function isJsonMime(mime) { - return Boolean(mime != null && mime.match(/^application\/json(;.*)?$/i)); +{{/emitJSDoc}} exports.prototype.isJsonMime = function(contentType) { + return Boolean(contentType != null && contentType.match(/^application\/json(;.*)?$/i)); }; - /** - * Choose a MIME from the given MIMEs with JSON preferred, - * i.e. return JSON if included, otherwise return the first one. +{{#emitJSDoc}} /** + * Chooses a content type from the given array, with JSON preferred; i.e. return JSON if included, otherwise return the first. + * @param {Array.} contentTypes + * @returns {String} The chosen content type, preferring JSON. */ - ApiClient.prototype.jsonPreferredMime = function jsonPreferredMime(mimes) { - var len = mimes.length; - for (var i = 0; i < len; i++) { - if (this.isJsonMime(mimes[i])) { - return mimes[i]; +{{/emitJSDoc}} exports.prototype.jsonPreferredMime = function(contentTypes) { + for (var i = 0; i < contentTypes.length; i++) { + if (this.isJsonMime(contentTypes[i])) { + return contentTypes[i]; } } - return mimes[0]; + return contentTypes[0]; }; - /** - * Check if the given parameter value is like file content. +{{#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. */ - ApiClient.prototype.isFileParam = function isFileParam(param) { +{{/emitJSDoc}} exports.prototype.isFileParam = function(param) { // fs.ReadStream in Node.js (but not in runtime like browserify) if (typeof window === 'undefined' && typeof require === 'function' && @@ -123,16 +157,20 @@ return false; }; - /** - * Normalize parameters values: - * remove nils, - * keep files and arrays, - * format to string with `paramToString` for other cases. +{{#emitJSDoc}} /** + * Normalizes parameter values: + *
    + *
  • remove nils
  • + *
  • keep files and arrays
  • + *
  • format to string with `paramToString` for other cases
  • + *
+ * @param {Object.} params The parameters as object properties. + * @returns {Object.} normalized parameters. */ - ApiClient.prototype.normalizeParams = function normalizeParams(params) { +{{/emitJSDoc}} exports.prototype.normalizeParams = function(params) { var newParams = {}; for (var key in params) { - if (params.hasOwnProperty(key) && params[key] != null) { + if (params.hasOwnProperty(key) && params[key] != undefined && params[key] != null) { var value = params[key]; if (this.isFileParam(value) || Array.isArray(value)) { newParams[key] = value; @@ -144,11 +182,47 @@ return newParams; }; - /** - * Build parameter value according to the given collection format. - * @param {String} collectionFormat one of 'csv', 'ssv', 'tsv', 'pipes' and 'multi' +{{#emitJSDoc}} /** + * Enumeration of collection format separator strategies. + * @enum {String} + * @readonly */ - ApiClient.prototype.buildCollectionParam = function buildCollectionParam(param, collectionFormat) { + exports.CollectionFormatEnum = { + /** + * Comma-separated values. Value: csv + * @const + */ + CSV: ',', + /** + * Space-separated values. Value: ssv + * @const + */ + SSV: ' ', + /** + * Tab-separated values. Value: tsv + * @const + */ + TSV: '\t', + /** + * Pipe(|)-separated values. Value: pipes + * @const + */ + PIPES: '|', + /** + * Native array. Value: multi + * @const + */ + MULTI: 'multi' + }; + + /** + * Builds a string representation of an array-type actual parameter, according to the given collection format. + * @param {Array} param An array parameter. + * @param {module:ApiClient.CollectionFormatEnum} collectionFormat The array element separator strategy. + * @returns {String|Array} A string representation of the supplied collection, using the specified delimiter. Returns + * param as is if collectionFormat is multi. + */ +{{/emitJSDoc}} exports.prototype.buildCollectionParam = function buildCollectionParam(param, collectionFormat) { if (param == null) { return null; } @@ -162,14 +236,19 @@ case 'pipes': return param.map(this.paramToString).join('|'); case 'multi': - // return the array directly as Superagent will handle it as expected + // return the array directly as SuperAgent will handle it as expected return param.map(this.paramToString); default: throw new Error('Unknown collection format: ' + collectionFormat); } }; - ApiClient.prototype.applyAuthToRequest = function applyAuthToRequest(request, authNames) { +{{#emitJSDoc}} /** + * Applies authentication headers to the request. + * @param {Object} request The request object created by a superagent() call. + * @param {Array.} authNames An array of authentication method names. + */ +{{/emitJSDoc}} exports.prototype.applyAuthToRequest = function(request, authNames) { var _this = this; authNames.forEach(function(authName) { var auth = _this.authentications[authName]; @@ -187,7 +266,7 @@ } else { data[auth.name] = auth.apiKey; } - if (auth.in === 'header') { + if (auth['in'] === 'header') { request.set(data); } else { request.query(data); @@ -205,24 +284,58 @@ }); }; - ApiClient.prototype.deserialize = function deserialize(response, returnType) { +{{#emitJSDoc}} /** + * Deserializes an HTTP response body into a value of the specified type. + * @param {Object} response A SuperAgent response object. + * @param {(String|Array.|Object.|Function)} returnType The type to return. Pass a string for simple types + * or the constructor function for a complex type. Pass an array containing the type name to return an array of that type. To + * return an object, pass an object with one property whose name is the key type and whose value is the corresponding value type: + * all properties on data will be converted to this type. + * @returns A value of the specified type. + */ +{{/emitJSDoc}} exports.prototype.deserialize = function deserialize(response, returnType) { if (response == null || returnType == null) { return null; } - // Rely on Superagent for parsing response body. + // Rely on SuperAgent for parsing response body. // See http://visionmedia.github.io/superagent/#parsing-response-bodies var data = response.body; if (data == null) { - // Superagent does not always produce a body; use the unparsed response - // as a fallback + // SuperAgent does not always produce a body; use the unparsed response as a fallback data = response.text; } - return ApiClient.convertToType(data, returnType); + return exports.convertToType(data, returnType); }; - ApiClient.prototype.callApi = function callApi(path, httpMethod, pathParams, - queryParams, headerParams, formParams, bodyParam, authNames, contentTypes, - accepts, returnType{{^usePromises}}, callback{{/usePromises}}) { +{{#emitJSDoc}}{{^usePromises}} /** + * Callback function to receive the result of the operation. + * @callback module:ApiClient~callApiCallback + * @param {String} error Error message, if any. + * @param data The data returned by the service call. + * @param {String} response The complete HTTP response. + */ + +{{/usePromises}} /** + * Invokes the REST service using the supplied settings and parameters. + * @param {String} path The base URL to invoke. + * @param {String} httpMethod The HTTP method to use. + * @param {Object.} pathParams A map of path parameters and their values. + * @param {Object.} queryParams A map of query parameters and their values. + * @param {Object.} headerParams A map of header parameters and their values. + * @param {Object.} formParams A map of form parameters and their values. + * @param {Object} bodyParam The value to pass as the request body. + * @param {Array.} authNames An array of authentication type names. + * @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.{{^usePromises}} + * @param {module:ApiClient~callApiCallback} callback The callback function. +{{/usePromises}} * @returns {{#usePromises}}{Promise} A 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, + returnType{{^usePromises}}, callback{{/usePromises}}) { + var _this = this; var url = this.buildUrl(path, pathParams); var request = superagent(httpMethod, url); @@ -236,7 +349,7 @@ // set header parameters request.set(this.defaultHeaders).set(this.normalizeParams(headerParams)); - //set request timeout + // set request timeout request.timeout(this.timeout); var contentType = this.jsonPreferredMime(contentTypes); @@ -269,21 +382,17 @@ request.accept(accept); } - {{#usePromises}} - return new Promise( function(resolve,reject) { +{{#usePromises}} return new Promise(function(resolve, reject) { request.end(function(error, response) { if (error) { reject(error); - } - else { + } else { var data = _this.deserialize(response, returnType); resolve(data); } }); - }); - {{/usePromises}} - {{^usePromises}} - request.end(function(error, response) { + });{{/usePromises}} +{{^usePromises}} request.end(function(error, response) { if (callback) { var data = null; if (!error) { @@ -294,15 +403,27 @@ }); return request; - {{/usePromises}} +{{/usePromises}} }; + +{{#emitJSDoc}} /** + * Parses an ISO-8601 string representation of a date value. + * @param {String} str The date value as a string. + * @returns {Date} The parsed date object. + */ +{{/emitJSDoc}} exports.parseDate = function(str) { + return new Date(str.replace(/T/i, ' ')); }; - ApiClient.parseDate = function parseDate(str) { - str = str.replace(/T/i, ' '); - return new Date(str); - }; - - ApiClient.convertToType = function convertToType(data, type) { +{{#emitJSDoc}} /** + * Converts a value to the specified type. + * @param {(String|Object)} data The data to convert, as a string or object. + * @param {(String|Array.|Object.|Function)} type The type to return. Pass a string for simple types + * or the constructor function for a complex type. Pass an array containing the type name to return an array of that type. To + * return an object, pass an object with one property whose name is the key type and whose value is the corresponding value type: + * all properties on data will be converted to this type. + * @returns An instance of the specified type. + */ +{{/emitJSDoc}} exports.convertToType = function(data, type) { switch (type) { case 'Boolean': return Boolean(data); @@ -320,13 +441,12 @@ return data; } else if (typeof type === 'function') { // for model type like: User - var model = type.constructFromObject(data); - return model; + return type.constructFromObject(data); } else if (Array.isArray(type)) { // for array type like: ['String'] var itemType = type[0]; return data.map(function(item) { - return ApiClient.convertToType(item, itemType); + return exports.convertToType(item, itemType); }); } else if (typeof type === 'object') { // for plain object type like: {'String': 'Integer'} @@ -341,8 +461,8 @@ var result = {}; for (var k in data) { if (data.hasOwnProperty(k)) { - var key = ApiClient.convertToType(k, keyType); - var value = ApiClient.convertToType(data[k], valueType); + var key = exports.convertToType(k, keyType); + var value = exports.convertToType(data[k], valueType); result[key] = value; } } @@ -354,7 +474,11 @@ } }; - ApiClient.default = new ApiClient(); +{{#emitJSDoc}} /** + * The default API client implementation. + * @type {module:ApiClient} + */ +{{/emitJSDoc}} exports.instance = new exports(); - return ApiClient; + return exports; })); diff --git a/modules/swagger-codegen/src/main/resources/Javascript/README.mustache b/modules/swagger-codegen/src/main/resources/Javascript/README.mustache new file mode 100644 index 00000000000..633f2f0aebb --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Javascript/README.mustache @@ -0,0 +1,138 @@ +# {{projectName}} + +{{moduleName}} - JavaScript client for {{projectName}} +{{#appDescription}} +{{{appDescription}}} +{{/appDescription}} +This SDK is automatically generated by the [Swagger Codegen](https://github.com/swagger-api/swagger-codegen) project: + +- API version: {{appVersion}} +- Package version: {{projectVersion}} +- Build date: {{generatedDate}} +- Build package: {{generatorClass}} +{{#infoUrl}} +For more information, please visit [{{{infoUrl}}}]({{{infoUrl}}}) +{{/infoUrl}} + +## Installation + +### For [Node.js](https://nodejs.org/) + +#### npm + +To publish the library as a [npm](https://www.npmjs.com/), +please follow the procedure in ["Publishing npm packages"](https://docs.npmjs.com/getting-started/publishing-npm-packages). + +Then install it via: + +```shell +npm install {{{projectName}}} --save +``` + +#### git +# +If the library is hosted at a git repository, e.g. +https://github.com/{{#gitUserName}}{{.}}{{/gitUserName}}{{^gitUserName}}YOUR_USERNAME{{/gitUserName}}/{{#gitRepoId}}{{.}}{{/gitRepoId}}{{^gitRepoId}}{{projectName}}{{/gitRepoId}} +then install it via: + +```shell +npm install {{#gitUserName}}{{.}}{{/gitUserName}}{{^gitUserName}}YOUR_USERNAME{{/gitUserName}}/{{#gitRepoId}}{{.}}{{/gitRepoId}}{{^gitRepoId}}{{projectName}}{{/gitRepoId}} --save +``` + +### For browser + +The library also works in the browser environment via npm and [browserify](http://browserify.org/). After following +the above steps with Node.js and installing browserify with `npm install -g browserify`, +perform the following (assuming *main.js* is your entry file): + +```shell +browserify main.js > bundle.js +``` + +Then include *bundle.js* in the HTML pages. + +## Getting Started + +Please follow the [installation](#installation) instruction and execute the following JS code: + +```javascript +var {{{moduleName}}} = require('{{{projectName}}}'); +{{#apiInfo}}{{#apis}}{{#-first}}{{#operations}}{{#operation}}{{#-first}}{{#hasAuthMethods}} +var defaultClient = {{{moduleName}}}.ApiClient.default; +{{#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}}{{/-first}}{{/operation}}{{/operations}}{{/-first}}{{/apis}}{{/apiInfo}} +``` + +## Documentation for API Endpoints + +All URIs are relative to *{{basePath}}* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}*{{moduleName}}.{{classname}}* | [**{{operationId}}**]({{apiDocPath}}{{classname}}.md#{{operationId}}) | **{{httpMethod}}** {{path}} | {{#summary}}{{summary}}{{/summary}} +{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} + +## Documentation for Models + +{{#models}}{{#model}} - [{{moduleName}}.{{classname}}]({{modelDocPath}}{{classname}}.md) +{{/model}}{{/models}} + +## Documentation for Authorization + +{{^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}} +- **Location**: {{#isKeyInQuery}}URL query string{{/isKeyInQuery}}{{#isKeyInHeader}}HTTP header{{/isKeyInHeader}} +{{/isApiKey}} +{{#isBasic}}- **Type**: HTTP basic authentication +{{/isBasic}} +{{#isOAuth}}- **Type**: OAuth +- **Flow**: {{flow}} +- **Authorizatoin URL**: {{authorizationUrl}} +- **Scopes**: {{^scopes}}N/A{{/scopes}} +{{#scopes}} - {{scope}}: {{description}} +{{/scopes}} +{{/isOAuth}} + +{{/authMethods}} diff --git a/modules/swagger-codegen/src/main/resources/Javascript/api.mustache b/modules/swagger-codegen/src/main/resources/Javascript/api.mustache index 79a5fd2a674..8cc6cee18b9 100644 --- a/modules/swagger-codegen/src/main/resources/Javascript/api.mustache +++ b/modules/swagger-codegen/src/main/resources/Javascript/api.mustache @@ -1,10 +1,10 @@ {{=< >=}}(function(root, factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. - define(['../ApiClient'<#imports>, '../model/'], factory); + define(['../ApiClient'<#imports>, '../<#modelPackage>/'], factory); } else if (typeof module === 'object' && module.exports) { // CommonJS-like environments that support module.exports, like Node. - module.exports = factory(require('../ApiClient')<#imports>, require('../model/')); + module.exports = factory(require('../ApiClient')<#imports>, require('../<#modelPackage>/')); } else { // Browser globals (root is window) if (!root.) { @@ -15,28 +15,50 @@ }(this, function(ApiClient<#imports>, ) { 'use strict'; - var = function (apiClient) { - this.apiClient = apiClient || ApiClient.default; +<#emitJSDoc> /** + * service. + * @module <#apiPackage>/ + * @version + */ - var self = this; - <#operations> - <#operation> + /** + * Constructs a new . <#description> + * + * @alias module:<#apiPackage>/ + * @class + * @param {module:ApiClient} apiClient Optional API client implementation to use, default to {@link module:ApiClient#instance} + * if unspecified. + */ + var exports = function(apiClient) { + this.apiClient = apiClient || ApiClient.instance; + +<#operations><#operation><#emitJSDoc><^usePromises> /** - * - * <#allParams> - * @param {} <#required><^required>opts[''] <^usePromises> - * @param {function} callback the callback function, accepting three arguments: error, data, response<#returnType> - * data is of type: <&returnType> + * Callback function to receive the result of the operation. + * @callback module:<#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 {String} response The complete HTTP response. + */ + + /**<#summary> + * <#notes> + * <#allParams><#required> + * @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:<#apiPackage>/~Callback} callback The callback function, accepting three arguments: error, data, response<#returnType> + * data is of type: <&vendorExtensions.x-jsdoc-type> */ - self. = function() {<#hasOptionalParams> + this. = function() {<#hasOptionalParams> opts = opts || {}; var postBody = <#bodyParam><#required><^required>opts['']<^bodyParam>null; - <#allParams><#required> +<#allParams><#required> // verify the required parameter '' is set - if ( == null) { + if ( == undefined || == null) { throw "Missing the required parameter '' when calling "; } - + var pathParams = {<#pathParams> '': <#required><^required>opts['']<#hasMore>, @@ -61,11 +83,8 @@ pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType<^usePromises>, callback ); - } - - - }; + }; - return ; + return exports; }));<={{ }}=> diff --git a/modules/swagger-codegen/src/main/resources/Javascript/api_doc.mustache b/modules/swagger-codegen/src/main/resources/Javascript/api_doc.mustache new file mode 100644 index 00000000000..698b42dfe11 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Javascript/api_doc.mustache @@ -0,0 +1,89 @@ +# {{moduleName}}.{{classname}}{{#description}} +{{description}}{{/description}} + +All URIs are relative to *{{basePath}}* + +Method | HTTP request | Description +------------- | ------------- | ------------- +{{#operations}}{{#operation}}[**{{operationId}}**]({{classname}}.md#{{operationId}}) | **{{httpMethod}}** {{path}} | {{#summary}}{{summary}}{{/summary}} +{{/operation}}{{/operations}} + +{{#operations}} +{{#operation}} + +# **{{operationId}}** +> {{#returnType}}{{returnType}} {{/returnType}}{{operationId}}{{#hasParams}}({{#allParams}}{{#required}}{{{paramName}}}{{#vendorExtensions.x-codegen-hasMoreRequired}}, {{/vendorExtensions.x-codegen-hasMoreRequired}}{{/required}}{{/allParams}}{{#hasOptionalParams}}{{#vendorExtensions.x-codegen-hasRequiredParams}}, {{/vendorExtensions.x-codegen-hasRequiredParams}}opts{{/hasOptionalParams}}){{/hasParams}} + +{{summary}}{{#notes}} + +{{notes}}{{/notes}} + +### Example +```javascript +var {{{moduleName}}} = require('{{{projectName}}}'); +{{#hasAuthMethods}} +var defaultClient = {{{moduleName}}}.ApiClient.default; +{{#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 apiInstance = 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}} +apiInstance.{{{operationId}}}({{#allParams}}{{#required}}{{{paramName}}}{{#vendorExtensions.x-codegen-hasMoreRequired}}, {{/vendorExtensions.x-codegen-hasMoreRequired}}{{/required}}{{/allParams}}{{#hasOptionalParams}}{{#vendorExtensions.x-codegen-hasRequiredParams}}, {{/vendorExtensions.x-codegen-hasRequiredParams}}opts{{/hasOptionalParams}}).then(function({{#returnType}}data{{/returnType}}) { + {{#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}} +``` + +### Parameters +{{^allParams}}This endpoint does not need any parameter.{{/allParams}}{{#allParams}}{{#-last}} +Name | Type | Description | Notes +------------- | ------------- | ------------- | -------------{{/-last}}{{/allParams}} +{{#allParams}} **{{paramName}}** | {{#isPrimitiveType}}**{{dataType}}**{{/isPrimitiveType}}{{^isPrimitiveType}}{{#isFile}}**{{dataType}}**{{/isFile}}{{^isFile}}[**{{dataType}}**]({{baseType}}.md){{/isFile}}{{/isPrimitiveType}}| {{description}} | {{^required}}[optional] {{/required}}{{#defaultValue}}[default to {{defaultValue}}]{{/defaultValue}} +{{/allParams}} + +### Return type + +{{#returnType}}{{#returnTypeIsPrimitive}}**{{returnType}}**{{/returnTypeIsPrimitive}}{{^returnTypeIsPrimitive}}[**{{returnType}}**]({{returnBaseType}}.md){{/returnTypeIsPrimitive}}{{/returnType}}{{^returnType}}null (empty response body){{/returnType}} + +### Authorization + +{{^authMethods}}No authorization required{{/authMethods}}{{#authMethods}}[{{name}}](../README.md#{{name}}){{^-last}}, {{/-last}}{{/authMethods}} + +### HTTP reuqest headers + + - **Content-Type**: {{#consumes}}{{mediaType}}{{#hasMore}}, {{/hasMore}}{{/consumes}}{{^consumes}}Not defined{{/consumes}} + - **Accept**: {{#produces}}{{mediaType}}{{#hasMore}}, {{/hasMore}}{{/produces}}{{^produces}}Not defined{{/produces}} + +{{/operation}} +{{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/Javascript/enumClass.mustache b/modules/swagger-codegen/src/main/resources/Javascript/enumClass.mustache index 5acd5504bb5..d245084042a 100644 --- a/modules/swagger-codegen/src/main/resources/Javascript/enumClass.mustache +++ b/modules/swagger-codegen/src/main/resources/Javascript/enumClass.mustache @@ -1,10 +1,13 @@ -var {{datatypeWithEnum}} = { -{{#allowableValues}}{{#enumVars}} - /** - * @const - */ - {{name}}: "{{value}}"{{^-last}}, - {{/-last}}{{/enumVars}}{{/allowableValues}} - }; - - {{classname}}.{{datatypeWithEnum}} = {{datatypeWithEnum}}; +{{#emitJSDoc}} /** + * Allowed values for the {{baseName}} property. + * @enum {{=<% %>=}}{<%datatype%>}<%={{ }}=%> + * @readonly + */{{/emitJSDoc}} + exports.{{datatypeWithEnum}} = { {{#allowableValues}}{{#enumVars}} +{{#emitJSDoc}} /** + * value: {{value}} + * @const + */ +{{/emitJSDoc}} {{name}}: "{{value}}"{{^-last}}, + {{/-last}}{{/enumVars}}{{/allowableValues}} + }; \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/Javascript/git_push.sh.mustache b/modules/swagger-codegen/src/main/resources/Javascript/git_push.sh.mustache new file mode 100755 index 00000000000..e153ce23ecf --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Javascript/git_push.sh.mustache @@ -0,0 +1,52 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 swagger-petstore-perl "minor update" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 + +if [ "$git_user_id" = "" ]; then + git_user_id="{{{gitUserId}}}" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="{{{gitRepoId}}}" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="{{{releaseNote}}}" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=`git remote` +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git crediential in your environment." + git remote add origin https://github.com/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:${GIT_TOKEN}@github.com/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://github.com/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' + diff --git a/modules/swagger-codegen/src/main/resources/Javascript/gitignore.mustache b/modules/swagger-codegen/src/main/resources/Javascript/gitignore.mustache new file mode 100644 index 00000000000..e920c16718d --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Javascript/gitignore.mustache @@ -0,0 +1,33 @@ +# Logs +logs +*.log +npm-debug.log* + +# Runtime data +pids +*.pid +*.seed + +# Directory for instrumented libs generated by jscoverage/JSCover +lib-cov + +# Coverage directory used by tools like istanbul +coverage + +# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) +.grunt + +# node-waf configuration +.lock-wscript + +# Compiled binary addons (http://nodejs.org/api/addons.html) +build/Release + +# Dependency directory +node_modules + +# Optional npm cache directory +.npm + +# Optional REPL history +.node_repl_history diff --git a/modules/swagger-codegen/src/main/resources/Javascript/index.mustache b/modules/swagger-codegen/src/main/resources/Javascript/index.mustache index 760c8a3cd73..b48956afbb4 100644 --- a/modules/swagger-codegen/src/main/resources/Javascript/index.mustache +++ b/modules/swagger-codegen/src/main/resources/Javascript/index.mustache @@ -1,17 +1,62 @@ (function(factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. - define(['./ApiClient'{{#models}}, './model/{{importPath}}'{{/models}}{{#apiInfo}}{{#apis}}, './api/{{importPath}}'{{/apis}}{{/apiInfo}}], factory); + define(['./ApiClient'{{#models}}, './{{#modelPackage}}{{modelPackage}}/{{/modelPackage}}{{importPath}}'{{/models}}{{#apiInfo}}{{#apis}}, './{{#apiPackage}}{{apiPackage}}/{{/apiPackage}}{{importPath}}'{{/apis}}{{/apiInfo}}], factory); } else if (typeof module === 'object' && module.exports) { // CommonJS-like environments that support module.exports, like Node. - module.exports = factory(require('./ApiClient'){{#models}}, require('./model/{{importPath}}'){{/models}}{{#apiInfo}}{{#apis}}, require('./api/{{importPath}}'){{/apis}}{{/apiInfo}}); + module.exports = factory(require('./ApiClient'){{#models}}, require('./{{#modelPackage}}{{modelPackage}}/{{/modelPackage}}{{importPath}}'){{/models}}{{#apiInfo}}{{#apis}}, require('./{{#apiPackage}}{{apiPackage}}/{{/apiPackage}}{{importPath}}'){{/apis}}{{/apiInfo}}); } }(function(ApiClient{{#models}}{{#model}}, {{classFilename}}{{/model}}{{/models}}{{#apiInfo}}{{#apis}}, {{importPath}}{{/apis}}{{/apiInfo}}) { 'use strict'; - return { - ApiClient: ApiClient{{#models}}, - {{importPath}}: {{importPath}}{{/models}}{{#apiInfo}}{{#apis}}, - {{importPath}}: {{importPath}}{{/apis}}{{/apiInfo}} +{{#emitJSDoc}} /**{{#projectDescription}} + * {{projectDescription}}.
{{/projectDescription}} + * The index module provides access to constructors for all the classes which comprise the public API. + *

+ * An AMD (recommended!) or CommonJS application will generally do something equivalent to the following: + *

+   * var {{moduleName}} = require('./index'); // See note below*.
+   * var xxxSvc = new {{moduleName}}.XxxApi(); // Allocate the API class we're going to use.
+   * var yyyModel = new {{moduleName}}.Yyy(); // Construct a model instance.
+   * yyyModel.someProperty = 'someValue';
+   * ...
+   * var zzz = xxxSvc.doSomething(yyyModel); // Invoke the service.
+   * ...
+   * 
+ * *NOTE: For a top-level AMD script, use require(['./index'], function(){...}) and put the application logic within the + * callback function. + *

+ *

+ * A non-AMD browser application (discouraged) might do something like this: + *

+   * var xxxSvc = new {{moduleName}}.XxxApi(); // Allocate the API class we're going to use.
+   * var yyy = new {{moduleName}}.Yyy(); // Construct a model instance.
+   * yyyModel.someProperty = 'someValue';
+   * ...
+   * var zzz = xxxSvc.doSomething(yyyModel); // Invoke the service.
+   * ...
+   * 
+ *

+ * @module index + * @version {{projectVersion}} + */{{/emitJSDoc}} +{{=< >=}} var exports = {<#emitJSDoc> + /** + * The ApiClient constructor. + * @property {module:ApiClient} + */ + ApiClient: ApiClient<#models>,<#emitJSDoc> + /** + * The model constructor. + * @property {module:<#modelPackage>/} + */ + : <#apiInfo><#apis>,<#emitJSDoc> + /** + * The service constructor. + * @property {module:<#apiPackage>/} + */ + : }; + + return exports;<={{ }}=> })); diff --git a/modules/swagger-codegen/src/main/resources/Javascript/model.mustache b/modules/swagger-codegen/src/main/resources/Javascript/model.mustache index 068a42c8d4c..c8849223fc4 100644 --- a/modules/swagger-codegen/src/main/resources/Javascript/model.mustache +++ b/modules/swagger-codegen/src/main/resources/Javascript/model.mustache @@ -1,86 +1,100 @@ (function(root, factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. - define([undefined, '../ApiClient'{{#imports}}, './{{import}}'{{/imports}}], factory); + define(['../ApiClient'{{#imports}}, './{{import}}'{{/imports}}], factory); } else if (typeof module === 'object' && module.exports) { // CommonJS-like environments that support module.exports, like Node. - module.exports = factory(undefined, require('../ApiClient'){{#imports}}, require('./{{import}}'){{/imports}}); + module.exports = factory(require('../ApiClient'){{#imports}}, require('./{{import}}'){{/imports}}); } else { // Browser globals (root is window) if (!root.{{moduleName}}) { root.{{moduleName}} = {}; } - factory(root.{{moduleName}}, root.{{moduleName}}.ApiClient{{#imports}}, root.{{moduleName}}.{{import}}{{/imports}}); + root.{{moduleName}}.{{classname}} = factory(root.{{moduleName}}.ApiClient{{#imports}}, root.{{moduleName}}.{{import}}{{/imports}}); } -}(this, function(module, ApiClient{{#imports}}, {{import}}{{/imports}}) { +}(this, function(ApiClient{{#imports}}, {{import}}{{/imports}}) { 'use strict'; - {{#models}}{{#model}} - {{#description}}/** - * {{description}} - **/{{/description}} - var {{classname}} = function {{classname}}({{#vars}}{{#required}}{{name}}{{#vendorExtensions.x-codegen-hasMoreRequired}}, {{/vendorExtensions.x-codegen-hasMoreRequired}}{{/required}}{{/vars}}) { {{#parent}}/* extends {{{parent}}}*/{{/parent}} - {{#vars}}{{#required}} - /**{{#description}} - * {{{description}}}{{/description}} - * datatype: {{{datatypeWithEnum}}} - * required {{#minimum}} - * minimum: {{minimum}}{{/minimum}}{{#maximum}} - * maximum: {{maximum}}{{/maximum}} - **/ - this['{{baseName}}'] = {{name}};{{/required}}{{^required}}{{#defaultValue}} - /**{{#description}} - * {{{description}}}{{/description}} - * datatype: {{{datatypeWithEnum}}} - * required {{#minimum}} - * minimum: {{minimum}}{{/minimum}}{{#maximum}} - * maximum: {{maximum}}{{/maximum}} - **/ - this['{{baseName}}'] = {{{defaultValue}}};{{/defaultValue}}{{/required}}{{/vars}} - }; - {{classname}}.constructFromObject = function(data) { - if (!data) { - return null; - } - var _this = new {{classname}}(); - {{#vars}} - if (data['{{baseName}}']) { - _this['{{baseName}}']{{{defaultValueWithParam}}} - } - {{/vars}} - return _this; +{{#models}}{{#model}}{{#emitJSDoc}} /** + * The {{classname}} model module. + * @module {{#modelPackage}}{{modelPackage}}/{{/modelPackage}}{{classname}} + * @version {{projectVersion}} + */ + + /** + * Constructs a new {{classname}}.{{#description}} + * {{description}}{{/description}} + * @alias module:{{#modelPackage}}{{modelPackage}}/{{/modelPackage}}{{classname}} + * @class{{#useInheritance}}{{#parent}} + * @extends module:{{#modelPackage}}{{modelPackage}}/{{/modelPackage}}{{parent}}{{/parent}}{{#interfaces}} + * @implements module:{{#modelPackage}}{{modelPackage}}/{{/modelPackage}}{{.}}{{/interfaces}}{{/useInheritance}}{{#vendorExtensions.x-all-required}} + * @param {{.}}{{/vendorExtensions.x-all-required}} + */{{/emitJSDoc}} + var exports = function({{#vendorExtensions.x-all-required}}{{.}}{{^-last}}, {{/-last}}{{/vendorExtensions.x-all-required}}) { +{{#useInheritance}}{{#parentModel}} {{classname}}.call(this{{#vendorExtensions.x-all-required}}, {{.}}{{/vendorExtensions.x-all-required}});{{/parentModel}} +{{#interfaceModels}} {{classname}}.call(this{{#vendorExtensions.x-all-required}}, {{.}}{{/vendorExtensions.x-all-required}}); +{{/interfaceModels}}{{/useInheritance}}{{#vars}}{{#required}} this['{{baseName}}'] = {{name}};{{/required}} +{{/vars}} }; + +{{#emitJSDoc}} /** + * Constructs a {{classname}} 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:<#modelPackage>/}<={{ }}=> obj Optional instance to populate. + * @return {{=< >=}}{module:<#modelPackage>/}<={{ }}=> The populated {{classname}} instance. + */ +{{/emitJSDoc}} exports.constructFromObject = function(data, obj) { + if (data) { {{!// TODO: support polymorphism: discriminator property on data determines class to instantiate.}} + obj = obj || new exports(); +{{#useInheritance}}{{#parent}} {{.}}.constructFromObject(data, obj);{{/parent}} +{{#interfaces}} {{.}}.constructFromObject(data, obj); +{{/interfaces}}{{/useInheritance}}{{#vars}} if (data.hasOwnProperty('{{baseName}}')) { + obj['{{baseName}}']{{{defaultValueWithParam}}} + } +{{/vars}} } + return obj; } - - {{^omitModelMethods}} - {{#vars}} +{{#useInheritance}}{{#parent}} + exports.prototype = Object.create({{parent}}.prototype); + exports.prototype.constructor = exports; +{{/parent}}{{/useInheritance}} +{{#vars}}{{#emitJSDoc}} /**{{#description}} - * get {{{description}}}{{/description}}{{#minimum}} + * {{{description}}}{{/description}} + * @member {{{vendorExtensions.x-jsdoc-type}}} {{baseName}}{{#defaultValue}} + * @default {{{defaultValue}}}{{/defaultValue}} + */ +{{/emitJSDoc}} exports.prototype['{{baseName}}'] = {{#defaultValue}}{{{defaultValue}}}{{/defaultValue}}{{^defaultValue}}undefined{{/defaultValue}}; +{{/vars}}{{#useInheritance}}{{#interfaceModels}} + // Implement {{classname}} interface:{{#allVars}}{{#emitJSDoc}} + /**{{#description}} + * {{{description}}}{{/description}} + * @member {{{vendorExtensions.x-jsdoc-type}}} {{baseName}}{{#defaultValue}} + * @default {{{defaultValue}}}{{/defaultValue}} + */ +{{/emitJSDoc}} exports.prototype['{{baseName}}'] = {{#defaultValue}}{{{defaultValue}}}{{/defaultValue}}{{^defaultValue}}undefined{{/defaultValue}}; +{{/allVars}}{{/interfaceModels}}{{/useInheritance}} +{{#emitModelMethods}}{{#vars}}{{#emitJSDoc}} /**{{#description}} + * Returns {{{description}}}{{/description}}{{#minimum}} * minimum: {{minimum}}{{/minimum}}{{#maximum}} * maximum: {{maximum}}{{/maximum}} - * @return {{=<% %>=}}{<% datatypeWithEnum %>}<%={{ }}=%> - **/ - {{classname}}.prototype.{{getter}} = function() { + * @return {{{vendorExtensions.x-jsdoc-type}}} + */ +{{/emitJSDoc}} exports.prototype.{{getter}} = function() { return this['{{baseName}}']; } - /**{{#description}} - * set {{{description}}}{{/description}} - * @param {{=<% %>=}}{<% datatypeWithEnum %>}<%={{ }}=%> {{name}} - **/ - {{classname}}.prototype.{{setter}} = function({{name}}) { +{{#emitJSDoc}} /**{{#description}} + * Sets {{{description}}}{{/description}} + * @param {{{vendorExtensions.x-jsdoc-type}}} {{name}}{{#description}} {{{description}}}{{/description}} + */ +{{/emitJSDoc}} exports.prototype.{{setter}} = function({{name}}) { this['{{baseName}}'] = {{name}}; } - {{/vars}} - {{/omitModelMethods}} - {{#vars}}{{#isEnum}}{{>enumClass}}{{/isEnum}}{{#items.isEnum}}{{#items}} - {{>enumClass}}{{/items}}*/{{/items.isEnum}}{{/vars}} +{{/vars}}{{/emitModelMethods}} +{{#vars}}{{#isEnum}}{{>enumClass}}{{/isEnum}}{{#items.isEnum}}{{#items}} +{{>enumClass}}{{/items}}*/{{/items.isEnum}}{{/vars}} - if (module) { - module.{{classname}} = {{classname}}; - } - - return {{classname}}; - {{/model}} - {{/models}} -})); + return exports; +{{/model}}{{/models}}})); diff --git a/modules/swagger-codegen/src/main/resources/Javascript/model_doc.mustache b/modules/swagger-codegen/src/main/resources/Javascript/model_doc.mustache new file mode 100644 index 00000000000..306d8a2b3f7 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Javascript/model_doc.mustache @@ -0,0 +1,9 @@ +{{#models}}{{#model}}# {{moduleName}}.{{classname}} + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +{{#vars}}**{{name}}** | {{#isPrimitiveType}}**{{datatype}}**{{/isPrimitiveType}}{{^isPrimitiveType}}[**{{datatype}}**]({{complexType}}.md){{/isPrimitiveType}} | {{description}} | {{^required}}[optional] {{/required}}{{#readOnly}}[readonly] {{/readOnly}}{{#defaultValue}}[default to {{defaultValue}}]{{/defaultValue}} +{{/vars}} + +{{/model}}{{/models}} 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 5c86c501392..070b084fdb6 100644 --- a/modules/swagger-codegen/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig +++ b/modules/swagger-codegen/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig @@ -13,6 +13,7 @@ io.swagger.codegen.languages.JavaResteasyServerCodegen io.swagger.codegen.languages.JavaInflectorServerCodegen io.swagger.codegen.languages.JavascriptClientCodegen io.swagger.codegen.languages.JavascriptClosureAngularClientCodegen +io.swagger.codegen.languages.JavaJerseyServerCodegen io.swagger.codegen.languages.JMeterCodegen io.swagger.codegen.languages.NodeJSServerCodegen io.swagger.codegen.languages.ObjcClientCodegen diff --git a/modules/swagger-codegen/src/main/resources/TypeScript-Angular/git_push.sh.mustache b/modules/swagger-codegen/src/main/resources/TypeScript-Angular/git_push.sh.mustache new file mode 100755 index 00000000000..e153ce23ecf --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/TypeScript-Angular/git_push.sh.mustache @@ -0,0 +1,52 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 swagger-petstore-perl "minor update" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 + +if [ "$git_user_id" = "" ]; then + git_user_id="{{{gitUserId}}}" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="{{{gitRepoId}}}" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="{{{releaseNote}}}" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=`git remote` +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git crediential in your environment." + git remote add origin https://github.com/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:${GIT_TOKEN}@github.com/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://github.com/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' + diff --git a/modules/swagger-codegen/src/main/resources/TypeScript-node/git_push.sh.mustache b/modules/swagger-codegen/src/main/resources/TypeScript-node/git_push.sh.mustache new file mode 100755 index 00000000000..e153ce23ecf --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/TypeScript-node/git_push.sh.mustache @@ -0,0 +1,52 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 swagger-petstore-perl "minor update" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 + +if [ "$git_user_id" = "" ]; then + git_user_id="{{{gitUserId}}}" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="{{{gitRepoId}}}" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="{{{releaseNote}}}" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=`git remote` +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git crediential in your environment." + git remote add origin https://github.com/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:${GIT_TOKEN}@github.com/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://github.com/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' + diff --git a/modules/swagger-codegen/src/main/resources/akka-scala/pom.mustache b/modules/swagger-codegen/src/main/resources/akka-scala/pom.mustache index a547542ff21..b7bd04afffb 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.7 + 1.5.8 1.0.0 4.8.1 diff --git a/modules/swagger-codegen/src/main/resources/android/apiInvoker.mustache b/modules/swagger-codegen/src/main/resources/android/apiInvoker.mustache index 1f6d77a071c..a2df0ea9b7c 100644 --- a/modules/swagger-codegen/src/main/resources/android/apiInvoker.mustache +++ b/modules/swagger-codegen/src/main/resources/android/apiInvoker.mustache @@ -83,7 +83,7 @@ public class ApiInvoker { DATE_FORMAT.setTimeZone(TimeZone.getTimeZone("UTC")); // Set default User-Agent. - setUserAgent("Android-Java-Swagger"); + setUserAgent("{{#httpUserAgent}}{{{.}}}{{/httpUserAgent}}{{^httpUserAgent}}Swagger-Codegen/{{{artifactVersion}}}/android{{/httpUserAgent}}"); } public static void setUserAgent(String userAgent) { diff --git a/modules/swagger-codegen/src/main/resources/android/build.mustache b/modules/swagger-codegen/src/main/resources/android/build.mustache index dff18970462..41c9a2dfbb1 100644 --- a/modules/swagger-codegen/src/main/resources/android/build.mustache +++ b/modules/swagger-codegen/src/main/resources/android/build.mustache @@ -8,9 +8,9 @@ buildscript { jcenter() } dependencies { - classpath 'com.android.tools.build:gradle:1.2.2' + classpath 'com.android.tools.build:gradle:1.5.+' {{#useAndroidMavenGradlePlugin}} - classpath 'com.github.dcendents:android-maven-plugin:1.2' + classpath 'com.github.dcendents:android-maven-gradle-plugin:1.3' {{/useAndroidMavenGradlePlugin}} } } @@ -28,11 +28,12 @@ apply plugin: 'com.github.dcendents.android-maven' {{/useAndroidMavenGradlePlugin}} android { - compileSdkVersion 22 - buildToolsVersion '22.0.0' + compileSdkVersion 23 + buildToolsVersion '23.0.2' + useLibrary 'org.apache.http.legacy' defaultConfig { minSdkVersion 14 - targetSdkVersion 22 + targetSdkVersion 23 } compileOptions { sourceCompatibility JavaVersion.VERSION_1_7 @@ -55,16 +56,17 @@ android { ext { swagger_annotations_version = "1.5.0" gson_version = "2.3.1" - httpclient_version = "4.3.3" - junit_version = "4.8.1" + httpclient_version = "4.5.2" + httpcore_version = "4.4.4" + junit_version = "4.12" } dependencies { compile "io.swagger:swagger-annotations:$swagger_annotations_version" compile "com.google.code.gson:gson:$gson_version" - compile "org.apache.httpcomponents:httpcore:$httpclient_version" + compile "org.apache.httpcomponents:httpcore:$httpcore_version" compile "org.apache.httpcomponents:httpclient:$httpclient_version" - compile ("org.apache.httpcomponents:httpcore:$httpclient_version") { + compile ("org.apache.httpcomponents:httpcore:$httpcore_version") { exclude(group: 'org.apache.httpcomponents', module: 'httpclient') } compile ("org.apache.httpcomponents:httpmime:$httpclient_version") { diff --git a/modules/swagger-codegen/src/main/resources/android/git_push.sh.mustache b/modules/swagger-codegen/src/main/resources/android/git_push.sh.mustache new file mode 100755 index 00000000000..e153ce23ecf --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/android/git_push.sh.mustache @@ -0,0 +1,52 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 swagger-petstore-perl "minor update" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 + +if [ "$git_user_id" = "" ]; then + git_user_id="{{{gitUserId}}}" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="{{{gitRepoId}}}" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="{{{releaseNote}}}" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=`git remote` +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git crediential in your environment." + git remote add origin https://github.com/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:${GIT_TOKEN}@github.com/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://github.com/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' + diff --git a/modules/swagger-codegen/src/main/resources/android/gitignore.mustache b/modules/swagger-codegen/src/main/resources/android/gitignore.mustache new file mode 100644 index 00000000000..a8363b06f95 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/android/gitignore.mustache @@ -0,0 +1,39 @@ +# Built application files +*.apk +*.ap_ + +# Files for the Dalvik VM +*.dex + +# Java class files +*.class + +# Generated files +bin/ +gen/ +out/ + +# Gradle files +.gradle/ +build/ + +# Local configuration file (sdk path, etc) +local.properties + +# Proguard folder generated by Eclipse +proguard/ + +# Log Files +*.log + +# Android Studio Navigation editor temp files +.navigation/ + +# Android Studio captures folder +captures/ + +# Intellij +*.iml + +#Keystore files +*.jks diff --git a/modules/swagger-codegen/src/main/resources/android/libraries/volley/apiInvoker.mustache b/modules/swagger-codegen/src/main/resources/android/libraries/volley/apiInvoker.mustache index 2a04c1c86b1..e76bf1357e1 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 @@ -185,7 +185,7 @@ public class ApiInvoker { public static void initializeInstance(Cache cache, Network network, int threadPoolSize, ResponseDelivery delivery, int connectionTimeout) { INSTANCE = new ApiInvoker(cache, network, threadPoolSize, delivery, connectionTimeout); - setUserAgent("Android-Volley-Swagger"); + setUserAgent("{{#httpUserAgent}}{{{.}}}{{/httpUserAgent}}{{^httpUserAgent}}Swagger-Codegen/{{{artifactVersion}}}/android{{/httpUserAgent}}"); // Setup authentications (key: authentication name, value: authentication). INSTANCE.authentications = new HashMap(); @@ -197,7 +197,8 @@ public class ApiInvoker { INSTANCE.authentications.put("{{name}}", new HttpBasicAuth()); {{/isBasic}} {{#isOAuth}} - INSTANCE.authentications.put("{{name}}", new OAuth()); + // TODO: comment out below as OAuth does not exist + //INSTANCE.authentications.put("{{name}}", new OAuth()); {{/isOAuth}} {{/authMethods}} // Prevent the authentications from being modified. 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 197dd32b7c1..fabdd14a6d6 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 @@ -8,9 +8,9 @@ buildscript { jcenter() } dependencies { - classpath 'com.android.tools.build:gradle:1.2.2' + classpath 'com.android.tools.build:gradle:1.5.+' {{#useAndroidMavenGradlePlugin}} - classpath 'com.github.dcendents:android-maven-plugin:1.2' + classpath 'com.github.dcendents:android-maven-gradle-plugin:1.3' {{/useAndroidMavenGradlePlugin}} } } @@ -59,9 +59,10 @@ android { ext { swagger_annotations_version = "1.5.0" gson_version = "2.3.1" - httpclient_version = "4.3.3" + httpclient_version = "4.5.2" + httpcore_version = "4.4.4" volley_version = "1.0.19" - junit_version = "4.8.1" + junit_version = "4.12" robolectric_version = "3.0" concurrent_unit_version = "0.4.2" } diff --git a/modules/swagger-codegen/src/main/resources/android/pom.mustache b/modules/swagger-codegen/src/main/resources/android/pom.mustache index ad093828ecc..0c00c55de1f 100644 --- a/modules/swagger-codegen/src/main/resources/android/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/android/pom.mustache @@ -110,7 +110,7 @@ io.swagger swagger-annotations - ${swagger-annotations-version} + ${swagger-core-version} com.google.code.gson @@ -145,7 +145,7 @@ - 1.5.4 + 1.5.8 2.3.1 4.8.1 1.0.0 diff --git a/modules/swagger-codegen/src/main/resources/asyncscala/api.mustache b/modules/swagger-codegen/src/main/resources/asyncscala/api.mustache index 49b7c089704..dfec3d789dd 100644 --- a/modules/swagger-codegen/src/main/resources/asyncscala/api.mustache +++ b/modules/swagger-codegen/src/main/resources/asyncscala/api.mustache @@ -2,9 +2,8 @@ package {{package}} {{#imports}}import {{import}} {{/imports}} -import io.swagger.client._ -import scala.concurrent.{ Future, Await } -import scala.concurrent.duration._ +import com.wordnik.swagger.client._ +import scala.concurrent.Future import collection.mutable {{#operations}} diff --git a/modules/swagger-codegen/src/main/resources/asyncscala/client.mustache b/modules/swagger-codegen/src/main/resources/asyncscala/client.mustache index 7d2093f8609..d48d031860e 100644 --- a/modules/swagger-codegen/src/main/resources/asyncscala/client.mustache +++ b/modules/swagger-codegen/src/main/resources/asyncscala/client.mustache @@ -4,7 +4,7 @@ package {{invokerPackage}} {{/imports}} import {{apiPackage}}._ -import io.swagger.client._ +import com.wordnik.swagger.client._ import java.io.Closeable @@ -22,4 +22,4 @@ class {{clientName}}(config: SwaggerConfig) extends Closeable { def close() { client.close() } -} \ No newline at end of file +} diff --git a/modules/swagger-codegen/src/main/resources/asyncscala/model.mustache b/modules/swagger-codegen/src/main/resources/asyncscala/model.mustache index b0da2825b32..bf63e76658a 100644 --- a/modules/swagger-codegen/src/main/resources/asyncscala/model.mustache +++ b/modules/swagger-codegen/src/main/resources/asyncscala/model.mustache @@ -1,6 +1,7 @@ package {{package}} import org.joda.time.DateTime +import java.util.UUID {{#models}} @@ -10,4 +11,4 @@ case class {{classname}} ( {{/vars}} ) {{/model}} -{{/models}} \ No newline at end of file +{{/models}} diff --git a/modules/swagger-codegen/src/main/resources/asyncscala/sbt.mustache b/modules/swagger-codegen/src/main/resources/asyncscala/sbt.mustache index aef5e1f389a..b96e132d8a7 100644 --- a/modules/swagger-codegen/src/main/resources/asyncscala/sbt.mustache +++ b/modules/swagger-codegen/src/main/resources/asyncscala/sbt.mustache @@ -3,7 +3,7 @@ organization := "{{package}}" name := "{{projectName}}-client" libraryDependencies ++= Seq( - "io.swagger" %% "swagger-async-httpclient" % "0.3.5", + "com.wordnik.swagger" %% "swagger-async-httpclient" % "0.3.5", "joda-time" % "joda-time" % "2.3", "org.joda" % "joda-convert" % "1.3.1", "ch.qos.logback" % "logback-classic" % "1.0.13" % "provided", diff --git a/modules/swagger-codegen/src/main/resources/clojure/git_push.sh.mustache b/modules/swagger-codegen/src/main/resources/clojure/git_push.sh.mustache new file mode 100755 index 00000000000..e153ce23ecf --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/clojure/git_push.sh.mustache @@ -0,0 +1,52 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 swagger-petstore-perl "minor update" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 + +if [ "$git_user_id" = "" ]; then + git_user_id="{{{gitUserId}}}" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="{{{gitRepoId}}}" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="{{{releaseNote}}}" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=`git remote` +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git crediential in your environment." + git remote add origin https://github.com/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:${GIT_TOKEN}@github.com/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://github.com/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' + diff --git a/modules/swagger-codegen/src/main/resources/clojure/gitignore.mustache b/modules/swagger-codegen/src/main/resources/clojure/gitignore.mustache new file mode 100644 index 00000000000..47fed6c20d9 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/clojure/gitignore.mustache @@ -0,0 +1,12 @@ +pom.xml +pom.xml.asc +*jar +/lib/ +/classes/ +/target/ +/checkouts/ +.lein-deps-sum +.lein-repl-history +.lein-plugins/ +.lein-failures +.nrepl-port diff --git a/modules/swagger-codegen/src/main/resources/csharp/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/csharp/ApiClient.mustache index bf6b5a3cc74..75f43b8aa1c 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/ApiClient.mustache @@ -63,7 +63,7 @@ namespace {{packageName}}.Client /// The default API client. [Obsolete("ApiClient.Default is deprecated, please use 'Configuration.Default.ApiClient' instead.")] public static ApiClient Default; - + /// /// Gets or sets the Configuration. /// @@ -75,7 +75,7 @@ namespace {{packageName}}.Client ///
/// 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, @@ -84,10 +84,10 @@ namespace {{packageName}}.Client 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); + request.AddParameter(param.Key, param.Value, ParameterType.UrlSegment); // add header parameter, if any foreach(var param in headerParams) @@ -116,7 +116,7 @@ namespace {{packageName}}.Client request.AddParameter(contentType, postBody, ParameterType.RequestBody); } } - + return request; } @@ -143,6 +143,11 @@ namespace {{packageName}}.Client path, method, queryParams, postBody, headerParams, formParams, fileParams, pathParams, contentType); + // set timeout + RestClient.Timeout = Configuration.Timeout; + // set user agent + RestClient.UserAgent = Configuration.UserAgent; + var response = RestClient.Execute(request); return (Object) response; } @@ -172,7 +177,7 @@ namespace {{packageName}}.Client var response = await RestClient.ExecuteTaskAsync(request); return (Object)response; }{{/supportsAsync}} - + /// /// Escape string (url-encoded). /// @@ -182,7 +187,7 @@ namespace {{packageName}}.Client { return UrlEncode(str); } - + /// /// Create FileParameter based on Stream. /// @@ -196,7 +201,7 @@ namespace {{packageName}}.Client 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 ",". @@ -217,7 +222,7 @@ namespace {{packageName}}.Client // 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); + return ((DateTimeOffset)obj).ToString (Configuration.DateTimeFormat); else if (obj is IList) { var flattenedString = new StringBuilder(); @@ -232,7 +237,7 @@ namespace {{packageName}}.Client else return Convert.ToString (obj); } - + /// /// Deserialize the JSON string into a proper object. /// @@ -277,9 +282,9 @@ namespace {{packageName}}.Client if (type == typeof(String) || type.Name.StartsWith("System.Nullable")) // return primitive type { - return ConvertType(response.Content, type); + return ConvertType(response.Content, type); } - + // at this point, it must be a model (json) try { @@ -290,7 +295,7 @@ namespace {{packageName}}.Client throw new ApiException(500, e.Message); } } - + /// /// Serialize an input (model) into JSON string /// @@ -307,7 +312,7 @@ namespace {{packageName}}.Client 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; @@ -343,7 +348,7 @@ namespace {{packageName}}.Client return String.Join(",", accepts); } - + /// /// Encode string in base64 format. /// @@ -353,7 +358,7 @@ namespace {{packageName}}.Client { 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 diff --git a/modules/swagger-codegen/src/main/resources/csharp/ApiException.mustache b/modules/swagger-codegen/src/main/resources/csharp/ApiException.mustache index 8e56fb31f43..e6185abc162 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/ApiException.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/ApiException.mustache @@ -12,18 +12,18 @@ namespace {{packageName}}.Client /// /// 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 {{#supportsAsync}}dynamic{{/supportsAsync}}{{^supportsAsync}}object{{/supportsAsync}} ErrorContent { get; private set; } - + /// /// Initializes a new instance of the class. /// public ApiException() {} - + /// /// Initializes a new instance of the class. /// @@ -33,7 +33,7 @@ namespace {{packageName}}.Client { this.ErrorCode = errorCode; } - + /// /// Initializes a new instance of the class. /// @@ -46,5 +46,5 @@ namespace {{packageName}}.Client this.ErrorContent = errorContent; } } - + } diff --git a/modules/swagger-codegen/src/main/resources/csharp/ApiResponse.mustache b/modules/swagger-codegen/src/main/resources/csharp/ApiResponse.mustache index c4317c35b65..4b9f0a3a43c 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/ApiResponse.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/ApiResponse.mustache @@ -13,19 +13,19 @@ namespace {{packageName}}.Client /// /// 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. /// @@ -38,7 +38,7 @@ namespace {{packageName}}.Client this.Headers = headers; this.Data = data; } - + } - + } diff --git a/modules/swagger-codegen/src/main/resources/csharp/Configuration.mustache b/modules/swagger-codegen/src/main/resources/csharp/Configuration.mustache index 5a61114e2c4..6cec586b453 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/Configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/Configuration.mustache @@ -25,6 +25,7 @@ namespace {{packageName}}.Client /// 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, @@ -34,7 +35,8 @@ namespace {{packageName}}.Client Dictionary apiKeyPrefix = null, string tempFolderPath = null, string dateTimeFormat = null, - int timeout = 100000 + int timeout = 100000, + string userAgent = "{{#httpUserAgent}}{{.}}{{/httpUserAgent}}{{^httpUserAgent}}Swagger-Codegen/{{packageVersion}}/csharp{{/httpUserAgent}}" ) { setApiClientUsingDefault(apiClient); @@ -42,6 +44,7 @@ namespace {{packageName}}.Client Username = username; Password = password; AccessToken = accessToken; + UserAgent = userAgent; if (defaultHeader != null) DefaultHeader = defaultHeader; @@ -84,7 +87,7 @@ namespace {{packageName}}.Client { get { return ApiClient.RestClient.Timeout; } - set + set { if (ApiClient != null) ApiClient.RestClient.Timeout = value; @@ -146,6 +149,12 @@ namespace {{packageName}}.Client _defaultHeaderMap.Add(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). /// @@ -211,7 +220,7 @@ namespace {{packageName}}.Client } // create the directory if it does not exist - if (!Directory.Exists(value)) + if (!Directory.Exists(value)) Directory.CreateDirectory(value); // check if the path contains directory separator at the end diff --git a/modules/swagger-codegen/src/main/resources/csharp/api.mustache b/modules/swagger-codegen/src/main/resources/csharp/api.mustache index 5793f18e448..e5b497b31e2 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/api.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/api.mustache @@ -25,10 +25,10 @@ namespace {{packageName}}.Api /// {{notes}} /// /// Thrown when fails to make API call - {{#allParams}}/// {{description}} + {{#allParams}}/// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}} {{/allParams}}/// {{#returnType}}{{returnType}}{{/returnType}} {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} {{operationId}} ({{#allParams}}{{{dataType}}} {{paramName}}{{^required}}{{#optionalMethodArgument}} = null{{/optionalMethodArgument}}{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); - + /// /// {{summary}} /// @@ -36,7 +36,7 @@ namespace {{packageName}}.Api /// {{notes}} /// /// Thrown when fails to make API call - {{#allParams}}/// {{description}} + {{#allParams}}/// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}} {{/allParams}}/// ApiResponse of {{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}Object(void){{/returnType}} ApiResponse<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Object{{/returnType}}> {{operationId}}WithHttpInfo ({{#allParams}}{{{dataType}}} {{paramName}}{{^required}}{{#optionalMethodArgument}} = null{{/optionalMethodArgument}}{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); {{/operation}} @@ -51,7 +51,7 @@ namespace {{packageName}}.Api /// {{notes}} /// /// Thrown when fails to make API call - {{#allParams}}/// {{description}} + {{#allParams}}/// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}} {{/allParams}}/// Task of {{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}void{{/returnType}} {{#returnType}}System.Threading.Tasks.Task<{{{returnType}}}>{{/returnType}}{{^returnType}}System.Threading.Tasks.Task{{/returnType}} {{operationId}}Async ({{#allParams}}{{{dataType}}} {{paramName}}{{^required}}{{#optionalMethodArgument}} = null{{/optionalMethodArgument}}{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); @@ -62,14 +62,14 @@ namespace {{packageName}}.Api /// {{notes}} /// /// Thrown when fails to make API call - {{#allParams}}/// {{description}} + {{#allParams}}/// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}} {{/allParams}}/// Task of ApiResponse{{#returnType}} ({{returnType}}){{/returnType}} System.Threading.Tasks.Task> {{operationId}}AsyncWithHttpInfo ({{#allParams}}{{{dataType}}} {{paramName}}{{^required}}{{#optionalMethodArgument}} = null{{/optionalMethodArgument}}{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); {{/operation}} #endregion Asynchronous Operations {{/supportsAsync}} } - + /// /// Represents a collection of functions to interact with the API endpoints /// @@ -82,8 +82,14 @@ namespace {{packageName}}.Api public {{classname}}(String basePath) { this.Configuration = new Configuration(new ApiClient(basePath)); + + // ensure API client has configuration ready + if (Configuration.ApiClient.Configuration == null) + { + this.Configuration.ApiClient.Configuration = this.Configuration; + } } - + /// /// Initializes a new instance of the class /// using Configuration object @@ -93,9 +99,15 @@ namespace {{packageName}}.Api public {{classname}}(Configuration configuration = null) { if (configuration == null) // use the default one in Configuration - this.Configuration = Configuration.Default; + this.Configuration = Configuration.Default; else this.Configuration = configuration; + + // ensure API client has configuration ready + if (Configuration.ApiClient.Configuration == null) + { + this.Configuration.ApiClient.Configuration = this.Configuration; + } } /// @@ -116,7 +128,7 @@ namespace {{packageName}}.Api { // do nothing } - + /// /// Gets or sets the configuration object /// @@ -144,13 +156,13 @@ namespace {{packageName}}.Api { this.Configuration.AddDefaultHeader(key, value); } - + {{#operation}} /// /// {{summary}} {{notes}} /// /// Thrown when fails to make API call - {{#allParams}}/// {{description}} + {{#allParams}}/// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}} {{/allParams}}/// {{#returnType}}{{returnType}}{{/returnType}} public {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} {{operationId}} ({{#allParams}}{{{dataType}}} {{paramName}}{{^required}}{{#optionalMethodArgument}} = null{{/optionalMethodArgument}}{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) { @@ -162,7 +174,7 @@ namespace {{packageName}}.Api /// {{summary}} {{notes}} /// /// Thrown when fails to make API call - {{#allParams}}/// {{description}} + {{#allParams}}/// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}} {{/allParams}}/// ApiResponse of {{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}Object(void){{/returnType}} public ApiResponse<{{#returnType}} {{{returnType}}} {{/returnType}}{{^returnType}}Object{{/returnType}}> {{operationId}}WithHttpInfo ({{#allParams}}{{{dataType}}} {{paramName}}{{^required}}{{#optionalMethodArgument}} = null{{/optionalMethodArgument}}{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) { @@ -171,9 +183,9 @@ namespace {{packageName}}.Api if ({{paramName}} == null) throw new ApiException(400, "Missing required parameter '{{paramName}}' when calling {{classname}}->{{operationId}}"); {{/required}}{{/allParams}} - + var localVarPath = "{{path}}"; - + var localVarPathParams = new Dictionary(); var localVarQueryParams = new Dictionary(); var localVarHeaderParams = new Dictionary(Configuration.DefaultHeader); @@ -228,7 +240,7 @@ namespace {{packageName}}.Api // http basic authentication required if (!String.IsNullOrEmpty(Configuration.Username) || !String.IsNullOrEmpty(Configuration.Password)) { - localVarHeaderParams["Authorization"] = "Basic " + Base64Encode(Configuration.Username + ":" + Configuration.Password); + localVarHeaderParams["Authorization"] = "Basic " + ApiClient.Base64Encode(Configuration.Username + ":" + Configuration.Password); }{{/isBasic}}{{#isOAuth}} // oauth required if (!String.IsNullOrEmpty(Configuration.AccessToken)) @@ -236,19 +248,19 @@ namespace {{packageName}}.Api localVarHeaderParams["Authorization"] = "Bearer " + Configuration.AccessToken; }{{/isOAuth}} {{/authMethods}} - + // make the HTTP request - IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, + IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, Method.{{httpMethod}}, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; - + if (localVarStatusCode >= 400) throw new ApiException (localVarStatusCode, "Error calling {{operationId}}: " + localVarResponse.Content, localVarResponse.Content); else if (localVarStatusCode == 0) throw new ApiException (localVarStatusCode, "Error calling {{operationId}}: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); - + {{#returnType}}return new ApiResponse<{{{returnType}}}>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), ({{{returnType}}}) Configuration.ApiClient.Deserialize(localVarResponse, typeof({{#returnContainer}}{{{returnContainer}}}{{/returnContainer}}{{^returnContainer}}{{{returnType}}}{{/returnContainer}})));{{/returnType}} @@ -262,7 +274,7 @@ namespace {{packageName}}.Api /// {{summary}} {{notes}} /// /// Thrown when fails to make API call - {{#allParams}}/// {{description}} + {{#allParams}}/// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}} {{/allParams}}/// Task of {{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}void{{/returnType}} {{#returnType}}public async System.Threading.Tasks.Task<{{{returnType}}}>{{/returnType}}{{^returnType}}public async System.Threading.Tasks.Task{{/returnType}} {{operationId}}Async ({{#allParams}}{{{dataType}}} {{paramName}}{{^required}}{{#optionalMethodArgument}} = null{{/optionalMethodArgument}}{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) { @@ -275,16 +287,16 @@ namespace {{packageName}}.Api /// {{summary}} {{notes}} /// /// Thrown when fails to make API call - {{#allParams}}/// {{description}} + {{#allParams}}/// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}} {{/allParams}}/// Task of ApiResponse{{#returnType}} ({{returnType}}){{/returnType}} public async System.Threading.Tasks.Task> {{operationId}}AsyncWithHttpInfo ({{#allParams}}{{{dataType}}} {{paramName}}{{^required}}{{#optionalMethodArgument}} = null{{/optionalMethodArgument}}{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) { {{#allParams}}{{#required}}// verify the required parameter '{{paramName}}' is set if ({{paramName}} == null) throw new ApiException(400, "Missing required parameter '{{paramName}}' when calling {{operationId}}"); {{/required}}{{/allParams}} - + var localVarPath = "{{path}}"; - + var localVarPathParams = new Dictionary(); var localVarQueryParams = new Dictionary(); var localVarHeaderParams = new Dictionary(Configuration.DefaultHeader); @@ -340,7 +352,7 @@ namespace {{packageName}}.Api // http basic authentication required if (!String.IsNullOrEmpty(Configuration.Username) || !String.IsNullOrEmpty(Configuration.Password)) { - localVarHeaderParams["Authorization"] = "Basic " + Base64Encode(Configuration.Username + ":" + Configuration.Password); + localVarHeaderParams["Authorization"] = "Basic " + ApiClient.Base64Encode(Configuration.Username + ":" + Configuration.Password); }{{/isBasic}}{{#isOAuth}} // oauth required if (!String.IsNullOrEmpty(Configuration.AccessToken)) @@ -350,12 +362,12 @@ namespace {{packageName}}.Api {{/authMethods}} // make the HTTP request - IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath, - Method.{{httpMethod}}, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, + IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath, + Method.{{httpMethod}}, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; - + if (localVarStatusCode >= 400) throw new ApiException (localVarStatusCode, "Error calling {{operationId}}: " + localVarResponse.Content, localVarResponse.Content); else if (localVarStatusCode == 0) 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 d44ebca31b5..5f5a03aa612 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/api_test.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/api_test.mustache @@ -64,7 +64,7 @@ namespace {{packageName}}.Test {{#allParams}}{{{dataType}}} {{paramName}} = null; // TODO: replace null with proper value {{/allParams}} {{#returnType}}var response = {{/returnType}}instance.{{operationId}}({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); - {{#returnType}}Assert.IsInstanceOf<{{{returnType}}}> (response, "response is {{{returnType}}}");{{/returnType}} + {{#returnType}}Assert.IsInstanceOf<{{{returnType}}}> (response, "response is {{{returnType}}}");{{/returnType}} } {{/operation}}{{/operations}} } diff --git a/modules/swagger-codegen/src/main/resources/csharp/compile.mustache b/modules/swagger-codegen/src/main/resources/csharp/compile.mustache index 2c50dbda186..76b94cad5a1 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/compile.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/compile.mustache @@ -1,12 +1,14 @@ -@echo off - -{{#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 vendor/packages.config -o vendor - -copy vendor/Newtonsoft.Json.8.0.2/lib/{{targetFrameworkNuget}}/Newtonsoft.Json.dll bin/Newtonsoft.Json.dll -copy vendor/RestSharp.105.1.0/lib/{{targetFrameworkNuget}}/RestSharp.dll bin/RestSharp.dll - -%CSCPATH%\csc /reference:bin/Newtonsoft.Json.dll;bin/RestSharp.dll /target:library /out:bin/{{packageName}}.dll /recurse:src\*.cs /doc:bin/{{packageName}}.xml +@echo off + +{{#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 vendor/packages.config -o vendor + +if not exist ".\bin" mkdir bin + +copy vendor\Newtonsoft.Json.8.0.2\lib\{{targetFrameworkNuget}}\Newtonsoft.Json.dll bin\Newtonsoft.Json.dll +copy vendor\RestSharp.105.1.0\lib\{{targetFrameworkNuget}}\RestSharp.dll bin\RestSharp.dll + +%CSCPATH%\csc /reference:bin\Newtonsoft.Json.dll;bin\RestSharp.dll /target:library /out:bin\{{packageName}}.dll /recurse:src\*.cs /doc:bin\{{packageName}}.xml diff --git a/modules/swagger-codegen/src/main/resources/csharp/enumClass.mustache b/modules/swagger-codegen/src/main/resources/csharp/enumClass.mustache index 3a2a93cd109..d882e33595c 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/enumClass.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/enumClass.mustache @@ -1,6 +1,6 @@ -public enum {{vendorExtensions.plainDatatypeWithEnum}} { + public enum {{vendorExtensions.plainDatatypeWithEnum}} { {{#allowableValues}}{{#enumVars}} [EnumMember(Value = "{{jsonname}}")] {{name}}{{^-last}}, {{/-last}}{{#-last}}{{/-last}}{{/enumVars}}{{/allowableValues}} - } \ No newline at end of file + } diff --git a/modules/swagger-codegen/src/main/resources/csharp/git_push.sh.mustache b/modules/swagger-codegen/src/main/resources/csharp/git_push.sh.mustache new file mode 100755 index 00000000000..a9b0f28edfb --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/csharp/git_push.sh.mustache @@ -0,0 +1,52 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 swagger-petstore-perl "minor update" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 + +if [ "$git_user_id" = "" ]; then + git_user_id="{{{gitUserId}}}" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="{{{gitRepoId}}}" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="{{{releaseNote}}}" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=`git remote` +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git crediential in your environment." + git remote add origin https://github.com/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:${GIT_TOKEN}@github.com/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://github.com/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' + diff --git a/modules/swagger-codegen/src/main/resources/csharp/gitignore.mustache b/modules/swagger-codegen/src/main/resources/csharp/gitignore.mustache new file mode 100644 index 00000000000..56fef626922 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/csharp/gitignore.mustache @@ -0,0 +1,185 @@ +# Ref: https://gist.github.com/kmorcinek/2710267 +# Download this file using PowerShell v3 under Windows with the following comand +# Invoke-WebRequest https://gist.githubusercontent.com/kmorcinek/2710267/raw/ -OutFile .gitignore + +# User-specific files +*.suo +*.user +*.sln.docstates + +# Build results + +[Dd]ebug/ +[Rr]elease/ +x64/ +build/ +[Bb]in/ +[Oo]bj/ + +# NuGet Packages +*.nupkg +# The packages folder can be ignored because of Package Restore +**/packages/* +# except build/, which is used as an MSBuild target. +!**/packages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/packages/repositories.config + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +*_i.c +*_p.c +*.ilk +*.meta +*.obj +*.pch +*.pdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.log +*.scc + +# OS generated files # +.DS_Store* +ehthumbs.db +Icon? +Thumbs.db + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opensdf +*.sdf +*.cachefile + +# Visual Studio profiler +*.psess +*.vsp +*.vspx + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# NCrunch +*.ncrunch* +.*crunch*.local.xml + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.Publish.xml + +# Windows Azure Build Output +csx +*.build.csdef + +# Windows Store app package directory +AppPackages/ + +# Others +sql/ +*.Cache +ClientBin/ +[Ss]tyle[Cc]op.* +~$* +*~ +*.dbmdl +*.[Pp]ublish.xml +*.pfx +*.publishsettings +modulesbin/ +tempbin/ + +# EPiServer Site file (VPP) +AppData/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file to a newer +# Visual Studio version. Backup files are not needed, because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm + +# vim +*.txt~ +*.swp +*.swo + + # svn + .svn + + # SQL Server files + **/App_Data/*.mdf + **/App_Data/*.ldf + **/App_Data/*.sdf + + + #LightSwitch generated files + GeneratedArtifacts/ + _Pvt_Extensions/ + ModelManifest.xml + + # ========================= + # Windows detritus + # ========================= + + # Windows image file caches + Thumbs.db + ehthumbs.db + + # Folder config file + Desktop.ini + + # Recycle Bin used on file shares + $RECYCLE.BIN/ + + # Mac desktop service store files + .DS_Store + + # SASS Compiler cache + .sass-cache + + # Visual Studio 2014 CTP + **/*.sln.ide diff --git a/modules/swagger-codegen/src/main/resources/csharp/model.mustache b/modules/swagger-codegen/src/main/resources/csharp/model.mustache index 86589816d12..a3c289cdbb3 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/model.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/model.mustache @@ -19,10 +19,14 @@ namespace {{packageName}}.Model [DataContract] public partial class {{classname}} : {{#parent}}{{{parent}}}, {{/parent}} IEquatable<{{classname}}> { {{#vars}}{{#isEnum}} - + + /// + /// {{^description}}Gets or Sets {{{name}}}{{/description}}{{#description}}{{{description}}}{{/description}} + /// {{#description}} + /// {{{description}}}{{/description}} [JsonConverter(typeof(StringEnumConverter))] - {{>enumClass}}{{/isEnum}}{{#items.isEnum}}{{#items}} - {{>enumClass}}{{/items}}{{/items.isEnum}}{{/vars}} +{{>enumClass}}{{/isEnum}}{{#items.isEnum}}{{#items}} +{{>enumClass}}{{/items}}{{/items.isEnum}}{{/vars}} {{#vars}}{{#isEnum}} /// /// {{^description}}Gets or Sets {{{name}}}{{/description}}{{#description}}{{{description}}}{{/description}} @@ -37,7 +41,7 @@ namespace {{packageName}}.Model /// {{#vars}}{{^isReadOnly}} /// {{#description}}{{description}}{{/description}}{{^description}}{{name}}{{/description}}{{#required}} (required){{/required}}{{#defaultValue}} (default to {{defaultValue}}){{/defaultValue}}. {{/isReadOnly}}{{/vars}} - public {{classname}}({{#vars}}{{^isReadOnly}}{{{datatypeWithEnum}}} {{name}} = null{{#hasMore}}, {{/hasMore}}{{/isReadOnly}}{{/vars}}) + public {{classname}}({{#vars}}{{^isReadOnly}}{{{datatypeWithEnum}}} {{name}} = null{{#hasMoreNonReadOnly}}, {{/hasMoreNonReadOnly}}{{/isReadOnly}}{{/vars}}) { {{#vars}}{{^isReadOnly}}{{#required}}// to ensure "{{name}}" is required (not null) if ({{name}} == null) @@ -60,12 +64,12 @@ namespace {{packageName}}.Model {{/defaultValue}}{{^defaultValue}}this.{{name}} = {{name}}; {{/defaultValue}}{{/required}}{{/isReadOnly}}{{/vars}} } - + {{#vars}}{{^isEnum}} /// - /// {{^description}}Gets or Sets {{{name}}}{{/description}}{{#description}}{{{description}}}{{/description}} + /// {{^description}}Gets or Sets {{{name}}}{{/description}}{{#description}}{{description}}{{/description}} /// {{#description}} - /// {{{description}}}{{/description}} + /// {{description}}{{/description}} [DataMember(Name="{{baseName}}", EmitDefaultValue={{emitDefaultValue}})] public {{{datatype}}} {{name}} { get; {{#isReadOnly}}private {{/isReadOnly}}set; } {{/isEnum}}{{/vars}} @@ -82,7 +86,7 @@ namespace {{packageName}}.Model sb.Append("}\n"); return sb.ToString(); } - + /// /// Returns the JSON string presentation of the object /// diff --git a/modules/swagger-codegen/src/main/resources/csharp/model_test.mustache b/modules/swagger-codegen/src/main/resources/csharp/model_test.mustache index c2e8d948050..0d20b9f03a3 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/model_test.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/model_test.mustache @@ -33,7 +33,7 @@ namespace {{packageName}}.Test { instance = new {{classname}}(); } - + /// /// Clean up after each test /// @@ -41,7 +41,7 @@ namespace {{packageName}}.Test public void Cleanup() { - } + } /// /// Test an instance of {{classname}} @@ -54,12 +54,12 @@ namespace {{packageName}}.Test {{#vars}} /// - /// Test the property '{{name}}' + /// Test the property '{{name}}' /// [Test] public void {{name}}Test() { - // TODO: unit test for the property '{{name}}' + // TODO: unit test for the property '{{name}}' } {{/vars}} diff --git a/modules/swagger-codegen/src/main/resources/dart/apilib.mustache b/modules/swagger-codegen/src/main/resources/dart/apilib.mustache index f9699315566..178fe027e39 100644 --- a/modules/swagger-codegen/src/main/resources/dart/apilib.mustache +++ b/modules/swagger-codegen/src/main/resources/dart/apilib.mustache @@ -18,5 +18,5 @@ part 'auth/http_basic_auth.dart'; {{#apiInfo}}{{#apis}}part 'api/{{classVarName}}_api.dart'; {{/apis}}{{/apiInfo}} -{{#models}}{{#model}}part 'model/{{classVarName}}.dart'; -{{/model}}{{/models}} \ No newline at end of file +{{#models}}{{#model}}part 'model/{{classFilename}}.dart'; +{{/model}}{{/models}} diff --git a/modules/swagger-codegen/src/main/resources/dart/git_push.sh.mustache b/modules/swagger-codegen/src/main/resources/dart/git_push.sh.mustache new file mode 100755 index 00000000000..e153ce23ecf --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/dart/git_push.sh.mustache @@ -0,0 +1,52 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 swagger-petstore-perl "minor update" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 + +if [ "$git_user_id" = "" ]; then + git_user_id="{{{gitUserId}}}" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="{{{gitRepoId}}}" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="{{{releaseNote}}}" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=`git remote` +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git crediential in your environment." + git remote add origin https://github.com/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:${GIT_TOKEN}@github.com/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://github.com/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' + diff --git a/modules/swagger-codegen/src/main/resources/dart/gitignore.mustache b/modules/swagger-codegen/src/main/resources/dart/gitignore.mustache new file mode 100644 index 00000000000..7c280441649 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/dart/gitignore.mustache @@ -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/modules/swagger-codegen/src/main/resources/flash/.gitignore b/modules/swagger-codegen/src/main/resources/flash/.gitignore new file mode 100644 index 00000000000..f112f7fb78f --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/flash/.gitignore @@ -0,0 +1,11 @@ +# Build and Release Folders +bin/ +bin-debug/ +bin-release/ + +# Other files and folders +.settings/ + +# Project files, i.e. `.project`, `.actionScriptProperties` and `.flexProperties` +# should NOT be excluded as they contain compiler settings and other important +# information for Eclipse / Flash Builder. diff --git a/modules/swagger-codegen/src/main/resources/go/api.mustache b/modules/swagger-codegen/src/main/resources/go/api.mustache index 49b7f92693e..d1cf877cd43 100644 --- a/modules/swagger-codegen/src/main/resources/go/api.mustache +++ b/modules/swagger-codegen/src/main/resources/go/api.mustache @@ -12,18 +12,22 @@ import ( ) type {{classname}} struct { - basePath string + Configuration Configuration } func New{{classname}}() *{{classname}}{ + configuration := NewConfiguration() return &{{classname}} { - basePath: "{{basePath}}", + Configuration: *configuration, } } func New{{classname}}WithBasePath(basePath string) *{{classname}}{ + configuration := NewConfiguration() + configuration.BasePath = basePath + return &{{classname}} { - basePath: basePath, + Configuration: *configuration, } } @@ -37,7 +41,7 @@ func New{{classname}}WithBasePath(basePath string) *{{classname}}{ //func (a {{classname}}) {{nickname}} ({{#allParams}}{{paramName}} {{{dataType}}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) ({{#returnType}}{{{returnType}}}, {{/returnType}}error) { func (a {{classname}}) {{nickname}} ({{#allParams}}{{paramName}} {{{dataType}}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) ({{#returnType}}{{{returnType}}}, {{/returnType}}error) { - _sling := sling.New().{{httpMethod}}(a.basePath) + _sling := sling.New().{{httpMethod}}(a.Configuration.BasePath) // create path and map variables path := "{{basePathWithoutHost}}{{path}}" diff --git a/modules/swagger-codegen/src/main/resources/go/configuration.mustache b/modules/swagger-codegen/src/main/resources/go/configuration.mustache new file mode 100644 index 00000000000..bf3a8f92bed --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/go/configuration.mustache @@ -0,0 +1,25 @@ +package {{packageName}} + +import ( + +) + +type Configuration struct { + UserName string `json:"userName,omitempty"` + ApiKey string `json:"apiKey,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"` +} + +func NewConfiguration() *Configuration { + return &Configuration{ + BasePath: "{{basePath}}", + UserName: "", + Debug: false, + } +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/go/git_push.sh.mustache b/modules/swagger-codegen/src/main/resources/go/git_push.sh.mustache new file mode 100755 index 00000000000..e153ce23ecf --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/go/git_push.sh.mustache @@ -0,0 +1,52 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 swagger-petstore-perl "minor update" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 + +if [ "$git_user_id" = "" ]; then + git_user_id="{{{gitUserId}}}" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="{{{gitRepoId}}}" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="{{{releaseNote}}}" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=`git remote` +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git crediential in your environment." + git remote add origin https://github.com/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:${GIT_TOKEN}@github.com/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://github.com/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' + diff --git a/modules/swagger-codegen/src/main/resources/go/gitignore.mustache b/modules/swagger-codegen/src/main/resources/go/gitignore.mustache new file mode 100644 index 00000000000..daf913b1b34 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/go/gitignore.mustache @@ -0,0 +1,24 @@ +# Compiled Object files, Static and Dynamic libs (Shared Objects) +*.o +*.a +*.so + +# Folders +_obj +_test + +# Architecture specific extensions/prefixes +*.[568vq] +[568vq].out + +*.cgo1.go +*.cgo2.c +_cgo_defun.c +_cgo_gotypes.go +_cgo_export.* + +_testmain.go + +*.exe +*.test +*.prof diff --git a/modules/swagger-codegen/src/main/resources/objc/ApiClient-body.mustache b/modules/swagger-codegen/src/main/resources/objc/ApiClient-body.mustache index 2fcd91ac323..142e14a9e80 100644 --- a/modules/swagger-codegen/src/main/resources/objc/ApiClient-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/ApiClient-body.mustache @@ -53,6 +53,10 @@ static void (^reachabilityChangeBlock)(int); cacheEnabled = enabled; } ++(void) setReachabilityStatus:(AFNetworkReachabilityStatus)status { + reachabilityStatus = status; +} + - (void)setHeaderValue:(NSString*) value forKey:(NSString*) forKey { [self.requestSerializer setValue:value forHTTPHeaderField:forKey]; @@ -238,6 +242,10 @@ static void (^reachabilityChangeBlock)(int); return reachabilityStatus; } ++(bool) getOfflineState { + return offlineState; +} + +(void) setReachabilityChangeBlock:(void(^)(int))changeBlock { reachabilityChangeBlock = changeBlock; } @@ -708,11 +716,11 @@ static void (^reachabilityChangeBlock)(int); for (NSString *auth in authSettings) { NSDictionary *authSetting = [[config authSettings] objectForKey:auth]; - if (authSetting) { - if ([authSetting[@"in"] isEqualToString:@"header"]) { + if (authSetting) { // auth setting is set only if the key is non-empty + if ([authSetting[@"in"] isEqualToString:@"header"] && [authSetting[@"key"] length] != 0) { [headersWithAuth setObject:authSetting[@"value"] forKey:authSetting[@"key"]]; } - else if ([authSetting[@"in"] isEqualToString:@"query"]) { + else if ([authSetting[@"in"] isEqualToString:@"query"] && [authSetting[@"key"] length] != 0) { [querysWithAuth setObject:authSetting[@"value"] forKey:authSetting[@"key"]]; } } 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 41f964044a1..a039e7e168e 100644 --- a/modules/swagger-codegen/src/main/resources/objc/ApiClient-header.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/ApiClient-header.mustache @@ -14,6 +14,7 @@ {{#models}}{{#model}}#import "{{classname}}.h" {{/model}}{{/models}} +{{^models}}#import "{{classPrefix}}Object.h"{{/models}} @class {{classPrefix}}Configuration; @@ -64,6 +65,20 @@ extern NSString *const {{classPrefix}}ResponseObjectErrorKey; */ +(void) setOfflineState:(BOOL) state; +/** + * Gets if the client is unreachable + * + * @return The client offline state + */ ++(bool) getOfflineState; + +/** + * Sets the client reachability, this may be overridden by the reachability manager if reachability changes + * + * @param The client reachability. + */ ++(void) setReachabilityStatus:(AFNetworkReachabilityStatus) status; + /** * Gets the client reachability * diff --git a/modules/swagger-codegen/src/main/resources/objc/Configuration-body.mustache b/modules/swagger-codegen/src/main/resources/objc/Configuration-body.mustache index 167b05aef1f..4f5442ed213 100644 --- a/modules/swagger-codegen/src/main/resources/objc/Configuration-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/Configuration-body.mustache @@ -29,6 +29,7 @@ self.host = @"{{basePath}}"; self.username = @""; self.password = @""; + self.accessToken= @""; self.tempFolderPath = nil; self.debug = NO; self.verifySSL = YES; @@ -42,18 +43,23 @@ #pragma mark - Instance Methods - (NSString *) getApiKeyWithPrefix:(NSString *)key { - if ([self.apiKeyPrefix objectForKey:key] && [self.apiKey objectForKey:key]) { + if ([self.apiKeyPrefix objectForKey:key] && [self.apiKey objectForKey:key] != (id)[NSNull null] && [[self.apiKey objectForKey:key] length] != 0) { // both api key prefix and api key are set return [NSString stringWithFormat:@"%@ %@", [self.apiKeyPrefix objectForKey:key], [self.apiKey objectForKey:key]]; } - else if ([self.apiKey objectForKey:key]) { + else if ([self.apiKey objectForKey:key] != (id)[NSNull null] && [[self.apiKey objectForKey:key] length] != 0) { // only api key, no api key prefix return [NSString stringWithFormat:@"%@", [self.apiKey objectForKey:key]]; } - else { + else { // return empty string if nothing is set return @""; } } - (NSString *) getBasicAuthToken { + // return empty string if username and password are empty + if (self.username.length == 0 && self.password.length == 0){ + return @""; + } + NSString *basicAuthCredentials = [NSString stringWithFormat:@"%@:%@", self.username, self.password]; NSData *data = [basicAuthCredentials dataUsingEncoding:NSUTF8StringEncoding]; basicAuthCredentials = [NSString stringWithFormat:@"Basic %@", [data base64EncodedStringWithOptions:0]]; @@ -61,6 +67,15 @@ return basicAuthCredentials; } +- (NSString *) getAccessToken { + if (self.accessToken.length == 0) { // token not set, return empty string + return @""; + } + else { + return [NSString stringWithFormat:@"BEARER %@", self.accessToken]; + } +} + #pragma mark - Setter Methods - (void) setApiKey:(NSString *)apiKey forApiKeyIdentifier:(NSString *)identifier { @@ -126,6 +141,15 @@ @"value": [self getBasicAuthToken] }, {{/isBasic}} +{{#isOAuth}} + @"{{name}}": + @{ + @"type": @"oauth", + @"in": @"header", + @"key": @"Authorization", + @"value": [self getAccessToken] + }, +{{/isOAuth}} {{/authMethods}} }; } diff --git a/modules/swagger-codegen/src/main/resources/objc/Configuration-header.mustache b/modules/swagger-codegen/src/main/resources/objc/Configuration-header.mustache index 9abe135bc47..b77ddfe5dee 100644 --- a/modules/swagger-codegen/src/main/resources/objc/Configuration-header.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/Configuration-header.mustache @@ -46,6 +46,11 @@ */ @property (nonatomic) NSString *password; +/** + * Access token for OAuth + */ +@property (nonatomic) NSString *accessToken; + /** * Temp folder for file download */ @@ -132,6 +137,11 @@ */ - (NSString *) getBasicAuthToken; +/** + * Gets OAuth access token + */ +- (NSString *) getAccessToken; + /** * Gets Authentication Setings */ diff --git a/modules/swagger-codegen/src/main/resources/objc/README.mustache b/modules/swagger-codegen/src/main/resources/objc/README.mustache index 30a8927c41a..2e6ffe2f060 100644 --- a/modules/swagger-codegen/src/main/resources/objc/README.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/README.mustache @@ -1,20 +1,147 @@ # {{podName}} +{{#appDescription}} +{{{appDescription}}} +{{/appDescription}} + +This ObjC package is automatically generated by the [Swagger Codegen](https://github.com/swagger-api/swagger-codegen) project: + +- API version: {{appVersion}} +- Package version: {{artifactVersion}} +- Build date: {{generatedDate}} +- Build package: {{generatorClass}} +{{#infoUrl}} +For more information, please visit [{{{infoUrl}}}]({{{infoUrl}}}) +{{/infoUrl}} + ## Requirements -The API client library requires ARC (Automatic Reference Counting) to be enabled in your Xcode project. +The SDK requires [**ARC (Automatic Reference Counting)**](http://stackoverflow.com/questions/7778356/how-to-enable-disable-automatic-reference-counting) to be enabled in the Xcode project. -## Installation +## Installation & Usage +### Install from Github using [CocoaPods](https://cocoapods.org/) -To install it, put the API client library in your project and then simply add the following line to your Podfile: +Add the following to the Podfile: ```ruby -pod "{{podName}}", :path => "/path/to/lib" +pod '{{podName}}', :git => 'https://github.com/{{gitUserId}}/{{gitRepoId}}.git' +``` + +To specify a particular branch, append `, :branch => 'branch-name-here'` + +To specify a particular commit, append `, :commit => '11aa22'` + +### Install from local path using [CocoaPods](https://cocoapods.org/) + +Put the SDK under your project folder (e.g. /path/to/objc_project/Vendor/{{podName}}) and then add the following to the Podfile: + +```ruby +pod '{{podName}}', :path => 'Vendor/{{podName}}' +``` + +### Usage + +Import the following: +```objc +#import <{{podName}}/{{{classPrefix}}}ApiClient.h> +#import <{{podName}}/{{{classPrefix}}}Configuration.h> +// load models +{{#models}}{{#model}}#import <{{podName}}/{{{classname}}}.h> +{{/model}}{{/models}}// load API classes for accessing endpoints +{{#apiInfo}}{{#apis}}#import <{{podName}}/{{{classname}}}.h> +{{/apis}}{{/apiInfo}} ``` ## 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 multi-threaded environment to avoid any potential issue. + +## Getting Started + +Please follow the [installation procedure](#installation--usage) and then run the following: + +```objc +{{#apiInfo}}{{#apis}}{{#-first}}{{#operations}}{{#operation}}{{#-first}} +{{#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}} + +@try +{ + {{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); + } + }]; +} +@catch (NSException *exception) +{ + NSLog(@"Exception when calling {{classname}}->{{operationId}}: %@ ", exception.name); + NSLog(@"Reason: %@ ", exception.reason); +} +{{/-first}}{{/operation}}{{/operations}}{{/-first}}{{/apis}}{{/apiInfo}} +``` + +## Documentation for API Endpoints + +All URIs are relative to *{{basePath}}* + +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 + +{{#models}}{{#model}} - [{{{classname}}}]({{modelDocPath}}{{{classname}}}.md) +{{/model}}{{/models}} + +## Documentation For Authorization + +{{^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}}} +- **Location**: {{#isKeyInQuery}}URL query string{{/isKeyInQuery}}{{#isKeyInHeader}}HTTP header{{/isKeyInHeader}} +{{/isApiKey}} +{{#isBasic}}- **Type**: HTTP basic authentication +{{/isBasic}} +{{#isOAuth}}- **Type**: OAuth +- **Flow**: {{{flow}}} +- **Authorizatoin URL**: {{{authorizationUrl}}} +- **Scopes**: {{^scopes}}N/A{{/scopes}} +{{#scopes}} - **{{{scope}}}**: {{{description}}} +{{/scopes}} +{{/isOAuth}} + +{{/authMethods}} ## Author diff --git a/modules/swagger-codegen/src/main/resources/objc/api-body.mustache b/modules/swagger-codegen/src/main/resources/objc/api-body.mustache index 0aa3c7ce7ab..2a7880d8367 100644 --- a/modules/swagger-codegen/src/main/resources/objc/api-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/api-body.mustache @@ -40,7 +40,6 @@ static {{classname}}* singletonAPI = nil; #pragma mark - +({{classname}}*) apiWithHeader:(NSString*)headerValue key:(NSString*)key { - if (singletonAPI == nil) { singletonAPI = [[{{classname}} alloc] init]; [singletonAPI addHeader:headerValue forKey:key]; @@ -49,7 +48,6 @@ static {{classname}}* singletonAPI = nil; } +({{classname}}*) sharedAPI { - if (singletonAPI == nil) { singletonAPI = [[{{classname}} alloc] init]; } @@ -75,21 +73,22 @@ static {{classname}}* singletonAPI = nil; /// /// {{{summary}}} /// {{{notes}}} -/// {{#allParams}} @param {{paramName}} {{{description}}} +/// {{#allParams}} @param {{paramName}} {{{description}}} {{^required}}(optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}} /// /// {{/allParams}} @returns {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} /// -(NSNumber*) {{#vendorExtensions.x-objc-operationId}}{{vendorExtensions.x-objc-operationId}}{{/vendorExtensions.x-objc-operationId}}{{^vendorExtensions.x-objc-operationId}}{{nickname}}{{#hasParams}}With{{vendorExtensions.firstParamAltName}}{{/hasParams}}{{^hasParams}}WithCompletionHandler: {{/hasParams}}{{/vendorExtensions.x-objc-operationId}}{{#allParams}}{{#secondaryParam}} {{paramName}}{{/secondaryParam}}: ({{{dataType}}}) {{paramName}}{{/allParams}} {{#hasParams}}completionHandler: {{/hasParams}}(void (^)({{#returnBaseType}}{{{returnType}}} output, {{/returnBaseType}}NSError* error)) handler { - - {{#allParams}}{{#required}} + {{#allParams}} + {{#required}} // verify the required parameter '{{paramName}}' is set if ({{paramName}} == nil) { [NSException raise:@"Invalid parameter" format:@"Missing the required parameter `{{paramName}}` when calling `{{nickname}}`"]; } - {{/required}}{{/allParams}} + {{/required}} + {{/allParams}} NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"{{path}}"]; // remove format in URL if needed @@ -98,13 +97,15 @@ static {{classname}}* singletonAPI = nil; } NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; - {{#pathParams}}if ({{paramName}} != nil) { + {{#pathParams}} + if ({{paramName}} != nil) { pathParams[@"{{baseName}}"] = {{paramName}}; } {{/pathParams}} NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; - {{#queryParams}}if ({{paramName}} != nil) { + {{#queryParams}} + if ({{paramName}} != nil) { {{#collectionFormat}} queryParams[@"{{baseName}}"] = [[{{classPrefix}}QueryParamCollection alloc] initWithValuesAndFormat: {{baseName}} format: @"{{collectionFormat}}"]; {{/collectionFormat}} @@ -112,12 +113,13 @@ static {{classname}}* singletonAPI = nil; } {{/queryParams}} NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; - - {{#headerParams}}if ({{paramName}} != nil) { + {{#headerParams}} + + if ({{paramName}} != nil) { headerParams[@"{{baseName}}"] = {{paramName}}; } - {{/headerParams}} + {{/headerParams}} // HTTP header `Accept` headerParams[@"Accept"] = [{{classPrefix}}ApiClient selectHeaderAccept:@[{{#produces}}@"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/produces}}]]; if ([headerParams[@"Accept"] length] == 0) { @@ -144,25 +146,20 @@ static {{classname}}* singletonAPI = nil; NSMutableDictionary *localVarFiles = [[NSMutableDictionary alloc] init]; {{#bodyParam}} bodyParam = {{paramName}}; - {{/bodyParam}}{{^bodyParam}} + {{/bodyParam}} + {{^bodyParam}} {{#formParams}} {{#notFile}} if ({{paramName}}) { formParams[@"{{baseName}}"] = {{paramName}}; } - {{/notFile}}{{#isFile}} + {{/notFile}} + {{#isFile}} localVarFiles[@"{{paramName}}"] = {{paramName}}; {{/isFile}} {{/formParams}} {{/bodyParam}} - {{#requiredParamCount}} - {{#requiredParams}} - if ({{paramName}} == nil) { - // error - } - {{/requiredParams}} - {{/requiredParamCount}} return [self.apiClient requestWithPath: resourcePath method: @"{{httpMethod}}" pathParams: pathParams diff --git a/modules/swagger-codegen/src/main/resources/objc/api_doc.mustache b/modules/swagger-codegen/src/main/resources/objc/api_doc.mustache new file mode 100644 index 00000000000..109128c1ca1 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/objc/api_doc.mustache @@ -0,0 +1,93 @@ +# {{classname}}{{#description}} +{{description}}{{/description}} + +All URIs are relative to *{{basePath}}* + +Method | HTTP request | Description +------------- | ------------- | ------------- +{{#operations}}{{#operation}}[**{{operationId}}**]({{classname}}.md#{{operationIdLowerCase}}) | **{{httpMethod}}** {{path}} | {{#summary}}{{summary}}{{/summary}} +{{/operation}}{{/operations}} + +{{#operations}} +{{#operation}} +# **{{{operationId}}}** +```objc +-(NSNumber*) {{#vendorExtensions.x-objc-operationId}}{{vendorExtensions.x-objc-operationId}}{{/vendorExtensions.x-objc-operationId}}{{^vendorExtensions.x-objc-operationId}}{{nickname}}{{#hasParams}}With{{vendorExtensions.firstParamAltName}}{{/hasParams}}{{^hasParams}}WithCompletionHandler: {{/hasParams}}{{/vendorExtensions.x-objc-operationId}}{{#allParams}}{{#secondaryParam}} + {{paramName}}{{/secondaryParam}}: ({{{dataType}}}) {{paramName}}{{/allParams}} + {{#hasParams}}completionHandler: {{/hasParams}}(void (^)({{#returnBaseType}}{{{returnType}}} output, {{/returnBaseType}}NSError* error)) handler; +``` + +{{{summary}}}{{#notes}} + +{{{notes}}}{{/notes}} + +### Example +```objc +{{#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}} + +@try +{ + {{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); + } + }]; +} +@catch (NSException *exception) +{ + NSLog(@"Exception when calling {{classname}}->{{operationId}}: %@ ", exception.name); + NSLog(@"Reason: %@ ", exception.reason); +} +``` + +### Parameters +{{^allParams}}This endpoint does not need any parameter.{{/allParams}}{{#allParams}}{{#-last}} +Name | Type | Description | Notes +------------- | ------------- | ------------- | -------------{{/-last}}{{/allParams}} +{{#allParams}} **{{paramName}}** | {{#isFile}}**{{dataType}}**{{/isFile}}{{#isPrimitiveType}}**{{dataType}}**{{/isPrimitiveType}}{{^isPrimitiveType}}{{^isFile}}[**{{dataType}}**]({{baseType}}.md){{/isFile}}{{/isPrimitiveType}}| {{description}} | {{^required}}[optional] {{/required}}{{#defaultValue}}[default to {{defaultValue}}]{{/defaultValue}} +{{/allParams}} + +### Return type + +{{#returnType}}{{#returnTypeIsPrimitive}}**{{{returnType}}}**{{/returnTypeIsPrimitive}}{{^returnTypeIsPrimitive}}[**{{{returnType}}}**]({{returnBaseType}}.md){{/returnTypeIsPrimitive}}{{/returnType}}{{^returnType}}void (empty response body){{/returnType}} + +### Authorization + +{{^authMethods}}No authorization required{{/authMethods}}{{#authMethods}}[{{{name}}}](../README.md#{{{name}}}){{^-last}}, {{/-last}}{{/authMethods}} + +### HTTP reuqest headers + + - **Content-Type**: {{#consumes}}{{mediaType}}{{#hasMore}}, {{/hasMore}}{{/consumes}}{{^consumes}}Not defined{{/consumes}} + - **Accept**: {{#produces}}{{mediaType}}{{#hasMore}}, {{/hasMore}}{{/produces}}{{^produces}}Not defined{{/produces}} + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +{{/operation}} +{{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/objc/git_push.sh.mustache b/modules/swagger-codegen/src/main/resources/objc/git_push.sh.mustache new file mode 100755 index 00000000000..e153ce23ecf --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/objc/git_push.sh.mustache @@ -0,0 +1,52 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 swagger-petstore-perl "minor update" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 + +if [ "$git_user_id" = "" ]; then + git_user_id="{{{gitUserId}}}" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="{{{gitRepoId}}}" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="{{{releaseNote}}}" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=`git remote` +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git crediential in your environment." + git remote add origin https://github.com/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:${GIT_TOKEN}@github.com/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://github.com/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' + diff --git a/modules/swagger-codegen/src/main/resources/objc/gitignore.mustache b/modules/swagger-codegen/src/main/resources/objc/gitignore.mustache new file mode 100644 index 00000000000..79d9331b6d4 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/objc/gitignore.mustache @@ -0,0 +1,53 @@ +# 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 + +# 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/modules/swagger-codegen/src/main/resources/objc/model_doc.mustache b/modules/swagger-codegen/src/main/resources/objc/model_doc.mustache new file mode 100644 index 00000000000..569550df372 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/objc/model_doc.mustache @@ -0,0 +1,11 @@ +{{#models}}{{#model}}# {{classname}} + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +{{#vars}}**{{name}}** | {{#isPrimitiveType}}**{{datatype}}**{{/isPrimitiveType}}{{^isPrimitiveType}}[**{{datatype}}**]({{complexType}}.md){{/isPrimitiveType}} | {{description}} | {{^required}}[optional] {{/required}}{{#readOnly}}[readonly] {{/readOnly}}{{#defaultValue}}[default to {{{.}}}]{{/defaultValue}} +{{/vars}} + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + +{{/model}}{{/models}} diff --git a/modules/swagger-codegen/src/main/resources/perl/README.mustache b/modules/swagger-codegen/src/main/resources/perl/README.mustache index 62d57f6b3cf..630a0a5979b 100644 --- a/modules/swagger-codegen/src/main/resources/perl/README.mustache +++ b/modules/swagger-codegen/src/main/resources/perl/README.mustache @@ -1,16 +1,20 @@ # NAME -{{moduleName}}::Role - a Moose role for the {{appName}} +{{moduleName}}::Role - a Moose role for the {{appName}} -## {{appName}} version: {{appVersion}} +{{#appDescription}}{{{appDescription}}}{{/appDescription}} # VERSION -Automatically generated by the Perl Swagger Codegen project: +Automatically generated by the [Swagger Codegen](https://github.com/swagger-api/swagger-codegen) project: +- API version: {{appVersion}} +- Package version: {{moduleVersion}} - Build date: {{generatedDate}} - Build package: {{generatorClass}} -- Codegen version: +{{#infoUrl}} +For more information, please visit [{{{infoUrl}}}]({{{infoUrl}}}) +{{/infoUrl}} ## A note on Moose @@ -216,4 +220,95 @@ spec. If so, this is available via the `class_documentation()` and my $omdoc = $api->get_pet_by_id->(pet_id => $pet_id)->method_documentation->{method_name}; -Each of these calls returns a hashref with various useful pieces of information. +Each of these calls returns a hashref with various useful pieces of information. + +# LOAD THE MODULES + +To load the API packages: +```perl +{{#apiInfo}}{{#apis}}use {{moduleName}}::{{classname}}; +{{/apis}}{{/apiInfo}} +``` + +To load the models: +```perl +{{#models}}{{#model}}use {{moduleName}}::Object::{{classname}}; +{{/model}}{{/models}} +```` + +# GETTING STARTED +Put the Perl SDK under the 'lib' folder in your project directory, then run the following +```perl +#!/usr/bin/perl +use lib 'lib'; +use strict; +use warnings; +# load the API package +{{#apiInfo}}{{#apis}}use {{moduleName}}::{{classname}}; +{{/apis}}{{/apiInfo}} +# load the models +{{#models}}{{#model}}use {{moduleName}}::Object::{{classname}}; +{{/model}}{{/models}} +# for displaying the API response data +use Data::Dumper; +{{#apiInfo}}{{#apis}}{{#-first}}{{#operations}}{{#operation}}{{#-first}}{{#hasAuthMethods}}{{#authMethods}}{{#isBasic}} +# Configure HTTP basic authorization: {{{name}}} +${{{moduleName}}}::Configuration::username = 'YOUR_USERNAME'; +${{{moduleName}}}::Configuration::password = 'YOUR_PASSWORD';{{/isBasic}}{{#isApiKey}} +# Configure API key authorization: {{{name}}} +${{{moduleName}}}::Configuration::api_key->{'{{{keyParamName}}}'} = 'YOUR_API_KEY'; +# uncomment below to setup prefix (e.g. BEARER) for API key, if needed +#${{{moduleName}}}::Configuration::api_key_prefix->{'{{{keyParamName}}}'} = 'BEARER';{{/isApiKey}}{{#isOAuth}} +# Configure OAuth2 access token for authorization: {{{name}}} +${{{moduleName}}}::Configuration::access_token = 'YOUR_ACCESS_TOKEN';{{/isOAuth}}{{/authMethods}} +{{/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}} + +eval { + {{#returnType}}my $result = {{/returnType}}$api_instance->{{{operationId}}}({{#allParams}}{{paramName}} => ${{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}});{{#returnType}} + print Dumper($result);{{/returnType}} +}; +if ($@) { + warn "Exception when calling {{classname}}->{{operationId}}: $@\n"; +} +{{/-first}}{{/operation}}{{/operations}}{{/-first}}{{/apis}}{{/apiInfo}} +``` + +# DOCUMENTATION FOR API ENDPOINTS + +All URIs are relative to *{{basePath}}* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}*{{classname}}* | [**{{nickname}}**]({{apiDocPath}}{{classname}}.md#{{nickname}}) | **{{httpMethod}}** {{path}} | {{#summary}}{{summary}}{{/summary}} +{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} + +# DOCUMENTATION FOR MODELS +{{#models}}{{#model}} - [{{moduleName}}::Object::{{classname}}]({{modelDocPath}}{{classname}}.md) +{{/model}}{{/models}} + +# DOCUMENTATION FOR AUTHORIATION +{{^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}}} +- **Location**: {{#isKeyInQuery}}URL query string{{/isKeyInQuery}}{{#isKeyInHeader}}HTTP header{{/isKeyInHeader}} +{{/isApiKey}} +{{#isBasic}}- **Type**: HTTP basic authentication +{{/isBasic}} +{{#isOAuth}}- **Type**: OAuth +- **Flow**: {{{flow}}} +- **Authorizatoin URL**: {{{authorizationUrl}}} +- **Scopes**: {{^scopes}}N/A{{/scopes}} +{{#scopes}} - **{{{scope}}}**: {{{description}}} +{{/scopes}} +{{/isOAuth}} + +{{/authMethods}} + + diff --git a/modules/swagger-codegen/src/main/resources/perl/api.mustache b/modules/swagger-codegen/src/main/resources/perl/api.mustache index dcebb0bb518..7e0770f332f 100644 --- a/modules/swagger-codegen/src/main/resources/perl/api.mustache +++ b/modules/swagger-codegen/src/main/resources/perl/api.mustache @@ -54,11 +54,11 @@ sub new { {{#operation}} # -# {{{nickname}}} +# {{{operationId}}} # # {{{summary}}} # -{{#allParams}}# @param {{dataType}} ${{paramName}} {{description}} {{#required}}(required){{/required}}{{^required}}(optional){{/required}} +{{#allParams}}# @param {{dataType}} ${{paramName}} {{description}} {{#required}}(required){{/required}}{{^required}}(optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}} {{/allParams}} { my $params = { @@ -70,7 +70,7 @@ sub new { }, {{/allParams}} }; - __PACKAGE__->method_documentation->{ {{nickname}} } = { + __PACKAGE__->method_documentation->{ {{operationId}} } = { summary => '{{summary}}', params => $params, returns => {{#returnType}}'{{{returnType}}}'{{/returnType}}{{^returnType}}undef{{/returnType}}, @@ -78,13 +78,13 @@ sub new { } # @return {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} # -sub {{nickname}} { +sub {{operationId}} { my ($self, %args) = @_; {{#allParams}}{{#required}} # verify the required parameter '{{paramName}}' is set unless (exists $args{'{{paramName}}'}) { - croak("Missing the required parameter '{{paramName}}' when calling {{nickname}}"); + croak("Missing the required parameter '{{paramName}}' when calling {{operationId}}"); } {{/required}}{{/allParams}} diff --git a/modules/swagger-codegen/src/main/resources/perl/api_doc.mustache b/modules/swagger-codegen/src/main/resources/perl/api_doc.mustache new file mode 100644 index 00000000000..eb270b7e216 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/perl/api_doc.mustache @@ -0,0 +1,76 @@ +# {{moduleName}}::{{classname}}{{#description}} +{{description}}{{/description}} + +## Load the API package +```perl +use {{moduleName}}::Object::{{classname}}; +``` + +All URIs are relative to *{{basePath}}* + +Method | HTTP request | Description +------------- | ------------- | ------------- +{{#operations}}{{#operation}}[**{{operationId}}**]({{classname}}.md#{{operationId}}) | **{{httpMethod}}** {{path}} | {{#summary}}{{summary}}{{/summary}} +{{/operation}}{{/operations}} + +{{#operations}} +{{#operation}} +# **{{{operationId}}}** +> {{#returnType}}{{{returnType}}} {{/returnType}}{{{operationId}}}({{#allParams}}{{paramName}} => ${{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) + +{{{summary}}}{{#notes}} + +{{{notes}}}{{/notes}} + +### Example +```perl +use Data::Dumper; +{{#hasAuthMethods}}{{#authMethods}}{{#isBasic}} +# Configure HTTP basic authorization: {{{name}}} +${{{moduleName}}}::Configuration::username = 'YOUR_USERNAME'; +${{{moduleName}}}::Configuration::password = 'YOUR_PASSWORD';{{/isBasic}}{{#isApiKey}} +# Configure API key authorization: {{{name}}} +${{{moduleName}}}::Configuration::api_key->{'{{{keyParamName}}}'} = 'YOUR_API_KEY'; +# uncomment below to setup prefix (e.g. BEARER) for API key, if needed +#${{{moduleName}}}::Configuration::api_key_prefix->{'{{{keyParamName}}}'} = "BEARER";{{/isApiKey}}{{#isOAuth}} +# Configure OAuth2 access token for authorization: {{{name}}} +${{{moduleName}}}::Configuration::access_token = 'YOUR_ACCESS_TOKEN';{{/isOAuth}}{{/authMethods}} +{{/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}} + +eval { + {{#returnType}}my $result = {{/returnType}}$api_instance->{{{operationId}}}({{#allParams}}{{paramName}} => ${{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}});{{#returnType}} + print Dumper($result);{{/returnType}} +}; +if ($@) { + warn "Exception when calling {{classname}}->{{operationId}}: $@\n"; +} +``` + +### Parameters +{{^allParams}}This endpoint does not need any parameter.{{/allParams}}{{#allParams}}{{#-last}} +Name | Type | Description | Notes +------------- | ------------- | ------------- | -------------{{/-last}}{{/allParams}} +{{#allParams}} **{{paramName}}** | {{#isFile}}**{{dataType}}**{{/isFile}}{{#isPrimitiveType}}**{{dataType}}**{{/isPrimitiveType}}{{^isPrimitiveType}}{{^isFile}}[**{{dataType}}**]({{baseType}}.md){{/isFile}}{{/isPrimitiveType}}| {{description}} | {{^required}}[optional] {{/required}}{{#defaultValue}}[default to {{defaultValue}}]{{/defaultValue}} +{{/allParams}} + +### Return type + +{{#returnType}}{{#returnTypeIsPrimitive}}**{{{returnType}}}**{{/returnTypeIsPrimitive}}{{^returnTypeIsPrimitive}}[**{{{returnType}}}**]({{returnBaseType}}.md){{/returnTypeIsPrimitive}}{{/returnType}}{{^returnType}}void (empty response body){{/returnType}} + +### Authorization + +{{^authMethods}}No authorization required{{/authMethods}}{{#authMethods}}[{{{name}}}](../README.md#{{{name}}}){{^-last}}, {{/-last}}{{/authMethods}} + +### HTTP reuqest headers + + - **Content-Type**: {{#consumes}}{{mediaType}}{{#hasMore}}, {{/hasMore}}{{/consumes}}{{^consumes}}Not defined{{/consumes}} + - **Accept**: {{#produces}}{{mediaType}}{{#hasMore}}, {{/hasMore}}{{/produces}}{{^produces}}Not defined{{/produces}} + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +{{/operation}} +{{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/perl/git_push.sh.mustache b/modules/swagger-codegen/src/main/resources/perl/git_push.sh.mustache new file mode 100755 index 00000000000..e153ce23ecf --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/perl/git_push.sh.mustache @@ -0,0 +1,52 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 swagger-petstore-perl "minor update" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 + +if [ "$git_user_id" = "" ]; then + git_user_id="{{{gitUserId}}}" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="{{{gitRepoId}}}" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="{{{releaseNote}}}" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=`git remote` +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git crediential in your environment." + git remote add origin https://github.com/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:${GIT_TOKEN}@github.com/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://github.com/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' + diff --git a/modules/swagger-codegen/src/main/resources/perl/gitignore.mustache b/modules/swagger-codegen/src/main/resources/perl/gitignore.mustache new file mode 100644 index 00000000000..ae2ad536abb --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/perl/gitignore.mustache @@ -0,0 +1,20 @@ +/blib/ +/.build/ +_build/ +cover_db/ +inc/ +Build +!Build/ +Build.bat +.last_cover_stats +/Makefile +/Makefile.old +/MANIFEST.bak +/META.yml +/META.json +/MYMETA.* +nytprof.out +/pm_to_blib +*.o +*.bs +/_eumm/ diff --git a/modules/swagger-codegen/src/main/resources/perl/object_doc.mustache b/modules/swagger-codegen/src/main/resources/perl/object_doc.mustache new file mode 100644 index 00000000000..b76874f9050 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/perl/object_doc.mustache @@ -0,0 +1,16 @@ +{{#models}}{{#model}}# {{moduleName}}::Object::{{classname}} + +## Load the model package +```perl +use {{moduleName}}::Object::{{classname}}; +``` + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +{{#vars}}**{{name}}** | {{#isPrimitiveType}}**{{datatype}}**{{/isPrimitiveType}}{{^isPrimitiveType}}[**{{datatype}}**]({{complexType}}.md){{/isPrimitiveType}} | {{description}} | {{^required}}[optional] {{/required}}{{#readOnly}}[readonly] {{/readOnly}}{{#defaultValue}}[default to {{defaultValue}}]{{/defaultValue}} +{{/vars}} + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + +{{/model}}{{/models}} diff --git a/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache index 891149d8f55..7945137c664 100644 --- a/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache @@ -259,7 +259,7 @@ class ApiClient * * @return string Accept (e.g. application/json) */ - public static function selectHeaderAccept($accept) + public function selectHeaderAccept($accept) { if (count($accept) === 0 or (count($accept) === 1 and $accept[0] === '')) { return null; @@ -277,7 +277,7 @@ class ApiClient * * @return string Content-Type (e.g. application/json) */ - public static function selectHeaderContentType($content_type) + public function selectHeaderContentType($content_type) { if (count($content_type) === 0 or (count($content_type) === 1 and $content_type[0] === '')) { return 'application/json'; @@ -299,9 +299,9 @@ class ApiClient { // ref/credit: http://php.net/manual/en/function.http-parse-headers.php#112986 $headers = array(); - $key = ''; // [+] + $key = ''; - foreach(explode("\n", $raw_headers) as $i => $h) + foreach(explode("\n", $raw_headers) as $h) { $h = explode(':', $h, 2); @@ -311,26 +311,22 @@ class ApiClient $headers[$h[0]] = trim($h[1]); elseif (is_array($headers[$h[0]])) { - // $tmp = array_merge($headers[$h[0]], array(trim($h[1]))); // [-] - // $headers[$h[0]] = $tmp; // [-] - $headers[$h[0]] = array_merge($headers[$h[0]], array(trim($h[1]))); // [+] + $headers[$h[0]] = array_merge($headers[$h[0]], array(trim($h[1]))); } else { - // $tmp = array_merge(array($headers[$h[0]]), array(trim($h[1]))); // [-] - // $headers[$h[0]] = $tmp; // [-] - $headers[$h[0]] = array_merge(array($headers[$h[0]]), array(trim($h[1]))); // [+] + $headers[$h[0]] = array_merge(array($headers[$h[0]]), array(trim($h[1]))); } - $key = $h[0]; // [+] + $key = $h[0]; + } + else + { + if (substr($h[0], 0, 1) == "\t") + $headers[$key] .= "\r\n\t".trim($h[0]); + elseif (!$key) + $headers[0] = trim($h[0]);trim($h[0]); } - else // [+] - { // [+] - if (substr($h[0], 0, 1) == "\t") // [+] - $headers[$key] .= "\r\n\t".trim($h[0]); // [+] - elseif (!$key) // [+] - $headers[0] = trim($h[0]);trim($h[0]); // [+] - } // [+] } return $headers; diff --git a/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache b/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache index dc1d87a3afe..34d79b0ae39 100644 --- a/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache +++ b/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache @@ -55,28 +55,26 @@ class ObjectSerializer public static function sanitizeForSerialization($data) { if (is_scalar($data) || null === $data) { - $sanitized = $data; + return $data; } elseif ($data instanceof \DateTime) { - $sanitized = $data->format(\DateTime::ISO8601); + return $data->format(\DateTime::ATOM); } elseif (is_array($data)) { foreach ($data as $property => $value) { $data[$property] = self::sanitizeForSerialization($value); } - $sanitized = $data; + return $data; } elseif (is_object($data)) { $values = array(); - foreach (array_keys($data::$swaggerTypes) as $property) { - $getter = $data::$getters[$property]; + foreach (array_keys($data::swaggerTypes()) as $property) { + $getter = $data::getters()[$property]; if ($data->$getter() !== null) { - $values[$data::$attributeMap[$property]] = self::sanitizeForSerialization($data->$getter()); + $values[$data::attributeMap()[$property]] = self::sanitizeForSerialization($data->$getter()); } } - $sanitized = (object)$values; + return (object)$values; } else { - $sanitized = (string)$data; + return (string)$data; } - - return $sanitized; } /** @@ -172,7 +170,7 @@ class ObjectSerializer public function toString($value) { if ($value instanceof \DateTime) { // datetime in ISO8601 format - return $value->format(\DateTime::ISO8601); + return $value->format(\DateTime::ATOM); } else { return $value; } @@ -214,16 +212,17 @@ 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 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 */ - public static function deserialize($data, $class, $httpHeaders=null) + public static function deserialize($data, $class, $httpHeaders=null, $discriminator=null) { if (null === $data) { - $deserialized = null; + return null; } elseif (substr($class, 0, 4) === 'map[') { // for associative array e.g. map[string,int] $inner = substr($class, 4, -1); $deserialized = array(); @@ -231,24 +230,35 @@ class ObjectSerializer $subClass_array = explode(',', $inner, 2); $subClass = $subClass_array[1]; foreach ($data as $key => $value) { - $deserialized[$key] = self::deserialize($value, $subClass); + $deserialized[$key] = self::deserialize($value, $subClass, null, $discriminator); } } + return $deserialized; } elseif (strcasecmp(substr($class, -2), '[]') == 0) { $subClass = substr($class, 0, -2); $values = array(); foreach ($data as $key => $value) { - $values[] = self::deserialize($value, $subClass); + $values[] = self::deserialize($value, $subClass, null, $discriminator); } - $deserialized = $values; + return $values; } elseif ($class === 'object') { settype($data, 'array'); - $deserialized = $data; + return $data; } elseif ($class === '\DateTime') { - $deserialized = new \DateTime($data); + // Some API's return an invalid, empty string as a + // date-time property. DateTime::__construct() will return + // the current time for empty input which is probably not + // what is meant. The invalid empty string is probably to + // be interpreted as a missing field/value. Let's handle + // this graceful. + if (!empty($data)) { + return new \DateTime($data); + } else { + return null; + } } elseif (in_array($class, array({{&primitives}}))) { settype($data, $class); - $deserialized = $data; + return $data; } elseif ($class === '\SplFileObject') { // determine file name if (array_key_exists('Content-Disposition', $httpHeaders) && preg_match('/inline; filename=[\'"]?([^\'"\s]+)[\'"]?$/i', $httpHeaders['Content-Disposition'], $match)) { @@ -259,24 +269,30 @@ class ObjectSerializer $deserialized = new \SplFileObject($filename, "w"); $byte_written = $deserialized->fwrite($data); error_log("[INFO] Written $byte_written byte to $filename. Please move the file to a proper folder or delete the temp file after processing.\n", 3, Configuration::getDefaultConfiguration()->getDebugFile()); - + return $deserialized; + } else { + // If a discriminator is defined and points to a valid subclass, use it. + if (!empty($discriminator) && isset($data->{$discriminator}) && is_string($data->{$discriminator})) { + $subclass = '\{{invokerPackage}}\Model\\' . $data->{$discriminator}; + if (is_subclass_of($subclass, $class)) { + $class = $subclass; + } + } $instance = new $class(); - foreach ($instance::$swaggerTypes as $property => $type) { - $propertySetter = $instance::$setters[$property]; + foreach ($instance::swaggerTypes() as $property => $type) { + $propertySetter = $instance::setters()[$property]; - if (!isset($propertySetter) || !isset($data->{$instance::$attributeMap[$property]})) { + if (!isset($propertySetter) || !isset($data->{$instance::attributeMap()[$property]})) { continue; } - $propertyValue = $data->{$instance::$attributeMap[$property]}; + $propertyValue = $data->{$instance::attributeMap()[$property]}; if (isset($propertyValue)) { - $instance->$propertySetter(self::deserialize($propertyValue, $type)); + $instance->$propertySetter(self::deserialize($propertyValue, $type, null, $discriminator)); } } - $deserialized = $instance; + return $instance; } - - return $deserialized; } } diff --git a/modules/swagger-codegen/src/main/resources/php/README.mustache b/modules/swagger-codegen/src/main/resources/php/README.mustache index a795b58be1d..8275c4c9d7c 100644 --- a/modules/swagger-codegen/src/main/resources/php/README.mustache +++ b/modules/swagger-codegen/src/main/resources/php/README.mustache @@ -1,4 +1,17 @@ # {{packagePath}} +{{#appDescription}} +{{{appDescription}}} +{{/appDescription}} + +This PHP package is automatically generated by the [Swagger Codegen](https://github.com/swagger-api/swagger-codegen) project: + +- API version: {{appVersion}} +- Package version: {{artifactVersion}} +- Build date: {{generatedDate}} +- Build package: {{generatorClass}} +{{#infoUrl}} +For more information, please visit [{{{infoUrl}}}]({{{infoUrl}}}) +{{/infoUrl}} ## Requirements @@ -7,27 +20,28 @@ PHP 5.4.0 and later ## Installation & Usage ### Composer -You can install the bindings via [Composer](http://getcomposer.org/). Add this to your `composer.json`: +To install the bindings via [Composer](http://getcomposer.org/), add the following to `composer.json`: ``` { "repositories": [ { "type": "git", - "url": "https://github.com/{{composerVendorName}}/{{composerProjectName}}.git" + "url": "https://github.com/{{#gitUserId}}{{.}}{{/gitUserId}}{{^gitUserId}}{{composerVendorName}}{{/gitUserId}}/{{#gitRepoId}}{{.}}{{/gitRepoId}}{{^gitRepoId}}{{composerProjectName}}{{/gitRepoId}}.git" } ], "require": { - "{{composerVendorName}}/{{composerProjectName}}": "*@dev" + "{{#gitUserId}}{{.}}{{/gitUserId}}{{^gitUserId}}{{composerVendorName}}{{/gitUserId}}/{{#gitRepoId}}{{.}}{{/gitRepoId}}{{^gitRepoId}}{{composerProjectName}}{{/gitRepoId}}": "*@dev" } } ``` -Then install via `composer install` +Then run `composer install` ### Manual Installation -If you do not wish to use Composer, you can download the latest release. Then, to use the bindings, include the `autoload.php` file. +Download the files and include `autoload.php`: + ```php require_once('/path/to/{{packagePath}}/autoload.php'); ``` @@ -35,11 +49,81 @@ If you do not wish to use Composer, you can download the latest release. Then, t ## Tests To run the unit tests: + ``` composer install ./vendor/bin/phpunit lib/Tests ``` +## Getting Started + +Please follow the [installation procedure](#installation--usage) and then run the following: + +```php +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(), "\n"; +} +{{/-first}}{{/operation}}{{/operations}}{{/-first}}{{/apis}}{{/apiInfo}} +?> +``` + +## Documentation for API Endpoints + +All URIs are relative to *{{basePath}}* + +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 + +{{#models}}{{#model}} - [{{{classname}}}]({{modelDocPath}}{{{classname}}}.md) +{{/model}}{{/models}} + +## Documentation For Authorization + +{{^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}}} +- **Location**: {{#isKeyInQuery}}URL query string{{/isKeyInQuery}}{{#isKeyInHeader}}HTTP header{{/isKeyInHeader}} +{{/isApiKey}} +{{#isBasic}}- **Type**: HTTP basic authentication +{{/isBasic}} +{{#isOAuth}}- **Type**: OAuth +- **Flow**: {{{flow}}} +- **Authorizatoin URL**: {{{authorizationUrl}}} +- **Scopes**: {{^scopes}}N/A{{/scopes}} +{{#scopes}} - **{{{scope}}}**: {{{description}}} +{{/scopes}} +{{/isOAuth}} + +{{/authMethods}} + ## Author {{#apiInfo}}{{#apis}}{{^hasMore}}{{infoEmail}} diff --git a/modules/swagger-codegen/src/main/resources/php/api.mustache b/modules/swagger-codegen/src/main/resources/php/api.mustache index 1740a380102..2692ba66f94 100644 --- a/modules/swagger-codegen/src/main/resources/php/api.mustache +++ b/modules/swagger-codegen/src/main/resources/php/api.mustache @@ -96,13 +96,13 @@ use \{{invokerPackage}}\ObjectSerializer; * * {{{summary}}} * - {{#allParams}} * @param {{dataType}} ${{paramName}} {{description}} {{#required}}(required){{/required}}{{^required}}(optional){{/required}} + {{#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 */ public function {{operationId}}({{#allParams}}${{paramName}}{{^required}} = null{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) { - list($response, $statusCode, $httpHeader) = $this->{{operationId}}WithHttpInfo ({{#allParams}}${{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); + list($response) = $this->{{operationId}}WithHttpInfo ({{#allParams}}${{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); return $response; } @@ -112,7 +112,7 @@ use \{{invokerPackage}}\ObjectSerializer; * * {{{summary}}} * - {{#allParams}} * @param {{dataType}} ${{paramName}} {{description}} {{#required}}(required){{/required}}{{^required}}(optional){{/required}} + {{#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) * @throws \{{invokerPackage}}\ApiException on non-2xx response */ @@ -130,11 +130,11 @@ use \{{invokerPackage}}\ObjectSerializer; $queryParams = array(); $headerParams = array(); $formParams = array(); - $_header_accept = ApiClient::selectHeaderAccept(array({{#produces}}'{{mediaType}}'{{#hasMore}}, {{/hasMore}}{{/produces}})); + $_header_accept = $this->apiClient->selectHeaderAccept(array({{#produces}}'{{mediaType}}'{{#hasMore}}, {{/hasMore}}{{/produces}})); if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array({{#consumes}}'{{mediaType}}'{{#hasMore}},{{/hasMore}}{{/consumes}})); + $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array({{#consumes}}'{{mediaType}}'{{#hasMore}},{{/hasMore}}{{/consumes}})); {{#queryParams}}// query params {{#collectionFormat}} @@ -223,14 +223,14 @@ use \{{invokerPackage}}\ObjectSerializer; return array(null, $statusCode, $httpHeader); } - return array(\{{invokerPackage}}\ObjectSerializer::deserialize($response, '{{returnType}}', $httpHeader), $statusCode, $httpHeader); + return array($this->apiClient->getSerializer()->deserialize($response, '{{returnType}}', $httpHeader{{#discriminator}}, '{{discriminator}}'{{/discriminator}}), $statusCode, $httpHeader); {{/returnType}}{{^returnType}} return array(null, $statusCode, $httpHeader); {{/returnType}} } catch (ApiException $e) { switch ($e->getCode()) { {{#responses}}{{#dataType}} {{^isWildcard}}case {{code}}:{{/isWildcard}}{{#isWildcard}}default:{{/isWildcard}} - $data = \{{invokerPackage}}\ObjectSerializer::deserialize($e->getResponseBody(), '{{dataType}}', $e->getResponseHeaders()); + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '{{dataType}}', $e->getResponseHeaders()); $e->setResponseObject($data); break;{{/dataType}}{{/responses}} } diff --git a/modules/swagger-codegen/src/main/resources/php/api_doc.mustache b/modules/swagger-codegen/src/main/resources/php/api_doc.mustache new file mode 100644 index 00000000000..bb55e80604c --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/php/api_doc.mustache @@ -0,0 +1,72 @@ +# {{invokerPackage}}\{{classname}}{{#description}} +{{description}}{{/description}} + +All URIs are relative to *{{basePath}}* + +Method | HTTP request | Description +------------- | ------------- | ------------- +{{#operations}}{{#operation}}[**{{operationId}}**]({{classname}}.md#{{operationId}}) | **{{httpMethod}}** {{path}} | {{#summary}}{{summary}}{{/summary}} +{{/operation}}{{/operations}} + +{{#operations}} +{{#operation}} +# **{{{operationId}}}** +> {{#returnType}}{{{returnType}}} {{/returnType}}{{{operationId}}}({{#allParams}}${{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) + +{{{summary}}}{{#notes}} + +{{{notes}}}{{/notes}} + +### Example +```php +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(), "\n"; +} +?> +``` + +### Parameters +{{^allParams}}This endpoint does not need any parameter.{{/allParams}}{{#allParams}}{{#-last}} +Name | Type | Description | Notes +------------- | ------------- | ------------- | -------------{{/-last}}{{/allParams}} +{{#allParams}} **{{paramName}}** | {{#isFile}}**{{dataType}}**{{/isFile}}{{#isPrimitiveType}}**{{dataType}}**{{/isPrimitiveType}}{{^isPrimitiveType}}{{^isFile}}[**{{dataType}}**]({{baseType}}.md){{/isFile}}{{/isPrimitiveType}}| {{description}} | {{^required}}[optional] {{/required}}{{#defaultValue}}[default to {{defaultValue}}]{{/defaultValue}} +{{/allParams}} + +### Return type + +{{#returnType}}{{#returnTypeIsPrimitive}}**{{{returnType}}}**{{/returnTypeIsPrimitive}}{{^returnTypeIsPrimitive}}[**{{{returnType}}}**]({{returnBaseType}}.md){{/returnTypeIsPrimitive}}{{/returnType}}{{^returnType}}void (empty response body){{/returnType}} + +### Authorization + +{{^authMethods}}No authorization required{{/authMethods}}{{#authMethods}}[{{{name}}}](../README.md#{{{name}}}){{^-last}}, {{/-last}}{{/authMethods}} + +### HTTP reuqest headers + + - **Content-Type**: {{#consumes}}{{mediaType}}{{#hasMore}}, {{/hasMore}}{{/consumes}}{{^consumes}}Not defined{{/consumes}} + - **Accept**: {{#produces}}{{mediaType}}{{#hasMore}}, {{/hasMore}}{{/produces}}{{^produces}}Not defined{{/produces}} + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +{{/operation}} +{{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/php/composer.mustache b/modules/swagger-codegen/src/main/resources/php/composer.mustache index 994b6f1ccc7..64564e4ec57 100644 --- a/modules/swagger-codegen/src/main/resources/php/composer.mustache +++ b/modules/swagger-codegen/src/main/resources/php/composer.mustache @@ -1,5 +1,5 @@ { - "name": "{{composerVendorName}}/{{composerProjectName}}",{{#artifactVersion}} + "name": "{{#gitUserId}}{{.}}{{/gitUserId}}{{^gitUserId}}{{composerVendorName}}{{/gitUserId}}/{{#gitRepoId}}{{.}}{{/gitRepoId}}{{^gitRepoId}}{{composerProjectName}}{{/gitRepoId}}",{{#artifactVersion}} "version": "{{artifactVersion}}",{{/artifactVersion}} "description": "{{description}}", "keywords": [ diff --git a/modules/swagger-codegen/src/main/resources/php/configuration.mustache b/modules/swagger-codegen/src/main/resources/php/configuration.mustache index 8fa5e1cb1f0..0062fa8c25f 100644 --- a/modules/swagger-codegen/src/main/resources/php/configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/php/configuration.mustache @@ -110,7 +110,7 @@ class Configuration * * @var string */ - protected $userAgent = "PHP-Swagger/{{artifactVersion}}"; + protected $userAgent = "{{#httpUserAgent}}{{{.}}}{{/httpUserAgent}}{{^httpUserAgent}}Swagger-Codegen/{{{artifactVersion}}}/php{{/httpUserAgent}}"; /** * Debug switch (default set to false) diff --git a/modules/swagger-codegen/src/main/resources/php/git_push.sh.mustache b/modules/swagger-codegen/src/main/resources/php/git_push.sh.mustache new file mode 100755 index 00000000000..e153ce23ecf --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/php/git_push.sh.mustache @@ -0,0 +1,52 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 swagger-petstore-perl "minor update" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 + +if [ "$git_user_id" = "" ]; then + git_user_id="{{{gitUserId}}}" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="{{{gitRepoId}}}" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="{{{releaseNote}}}" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=`git remote` +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git crediential in your environment." + git remote add origin https://github.com/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:${GIT_TOKEN}@github.com/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://github.com/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' + diff --git a/modules/swagger-codegen/src/main/resources/php/model.mustache b/modules/swagger-codegen/src/main/resources/php/model.mustache index 75cf55bde0b..f19787f50b0 100644 --- a/modules/swagger-codegen/src/main/resources/php/model.mustache +++ b/modules/swagger-codegen/src/main/resources/php/model.mustache @@ -46,7 +46,7 @@ use \ArrayAccess; * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 * @link https://github.com/swagger-api/swagger-codegen */ -class {{classname}} implements ArrayAccess +class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}implements ArrayAccess { /** * Array of property to type mappings. Used for (de)serialization @@ -57,6 +57,10 @@ class {{classname}} implements ArrayAccess {{/hasMore}}{{/vars}} ); + static function swaggerTypes() { + return self::$swaggerTypes{{#parent}} + parent::swaggerTypes(){{/parent}}; + } + /** * Array of attributes where the key is the local name, and the value is the original name * @var string[] @@ -66,6 +70,10 @@ class {{classname}} implements ArrayAccess {{/hasMore}}{{/vars}} ); + static function attributeMap() { + return {{#parent}}parent::attributeMap() + {{/parent}}self::$attributeMap; + } + /** * Array of attributes to setter functions (for deserialization of responses) * @var string[] @@ -75,6 +83,10 @@ class {{classname}} implements ArrayAccess {{/hasMore}}{{/vars}} ); + static function setters() { + return {{#parent}}parent::setters() + {{/parent}}self::$setters; + } + /** * Array of attributes to getter functions (for serialization of requests) * @var string[] @@ -84,6 +96,10 @@ class {{classname}} implements ArrayAccess {{/hasMore}}{{/vars}} ); + static function getters() { + return {{#parent}}parent::getters() + {{/parent}}self::$getters; + } + {{#vars}} /** * ${{name}} {{#description}}{{{description}}}{{/description}} @@ -98,6 +114,7 @@ class {{classname}} implements ArrayAccess */ public function __construct(array $data = null) { + {{#parent}}parent::__construct($data);{{/parent}} if ($data != null) { {{#vars}}$this->{{name}} = $data["{{name}}"];{{#hasMore}} {{/hasMore}}{{/vars}} @@ -175,11 +192,11 @@ class {{classname}} implements ArrayAccess */ public function __toString() { - if (defined('JSON_PRETTY_PRINT')) { + if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print return json_encode(\{{invokerPackage}}\ObjectSerializer::sanitizeForSerialization($this), JSON_PRETTY_PRINT); - } else { - return json_encode(\{{invokerPackage}}\ObjectSerializer::sanitizeForSerialization($this)); } + + return json_encode(\{{invokerPackage}}\ObjectSerializer::sanitizeForSerialization($this)); } } {{/model}} diff --git a/modules/swagger-codegen/src/main/resources/php/model_doc.mustache b/modules/swagger-codegen/src/main/resources/php/model_doc.mustache new file mode 100644 index 00000000000..569550df372 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/php/model_doc.mustache @@ -0,0 +1,11 @@ +{{#models}}{{#model}}# {{classname}} + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +{{#vars}}**{{name}}** | {{#isPrimitiveType}}**{{datatype}}**{{/isPrimitiveType}}{{^isPrimitiveType}}[**{{datatype}}**]({{complexType}}.md){{/isPrimitiveType}} | {{description}} | {{^required}}[optional] {{/required}}{{#readOnly}}[readonly] {{/readOnly}}{{#defaultValue}}[default to {{{.}}}]{{/defaultValue}} +{{/vars}} + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + +{{/model}}{{/models}} diff --git a/modules/swagger-codegen/src/main/resources/python/README.mustache b/modules/swagger-codegen/src/main/resources/python/README.mustache index 463bbb37a18..a1ba2f0d298 100644 --- a/modules/swagger-codegen/src/main/resources/python/README.mustache +++ b/modules/swagger-codegen/src/main/resources/python/README.mustache @@ -1,73 +1,122 @@ +# {{packageName}} +{{#appDescription}} +{{{appDescription}}} +{{/appDescription}} + +This Python package is automatically generated by the [Swagger Codegen](https://github.com/swagger-api/swagger-codegen) project: + +- API version: {{appVersion}} +- Package version: {{packageVersion}} +- Build date: {{generatedDate}} +- Build package: {{generatorClass}} +{{#infoUrl}} +For more information, please visit [{{{infoUrl}}}]({{{infoUrl}}}) +{{/infoUrl}} + ## Requirements. -Python 2.7 and later. -## Setuptools -You can install the bindings via [Setuptools](http://pypi.python.org/pypi/setuptools). +Python 2.7 and 3.4+ + +## Installation & Usage +### pip install + +If the python package is hosted on Github, you can install directly from Github ```sh -python setup.py install +pip install git+https://github.com/{{{gitUserId}}}/{{{gitRepoId}}}.git +``` +(you may need to run `pip` with root permission: `sudo pip install git+https://github.com/{{{gitUserId}}}/{{{gitRepoId}}}.git`) + +Then import the package: +```python +import {{{packageName}}} ``` -Or you can install from Github via pip: +### Setuptools + +Install via [Setuptools](http://pypi.python.org/pypi/setuptools). ```sh -pip install git+https://github.com/geekerzp/swagger_client.git +python setup.py install --user ``` +(or `sudo python setup.py install` to install the package for all users) -To use the bindings, import the pacakge: - +Then import the package: ```python -import swagger_client -``` - -## Manual Installation -If you do not wish to use setuptools, you can download the latest release. -Then, to use the bindings, import the package: - -```python -import path.to.swagger_client +import {{{packageName}}} ``` ## Getting Started -TODO +Please follow the [installation procedure](#installation--usage) and then run the following: -## Documentation +```python +import time +import {{{packageName}}} +from {{{packageName}}}.rest import ApiException +from pprint import pprint +{{#apiInfo}}{{#apis}}{{#-first}}{{#operations}}{{#operation}}{{#-first}}{{#hasAuthMethods}}{{#authMethods}}{{#isBasic}} +# Configure HTTP basic authorization: {{{name}}} +{{{packageName}}}.configuration.username = 'YOUR_USERNAME' +{{{packageName}}}.configuration.password = 'YOUR_PASSWORD'{{/isBasic}}{{#isApiKey}} +# Configure API key authorization: {{{name}}} +{{{packageName}}}.configuration.api_key['{{{keyParamName}}}'] = 'YOUR_API_KEY' +# Uncomment below to setup prefix (e.g. BEARER) for API key, if needed +# {{{packageName}}}.configuration.api_key_prefix['{{{keyParamName}}}'] = 'BEARER'{{/isApiKey}}{{#isOAuth}} +# Configure OAuth2 access token for authorization: {{{name}}} +{{{packageName}}}.configuration.access_token = 'YOUR_ACCESS_TOKEN'{{/isOAuth}}{{/authMethods}} +{{/hasAuthMethods}} +# create an instance of the API class +api_instance = {{{packageName}}}.{{{classname}}} +{{#allParams}}{{paramName}} = {{{example}}} # {{{dataType}}} | {{{description}}}{{^required}} (optional){{/required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}} +{{/allParams}} -TODO - -## Tests - -(Please make sure you have [virtualenv](http://docs.python-guide.org/en/latest/dev/virtualenvs/) installed) - - Execute the following command to run the tests in the current Python (v2 or v3) environment: - -```sh -$ make test -[... magically installs dependencies and runs tests on your virtualenv] -Ran 7 tests in 19.289s - -OK +try: +{{#summary}} # {{{.}}} +{{/summary}} {{#returnType}}api_response = {{/returnType}}api_instance.{{{operationId}}}({{#allParams}}{{#required}}{{paramName}}{{/required}}{{^required}}{{paramName}}={{paramName}}{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}){{#returnType}} + pprint(api_response){{/returnType}} +except ApiException as e: + print "Exception when calling {{classname}}->{{operationId}}: %s\n" % e +{{/-first}}{{/operation}}{{/operations}}{{/-first}}{{/apis}}{{/apiInfo}} ``` -or -``` -$ mvn integration-test -rf :PythonPetstoreClientTests -Using 2195432783 as seed -[INFO] ------------------------------------------------------------------------ -[INFO] BUILD SUCCESS -[INFO] ------------------------------------------------------------------------ -[INFO] Total time: 37.594 s -[INFO] Finished at: 2015-05-16T18:00:35+08:00 -[INFO] Final Memory: 11M/156M -[INFO] ------------------------------------------------------------------------ -``` -If you want to run the tests in all the python platforms: +## Documentation for API Endpoints -```sh -$ make test-all -[... tox creates a virtualenv for every platform and runs tests inside of each] - py27: commands succeeded - py34: commands succeeded - congratulations :) -``` +All URIs are relative to *{{basePath}}* + +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 + +{{#models}}{{#model}} - [{{{classname}}}]({{modelDocPath}}{{{classname}}}.md) +{{/model}}{{/models}} + +## Documentation For Authorization + +{{^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}}} +- **Location**: {{#isKeyInQuery}}URL query string{{/isKeyInQuery}}{{#isKeyInHeader}}HTTP header{{/isKeyInHeader}} +{{/isApiKey}} +{{#isBasic}}- **Type**: HTTP basic authentication +{{/isBasic}} +{{#isOAuth}}- **Type**: OAuth +- **Flow**: {{{flow}}} +- **Authorizatoin URL**: {{{authorizationUrl}}} +- **Scopes**: {{^scopes}}N/A{{/scopes}} +{{#scopes}} - **{{{scope}}}**: {{{description}}} +{{/scopes}} +{{/isOAuth}} + +{{/authMethods}} + +## Author + +{{#apiInfo}}{{#apis}}{{^hasMore}}{{infoEmail}} +{{/hasMore}}{{/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 4d8b712a425..0967a2ec6b3 100644 --- a/modules/swagger-codegen/src/main/resources/python/api.mustache +++ b/modules/swagger-codegen/src/main/resources/python/api.mustache @@ -47,7 +47,7 @@ class {{classname}}(object): self.api_client = config.api_client {{#operation}} - def {{nickname}}(self, {{#sortParamsByRequiredFlag}}{{#allParams}}{{#required}}{{paramName}}, {{/required}}{{/allParams}}{{/sortParamsByRequiredFlag}}**kwargs): + def {{operationId}}(self, {{#sortParamsByRequiredFlag}}{{#allParams}}{{#required}}{{paramName}}, {{/required}}{{/allParams}}{{/sortParamsByRequiredFlag}}**kwargs): """ {{{summary}}} {{{notes}}} @@ -59,16 +59,16 @@ class {{classname}}(object): >>> pprint(response) >>> {{#sortParamsByRequiredFlag}} - >>> thread = api.{{nickname}}({{#allParams}}{{#required}}{{paramName}}, {{/required}}{{/allParams}}callback=callback_function) + >>> thread = api.{{operationId}}({{#allParams}}{{#required}}{{paramName}}, {{/required}}{{/allParams}}callback=callback_function) {{/sortParamsByRequiredFlag}} {{^sortParamsByRequiredFlag}} - >>> thread = api.{{nickname}}({{#allParams}}{{#required}}{{paramName}}={{paramName}}_value, {{/required}}{{/allParams}}callback=callback_function) + >>> thread = api.{{operationId}}({{#allParams}}{{#required}}{{paramName}}={{paramName}}_value, {{/required}}{{/allParams}}callback=callback_function) {{/sortParamsByRequiredFlag}} :param callback function: The callback function for asynchronous request. (optional) {{#allParams}} - :param {{dataType}} {{paramName}}: {{{description}}}{{#required}} (required){{/required}}{{#optional}}(optional){{/optional}} + :param {{dataType}} {{paramName}}: {{{description}}}{{#required}} (required){{/required}}{{#optional}}(optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/optional}} {{/allParams}} :return: {{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}None{{/returnType}} If the method is called asynchronously, @@ -83,7 +83,7 @@ class {{classname}}(object): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" - " to method {{nickname}}" % key + " to method {{operationId}}" % key ) params[key] = val del params['kwargs'] @@ -92,7 +92,7 @@ class {{classname}}(object): {{#required}} # verify the required parameter '{{paramName}}' is set if ('{{paramName}}' not in params) or (params['{{paramName}}'] is None): - raise ValueError("Missing the required parameter `{{paramName}}` when calling `{{nickname}}`") + raise ValueError("Missing the required parameter `{{paramName}}` when calling `{{operationId}}`") {{/required}} {{/allParams}} 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 7aac36e1a20..07b9419e08f 100644 --- a/modules/swagger-codegen/src/main/resources/python/api_client.mustache +++ b/modules/swagger-codegen/src/main/resources/python/api_client.mustache @@ -81,7 +81,7 @@ class ApiClient(object): self.host = host self.cookie = cookie # Set default User-Agent. - self.user_agent = 'Python-Swagger/{{packageVersion}}' + self.user_agent = '{{#httpUserAgent}}{{{.}}}{{/httpUserAgent}}{{^httpUserAgent}}Swagger-Codegen/{{{packageVersion}}}/python{{/httpUserAgent}}' @property def user_agent(self): @@ -371,7 +371,8 @@ class ApiClient(object): elif method == "DELETE": return self.rest_client.DELETE(url, query_params=query_params, - headers=headers) + headers=headers, + body=body) else: raise ValueError( "http method must be `GET`, `HEAD`," diff --git a/modules/swagger-codegen/src/main/resources/python/api_doc.mustache b/modules/swagger-codegen/src/main/resources/python/api_doc.mustache new file mode 100644 index 00000000000..b4f921fa870 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/python/api_doc.mustache @@ -0,0 +1,74 @@ +# {{packageName}}.{{classname}}{{#description}} +{{description}}{{/description}} + +All URIs are relative to *{{basePath}}* + +Method | HTTP request | Description +------------- | ------------- | ------------- +{{#operations}}{{#operation}}[**{{operationId}}**]({{classname}}.md#{{operationId}}) | **{{httpMethod}}** {{path}} | {{#summary}}{{summary}}{{/summary}} +{{/operation}}{{/operations}} + +{{#operations}} +{{#operation}} +# **{{{operationId}}}** +> {{#returnType}}{{{returnType}}} {{/returnType}}{{{operationId}}}({{#allParams}}{{#required}}{{{paramName}}}{{/required}}{{^required}}{{{paramName}}}={{{paramName}}}{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) + +{{{summary}}}{{#notes}} + +{{{notes}}}{{/notes}} + +### Example +```python +import time +import {{{packageName}}} +from {{{packageName}}}.rest import ApiException +from pprint import pprint +{{#hasAuthMethods}}{{#authMethods}}{{#isBasic}} +# Configure HTTP basic authorization: {{{name}}} +{{{packageName}}}.configuration.username = 'YOUR_USERNAME' +{{{packageName}}}.configuration.password = 'YOUR_PASSWORD'{{/isBasic}}{{#isApiKey}} +# Configure API key authorization: {{{name}}} +{{{packageName}}}.configuration.api_key['{{{keyParamName}}}'] = 'YOUR_API_KEY' +# Uncomment below to setup prefix (e.g. BEARER) for API key, if needed +# {{{packageName}}}.configuration.api_key_prefix['{{{keyParamName}}}'] = 'BEARER'{{/isApiKey}}{{#isOAuth}} +# Configure OAuth2 access token for authorization: {{{name}}} +{{{packageName}}}.configuration.access_token = 'YOUR_ACCESS_TOKEN'{{/isOAuth}}{{/authMethods}} +{{/hasAuthMethods}} + +# create an instance of the API class +api_instance = {{{packageName}}}.{{{classname}}}() +{{#allParams}}{{paramName}} = {{{example}}} # {{{dataType}}} | {{{description}}}{{^required}} (optional){{/required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}} +{{/allParams}} + +try: +{{#summary}} # {{{.}}} +{{/summary}} {{#returnType}}api_response = {{/returnType}}api_instance.{{{operationId}}}({{#allParams}}{{#required}}{{paramName}}{{/required}}{{^required}}{{paramName}}={{paramName}}{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}){{#returnType}} + pprint(api_response){{/returnType}} +except ApiException as e: + print "Exception when calling {{classname}}->{{operationId}}: %s\n" % e +``` + +### Parameters +{{^allParams}}This endpoint does not need any parameter.{{/allParams}}{{#allParams}}{{#-last}} +Name | Type | Description | Notes +------------- | ------------- | ------------- | -------------{{/-last}}{{/allParams}} +{{#allParams}} **{{paramName}}** | {{#isFile}}**{{dataType}}**{{/isFile}}{{#isPrimitiveType}}**{{dataType}}**{{/isPrimitiveType}}{{^isPrimitiveType}}{{^isFile}}[**{{dataType}}**]({{baseType}}.md){{/isFile}}{{/isPrimitiveType}}| {{description}} | {{^required}}[optional] {{/required}}{{#defaultValue}}[default to {{defaultValue}}]{{/defaultValue}} +{{/allParams}} + +### Return type + +{{#returnType}}{{#returnTypeIsPrimitive}}**{{{returnType}}}**{{/returnTypeIsPrimitive}}{{^returnTypeIsPrimitive}}[**{{{returnType}}}**]({{returnBaseType}}.md){{/returnTypeIsPrimitive}}{{/returnType}}{{^returnType}}void (empty response body){{/returnType}} + +### Authorization + +{{^authMethods}}No authorization required{{/authMethods}}{{#authMethods}}[{{{name}}}](../README.md#{{{name}}}){{^-last}}, {{/-last}}{{/authMethods}} + +### HTTP reuqest headers + + - **Content-Type**: {{#consumes}}{{mediaType}}{{#hasMore}}, {{/hasMore}}{{/consumes}}{{^consumes}}Not defined{{/consumes}} + - **Accept**: {{#produces}}{{mediaType}}{{#hasMore}}, {{/hasMore}}{{/produces}}{{^produces}}Not defined{{/produces}} + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +{{/operation}} +{{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/python/git_push.sh.mustache b/modules/swagger-codegen/src/main/resources/python/git_push.sh.mustache new file mode 100755 index 00000000000..e153ce23ecf --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/python/git_push.sh.mustache @@ -0,0 +1,52 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 swagger-petstore-perl "minor update" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 + +if [ "$git_user_id" = "" ]; then + git_user_id="{{{gitUserId}}}" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="{{{gitRepoId}}}" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="{{{releaseNote}}}" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=`git remote` +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git crediential in your environment." + git remote add origin https://github.com/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:${GIT_TOKEN}@github.com/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://github.com/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' + diff --git a/modules/swagger-codegen/src/main/resources/python/gitignore.mustache b/modules/swagger-codegen/src/main/resources/python/gitignore.mustache new file mode 100644 index 00000000000..1dbc687de01 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/python/gitignore.mustache @@ -0,0 +1,62 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +env/ +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +*.egg-info/ +.installed.cfg +*.egg + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*,cover +.hypothesis/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +#Ipython Notebook +.ipynb_checkpoints diff --git a/modules/swagger-codegen/src/main/resources/python/model_doc.mustache b/modules/swagger-codegen/src/main/resources/python/model_doc.mustache new file mode 100644 index 00000000000..569550df372 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/python/model_doc.mustache @@ -0,0 +1,11 @@ +{{#models}}{{#model}}# {{classname}} + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +{{#vars}}**{{name}}** | {{#isPrimitiveType}}**{{datatype}}**{{/isPrimitiveType}}{{^isPrimitiveType}}[**{{datatype}}**]({{complexType}}.md){{/isPrimitiveType}} | {{description}} | {{^required}}[optional] {{/required}}{{#readOnly}}[readonly] {{/readOnly}}{{#defaultValue}}[default to {{{.}}}]{{/defaultValue}} +{{/vars}} + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + +{{/model}}{{/models}} diff --git a/modules/swagger-codegen/src/main/resources/python/rest.mustache b/modules/swagger-codegen/src/main/resources/python/rest.mustache index c5b9a4e6f91..352bb503ac5 100644 --- a/modules/swagger-codegen/src/main/resources/python/rest.mustache +++ b/modules/swagger-codegen/src/main/resources/python/rest.mustache @@ -133,8 +133,8 @@ class RESTClientObject(object): headers['Content-Type'] = 'application/json' try: - # For `POST`, `PUT`, `PATCH`, `OPTIONS` - if method in ['POST', 'PUT', 'PATCH', 'OPTIONS']: + # For `POST`, `PUT`, `PATCH`, `OPTIONS`, `DELETE` + if method in ['POST', 'PUT', 'PATCH', 'OPTIONS', 'DELETE']: if query_params: url += '?' + urlencode(query_params) if headers['Content-Type'] == 'application/json': @@ -154,7 +154,7 @@ class RESTClientObject(object): fields=post_params, encode_multipart=True, headers=headers) - # For `GET`, `HEAD`, `DELETE` + # For `GET`, `HEAD` else: r = self.pool_manager.request(method, url, fields=query_params, @@ -195,10 +195,11 @@ class RESTClientObject(object): post_params=post_params, body=body) - def DELETE(self, url, headers=None, query_params=None): + def DELETE(self, url, headers=None, query_params=None, body=None): return self.request("DELETE", url, headers=headers, - query_params=query_params) + query_params=query_params, + body=body) def POST(self, url, headers=None, query_params=None, post_params=None, body=None): return self.request("POST", url, diff --git a/modules/swagger-codegen/src/main/resources/ruby/README.mustache b/modules/swagger-codegen/src/main/resources/ruby/README.mustache new file mode 100644 index 00000000000..164285e1533 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/ruby/README.mustache @@ -0,0 +1,128 @@ +# {{gemName}} + +{{moduleName}} - the Ruby gem for the {{appName}} + +{{#appDescription}} +{{{appDescription}}} +{{/appDescription}} + +This SDK is automatically generated by the [Swagger Codegen](https://github.com/swagger-api/swagger-codegen) project: + +- API version: {{appVersion}} +- Package version: {{gemVersion}} +- Build date: {{generatedDate}} +- Build package: {{generatorClass}} +{{#infoUrl}} +For more information, please visit [{{{infoUrl}}}]({{{infoUrl}}}) +{{/infoUrl}} + +## Installation + +### Build a gem + +To build the Ruby code into a gem: + +```shell +gem build {{{gemName}}}.gemspec +``` + +Then either install the gem locally: + +```shell +gem install ./{{{gemName}}}-{{{gemVersion}}}.gem +``` + +or publish the gem to a gem hosting service, e.g. [RubyGems](https://rubygems.org/). + +Finally add this to the Gemfile: + + gem '{{{gemName}}}', '~> {{{gemVersion}}}' + +### Install from Git + +If the Ruby gem is hosted at a git repository: https://github.com/{{#gitUserId}}{{.}}{{/gitUserId}}{{^gitUserId}}YOUR_GIT_USERNAME{{/gitUserId}}/{{#gitRepoId}}{{.}}{{/gitRepoId}}{{^gitRepoId}}YOUR_GIT_REPO{{/gitRepoId}}, then add the following in the Gemfile: + + gem '{{{gemName}}}', :git => 'https://github.com/{{#gitUserId}}{{.}}{{/gitUserId}}{{^gitUserId}}YOUR_GIT_USERNAME{{/gitUserId}}/{{#gitRepoId}}{{.}}{{/gitRepoId}}{{^gitRepoId}}YOUR_GIT_REPO{{/gitRepoId}}.git' + +### Include the Ruby code directly + +Include the Ruby code directly using `-I` as follows: + +```shell +ruby -Ilib script.rb +``` + +## Getting Started + +Please follow the [installation](#installation) procedure and then run the following code: +```ruby +# Load the gem +require '{{{gemName}}}' +{{#apiInfo}}{{#apis}}{{#-first}}{{#operations}}{{#operation}}{{#-first}}{{#hasAuthMethods}} +# Setup authorization +{{{moduleName}}}.configure do |config|{{#authMethods}}{{#isBasic}} + # Configure HTTP basic authorization: {{{name}}} + config.username = 'YOUR USERNAME' + config.password = 'YOUR PASSWORD'{{/isBasic}}{{#isApiKey}} + # Configure API key authorization: {{{name}}} + config.api_key['{{{keyParamName}}}'] = 'YOUR API KEY' + # Uncomment the following line to set a prefix for the API key, e.g. 'BEARER' (defaults to nil) + #config.api_key_prefix['{{{keyParamName}}}'] = 'BEARER'{{/isApiKey}}{{#isOAuth}} + # Configure OAuth2 access token for authorization: {{{name}}} + config.access_token = 'YOUR ACCESS TOKEN'{{/isOAuth}} +{{/authMethods}}end +{{/hasAuthMethods}} + +api_instance = {{{moduleName}}}::{{{classname}}}.new{{#hasParams}} +{{#vendorExtensions.x-codegen-hasRequiredParams}}{{#allParams}}{{#required}} +{{{paramName}}} = {{{example}}} # {{{dataType}}} | {{{description}}} +{{/required}}{{/allParams}}{{/vendorExtensions.x-codegen-hasRequiredParams}}{{#hasOptionalParams}} +opts = { {{#allParams}}{{^required}} + {{{paramName}}}: {{{example}}}{{#vendorExtensions.x-codegen-hasMoreOptional}},{{/vendorExtensions.x-codegen-hasMoreOptional}} # {{{dataType}}} | {{{description}}}{{/required}}{{/allParams}} +}{{/hasOptionalParams}}{{/hasParams}} + +begin +{{#summary}} #{{{.}}} +{{/summary}} {{#returnType}}result = {{/returnType}}api_instance.{{{operationId}}}{{#hasParams}}({{#allParams}}{{#required}}{{{paramName}}}{{#vendorExtensions.x-codegen-hasMoreRequired}}, {{/vendorExtensions.x-codegen-hasMoreRequired}}{{/required}}{{/allParams}}{{#hasOptionalParams}}{{#vendorExtensions.x-codegen-hasRequiredParams}}, {{/vendorExtensions.x-codegen-hasRequiredParams}}opts{{/hasOptionalParams}}){{/hasParams}}{{#returnType}} + p result{{/returnType}} +rescue {{{moduleName}}}::ApiError => e + puts "Exception when calling {{classname}}->{{{operationId}}}: #{e}" +end +{{/-first}}{{/operation}}{{/operations}}{{/-first}}{{/apis}}{{/apiInfo}} +``` + +## Documentation for API Endpoints + +All URIs are relative to *{{basePath}}* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}*{{moduleName}}::{{classname}}* | [**{{operationId}}**]({{apiDocPath}}{{classname}}.md#{{operationId}}) | **{{httpMethod}}** {{path}} | {{#summary}}{{{summary}}}{{/summary}} +{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} + +## Documentation for Models + +{{#models}}{{#model}} - [{{moduleName}}::{{classname}}]({{modelDocPath}}{{classname}}.md) +{{/model}}{{/models}} + +## Documentation for Authorization + +{{^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}} +- **Location**: {{#isKeyInQuery}}URL query string{{/isKeyInQuery}}{{#isKeyInHeader}}HTTP header{{/isKeyInHeader}} +{{/isApiKey}} +{{#isBasic}}- **Type**: HTTP basic authentication +{{/isBasic}} +{{#isOAuth}}- **Type**: OAuth +- **Flow**: {{flow}} +- **Authorizatoin URL**: {{authorizationUrl}} +- **Scopes**: {{^scopes}}N/A{{/scopes}} +{{#scopes}} - {{scope}}: {{description}} +{{/scopes}} +{{/isOAuth}} + +{{/authMethods}} diff --git a/modules/swagger-codegen/src/main/resources/ruby/api.mustache b/modules/swagger-codegen/src/main/resources/ruby/api.mustache index 522807541d9..594a813de72 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/api.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/api.mustache @@ -14,14 +14,14 @@ module {{moduleName}} end {{#operation}} {{newline}} - # {{summary}} - # {{notes}} + # {{{summary}}} + # {{{notes}}} {{#allParams}}{{#required}} # @param {{paramName}} {{description}} {{/required}}{{/allParams}} # @param [Hash] opts the optional parameters -{{#allParams}}{{^required}} # @option opts [{{{dataType}}}] :{{paramName}} {{description}} +{{#allParams}}{{^required}} # @option opts [{{{dataType}}}] :{{paramName}} {{description}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}} {{/required}}{{/allParams}} # @return [{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}nil{{/returnType}}] def {{operationId}}({{#allParams}}{{#required}}{{paramName}}, {{/required}}{{/allParams}}opts = {}) - {{#returnType}}data, status_code, headers = {{/returnType}}{{operationId}}_with_http_info({{#allParams}}{{#required}}{{paramName}}, {{/required}}{{/allParams}}opts) + {{#returnType}}data, _status_code, _headers = {{/returnType}}{{operationId}}_with_http_info({{#allParams}}{{#required}}{{paramName}}, {{/required}}{{/allParams}}opts) {{#returnType}}return data{{/returnType}}{{^returnType}}return nil{{/returnType}} end @@ -58,12 +58,12 @@ module {{moduleName}} header_params = {} # HTTP header 'Accept' (if needed) - _header_accept = [{{#produces}}'{{mediaType}}'{{#hasMore}}, {{/hasMore}}{{/produces}}] - _header_accept_result = @api_client.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + local_header_accept = [{{#produces}}'{{mediaType}}'{{#hasMore}}, {{/hasMore}}{{/produces}}] + local_header_accept_result = @api_client.select_header_accept(local_header_accept) and header_params['Accept'] = local_header_accept_result # HTTP header 'Content-Type' - _header_content_type = [{{#consumes}}'{{mediaType}}'{{#hasMore}}, {{/hasMore}}{{/consumes}}] - header_params['Content-Type'] = @api_client.select_header_content_type(_header_content_type){{#headerParams}}{{#required}} + local_header_content_type = [{{#consumes}}'{{mediaType}}'{{#hasMore}}, {{/hasMore}}{{/consumes}}] + header_params['Content-Type'] = @api_client.select_header_content_type(local_header_content_type){{#headerParams}}{{#required}} header_params[:'{{{baseName}}}'] = {{#collectionFormat}}@api_client.build_collection_param({{{paramName}}}, :{{{collectionFormat}}}){{/collectionFormat}}{{^collectionFormat}}{{{paramName}}}{{/collectionFormat}}{{/required}}{{/headerParams}}{{#headerParams}}{{^required}} header_params[:'{{{baseName}}}'] = {{#collectionFormat}}@api_client.build_collection_param(opts[:'{{{paramName}}}'], :{{{collectionFormat}}}){{/collectionFormat}}{{^collectionFormat}}opts[:'{{{paramName}}}']{{/collectionFormat}} if opts[:'{{{paramName}}}']{{/required}}{{/headerParams}} diff --git a/modules/swagger-codegen/src/main/resources/ruby/api_client.mustache b/modules/swagger-codegen/src/main/resources/ruby/api_client.mustache index d13ad44e5a2..d423ec82a19 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/api_client.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/api_client.mustache @@ -19,9 +19,11 @@ module {{moduleName}} # @return [Hash] attr_accessor :default_headers + # Initializes the ApiClient + # @option config [Configuration] Configuraiton for initializing the object, default to Configuration.default def initialize(config = Configuration.default) @config = config - @user_agent = "ruby-swagger-#{VERSION}" + @user_agent = "{{#httpUserAgent}}{{{.}}}{{/httpUserAgent}}{{^httpUserAgent}}Swagger-Codegen/#{VERSION}/ruby{{/httpUserAgent}}" @default_headers = { 'Content-Type' => "application/json", 'User-Agent' => @user_agent @@ -59,6 +61,15 @@ module {{moduleName}} return data, response.code, response.headers end + # Builds the HTTP request + # + # @param [String] http_method HTTP method/verb (e.g. POST) + # @param [String] path URL path (e.g. /account/new) + # @option opts [Hash] :header_params Header parameters + # @option opts [Hash] :query_params Query parameters + # @option opts [Hash] :form_params Query parameters + # @option opts [Object] :body HTTP body (JSON/XML) + # @return [Typhoeus::Request] A Typhoeus Request def build_request(http_method, path, opts = {}) url = build_request_url(path) http_method = http_method.to_sym.downcase @@ -100,12 +111,15 @@ module {{moduleName}} # application/json # application/json; charset=UTF8 # APPLICATION/JSON + # @param [String] mime MIME + # @return [Boolean] True if the MIME is applicaton/json def json_mime?(mime) - !!(mime =~ /\Aapplication\/json(;.*)?\z/i) + !(mime =~ /\Aapplication\/json(;.*)?\z/i).nil? end # Deserialize the response to the given return type. # + # @param [Response] response HTTP response # @param [String] return_type some examples: "User", "Array[User]", "Hash[String,Integer]" def deserialize(response, return_type) body = response.body @@ -136,6 +150,9 @@ module {{moduleName}} end # Convert data to the given return type. + # @param [Object] data Data to be converted + # @param [String] return_type Return type + # @return [Mixed] Data in a particular type def convert_to_type(data, return_type) return nil if data.nil? case return_type @@ -208,7 +225,7 @@ module {{moduleName}} # @param [String] filename the filename to be sanitized # @return [String] the sanitized filename def sanitize_filename(filename) - filename.gsub /.*[\/\\]/, '' + filename.gsub(/.*[\/\\]/, '') end def build_request_url(path) @@ -217,6 +234,12 @@ module {{moduleName}} URI.encode(@config.base_url + path) end + # Builds the HTTP request body + # + # @param [Hash] header_params Header parameters + # @param [Hash] form_params Query parameters + # @param [Object] body HTTP body (JSON/XML) + # @return [String] HTTP body data in the form of string def build_request_body(header_params, form_params, body) # http form if header_params['Content-Type'] == 'application/x-www-form-urlencoded' || @@ -240,6 +263,10 @@ module {{moduleName}} end # Update hearder and query params based on authentication settings. + # + # @param [Hash] header_params Header parameters + # @param [Hash] form_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| auth_setting = @config.auth_settings[auth_name] @@ -252,6 +279,9 @@ module {{moduleName}} end end + # Sets user agent in HTTP header + # + # @param [String] user_agent User agent (e.g. swagger-codegen/ruby/1.0.0) def user_agent=(user_agent) @user_agent = user_agent @default_headers['User-Agent'] = @user_agent @@ -283,13 +313,13 @@ module {{moduleName}} # @return [String] JSON string representation of the object def object_to_http_body(model) return model if model.nil? || model.is_a?(String) - _body = nil + local_body = nil if model.is_a?(Array) - _body = model.map{|m| object_to_hash(m) } + local_body = model.map{|m| object_to_hash(m) } else - _body = object_to_hash(model) + local_body = object_to_hash(model) end - _body.to_json + local_body.to_json end # Convert object(non-array) to hash. diff --git a/modules/swagger-codegen/src/main/resources/ruby/api_doc.mustache b/modules/swagger-codegen/src/main/resources/ruby/api_doc.mustache new file mode 100644 index 00000000000..6d36e7dfe89 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/ruby/api_doc.mustache @@ -0,0 +1,79 @@ +# {{moduleName}}::{{classname}}{{#description}} +{{description}}{{/description}} + +All URIs are relative to *{{basePath}}* + +Method | HTTP request | Description +------------- | ------------- | ------------- +{{#operations}}{{#operation}}[**{{operationId}}**]({{classname}}.md#{{operationId}}) | **{{httpMethod}}** {{path}} | {{#summary}}{{summary}}{{/summary}} +{{/operation}}{{/operations}} + +{{#operations}} +{{#operation}} +# **{{operationId}}** +> {{#returnType}}{{returnType}} {{/returnType}}{{operationId}}{{#hasParams}}({{#allParams}}{{#required}}{{{paramName}}}{{#vendorExtensions.x-codegen-hasMoreRequired}}, {{/vendorExtensions.x-codegen-hasMoreRequired}}{{/required}}{{/allParams}}{{#hasOptionalParams}}{{#vendorExtensions.x-codegen-hasRequiredParams}}, {{/vendorExtensions.x-codegen-hasRequiredParams}}opts{{/hasOptionalParams}}){{/hasParams}} + +{{{summary}}}{{#notes}} + +{{{notes}}}{{/notes}} + +### Example +```ruby +# load the gem +require '{{{gemName}}}' +{{#hasAuthMethods}} +# setup authorization +{{{moduleName}}}.configure do |config|{{#authMethods}}{{#isBasic}} + # Configure HTTP basic authorization: {{{name}}} + config.username = 'YOUR USERNAME' + config.password = 'YOUR PASSWORD'{{/isBasic}}{{#isApiKey}} + # Configure API key authorization: {{{name}}} + config.api_key['{{{keyParamName}}}'] = 'YOUR API KEY' + # Uncomment the following line to set a prefix for the API key, e.g. 'BEARER' (defaults to nil) + #config.api_key_prefix['{{{keyParamName}}}'] = 'BEARER'{{/isApiKey}}{{#isOAuth}} + # Configure OAuth2 access token for authorization: {{{name}}} + config.access_token = 'YOUR ACCESS TOKEN'{{/isOAuth}} +{{/authMethods}}end +{{/hasAuthMethods}} + +api_instance = {{{moduleName}}}::{{{classname}}}.new{{#hasParams}} +{{#vendorExtensions.x-codegen-hasRequiredParams}}{{#allParams}}{{#required}} +{{{paramName}}} = {{{example}}} # {{{dataType}}} | {{{description}}} +{{/required}}{{/allParams}}{{/vendorExtensions.x-codegen-hasRequiredParams}}{{#hasOptionalParams}} +opts = { {{#allParams}}{{^required}} + {{{paramName}}}: {{{example}}}{{#vendorExtensions.x-codegen-hasMoreOptional}},{{/vendorExtensions.x-codegen-hasMoreOptional}} # {{{dataType}}} | {{{description}}}{{/required}}{{/allParams}} +}{{/hasOptionalParams}}{{/hasParams}} + +begin +{{#summary}} #{{{.}}} +{{/summary}} {{#returnType}}result = {{/returnType}}api_instance.{{{operationId}}}{{#hasParams}}({{#allParams}}{{#required}}{{{paramName}}}{{#vendorExtensions.x-codegen-hasMoreRequired}}, {{/vendorExtensions.x-codegen-hasMoreRequired}}{{/required}}{{/allParams}}{{#hasOptionalParams}}{{#vendorExtensions.x-codegen-hasRequiredParams}}, {{/vendorExtensions.x-codegen-hasRequiredParams}}opts{{/hasOptionalParams}}){{/hasParams}}{{#returnType}} + p result{{/returnType}} +rescue {{{moduleName}}}::ApiError => e + puts "Exception when calling {{classname}}->{{{operationId}}}: #{e}" +end +``` + +### Parameters +{{^allParams}}This endpoint does not need any parameter.{{/allParams}}{{#allParams}}{{#-last}} +Name | Type | Description | Notes +------------- | ------------- | ------------- | -------------{{/-last}}{{/allParams}} +{{#allParams}} **{{paramName}}** | {{#isPrimitiveType}}**{{dataType}}**{{/isPrimitiveType}}{{^isPrimitiveType}}{{#isFile}}**{{dataType}}**{{/isFile}}{{^isFile}}[**{{dataType}}**]({{baseType}}.md){{/isFile}}{{/isPrimitiveType}}| {{description}} | {{^required}}[optional] {{/required}}{{#defaultValue}}[default to {{defaultValue}}]{{/defaultValue}} +{{/allParams}} + +### Return type + +{{#returnType}}{{#returnTypeIsPrimitive}}**{{returnType}}**{{/returnTypeIsPrimitive}}{{^returnTypeIsPrimitive}}[**{{returnType}}**]({{returnBaseType}}.md){{/returnTypeIsPrimitive}}{{/returnType}}{{^returnType}}nil (empty response body){{/returnType}} + +### Authorization + +{{^authMethods}}No authorization required{{/authMethods}}{{#authMethods}}[{{name}}](../README.md#{{name}}){{^-last}}, {{/-last}}{{/authMethods}} + +### HTTP reuqest headers + + - **Content-Type**: {{#consumes}}{{mediaType}}{{#hasMore}}, {{/hasMore}}{{/consumes}}{{^consumes}}Not defined{{/consumes}} + - **Accept**: {{#produces}}{{mediaType}}{{#hasMore}}, {{/hasMore}}{{/produces}}{{^produces}}Not defined{{/produces}} + + + +{{/operation}} +{{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/ruby/base_object.mustache b/modules/swagger-codegen/src/main/resources/ruby/base_object.mustache index 2c7747c4127..87877d1763e 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/base_object.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/base_object.mustache @@ -1,23 +1,27 @@ - # build the object from hash + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself def build_from_hash(attributes) return nil unless attributes.is_a?(Hash) self.class.swagger_types.each_pair do |key, type| if type =~ /^Array<(.*)>/i + # check to ensure the input is an array given that the the attribute + # is documented as an array but the input is not if attributes[self.class.attribute_map[key]].is_a?(Array) self.send("#{key}=", attributes[self.class.attribute_map[key]].map{ |v| _deserialize($1, v) } ) - else - #TODO show warning in debug mode end elsif !attributes[self.class.attribute_map[key]].nil? self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) - else - # data not found in attributes(hash), not an issue as the data can be optional - end + 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 @@ -51,21 +55,25 @@ end end else # model - _model = {{moduleName}}.const_get(type).new - _model.build_from_hash(value) + temp_model = {{moduleName}}.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_body (backward compatibility)) + # 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 - # return the object in the form of hash + # 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| @@ -76,8 +84,10 @@ hash end - # Method to output non-array value in the form of hash + # 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) } diff --git a/modules/swagger-codegen/src/main/resources/ruby/git_push.sh.mustache b/modules/swagger-codegen/src/main/resources/ruby/git_push.sh.mustache new file mode 100755 index 00000000000..e153ce23ecf --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/ruby/git_push.sh.mustache @@ -0,0 +1,52 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 swagger-petstore-perl "minor update" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 + +if [ "$git_user_id" = "" ]; then + git_user_id="{{{gitUserId}}}" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="{{{gitRepoId}}}" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="{{{releaseNote}}}" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=`git remote` +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git crediential in your environment." + git remote add origin https://github.com/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:${GIT_TOKEN}@github.com/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://github.com/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' + diff --git a/modules/swagger-codegen/src/main/resources/ruby/gitignore.mustache b/modules/swagger-codegen/src/main/resources/ruby/gitignore.mustache new file mode 100644 index 00000000000..a8b1cda23f8 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/ruby/gitignore.mustache @@ -0,0 +1,36 @@ +*.gem +*.rbc +/.config +/coverage/ +/InstalledFiles +/pkg/ +/spec/reports/ +/spec/examples.txt +/test/tmp/ +/test/version_tmp/ +/tmp/ + +## Specific to RubyMotion: +.dat* +.repl_history +build/ + +## Documentation cache and generated files: +/.yardoc/ +/_yardoc/ +/doc/ +/rdoc/ + +## Environment normalization: +/.bundle/ +/vendor/bundle +/lib/bundler/man/ + +# for a library or gem, you might want to ignore these files since the code is +# intended to run in multiple environments; otherwise, check them in: +# Gemfile.lock +# .ruby-version +# .ruby-gemset + +# unless supporting rvm < 1.11.0 or doing something fancy, ignore this: +.rvmrc diff --git a/modules/swagger-codegen/src/main/resources/ruby/model.mustache b/modules/swagger-codegen/src/main/resources/ruby/model.mustache index 86567e1d594..373a0634be2 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/model.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/model.mustache @@ -28,11 +28,13 @@ module {{moduleName}}{{#models}}{{#model}}{{#description}} } 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.inject({}){|memo,(k,v)| memo[k.to_sym] = v; memo} + attributes = attributes.each_with_object({}){|(k,v), h| h[k.to_sym] = v} {{#vars}} if attributes[:'{{{baseName}}}'] @@ -46,6 +48,7 @@ module {{moduleName}}{{#models}}{{#model}}{{#description}} end {{#vars}}{{#isEnum}} # Custom attribute writer method checking allowed values (enum). + # @param [Object] {{{name}}} Object to be assigned def {{{name}}}=({{{name}}}) allowed_values = [{{#allowableValues}}{{#values}}"{{{this}}}"{{^-last}}, {{/-last}}{{/values}}{{/allowableValues}}] if {{{name}}} && !allowed_values.include?({{{name}}}) @@ -54,7 +57,8 @@ module {{moduleName}}{{#models}}{{#model}}{{#description}} @{{{name}}} = {{{name}}} end {{/isEnum}}{{/vars}} - # Check equality by comparing each attribute. + # Checks equality by comparing each attribute. + # @param [Object] Object to be compared def ==(o) return true if self.equal?(o) self.class == o.class{{#vars}} && @@ -62,11 +66,13 @@ module {{moduleName}}{{#models}}{{#model}}{{#description}} end # @see the `==` method + # @param [Object] Object to be compared def eql?(o) self == o end - # Calculate hash code according to all attributes. + # Calculates hash code according to all attributes. + # @return [Fixnum] Hash code def hash [{{#vars}}{{name}}{{#hasMore}}, {{/hasMore}}{{/vars}}].hash end diff --git a/modules/swagger-codegen/src/main/resources/ruby/model_doc.mustache b/modules/swagger-codegen/src/main/resources/ruby/model_doc.mustache new file mode 100644 index 00000000000..00befadc578 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/ruby/model_doc.mustache @@ -0,0 +1,9 @@ +{{#models}}{{#model}}# {{moduleName}}::{{classname}} + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +{{#vars}}**{{name}}** | {{#isPrimitiveType}}**{{datatype}}**{{/isPrimitiveType}}{{^isPrimitiveType}}[**{{datatype}}**]({{complexType}}.md){{/isPrimitiveType}} | {{description}} | {{^required}}[optional] {{/required}}{{#readOnly}}[readonly] {{/readOnly}}{{#defaultValue}}[default to {{defaultValue}}]{{/defaultValue}} +{{/vars}} + +{{/model}}{{/models}} diff --git a/modules/swagger-codegen/src/main/resources/scala/api.mustache b/modules/swagger-codegen/src/main/resources/scala/api.mustache index 3b74dca8162..41b58374dea 100644 --- a/modules/swagger-codegen/src/main/resources/scala/api.mustache +++ b/modules/swagger-codegen/src/main/resources/scala/api.mustache @@ -27,7 +27,7 @@ class {{classname}}(val defBasePath: String = "{{basePath}}", /** * {{summary}} * {{notes}} -{{#allParams}} * @param {{paramName}} {{description}} +{{#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}} = { diff --git a/modules/swagger-codegen/src/main/resources/scala/git_push.sh.mustache b/modules/swagger-codegen/src/main/resources/scala/git_push.sh.mustache new file mode 100755 index 00000000000..e153ce23ecf --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/scala/git_push.sh.mustache @@ -0,0 +1,52 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 swagger-petstore-perl "minor update" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 + +if [ "$git_user_id" = "" ]; then + git_user_id="{{{gitUserId}}}" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="{{{gitRepoId}}}" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="{{{releaseNote}}}" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=`git remote` +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git crediential in your environment." + git remote add origin https://github.com/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:${GIT_TOKEN}@github.com/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://github.com/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' + diff --git a/modules/swagger-codegen/src/main/resources/scala/gitignore.mustache b/modules/swagger-codegen/src/main/resources/scala/gitignore.mustache new file mode 100644 index 00000000000..c58d83b3189 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/scala/gitignore.mustache @@ -0,0 +1,17 @@ +*.class +*.log + +# sbt specific +.cache +.history +.lib/ +dist/* +target/ +lib_managed/ +src_managed/ +project/boot/ +project/plugins/project/ + +# Scala-IDE specific +.scala_dependencies +.worksheet diff --git a/modules/swagger-codegen/src/main/resources/scala/pom.mustache b/modules/swagger-codegen/src/main/resources/scala/pom.mustache index b3260b9fd62..51256c42491 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.7 + 1.5.8 1.0.5 1.0.0 2.4.2 diff --git a/modules/swagger-codegen/src/main/resources/swift/Extensions.mustache b/modules/swagger-codegen/src/main/resources/swift/Extensions.mustache index ed5786d3faa..54a1f127ef7 100644 --- a/modules/swagger-codegen/src/main/resources/swift/Extensions.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/Extensions.mustache @@ -19,6 +19,14 @@ 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 } } diff --git a/modules/swagger-codegen/src/main/resources/swift/Models.mustache b/modules/swagger-codegen/src/main/resources/swift/Models.mustache index 352f4976966..31cb4a2e219 100644 --- a/modules/swagger-codegen/src/main/resources/swift/Models.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/Models.mustache @@ -56,6 +56,12 @@ class Decoders { 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 } @@ -132,8 +138,8 @@ class Decoders { Decoders.addDecoder(clazz: {{{classname}}}.self) { (source: AnyObject) -> {{{classname}}} in let sourceDictionary = source as! [NSObject:AnyObject] let instance = {{classname}}(){{#vars}}{{#isEnum}} - instance.{{name}} = {{classname}}.{{datatypeWithEnum}}(rawValue: (sourceDictionary["{{name}}"] as? String) ?? ""){{#unwrapRequired}}{{#required}}!{{/required}}{{/unwrapRequired}} {{/isEnum}}{{^isEnum}} - instance.{{name}} = Decoders.decode{{^unwrapRequired}}Optional{{/unwrapRequired}}{{#unwrapRequired}}{{^required}}Optional{{/required}}{{/unwrapRequired}}(clazz: {{{baseType}}}.self, source: sourceDictionary["{{name}}"]{{#unwrapRequired}}{{#required}}!{{/required}}{{/unwrapRequired}}){{/isEnum}}{{/vars}} + instance.{{name}} = {{classname}}.{{datatypeWithEnum}}(rawValue: (sourceDictionary["{{baseName}}"] as? String) ?? ""){{#unwrapRequired}}{{#required}}!{{/required}}{{/unwrapRequired}} {{/isEnum}}{{^isEnum}} + instance.{{name}} = Decoders.decode{{^unwrapRequired}}Optional{{/unwrapRequired}}{{#unwrapRequired}}{{^required}}Optional{{/required}}{{/unwrapRequired}}(clazz: {{{baseType}}}.self, source: sourceDictionary["{{baseName}}"]{{#unwrapRequired}}{{#required}}!{{/required}}{{/unwrapRequired}}){{/isEnum}}{{/vars}} return instance }{{/model}} {{/models}} diff --git a/modules/swagger-codegen/src/main/resources/swift/api.mustache b/modules/swagger-codegen/src/main/resources/swift/api.mustache index 64757126563..ada4ec90d36 100644 --- a/modules/swagger-codegen/src/main/resources/swift/api.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/api.mustache @@ -20,7 +20,7 @@ public class {{classname}}: APIBase { {{#summary}} {{{summary}}} {{/summary}}{{#allParams}} - - parameter {{paramName}}: ({{#isFormParam}}form{{/isFormParam}}{{#isQueryParam}}query{{/isQueryParam}}{{#isPathParam}}path{{/isPathParam}}{{#isHeaderParam}}header{{/isHeaderParam}}{{#isBodyParam}}body{{/isBodyParam}}) {{description}}{{/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}} - parameter completion: completion handler to receive the data and the error objects */ public class func {{operationId}}({{#allParams}}{{^secondaryParam}}{{paramName}} {{/secondaryParam}}{{paramName}}: {{{dataType}}}{{^required}}?{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}{{#hasParams}}, {{/hasParams}}completion: (({{#returnType}}data: {{{returnType}}}?, {{/returnType}}error: ErrorType?) -> Void)) { @@ -34,7 +34,7 @@ public class {{classname}}: APIBase { {{#summary}} {{{summary}}} {{/summary}}{{#allParams}} - - parameter {{paramName}}: ({{#isFormParam}}form{{/isFormParam}}{{#isQueryParam}}query{{/isQueryParam}}{{#isPathParam}}path{{/isPathParam}}{{#isHeaderParam}}header{{/isHeaderParam}}{{#isBodyParam}}body{{/isBodyParam}}) {{description}}{{/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: Promise<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> */ public class func {{operationId}}({{#allParams}}{{^secondaryParam}}{{paramName}} {{/secondaryParam}}{{paramName}}: {{{dataType}}}{{^required}}?{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) -> Promise<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> { @@ -65,7 +65,7 @@ public class {{classname}}: APIBase { - examples: {{{examples}}}{{/examples}}{{#externalDocs}} - externalDocs: {{externalDocs}}{{/externalDocs}}{{#hasParams}} {{/hasParams}}{{#allParams}} - - parameter {{paramName}}: ({{#isFormParam}}form{{/isFormParam}}{{#isQueryParam}}query{{/isQueryParam}}{{#isPathParam}}path{{/isPathParam}}{{#isHeaderParam}}header{{/isHeaderParam}}{{#isBodyParam}}body{{/isBodyParam}}) {{description}}{{/allParams}} + - parameter {{paramName}}: ({{#isFormParam}}form{{/isFormParam}}{{#isQueryParam}}query{{/isQueryParam}}{{#isPathParam}}path{{/isPathParam}}{{#isHeaderParam}}header{{/isHeaderParam}}{{#isBodyParam}}body{{/isBodyParam}}) {{description}} {{^required}}(optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}{{/allParams}} - returns: RequestBuilder<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> {{description}} */ diff --git a/modules/swagger-codegen/src/main/resources/swift/git_push.sh.mustache b/modules/swagger-codegen/src/main/resources/swift/git_push.sh.mustache new file mode 100755 index 00000000000..e153ce23ecf --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/swift/git_push.sh.mustache @@ -0,0 +1,52 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 swagger-petstore-perl "minor update" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 + +if [ "$git_user_id" = "" ]; then + git_user_id="{{{gitUserId}}}" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="{{{gitRepoId}}}" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="{{{releaseNote}}}" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=`git remote` +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git crediential in your environment." + git remote add origin https://github.com/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:${GIT_TOKEN}@github.com/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://github.com/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' + diff --git a/modules/swagger-codegen/src/main/resources/swift/gitignore.mustache b/modules/swagger-codegen/src/main/resources/swift/gitignore.mustache new file mode 100644 index 00000000000..5e5d5cebcf4 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/swift/gitignore.mustache @@ -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/modules/swagger-codegen/src/main/resources/swift/model.mustache b/modules/swagger-codegen/src/main/resources/swift/model.mustache index 892a3a59f96..7e2f99a9de8 100644 --- a/modules/swagger-codegen/src/main/resources/swift/model.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/model.mustache @@ -25,11 +25,13 @@ public class {{classname}}: JSONEncodable { // MARK: JSONEncodable func encodeToJSON() -> AnyObject { - var nillableDictionary = [String:AnyObject?](){{#vars}}{{#isNotContainer}}{{#isPrimitiveType}}{{^isEnum}} - nillableDictionary["{{name}}"] = self.{{name}}{{/isEnum}}{{/isPrimitiveType}}{{#isEnum}} - nillableDictionary["{{name}}"] = self.{{name}}{{^unwrapRequired}}?{{/unwrapRequired}}{{#unwrapRequired}}{{^required}}?{{/required}}{{/unwrapRequired}}.rawValue{{/isEnum}}{{^isPrimitiveType}} - nillableDictionary["{{name}}"] = self.{{name}}{{^unwrapRequired}}?{{/unwrapRequired}}{{#unwrapRequired}}{{^required}}?{{/required}}{{/unwrapRequired}}.encodeToJSON(){{/isPrimitiveType}}{{/isNotContainer}}{{#isContainer}} - nillableDictionary["{{name}}"] = self.{{name}}{{^unwrapRequired}}?{{/unwrapRequired}}{{#unwrapRequired}}{{^required}}?{{/required}}{{/unwrapRequired}}.encodeToJSON(){{/isContainer}}{{/vars}} + var nillableDictionary = [String:AnyObject?](){{#vars}}{{#isNotContainer}}{{#isPrimitiveType}}{{^isEnum}}{{#isInteger}} + nillableDictionary["{{baseName}}"] = self.{{name}}{{^unwrapRequired}}?{{/unwrapRequired}}{{#unwrapRequired}}{{^required}}?{{/required}}{{/unwrapRequired}}.encodeToJSON(){{/isInteger}}{{#isLong}} + nillableDictionary["{{baseName}}"] = self.{{name}}{{^unwrapRequired}}?{{/unwrapRequired}}{{#unwrapRequired}}{{^required}}?{{/required}}{{/unwrapRequired}}.encodeToJSON(){{/isLong}}{{^isLong}}{{^isInteger}} + nillableDictionary["{{baseName}}"] = self.{{name}}{{/isInteger}}{{/isLong}}{{/isEnum}}{{/isPrimitiveType}}{{#isEnum}} + nillableDictionary["{{baseName}}"] = self.{{name}}{{^unwrapRequired}}?{{/unwrapRequired}}{{#unwrapRequired}}{{^required}}?{{/required}}{{/unwrapRequired}}.rawValue{{/isEnum}}{{^isPrimitiveType}} + nillableDictionary["{{baseName}}"] = self.{{name}}{{^unwrapRequired}}?{{/unwrapRequired}}{{#unwrapRequired}}{{^required}}?{{/required}}{{/unwrapRequired}}.encodeToJSON(){{/isPrimitiveType}}{{/isNotContainer}}{{#isContainer}} + nillableDictionary["{{baseName}}"] = self.{{name}}{{^unwrapRequired}}?{{/unwrapRequired}}{{#unwrapRequired}}{{^required}}?{{/required}}{{/unwrapRequired}}.encodeToJSON(){{/isContainer}}{{/vars}} let dictionary: [String:AnyObject] = APIHelper.rejectNil(nillableDictionary) ?? [:] return dictionary } 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 70880a29a3b..4b422bb3c63 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 @@ -175,6 +175,17 @@ public class CodegenTest { Assert.assertTrue(op.responses.get(0).isBinary); } + @Test(description = "discriminator is present") + public void discriminatorTest() { + final Swagger model = parseAndPrepareSwagger("src/test/resources/2_0/discriminatorTest.json"); + final DefaultCodegen codegen = new DefaultCodegen(); + final String path = "/pets"; + final Operation p = model.getPaths().get(path).getGet(); + final CodegenOperation op = codegen.fromOperation(path, "get", p, model.getDefinitions()); + + Assert.assertEquals(op.discriminator, "className"); + } + @Test(description = "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/java/JavaModelTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaModelTest.java index e00d9c0ed66..d69b2361db1 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaModelTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaModelTest.java @@ -287,8 +287,8 @@ public class JavaModelTest { Assert.assertEquals(cm.description, "an array model"); Assert.assertEquals(cm.vars.size(), 0); Assert.assertEquals(cm.parent, "ArrayList"); - Assert.assertEquals(cm.imports.size(), 3); - Assert.assertEquals(Sets.intersection(cm.imports, Sets.newHashSet("List", "ArrayList", "Children")).size(), 3); + Assert.assertEquals(cm.imports.size(), 4); + Assert.assertEquals(Sets.intersection(cm.imports, Sets.newHashSet("ApiModel", "List", "ArrayList", "Children")).size(), 4); } @Test(description = "convert an map model") @@ -304,8 +304,8 @@ public class JavaModelTest { Assert.assertEquals(cm.description, "an map model"); Assert.assertEquals(cm.vars.size(), 0); Assert.assertEquals(cm.parent, "HashMap"); - Assert.assertEquals(cm.imports.size(), 3); - Assert.assertEquals(Sets.intersection(cm.imports, Sets.newHashSet("Map", "HashMap", "Children")).size(), 3); + Assert.assertEquals(cm.imports.size(), 4); + Assert.assertEquals(Sets.intersection(cm.imports, Sets.newHashSet("ApiModel", "Map", "HashMap", "Children")).size(), 4); } @Test(description = "convert a model with upper-case property names") diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/javascript/JavaScriptClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/javascript/JavaScriptClientOptionsTest.java new file mode 100644 index 00000000000..927d4d7755b --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/javascript/JavaScriptClientOptionsTest.java @@ -0,0 +1,71 @@ +package io.swagger.codegen.javascript; + +import io.swagger.codegen.AbstractOptionsTest; +import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.options.JavaScriptOptionsProvider; +import io.swagger.codegen.languages.JavascriptClientCodegen; +import io.swagger.codegen.options.OptionsProvider; + +import mockit.Expectations; +import mockit.Tested; + +public class JavaScriptClientOptionsTest extends AbstractOptionsTest { + @Tested + private JavascriptClientCodegen clientCodegen; + + public JavaScriptClientOptionsTest() { + super(new JavaScriptOptionsProvider()); + } + + protected JavaScriptClientOptionsTest(OptionsProvider optionsProvider) { + super(optionsProvider); + } + + @Override + protected CodegenConfig getCodegenConfig() { + return clientCodegen; + } + + @Override + protected void setExpectations() { + // Commented generic options not yet supported by JavaScript codegen. + new Expectations(clientCodegen) {{ + clientCodegen.setModelPackage(JavaScriptOptionsProvider.MODEL_PACKAGE_VALUE); + times = 1; + clientCodegen.setApiPackage(JavaScriptOptionsProvider.API_PACKAGE_VALUE); + times = 1; + clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(JavaScriptOptionsProvider.SORT_PARAMS_VALUE)); + times = 1; +// clientCodegen.setInvokerPackage(JavaScriptOptionsProvider.INVOKER_PACKAGE_VALUE); +// times = 1; +// clientCodegen.setGroupId(JavaScriptOptionsProvider.GROUP_ID_VALUE); +// times = 1; +// clientCodegen.setArtifactId(JavaScriptOptionsProvider.ARTIFACT_ID_VALUE); +// times = 1; +// clientCodegen.setArtifactVersion(JavaScriptOptionsProvider.ARTIFACT_VERSION_VALUE); +// times = 1; + clientCodegen.setSourceFolder(JavaScriptOptionsProvider.SOURCE_FOLDER_VALUE); + times = 1; + clientCodegen.setLocalVariablePrefix(JavaScriptOptionsProvider.LOCAL_PREFIX_VALUE); + times = 1; + clientCodegen.setProjectName(JavaScriptOptionsProvider.PROJECT_NAME_VALUE); + times = 1; + clientCodegen.setModuleName(JavaScriptOptionsProvider.MODULE_NAME_VALUE); + times = 1; + clientCodegen.setProjectDescription(JavaScriptOptionsProvider.PROJECT_DESCRIPTION_VALUE); + times = 1; + clientCodegen.setProjectVersion(JavaScriptOptionsProvider.PROJECT_VERSION_VALUE); + times = 1; + clientCodegen.setProjectLicenseName(JavaScriptOptionsProvider.PROJECT_LICENSE_NAME_VALUE); + times = 1; + clientCodegen.setUsePromises(Boolean.valueOf(JavaScriptOptionsProvider.USE_PROMISES_VALUE)); + times = 1; + clientCodegen.setUseInheritance(Boolean.valueOf(JavaScriptOptionsProvider.USE_INHERITANCE_VALUE)); + times = 1; + clientCodegen.setEmitModelMethods(Boolean.valueOf(JavaScriptOptionsProvider.EMIT_MODEL_METHODS_VALUE)); + times = 1; + clientCodegen.setEmitJSDoc(Boolean.valueOf(JavaScriptOptionsProvider.EMIT_JS_DOC_VALUE)); + times = 1; + }}; + } +} 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 new file mode 100644 index 00000000000..94285e46888 --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/javascript/JavaScriptInheritanceTest.java @@ -0,0 +1,102 @@ +package io.swagger.codegen.javascript; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + +import org.testng.Assert; +import org.testng.annotations.Test; + +import com.google.common.collect.Sets; + +import io.swagger.codegen.CodegenModel; +import io.swagger.codegen.languages.JavascriptClientCodegen; +import io.swagger.models.ComposedModel; +import io.swagger.models.Model; +import io.swagger.models.ModelImpl; +import io.swagger.models.RefModel; +import io.swagger.models.properties.StringProperty; + +public class JavaScriptInheritanceTest { + @SuppressWarnings("static-method") + @Test(description = "convert a composed model with inheritance enabled") + public void javascriptInheritanceTest() { + ModelImpl base = new ModelImpl(); + base.addProperty("baseProp", new StringProperty().required(true)); + ModelImpl intf1 = new ModelImpl(); + intf1.addProperty("intf1Prop", new StringProperty()); + ModelImpl intf2 = new ModelImpl(); + intf2.addProperty("intf2Prop", new StringProperty().required(true)); + ModelImpl child = new ModelImpl(); + child.addProperty("childProp", new StringProperty().required(true)); + + final Map allDefinitions = new HashMap(); + allDefinitions.put("Base", base); + allDefinitions.put("Interface1", intf1); + allDefinitions.put("Interface2", intf2); + + final Model model = new ComposedModel().parent(new RefModel("Base")) + .interfaces(Arrays.asList(new RefModel("Interface1"), new RefModel("Interface2"))) + .child(child); + + final JavascriptClientCodegen codegen = new JavascriptClientCodegen(); + codegen.setUseInheritance(true); + + final CodegenModel cm = codegen.fromModel("sample", model, allDefinitions); + Assert.assertEquals(cm.name, "sample"); + Assert.assertEquals(cm.classname, "Sample"); + Assert.assertEquals(cm.parent, "Base"); + Assert.assertEquals(cm.interfaces, Arrays.asList("Interface1", "Interface2")); + Assert.assertEquals(cm.imports, Sets.newHashSet("Base", "Interface1", "Interface2")); + Assert.assertEquals(cm.vars.size(), 1); + Assert.assertEquals(cm.vars.get(0).name, "childProp"); + Assert.assertEquals(cm.allVars.size(), 4); + String[] allVars = {"baseProp", "intf1Prop", "intf2Prop", "childProp"}; + for (int i = 0; i < allVars.length; i++) { + Assert.assertEquals(cm.allVars.get(i).name, allVars[i]); + } + Assert.assertEquals(cm.mandatory, Sets.newHashSet("childProp")); + Assert.assertEquals(cm.allMandatory, Sets.newHashSet("baseProp", "intf2Prop", "childProp")); + } + + @SuppressWarnings("static-method") + @Test(description = "convert a composed model with inheritance disabled") + public void javascriptNoInheritanceTest() { + ModelImpl base = new ModelImpl(); + base.addProperty("baseProp", new StringProperty().required(true)); + ModelImpl intf1 = new ModelImpl(); + intf1.addProperty("intf1Prop", new StringProperty()); + ModelImpl intf2 = new ModelImpl(); + intf2.addProperty("intf2Prop", new StringProperty().required(true)); + ModelImpl child = new ModelImpl(); + child.addProperty("childProp", new StringProperty().required(true)); + + final Map allDefinitions = new HashMap(); + allDefinitions.put("Base", base); + allDefinitions.put("Interface1", intf1); + allDefinitions.put("Interface2", intf2); + + final Model model = new ComposedModel().parent(new RefModel("Base")) + .interfaces(Arrays.asList(new RefModel("Interface1"), new RefModel("Interface2"))) + .child(child); + + final JavascriptClientCodegen codegen = new JavascriptClientCodegen(); + codegen.setUseInheritance(false); + + final CodegenModel cm = codegen.fromModel("sample", model, allDefinitions); + Assert.assertEquals(cm.name, "sample"); + Assert.assertEquals(cm.classname, "Sample"); + Assert.assertEquals(cm.parent, "Base"); + Assert.assertEquals(cm.interfaces, Arrays.asList("Interface1", "Interface2")); + Assert.assertEquals(cm.imports, Sets.newHashSet("Base", "Interface1", "Interface2")); + Assert.assertEquals(cm.vars.size(), 4); + Assert.assertEquals(cm.allVars.size(), 4); + String[] allVars = {"baseProp", "intf1Prop", "intf2Prop", "childProp"}; + for (int i = 0; i < allVars.length; i++) { + Assert.assertEquals(cm.vars.get(i).name, allVars[i]); + Assert.assertEquals(cm.allVars.get(i).name, allVars[i]); + } + Assert.assertEquals(cm.mandatory, Sets.newHashSet("baseProp", "intf2Prop", "childProp")); + Assert.assertEquals(cm.allMandatory, Sets.newHashSet("baseProp", "intf2Prop", "childProp")); + } +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/javascript/JavaScriptModelEnumTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/javascript/JavaScriptModelEnumTest.java new file mode 100644 index 00000000000..5e2306d73fb --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/javascript/JavaScriptModelEnumTest.java @@ -0,0 +1,95 @@ +package io.swagger.codegen.javascript; + +import io.swagger.codegen.CodegenModel; +import io.swagger.codegen.CodegenProperty; +import io.swagger.codegen.DefaultCodegen; +import io.swagger.codegen.languages.JavaClientCodegen; +import io.swagger.codegen.languages.JavascriptClientCodegen; +import io.swagger.models.ComposedModel; +import io.swagger.models.Model; +import io.swagger.models.ModelImpl; +import io.swagger.models.RefModel; +import io.swagger.models.properties.Property; +import io.swagger.models.properties.StringProperty; +import org.testng.Assert; +import org.testng.annotations.Test; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + +@SuppressWarnings("static-method") +public class JavaScriptModelEnumTest { + @Test(description = "convert a JavaScript model with an enum") + public void converterTest() { + final StringProperty enumProperty = new StringProperty(); + enumProperty.setEnum(Arrays.asList("VALUE1", "VALUE2", "VALUE3")); + final ModelImpl model = new ModelImpl().property("name", enumProperty); + + final DefaultCodegen codegen = new JavascriptClientCodegen(); + final CodegenModel cm = codegen.fromModel("sample", model); + + Assert.assertEquals(cm.vars.size(), 1); + + final CodegenProperty enumVar = cm.vars.get(0); + Assert.assertEquals(enumVar.baseName, "name"); + Assert.assertEquals(enumVar.datatype, "String"); + Assert.assertEquals(enumVar.datatypeWithEnum, "NameEnum"); + Assert.assertEquals(enumVar.name, "name"); + Assert.assertEquals(enumVar.defaultValue, null); + Assert.assertEquals(enumVar.baseType, "String"); + Assert.assertTrue(enumVar.isEnum); + } + + @Test(description = "not override identical parent enums") + public void overrideEnumTest() { + final StringProperty identicalEnumProperty = new StringProperty(); + identicalEnumProperty.setEnum(Arrays.asList("VALUE1", "VALUE2", "VALUE3")); + + final StringProperty subEnumProperty = new StringProperty(); + subEnumProperty.setEnum(Arrays.asList("SUB1", "SUB2", "SUB3")); + + // Add one enum property to the parent + final Map parentProperties = new HashMap(); + parentProperties.put("sharedThing", identicalEnumProperty); + + // Add TWO enums to the subType model; one of which is identical to the one in parent class + final Map subProperties = new HashMap(); + subProperties.put("sharedThing", identicalEnumProperty); + subProperties.put("unsharedThing", identicalEnumProperty); + + final ModelImpl parentModel = new ModelImpl(); + parentModel.setProperties(parentProperties); + parentModel.name("parentModel"); + + final ModelImpl subModel = new ModelImpl(); + subModel.setProperties(subProperties); + subModel.name("subModel"); + + final ComposedModel model = new ComposedModel() + .parent(new RefModel(parentModel.getName())) + .child(subModel) + .interfaces(new ArrayList()); + + final DefaultCodegen codegen = new JavaClientCodegen(); + final Map allModels = new HashMap(); + allModels.put(parentModel.getName(), parentModel); + allModels.put(subModel.getName(), subModel); + + final CodegenModel cm = codegen.fromModel("sample", model, allModels); + + Assert.assertEquals(cm.name, "sample"); + Assert.assertEquals(cm.classname, "Sample"); + Assert.assertEquals(cm.parent, "ParentModel"); + Assert.assertTrue(cm.imports.contains("ParentModel")); + + // Assert that only the unshared/uninherited enum remains + Assert.assertEquals(cm.vars.size(), 1); + final CodegenProperty enumVar = cm.vars.get(0); + Assert.assertEquals(enumVar.baseName, "unsharedThing"); + Assert.assertEquals(enumVar.datatype, "String"); + Assert.assertEquals(enumVar.datatypeWithEnum, "UnsharedThingEnum"); + Assert.assertTrue(enumVar.isEnum); + } +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/javascript/JavaScriptModelTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/javascript/JavaScriptModelTest.java new file mode 100644 index 00000000000..bb7afb942b7 --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/javascript/JavaScriptModelTest.java @@ -0,0 +1,491 @@ +package io.swagger.codegen.javascript; + +import java.util.List; + +import org.testng.Assert; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +import com.google.common.collect.Sets; + +import io.swagger.codegen.CodegenModel; +import io.swagger.codegen.CodegenParameter; +import io.swagger.codegen.CodegenProperty; +import io.swagger.codegen.DefaultCodegen; +import io.swagger.codegen.languages.JavascriptClientCodegen; +import io.swagger.models.ArrayModel; +import io.swagger.models.Model; +import io.swagger.models.ModelImpl; +import io.swagger.models.parameters.QueryParameter; +import io.swagger.models.properties.ArrayProperty; +import io.swagger.models.properties.ByteArrayProperty; +import io.swagger.models.properties.DateTimeProperty; +import io.swagger.models.properties.IntegerProperty; +import io.swagger.models.properties.LongProperty; +import io.swagger.models.properties.MapProperty; +import io.swagger.models.properties.RefProperty; +import io.swagger.models.properties.StringProperty; + +@SuppressWarnings("static-method") +public class JavaScriptModelTest { + @Test(description = "convert a simple java model") + public void simpleModelTest() { + final Model model = new ModelImpl() + .description("a sample model") + .property("id", new LongProperty()) + .property("name", new StringProperty() + .example("Tony")) + .property("createdAt", new DateTimeProperty()) + .required("id") + .required("name"); + final DefaultCodegen codegen = new JavascriptClientCodegen(); + final CodegenModel cm = codegen.fromModel("sample", model); + + Assert.assertEquals(cm.name, "sample"); + Assert.assertEquals(cm.classname, "Sample"); + Assert.assertEquals(cm.description, "a sample model"); + Assert.assertEquals(cm.vars.size(), 3); + + final List vars = cm.vars; + + final CodegenProperty property1 = vars.get(0); + Assert.assertEquals(property1.baseName, "id"); + Assert.assertEquals(property1.getter, "getId"); + Assert.assertEquals(property1.setter, "setId"); + Assert.assertEquals(property1.datatype, "Integer"); + Assert.assertEquals(property1.name, "id"); + Assert.assertEquals(property1.defaultValue, null); + Assert.assertEquals(property1.baseType, "Integer"); + Assert.assertTrue(property1.hasMore); + Assert.assertTrue(property1.required); + Assert.assertTrue(property1.isNotContainer); + + final CodegenProperty property2 = vars.get(1); + Assert.assertEquals(property2.baseName, "name"); + Assert.assertEquals(property2.getter, "getName"); + Assert.assertEquals(property2.setter, "setName"); + Assert.assertEquals(property2.datatype, "String"); + Assert.assertEquals(property2.name, "name"); + Assert.assertEquals(property2.defaultValue, null); + Assert.assertEquals(property2.baseType, "String"); + Assert.assertEquals(property2.example, "Tony"); + Assert.assertTrue(property2.hasMore); + Assert.assertTrue(property2.required); + Assert.assertTrue(property2.isNotContainer); + + final CodegenProperty property3 = vars.get(2); + Assert.assertEquals(property3.baseName, "createdAt"); + Assert.assertEquals(property3.getter, "getCreatedAt"); + Assert.assertEquals(property3.setter, "setCreatedAt"); + Assert.assertEquals(property3.datatype, "Date"); + Assert.assertEquals(property3.name, "createdAt"); + Assert.assertEquals(property3.defaultValue, null); + Assert.assertEquals(property3.baseType, "Date"); + Assert.assertNull(property3.hasMore); + Assert.assertNull(property3.required); + Assert.assertTrue(property3.isNotContainer); + } + + @Test(description = "convert a model with list property") + public void listPropertyTest() { + final Model model = new ModelImpl() + .description("a sample model") + .property("id", new LongProperty()) + .property("urls", new ArrayProperty() + .items(new StringProperty())) + .required("id"); + final DefaultCodegen codegen = new JavascriptClientCodegen(); + final CodegenModel cm = codegen.fromModel("sample", model); + + Assert.assertEquals(cm.name, "sample"); + Assert.assertEquals(cm.classname, "Sample"); + Assert.assertEquals(cm.description, "a sample model"); + Assert.assertEquals(cm.vars.size(), 2); + + final CodegenProperty property = cm.vars.get(1); + Assert.assertEquals(property.baseName, "urls"); + Assert.assertEquals(property.getter, "getUrls"); + Assert.assertEquals(property.setter, "setUrls"); + Assert.assertEquals(property.datatype, "[String]"); + Assert.assertEquals(property.name, "urls"); + // FIXME: should an array property have an empty array as its default value? What if the property is required? + Assert.assertEquals(property.defaultValue, /*"[]"*/null); + Assert.assertEquals(property.baseType, "Array"); + Assert.assertEquals(property.containerType, "array"); + Assert.assertNull(property.required); + Assert.assertTrue(property.isContainer); + } + + @Test(description = "convert a model with a map property") + public void mapPropertyTest() { + final Model model = new ModelImpl() + .description("a sample model") + .property("translations", new MapProperty() + .additionalProperties(new StringProperty())) + .required("id"); + final DefaultCodegen codegen = new JavascriptClientCodegen(); + final CodegenModel cm = codegen.fromModel("sample", model); + + Assert.assertEquals(cm.name, "sample"); + Assert.assertEquals(cm.classname, "Sample"); + Assert.assertEquals(cm.description, "a sample model"); + Assert.assertEquals(cm.vars.size(), 1); + + final CodegenProperty property = cm.vars.get(0); + Assert.assertEquals(property.baseName, "translations"); + Assert.assertEquals(property.getter, "getTranslations"); + Assert.assertEquals(property.setter, "setTranslations"); + Assert.assertEquals(property.datatype, "{String: String}"); + Assert.assertEquals(property.name, "translations"); + // FIXME: should a map property have an empty object as its default value? What if the property is required? + Assert.assertEquals(property.defaultValue, /*"{}"*/null); + Assert.assertEquals(property.baseType, "Object"); + Assert.assertEquals(property.containerType, "map"); + Assert.assertNull(property.required); + Assert.assertTrue(property.isContainer); + } + + @Test(description = "convert a model with a map with complex list property") + public void mapWithListPropertyTest() { + final Model model = new ModelImpl() + .description("a sample model") + .property("translations", + new MapProperty().additionalProperties(new ArrayProperty().items(new RefProperty("Pet")))) + .required("id"); + final DefaultCodegen codegen = new JavascriptClientCodegen(); + final CodegenModel cm = codegen.fromModel("sample", model); + + Assert.assertEquals(cm.name, "sample"); + Assert.assertEquals(cm.classname, "Sample"); + Assert.assertEquals(cm.description, "a sample model"); + Assert.assertEquals(cm.vars.size(), 1); + + final CodegenProperty property = cm.vars.get(0); + Assert.assertEquals(property.baseName, "translations"); + Assert.assertEquals(property.getter, "getTranslations"); + Assert.assertEquals(property.setter, "setTranslations"); + Assert.assertEquals(property.datatype, "{String: [Pet]}"); + Assert.assertEquals(property.name, "translations"); + // FIXME: should a map property have an empty object as its default value? What if the property is required? + Assert.assertEquals(property.defaultValue, /*"{}"*/null); + Assert.assertEquals(property.baseType, "Object"); + Assert.assertEquals(property.containerType, "map"); + Assert.assertNull(property.required); + Assert.assertTrue(property.isContainer); + } + + @Test(description = "convert a model with a 2D list property") + public void list2DPropertyTest() { + final Model model = new ModelImpl().name("sample").property("list2D", new ArrayProperty().items( + new ArrayProperty().items(new RefProperty("Pet")))); + final DefaultCodegen codegen = new JavascriptClientCodegen(); + final CodegenModel cm = codegen.fromModel("sample", model); + + Assert.assertEquals(cm.vars.size(), 1); + + final CodegenProperty property = cm.vars.get(0); + Assert.assertEquals(property.baseName, "list2D"); + Assert.assertEquals(property.getter, "getList2D"); + Assert.assertEquals(property.setter, "setList2D"); + Assert.assertEquals(property.datatype, "[[Pet]]"); + Assert.assertEquals(property.name, "list2D"); + // FIXME: should an array property have an empty array as its default value? What if the property is required? + Assert.assertEquals(property.defaultValue, /*"[]"*/null); + Assert.assertEquals(property.baseType, "Array"); + Assert.assertEquals(property.containerType, "array"); + Assert.assertNull(property.required); + Assert.assertTrue(property.isContainer); + } + + @Test(description = "convert a model with complex properties") + public void complexPropertiesTest() { + final Model model = new ModelImpl().description("a sample model") + .property("children", new RefProperty("#/definitions/Children")); + final DefaultCodegen codegen = new JavascriptClientCodegen(); + final CodegenModel cm = codegen.fromModel("sample", model); + + Assert.assertEquals(cm.name, "sample"); + Assert.assertEquals(cm.classname, "Sample"); + Assert.assertEquals(cm.description, "a sample model"); + Assert.assertEquals(cm.vars.size(), 1); + + final CodegenProperty property = cm.vars.get(0); + Assert.assertEquals(property.baseName, "children"); + Assert.assertEquals(property.getter, "getChildren"); + Assert.assertEquals(property.setter, "setChildren"); + Assert.assertEquals(property.datatype, "Children"); + Assert.assertEquals(property.name, "children"); + Assert.assertEquals(property.defaultValue, null); + Assert.assertEquals(property.baseType, "Children"); + Assert.assertNull(property.required); + Assert.assertTrue(property.isNotContainer); + } + + @Test(description = "convert a model with complex list property") + public void complexListPropertyTest() { + final Model model = new ModelImpl() + .description("a sample model") + .property("children", new ArrayProperty().items(new RefProperty("#/definitions/Children"))); + final DefaultCodegen codegen = new JavascriptClientCodegen(); + final CodegenModel cm = codegen.fromModel("sample", model); + + Assert.assertEquals(cm.name, "sample"); + Assert.assertEquals(cm.classname, "Sample"); + Assert.assertEquals(cm.description, "a sample model"); + Assert.assertEquals(cm.vars.size(), 1); + + final CodegenProperty property = cm.vars.get(0); + Assert.assertEquals(property.baseName, "children"); + Assert.assertEquals(property.complexType, "Children"); + Assert.assertEquals(property.getter, "getChildren"); + Assert.assertEquals(property.setter, "setChildren"); + // FIXME: what should datatype be for a JavaScript array? +// Assert.assertEquals(property.datatype, "Array"); + Assert.assertEquals(property.name, "children"); + // FIXME: should an array property have an empty array as its default value? What if the property is required? + Assert.assertEquals(property.defaultValue, /*"[]"*/null); + Assert.assertEquals(property.baseType, "Array"); + Assert.assertEquals(property.containerType, "array"); + Assert.assertNull(property.required); + Assert.assertTrue(property.isContainer); + } + + @Test(description = "convert a model with complex map property") + public void complexMapPropertyTest() { + final Model model = new ModelImpl() + .description("a sample model") + .property("children", new MapProperty().additionalProperties(new RefProperty("#/definitions/Children"))); + final DefaultCodegen codegen = new JavascriptClientCodegen(); + final CodegenModel cm = codegen.fromModel("sample", model); + + Assert.assertEquals(cm.name, "sample"); + Assert.assertEquals(cm.classname, "Sample"); + Assert.assertEquals(cm.description, "a sample model"); + Assert.assertEquals(cm.vars.size(), 1); + Assert.assertEquals(Sets.intersection(cm.imports, Sets.newHashSet("Children")).size(), 1); + + final CodegenProperty property = cm.vars.get(0); + Assert.assertEquals(property.baseName, "children"); + Assert.assertEquals(property.complexType, "Children"); + Assert.assertEquals(property.getter, "getChildren"); + Assert.assertEquals(property.setter, "setChildren"); + // TODO: create a functional test to see whether map properties actually work. + Assert.assertEquals(property.datatype, /*"Object"*/"{String: Children}"); + Assert.assertEquals(property.name, "children"); + // FIXME: should a map property have an empty object as its default value? What if the property is required? + Assert.assertEquals(property.defaultValue, /*"{}"*/ null); + Assert.assertEquals(property.baseType, "Object"); + Assert.assertEquals(property.containerType, "map"); + Assert.assertNull(property.required); + Assert.assertTrue(property.isContainer); + Assert.assertNull(property.isNotContainer); + } + + @Test(description = "convert an array model") + public void arrayModelTest() { + final Model model = new ArrayModel() + .description("an array model") + .items(new RefProperty("#/definitions/Children")); + final DefaultCodegen codegen = new JavascriptClientCodegen(); + final CodegenModel cm = codegen.fromModel("sample", model); + + Assert.assertEquals(cm.name, "sample"); + Assert.assertEquals(cm.classname, "Sample"); + Assert.assertEquals(cm.description, "an array model"); + Assert.assertEquals(cm.vars.size(), 0); + Assert.assertEquals(cm.parent, "Array"); + Assert.assertEquals(cm.imports.size(), 1); + Assert.assertEquals(Sets.intersection(cm.imports, Sets.newHashSet("Children")).size(), 1); + } + + @Test(description = "convert a map model") + public void mapModelTest() { + final Model model = new ModelImpl() + .description("an map model") + .additionalProperties(new RefProperty("#/definitions/Children")); + final DefaultCodegen codegen = new JavascriptClientCodegen(); + final CodegenModel cm = codegen.fromModel("sample", model); + + Assert.assertEquals(cm.name, "sample"); + Assert.assertEquals(cm.classname, "Sample"); + Assert.assertEquals(cm.description, "an map model"); + Assert.assertEquals(cm.vars.size(), 0); + Assert.assertEquals(cm.parent, "Object"); + Assert.assertEquals(cm.imports.size(), 1); + Assert.assertEquals(Sets.intersection(cm.imports, Sets.newHashSet("Children")).size(), 1); + } + + @Test(description = "convert a model with uppercase property names") + public void upperCaseNamesTest() { + final Model model = new ModelImpl() + .description("a model with uppercase property names") + .property("NAME", new StringProperty()) + .required("NAME"); + final DefaultCodegen codegen = new JavascriptClientCodegen(); + final CodegenModel cm = codegen.fromModel("sample", model); + + Assert.assertEquals(cm.name, "sample"); + Assert.assertEquals(cm.classname, "Sample"); + Assert.assertEquals(cm.vars.size(), 1); + + final CodegenProperty property = cm.vars.get(0); + Assert.assertEquals(property.baseName, "NAME"); + Assert.assertEquals(property.getter, "getNAME"); + Assert.assertEquals(property.setter, "setNAME"); + Assert.assertEquals(property.datatype, "String"); + Assert.assertEquals(property.name, "NAME"); + Assert.assertEquals(property.defaultValue, null); + Assert.assertEquals(property.baseType, "String"); + Assert.assertNull(property.hasMore); + Assert.assertTrue(property.required); + Assert.assertTrue(property.isNotContainer); + } + + @Test(description = "convert a model with a 2nd char uppercase property names") + public void secondCharUpperCaseNamesTest() { + final Model model = new ModelImpl() + .description("a model with a 2nd char uppercase property names") + .property("pId", new StringProperty()) + .required("pId"); + final DefaultCodegen codegen = new JavascriptClientCodegen(); + final CodegenModel cm = codegen.fromModel("sample", model); + + Assert.assertEquals(cm.name, "sample"); + Assert.assertEquals(cm.classname, "Sample"); + Assert.assertEquals(cm.vars.size(), 1); + + final CodegenProperty property = cm.vars.get(0); + Assert.assertEquals(property.baseName, "pId"); + Assert.assertEquals(property.getter, "getPId"); + Assert.assertEquals(property.setter, "setPId"); + Assert.assertEquals(property.datatype, "String"); + Assert.assertEquals(property.name, "pId"); + Assert.assertEquals(property.defaultValue, null); + Assert.assertEquals(property.baseType, "String"); + Assert.assertNull(property.hasMore); + Assert.assertTrue(property.required); + Assert.assertTrue(property.isNotContainer); + } + + @Test(description = "convert hyphens per issue 503") + public void hyphensTest() { + final Model model = new ModelImpl() + .description("a sample model") + .property("created-at", new DateTimeProperty()); + final DefaultCodegen codegen = new JavascriptClientCodegen(); + final CodegenModel cm = codegen.fromModel("sample", model); + + final CodegenProperty property = cm.vars.get(0); + Assert.assertEquals(property.baseName, "created-at"); + Assert.assertEquals(property.getter, "getCreatedAt"); + Assert.assertEquals(property.setter, "setCreatedAt"); + Assert.assertEquals(property.name, "createdAt"); + } + + @Test(description = "convert query[password] to queryPassword") + public void squareBracketsTest() { + final Model model = new ModelImpl() + .description("a sample model") + .property("query[password]", new StringProperty()); + final DefaultCodegen codegen = new JavascriptClientCodegen(); + final CodegenModel cm = codegen.fromModel("sample", model); + + final CodegenProperty property = cm.vars.get(0); + Assert.assertEquals(property.baseName, "query[password]"); + Assert.assertEquals(property.getter, "getQueryPassword"); + Assert.assertEquals(property.setter, "setQueryPassword"); + Assert.assertEquals(property.name, "queryPassword"); + } + + @Test(description = "properly escape names per 567") + public void escapeNamesTest() { + final Model model = new ModelImpl() + .description("a sample model") + .property("created-at", new DateTimeProperty()); + final DefaultCodegen codegen = new JavascriptClientCodegen(); + final CodegenModel cm = codegen.fromModel("with.dots", model); + + Assert.assertEquals(cm.classname, "WithDots"); + } + + @Test(description = "convert a model with binary data") + public void binaryDataTest() { + final Model model = new ModelImpl() + .description("model with binary") + .property("inputBinaryData", new ByteArrayProperty()); + final DefaultCodegen codegen = new JavascriptClientCodegen(); + final CodegenModel cm = codegen.fromModel("sample", model); + + final CodegenProperty property = cm.vars.get(0); + Assert.assertEquals(property.baseName, "inputBinaryData"); + Assert.assertEquals(property.getter, "getInputBinaryData"); + Assert.assertEquals(property.setter, "setInputBinaryData"); + Assert.assertEquals(property.datatype, "String"); + Assert.assertEquals(property.name, "inputBinaryData"); + Assert.assertEquals(property.defaultValue, null); + Assert.assertEquals(property.baseType, "String"); + Assert.assertNull(property.hasMore); + Assert.assertNull(property.required); + Assert.assertTrue(property.isNotContainer); + } + + @Test(description = "translate an invalid param name") + public void invalidParamNameTest() { + final Model model = new ModelImpl() + .description("a model with a 2nd char uppercase property name") + .property("_", new StringProperty()); + final DefaultCodegen codegen = new JavascriptClientCodegen(); + final CodegenModel cm = codegen.fromModel("sample", model); + + Assert.assertEquals(cm.name, "sample"); + Assert.assertEquals(cm.classname, "Sample"); + Assert.assertEquals(cm.vars.size(), 1); + + final CodegenProperty property = cm.vars.get(0); + Assert.assertEquals(property.baseName, "_"); + Assert.assertEquals(property.getter, "getU"); + Assert.assertEquals(property.setter, "setU"); + Assert.assertEquals(property.datatype, "String"); + Assert.assertEquals(property.name, "u"); + Assert.assertEquals(property.defaultValue, null); + Assert.assertEquals(property.baseType, "String"); + Assert.assertNull(property.hasMore); + Assert.assertTrue(property.isNotContainer); + } + + @Test(description = "convert a parameter") + public void convertParameterTest() { + final QueryParameter parameter = new QueryParameter() + .property(new IntegerProperty()) + .name("limit") + .required(true); + final DefaultCodegen codegen = new JavascriptClientCodegen(); + final CodegenParameter cm = codegen.fromParameter(parameter, null); + + Assert.assertNull(cm.allowableValues); + } + + @DataProvider(name = "modelNames") + public static Object[][] primeNumbers() { + return new Object[][] { + {"sample", "Sample"}, + {"sample_name", "SampleName"}, + {"sample__name", "SampleName"}, + {"/sample", "Sample"}, + {"\\sample", "Sample"}, + {"sample.name", "SampleName"}, + {"_sample", "Sample"}, + {"Sample", "Sample"}, + }; + } + + @Test(dataProvider = "modelNames", description = "avoid inner class") + public void modelNameTest(String name, String expectedName) { + final Model model = new ModelImpl(); + final DefaultCodegen codegen = new JavascriptClientCodegen(); + final CodegenModel cm = codegen.fromModel(name, model); + + Assert.assertEquals(cm.name, name); + Assert.assertEquals(cm.classname, expectedName); + } +} diff --git a/modules/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 bf6fd0aba7d..d2b51b06fe4 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 @@ -1,11 +1,9 @@ package io.swagger.codegen.options; -import io.swagger.codegen.Codegen; +import com.google.common.collect.ImmutableMap; import io.swagger.codegen.CodegenConstants; import io.swagger.codegen.languages.JavaClientCodegen; -import com.google.common.collect.ImmutableMap; - import java.util.Map; public class JavaOptionsProvider implements OptionsProvider { @@ -46,6 +44,7 @@ public class JavaOptionsProvider implements OptionsProvider { .put(CodegenConstants.SERIALIZE_BIG_DECIMAL_AS_STRING, "true") .put(JavaClientCodegen.USE_RX_JAVA, "false") .put(JavaClientCodegen.DATE_LIBRARY, "joda") + .put("hideGenerationTimestamp", "true") .build(); } 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 new file mode 100644 index 00000000000..9b0f06a1031 --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavaScriptOptionsProvider.java @@ -0,0 +1,88 @@ +package io.swagger.codegen.options; + +import io.swagger.codegen.CodegenConstants; +import io.swagger.codegen.options.OptionsProvider; +import io.swagger.codegen.languages.JavascriptClientCodegen; + +import com.google.common.collect.ImmutableMap; + +import java.util.Map; + +public class JavaScriptOptionsProvider implements OptionsProvider { + public static final String ARTIFACT_ID_VALUE = "swagger-javascript-client-test"; + public static final String MODEL_PACKAGE_VALUE = "model"; + public static final String API_PACKAGE_VALUE = "api"; +// public static final String INVOKER_PACKAGE_VALUE = "js"; + public static final String SORT_PARAMS_VALUE = "false"; + public static final String GROUP_ID_VALUE = "io.swagger.test"; + public static final String ARTIFACT_VERSION_VALUE = "1.0.0-SNAPSHOT"; + public static final String SOURCE_FOLDER_VALUE = "src/main/javascript"; + public static final String LOCAL_PREFIX_VALUE = "_"; +// public static final String SERIALIZABLE_MODEL_VALUE = "false"; + public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; + public static final String PROJECT_NAME_VALUE = "JavaScript Client Test"; + public static final String MODULE_NAME_VALUE = "JavaScriptClient"; + public static final String PROJECT_DESCRIPTION_VALUE = "Tests JavaScript code generator options"; + public static final String PROJECT_VERSION_VALUE = "1.0.0"; + public static final String PROJECT_LICENSE_NAME_VALUE = "Apache"; + public static final String USE_PROMISES_VALUE = "true"; + public static final String USE_INHERITANCE_VALUE = "false"; + public static final String EMIT_MODEL_METHODS_VALUE = "true"; + public static final String EMIT_JS_DOC_VALUE = "false"; + + private ImmutableMap options; + + /** + * Create an options provider with the default options. + */ + public JavaScriptOptionsProvider() { + // Commented generic options not yet supported by JavaScript codegen. + options = new ImmutableMap.Builder() + .put(CodegenConstants.MODEL_PACKAGE, MODEL_PACKAGE_VALUE) + .put(CodegenConstants.API_PACKAGE, API_PACKAGE_VALUE) + .put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) + .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) +// .put(CodegenConstants.INVOKER_PACKAGE, INVOKER_PACKAGE_VALUE) +// .put(CodegenConstants.GROUP_ID, GROUP_ID_VALUE) +// .put(CodegenConstants.ARTIFACT_ID, ARTIFACT_ID_VALUE) +// .put(CodegenConstants.ARTIFACT_VERSION, ARTIFACT_VERSION_VALUE) + .put(CodegenConstants.SOURCE_FOLDER, SOURCE_FOLDER_VALUE) + .put(CodegenConstants.LOCAL_VARIABLE_PREFIX, LOCAL_PREFIX_VALUE) +// .put(CodegenConstants.SERIALIZE_BIG_DECIMAL_AS_STRING, "true") + .put(JavascriptClientCodegen.PROJECT_NAME, PROJECT_NAME_VALUE) + .put(JavascriptClientCodegen.MODULE_NAME, MODULE_NAME_VALUE) + .put(JavascriptClientCodegen.PROJECT_DESCRIPTION, PROJECT_DESCRIPTION_VALUE) + .put(JavascriptClientCodegen.PROJECT_VERSION, PROJECT_VERSION_VALUE) + .put(JavascriptClientCodegen.PROJECT_LICENSE_NAME, PROJECT_LICENSE_NAME_VALUE) + .put(JavascriptClientCodegen.USE_PROMISES, USE_PROMISES_VALUE) + .put(JavascriptClientCodegen.USE_INHERITANCE, USE_INHERITANCE_VALUE) + .put(JavascriptClientCodegen.EMIT_MODEL_METHODS, EMIT_MODEL_METHODS_VALUE) + .put(JavascriptClientCodegen.EMIT_JS_DOC, EMIT_JS_DOC_VALUE) + .build(); + } + + /** + * Use the default options, but override the ones found in additionalOptions. + */ + public JavaScriptOptionsProvider(Map additionalOptions) { + options = new ImmutableMap.Builder() + .putAll(options) + .putAll(additionalOptions) + .build(); + } + + @Override + public Map createOptions() { + return options; + } + + @Override + public boolean isServer() { + return false; + } + + @Override + public String getLanguage() { + return "javascript"; + } +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/NodeJSServerOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/NodeJSServerOptionsProvider.java index 3d49fcb8d01..6252bbd08fc 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/NodeJSServerOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/NodeJSServerOptionsProvider.java @@ -12,7 +12,7 @@ public class NodeJSServerOptionsProvider implements OptionsProvider { @Override public String getLanguage() { - return "nodejs"; + return "nodejs-server"; } @Override diff --git a/modules/swagger-codegen/src/test/resources/2_0/petstore.json.orig b/modules/swagger-codegen/src/test/resources/2_0/petstore-orig.json similarity index 100% rename from modules/swagger-codegen/src/test/resources/2_0/petstore.json.orig rename to modules/swagger-codegen/src/test/resources/2_0/petstore-orig.json 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 3034c0a8ce5..64b56377393 100644 --- a/modules/swagger-codegen/src/test/resources/2_0/petstore.json +++ b/modules/swagger-codegen/src/test/resources/2_0/petstore.json @@ -1091,7 +1091,12 @@ "400": { "description": "Invalid username supplied" } - } + }, + "security": [ + { + "test_http_basic": [] + } + ] } } }, @@ -1129,6 +1134,9 @@ "type": "apiKey", "name": "test_api_key_query", "in": "query" + }, + "test_http_basic": { + "type": "basic" } }, "definitions": { @@ -1293,6 +1301,7 @@ } }, "Return": { + "description": "Model for testing reserved words", "properties": { "return": { "type": "integer", @@ -1302,6 +1311,127 @@ "xml": { "name": "Return" } + }, + "Name": { + "description": "Model for testing model name same as property name", + "required": [ + "name" + ], + "properties": { + "name": { + "type": "integer", + "format": "int32" + }, + "snake_case": { + "readOnly": true, + "type": "integer", + "format": "int32" + } + }, + "xml": { + "name": "Name" + } + }, + "200_response": { + "description": "Model for testing model name starting with number", + "properties": { + "name": { + "type": "integer", + "format": "int32" + } + }, + "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", + "discriminator": "className", + "required": [ + "className" + ], + "properties" : { + "className" : { + "type" : "string" + } + } + }, + "format_test" : { + "type" : "object", + "required": [ + "number" + ], + "properties" : { + "integer" : { + "type": "integer" + }, + "int32" : { + "type": "integer", + "format": "int32" + }, + "int64" : { + "type": "integer", + "format": "int64" + }, + "number" : { + "type": "number" + }, + "float" : { + "type": "number", + "format": "float" + }, + "double" : { + "type": "number", + "format": "double" + }, + "string" : { + "type": "string" + }, + "byte" : { + "type": "string", + "format": "byte" + }, + "binary" : { + "type": "string", + "format": "binary" + }, + "date" : { + "type": "string", + "format": "date" + }, + "dateTime" : { + "type": "string", + "format": "date-time" + }, + "dateTime" : { + "type": "string", + "format": "password" + } + } } } } diff --git a/modules/swagger-codegen/src/test/resources/2_0/petstore.yaml b/modules/swagger-codegen/src/test/resources/2_0/petstore.yaml new file mode 100644 index 00000000000..73493835106 --- /dev/null +++ b/modules/swagger-codegen/src/test/resources/2_0/petstore.yaml @@ -0,0 +1,695 @@ +swagger: '2.0' +info: + description: 'This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.' + version: 1.0.0 + title: Swagger Petstore + termsOfService: 'http://swagger.io/terms/' + contact: + email: apiteam@swagger.io + license: + name: Apache 2.0 + url: 'http://www.apache.org/licenses/LICENSE-2.0.html' +host: petstore.swagger.io +basePath: /v2 +tags: + - name: pet + description: Everything about your Pets + externalDocs: + description: Find out more + url: 'http://swagger.io' + - name: store + description: Access to Petstore orders + - name: user + description: Operations about user + externalDocs: + description: Find out more about our store + url: 'http://swagger.io' +schemes: + - http +paths: + /pet: + post: + tags: + - pet + summary: Add a new pet to the store + description: '' + operationId: addPet + consumes: + - application/json + - application/xml + produces: + - application/xml + - application/json + parameters: + - in: body + name: body + description: Pet object that needs to be added to the store + required: true + schema: + $ref: '#/definitions/Pet' + responses: + '405': + description: Invalid input + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + put: + tags: + - pet + summary: Update an existing pet + description: '' + operationId: updatePet + consumes: + - application/json + - application/xml + produces: + - application/xml + - application/json + parameters: + - in: body + name: body + description: Pet object that needs to be added to the store + required: true + schema: + $ref: '#/definitions/Pet' + responses: + '400': + description: Invalid ID supplied + '404': + description: Pet not found + '405': + description: Validation exception + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + /pet/findByStatus: + get: + tags: + - pet + summary: Finds Pets by status + description: Multiple status values can be provided with comma separated strings + operationId: findPetsByStatus + produces: + - application/xml + - application/json + parameters: + - name: status + in: query + description: Status values that need to be considered for filter + required: true + type: array + items: + type: string + enum: + - available + - pending + - sold + default: available + collectionFormat: csv + responses: + '200': + description: successful operation + schema: + type: array + items: + $ref: '#/definitions/Pet' + '400': + description: Invalid status value + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + /pet/findByTags: + get: + tags: + - pet + summary: Finds Pets by tags + description: 'Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.' + operationId: findPetsByTags + produces: + - application/xml + - application/json + parameters: + - name: tags + in: query + description: Tags to filter by + required: true + type: array + items: + type: string + collectionFormat: csv + responses: + '200': + description: successful operation + schema: + type: array + items: + $ref: '#/definitions/Pet' + '400': + description: Invalid tag value + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + '/pet/{petId}': + get: + tags: + - pet + summary: Find pet by ID + description: Returns a single pet + operationId: getPetById + produces: + - application/xml + - application/json + parameters: + - name: petId + in: path + description: ID of pet to return + required: true + type: integer + format: int64 + responses: + '200': + description: successful operation + schema: + $ref: '#/definitions/Pet' + '400': + description: Invalid ID supplied + '404': + description: Pet not found + security: + - api_key: [] + post: + tags: + - pet + summary: Updates a pet in the store with form data + description: '' + operationId: updatePetWithForm + consumes: + - application/x-www-form-urlencoded + produces: + - application/xml + - application/json + parameters: + - name: petId + in: path + description: ID of pet that needs to be updated + required: true + type: integer + format: int64 + - name: name + in: formData + description: Updated name of the pet + required: false + type: string + - name: status + in: formData + description: Updated status of the pet + required: false + type: string + responses: + '405': + description: Invalid input + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + delete: + tags: + - pet + summary: Deletes a pet + description: '' + operationId: deletePet + produces: + - application/xml + - application/json + parameters: + - name: api_key + in: header + required: false + type: string + - name: petId + in: path + description: Pet id to delete + required: true + type: integer + format: int64 + responses: + '400': + description: Invalid pet value + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + '/pet/{petId}/uploadImage': + post: + tags: + - pet + summary: uploads an image + description: '' + operationId: uploadFile + consumes: + - multipart/form-data + produces: + - application/json + parameters: + - name: petId + in: path + description: ID of pet to update + required: true + type: integer + format: int64 + - name: additionalMetadata + in: formData + description: Additional data to pass to server + required: false + type: string + - name: file + in: formData + description: file to upload + required: false + type: file + responses: + '200': + description: successful operation + schema: + $ref: '#/definitions/ApiResponse' + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + /store/inventory: + get: + tags: + - store + summary: Returns pet inventories by status + description: Returns a map of status codes to quantities + operationId: getInventory + produces: + - application/json + parameters: [] + responses: + '200': + description: successful operation + schema: + type: object + additionalProperties: + type: integer + format: int32 + security: + - api_key: [] + /store/order: + post: + tags: + - store + summary: Place an order for a pet + description: '' + operationId: placeOrder + produces: + - application/xml + - application/json + parameters: + - in: body + name: body + description: order placed for purchasing the pet + required: true + schema: + $ref: '#/definitions/Order' + responses: + '200': + description: successful operation + schema: + $ref: '#/definitions/Order' + '400': + description: Invalid Order + '/store/order/{orderId}': + get: + tags: + - store + summary: Find purchase order by ID + description: 'For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions' + operationId: getOrderById + produces: + - application/xml + - application/json + parameters: + - name: orderId + in: path + description: ID of pet that needs to be fetched + required: true + type: integer + maximum: 5 + minimum: 1 + format: int64 + responses: + '200': + description: successful operation + schema: + $ref: '#/definitions/Order' + '400': + description: Invalid ID supplied + '404': + description: Order not found + delete: + tags: + - store + summary: Delete purchase order by ID + description: For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + operationId: deleteOrder + produces: + - application/xml + - application/json + parameters: + - name: orderId + in: path + description: ID of the order that needs to be deleted + required: true + type: string + minimum: 1 + responses: + '400': + description: Invalid ID supplied + '404': + description: Order not found + /user: + post: + tags: + - user + summary: Create user + description: This can only be done by the logged in user. + operationId: createUser + produces: + - application/xml + - application/json + parameters: + - in: body + name: body + description: Created user object + required: true + schema: + $ref: '#/definitions/User' + responses: + default: + description: successful operation + /user/createWithArray: + post: + tags: + - user + summary: Creates list of users with given input array + description: '' + operationId: createUsersWithArrayInput + produces: + - application/xml + - application/json + parameters: + - in: body + name: body + description: List of user object + required: true + schema: + type: array + items: + $ref: '#/definitions/User' + responses: + default: + description: successful operation + /user/createWithList: + post: + tags: + - user + summary: Creates list of users with given input array + description: '' + operationId: createUsersWithListInput + produces: + - application/xml + - application/json + parameters: + - in: body + name: body + description: List of user object + required: true + schema: + type: array + items: + $ref: '#/definitions/User' + responses: + default: + description: successful operation + /user/login: + get: + tags: + - user + summary: Logs user into the system + description: '' + operationId: loginUser + produces: + - application/xml + - application/json + parameters: + - name: username + in: query + description: The user name for login + required: true + type: string + - name: password + in: query + description: The password for login in clear text + required: true + type: string + responses: + '200': + description: successful operation + schema: + type: string + headers: + X-Rate-Limit: + type: integer + format: int32 + description: calls per hour allowed by the user + X-Expires-After: + type: string + format: date-time + description: date in UTC when toekn expires + '400': + description: Invalid username/password supplied + /user/logout: + get: + tags: + - user + summary: Logs out current logged in user session + description: '' + operationId: logoutUser + produces: + - application/xml + - application/json + parameters: [] + responses: + default: + description: successful operation + '/user/{username}': + get: + tags: + - user + summary: Get user by user name + description: '' + operationId: getUserByName + produces: + - application/xml + - application/json + parameters: + - name: username + in: path + description: 'The name that needs to be fetched. Use user1 for testing. ' + required: true + type: string + responses: + '200': + description: successful operation + schema: + $ref: '#/definitions/User' + '400': + description: Invalid username supplied + '404': + description: User not found + put: + tags: + - user + summary: Updated user + description: This can only be done by the logged in user. + operationId: updateUser + produces: + - application/xml + - application/json + parameters: + - name: username + in: path + description: name that need to be deleted + required: true + type: string + - in: body + name: body + description: Updated user object + required: true + schema: + $ref: '#/definitions/User' + responses: + '400': + description: Invalid user supplied + '404': + description: User not found + delete: + tags: + - user + summary: Delete user + description: This can only be done by the logged in user. + operationId: deleteUser + produces: + - application/xml + - application/json + parameters: + - name: username + in: path + description: The name that needs to be deleted + required: true + type: string + responses: + '400': + description: Invalid username supplied + '404': + description: User not found +securityDefinitions: + petstore_auth: + type: oauth2 + authorizationUrl: 'http://petstore.swagger.io/api/oauth/dialog' + flow: implicit + scopes: + 'write:pets': modify pets in your account + 'read:pets': read your pets + api_key: + type: apiKey + name: api_key + in: header +definitions: + Order: + type: object + properties: + id: + type: integer + format: int64 + petId: + type: integer + format: int64 + quantity: + type: integer + format: int32 + shipDate: + type: string + format: date-time + status: + type: string + description: Order Status + enum: + - placed + - approved + - delivered + complete: + type: boolean + default: false + xml: + name: Order + 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/modules/swagger-generator/pom.xml b/modules/swagger-generator/pom.xml index 6210ed77f37..2d2b45d7892 100644 --- a/modules/swagger-generator/pom.xml +++ b/modules/swagger-generator/pom.xml @@ -4,7 +4,7 @@ io.swagger swagger-codegen-project - 2.1.6-SNAPSHOT + 2.1.6 ../.. swagger-generator diff --git a/modules/swagger-generator/src/main/java/io/swagger/generator/model/GeneratorInput.java b/modules/swagger-generator/src/main/java/io/swagger/generator/model/GeneratorInput.java index 5175ac3b60a..fabde1e3104 100644 --- a/modules/swagger-generator/src/main/java/io/swagger/generator/model/GeneratorInput.java +++ b/modules/swagger-generator/src/main/java/io/swagger/generator/model/GeneratorInput.java @@ -2,6 +2,7 @@ package io.swagger.generator.model; import com.fasterxml.jackson.databind.JsonNode; import io.swagger.annotations.ApiModelProperty; +import io.swagger.models.auth.AuthorizationValue; import io.swagger.models.auth.SecuritySchemeDefinition; import java.util.Map; @@ -11,6 +12,15 @@ public class GeneratorInput { private Map options; private String swaggerUrl; private SecuritySchemeDefinition auth; + private AuthorizationValue authorizationValue; + + public AuthorizationValue getAuthorizationValue() { + return authorizationValue; + } + + public void setAuthorizationValue(AuthorizationValue authorizationValue) { + this.authorizationValue = authorizationValue; + } @ApiModelProperty(dataType = "Object") public JsonNode getSpec() { @@ -38,10 +48,12 @@ public class GeneratorInput { this.swaggerUrl = url; } + @Deprecated public SecuritySchemeDefinition getSecurityDefinition() { return auth; } + @Deprecated public void setSecurityDefinition(SecuritySchemeDefinition auth) { this.auth = auth; } diff --git a/modules/swagger-generator/src/main/java/io/swagger/generator/online/Generator.java b/modules/swagger-generator/src/main/java/io/swagger/generator/online/Generator.java index 9b721d36a4f..fecd5706361 100644 --- a/modules/swagger-generator/src/main/java/io/swagger/generator/online/Generator.java +++ b/modules/swagger-generator/src/main/java/io/swagger/generator/online/Generator.java @@ -1,22 +1,16 @@ package io.swagger.generator.online; import com.fasterxml.jackson.databind.JsonNode; - -import io.swagger.codegen.CliOption; -import io.swagger.codegen.ClientOptInput; -import io.swagger.codegen.ClientOpts; -import io.swagger.codegen.Codegen; -import io.swagger.codegen.CodegenConfig; -import io.swagger.codegen.CodegenConfigLoader; +import io.swagger.codegen.*; import io.swagger.generator.exception.ApiException; import io.swagger.generator.exception.BadRequestException; import io.swagger.generator.model.GeneratorInput; import io.swagger.generator.model.InputOption; import io.swagger.generator.util.ZipUtil; import io.swagger.models.Swagger; +import io.swagger.models.auth.AuthorizationValue; import io.swagger.parser.SwaggerParser; import io.swagger.util.Json; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -79,21 +73,43 @@ public class Generator { Swagger swagger; if (node == null) { if (opts.getSwaggerUrl() != null) { - swagger = new SwaggerParser().read(opts.getSwaggerUrl()); + if(opts.getAuthorizationValue() != null) { + List authorizationValues = new ArrayList(); + authorizationValues.add(opts.getAuthorizationValue()); + + swagger = new SwaggerParser().read(opts.getSwaggerUrl(), authorizationValues, true); + } + else { + swagger = new SwaggerParser().read(opts.getSwaggerUrl()); + } } else { throw new BadRequestException("No swagger specification was supplied"); } - } else { + } else if(opts.getAuthorizationValue() != null) { + List authorizationValues = new ArrayList(); + authorizationValues.add(opts.getAuthorizationValue()); + swagger = new SwaggerParser().read(node, authorizationValues, true); + } + else { swagger = new SwaggerParser().read(node, true); } if (swagger == null) { throw new BadRequestException("The swagger specification supplied was not valid"); } + String destPath = null; + + if(opts != null && opts.getOptions() != null) { + destPath = opts.getOptions().get("outputFolder"); + } + if(destPath == null) { + destPath = language + "-" + + type.getTypeName(); + } + ClientOptInput clientOptInput = new ClientOptInput(); ClientOpts clientOpts = new ClientOpts(); - String outputFolder = getTmpFolder().getAbsolutePath() + File.separator + language + "-" - + type.getTypeName(); + String outputFolder = getTmpFolder().getAbsolutePath() + File.separator + destPath; String outputFilename = outputFolder + "-bundle.zip"; clientOptInput diff --git a/modules/swagger-generator/src/main/webapp/WEB-INF/web.xml b/modules/swagger-generator/src/main/webapp/WEB-INF/web.xml index 514cfab4435..904e0e34fb0 100644 --- a/modules/swagger-generator/src/main/webapp/WEB-INF/web.xml +++ b/modules/swagger-generator/src/main/webapp/WEB-INF/web.xml @@ -18,7 +18,7 @@ io.swagger.online.ExceptionWriter, io.swagger.generator.util.JacksonJsonProvider, - io.swagger.jersey.listing.ApiListingResourceJSON, + io.swagger.jaxrs.listing.ApiListingResource, io.swagger.jersey.listing.JerseyApiDeclarationProvider, io.swagger.jersey.listing.JerseyResourceListingProvider diff --git a/pom.xml b/pom.xml index 3519ce9f0cb..9ac1890ea91 100644 --- a/pom.xml +++ b/pom.xml @@ -10,7 +10,7 @@ swagger-codegen-project pom swagger-codegen-project - 2.1.6-SNAPSHOT + 2.1.6 https://github.com/swagger-api/swagger-codegen scm:git:git@github.com:swagger-api/swagger-codegen.git @@ -414,6 +414,18 @@ samples/client/petstore/swift/SwaggerClientTests + + jaxrs-resteasy-server + + + env + java + + + + samples/server/petstore/jaxrs-resteasy + + jaxrs-server @@ -473,6 +485,7 @@ samples/server/petstore/spring-mvc samples/client/petstore/ruby samples/server/petstore/jaxrs + samples/server/petstore/jaxrs-resteasy @@ -546,10 +559,10 @@ - 1.0.18-SNAPSHOT + 1.0.19 2.11.1 2.3.4 - 1.5.7 + 1.5.8 2.4 1.2 4.8.1 @@ -557,7 +570,7 @@ 2.4 1.7.12 3.2.1 - 1.9 + 1.12 6.9.6 2.18.1 1.19 diff --git a/samples/client/petstore/android/default/.gitignore b/samples/client/petstore/android/default/.gitignore new file mode 100644 index 00000000000..a8363b06f95 --- /dev/null +++ b/samples/client/petstore/android/default/.gitignore @@ -0,0 +1,39 @@ +# Built application files +*.apk +*.ap_ + +# Files for the Dalvik VM +*.dex + +# Java class files +*.class + +# Generated files +bin/ +gen/ +out/ + +# Gradle files +.gradle/ +build/ + +# Local configuration file (sdk path, etc) +local.properties + +# Proguard folder generated by Eclipse +proguard/ + +# Log Files +*.log + +# Android Studio Navigation editor temp files +.navigation/ + +# Android Studio captures folder +captures/ + +# Intellij +*.iml + +#Keystore files +*.jks diff --git a/samples/client/petstore/android/default/build.gradle b/samples/client/petstore/android/default/build.gradle index 417503cb51e..e48f72b3138 100644 --- a/samples/client/petstore/android/default/build.gradle +++ b/samples/client/petstore/android/default/build.gradle @@ -6,9 +6,9 @@ buildscript { jcenter() } dependencies { - classpath 'com.android.tools.build:gradle:1.2.2' + classpath 'com.android.tools.build:gradle:1.5.+' - classpath 'com.github.dcendents:android-maven-plugin:1.2' + classpath 'com.github.dcendents:android-maven-gradle-plugin:1.3' } } @@ -24,11 +24,12 @@ apply plugin: 'com.android.library' apply plugin: 'com.github.dcendents.android-maven' android { - compileSdkVersion 22 - buildToolsVersion '22.0.0' + compileSdkVersion 23 + buildToolsVersion '23.0.2' + useLibrary 'org.apache.http.legacy' defaultConfig { minSdkVersion 14 - targetSdkVersion 22 + targetSdkVersion 23 } compileOptions { sourceCompatibility JavaVersion.VERSION_1_7 @@ -51,16 +52,17 @@ android { ext { swagger_annotations_version = "1.5.0" gson_version = "2.3.1" - httpclient_version = "4.3.3" - junit_version = "4.8.1" + httpclient_version = "4.5.2" + httpcore_version = "4.4.4" + junit_version = "4.12" } dependencies { compile "io.swagger:swagger-annotations:$swagger_annotations_version" compile "com.google.code.gson:gson:$gson_version" - compile "org.apache.httpcomponents:httpcore:$httpclient_version" + compile "org.apache.httpcomponents:httpcore:$httpcore_version" compile "org.apache.httpcomponents:httpclient:$httpclient_version" - compile ("org.apache.httpcomponents:httpcore:$httpclient_version") { + compile ("org.apache.httpcomponents:httpcore:$httpcore_version") { exclude(group: 'org.apache.httpcomponents', module: 'httpclient') } compile ("org.apache.httpcomponents:httpmime:$httpclient_version") { diff --git a/samples/client/petstore/android/default/git_push.sh b/samples/client/petstore/android/default/git_push.sh new file mode 100644 index 00000000000..1a36388db02 --- /dev/null +++ b/samples/client/petstore/android/default/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="YOUR_GIT_USR_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="YOUR_GIT_REPO_ID" + 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/android/default/src/main/java/io/swagger/client/ApiInvoker.java b/samples/client/petstore/android/default/src/main/java/io/swagger/client/ApiInvoker.java index 5eddeb6b9e9..ecb787006dd 100644 --- a/samples/client/petstore/android/default/src/main/java/io/swagger/client/ApiInvoker.java +++ b/samples/client/petstore/android/default/src/main/java/io/swagger/client/ApiInvoker.java @@ -83,7 +83,7 @@ public class ApiInvoker { DATE_FORMAT.setTimeZone(TimeZone.getTimeZone("UTC")); // Set default User-Agent. - setUserAgent("Android-Java-Swagger"); + setUserAgent("Swagger-Codegen/1.0.0/android"); } public static void setUserAgent(String userAgent) { diff --git a/samples/client/petstore/android/default/src/main/java/io/swagger/client/JsonUtil.java b/samples/client/petstore/android/default/src/main/java/io/swagger/client/JsonUtil.java index 8a45f846f19..49ce07a07ae 100644 --- a/samples/client/petstore/android/default/src/main/java/io/swagger/client/JsonUtil.java +++ b/samples/client/petstore/android/default/src/main/java/io/swagger/client/JsonUtil.java @@ -35,24 +35,44 @@ public class JsonUtil { public static Type getListTypeForDeserialization(Class cls) { String className = cls.getSimpleName(); + if ("Category".equalsIgnoreCase(className)) { + return new TypeToken>(){}.getType(); + } + + if ("InlineResponse200".equalsIgnoreCase(className)) { + return new TypeToken>(){}.getType(); + } + + if ("Model200Response".equalsIgnoreCase(className)) { + return new TypeToken>(){}.getType(); + } + + if ("ModelReturn".equalsIgnoreCase(className)) { + return new TypeToken>(){}.getType(); + } + + if ("Name".equalsIgnoreCase(className)) { + return new TypeToken>(){}.getType(); + } + if ("Order".equalsIgnoreCase(className)) { return new TypeToken>(){}.getType(); } - if ("User".equalsIgnoreCase(className)) { - return new TypeToken>(){}.getType(); + if ("Pet".equalsIgnoreCase(className)) { + return new TypeToken>(){}.getType(); } - if ("Category".equalsIgnoreCase(className)) { - return new TypeToken>(){}.getType(); + if ("SpecialModelName".equalsIgnoreCase(className)) { + return new TypeToken>(){}.getType(); } if ("Tag".equalsIgnoreCase(className)) { return new TypeToken>(){}.getType(); } - if ("Pet".equalsIgnoreCase(className)) { - return new TypeToken>(){}.getType(); + if ("User".equalsIgnoreCase(className)) { + return new TypeToken>(){}.getType(); } return new TypeToken>(){}.getType(); @@ -61,26 +81,46 @@ public class JsonUtil { public static Type getTypeForDeserialization(Class cls) { String className = cls.getSimpleName(); - if ("Order".equalsIgnoreCase(className)) { - return new TypeToken(){}.getType(); - } - - if ("User".equalsIgnoreCase(className)) { - return new TypeToken(){}.getType(); - } - if ("Category".equalsIgnoreCase(className)) { return new TypeToken(){}.getType(); } - if ("Tag".equalsIgnoreCase(className)) { - return new TypeToken(){}.getType(); + if ("InlineResponse200".equalsIgnoreCase(className)) { + return new TypeToken(){}.getType(); + } + + if ("Model200Response".equalsIgnoreCase(className)) { + return new TypeToken(){}.getType(); + } + + if ("ModelReturn".equalsIgnoreCase(className)) { + return new TypeToken(){}.getType(); + } + + if ("Name".equalsIgnoreCase(className)) { + return new TypeToken(){}.getType(); + } + + if ("Order".equalsIgnoreCase(className)) { + return new TypeToken(){}.getType(); } if ("Pet".equalsIgnoreCase(className)) { return new TypeToken(){}.getType(); } + if ("SpecialModelName".equalsIgnoreCase(className)) { + return new TypeToken(){}.getType(); + } + + if ("Tag".equalsIgnoreCase(className)) { + return new TypeToken(){}.getType(); + } + + if ("User".equalsIgnoreCase(className)) { + return new TypeToken(){}.getType(); + } + return new TypeToken(){}.getType(); } diff --git a/samples/client/petstore/android/default/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/android/default/src/main/java/io/swagger/client/api/PetApi.java index 14811fb36be..41dac192d82 100644 --- a/samples/client/petstore/android/default/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/android/default/src/main/java/io/swagger/client/api/PetApi.java @@ -9,6 +9,7 @@ import io.swagger.client.model.*; import java.util.*; import io.swagger.client.model.Pet; +import io.swagger.client.model.InlineResponse200; import java.io.File; import org.apache.http.entity.mime.MultipartEntityBuilder; @@ -38,59 +39,6 @@ public class PetApi { } - /** - * Update an existing pet - * - * @param body Pet object that needs to be added to the store - * @return void - */ - public void updatePet (Pet body) throws ApiException { - Object localVarPostBody = body; - - - // create path and map variables - String localVarPath = "/pet".replaceAll("\\{format\\}","json"); - - // query params - List localVarQueryParams = new ArrayList(); - // header params - Map localVarHeaderParams = new HashMap(); - // form params - Map localVarFormParams = new HashMap(); - - - - - - String[] localVarContentTypes = { - "application/json","application/xml" - }; - String localVarContentType = localVarContentTypes.length > 0 ? localVarContentTypes[0] : "application/json"; - - if (localVarContentType.startsWith("multipart/form-data")) { - // file uploading - MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create(); - - - localVarPostBody = localVarBuilder.build(); - } else { - // normal form params - - } - - try { - String localVarResponse = apiInvoker.invokeAPI(basePath, localVarPath, "PUT", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarContentType); - if(localVarResponse != null){ - return ; - } - else { - return ; - } - } catch (ApiException ex) { - throw ex; - } - } - /** * Add a new pet to the store * @@ -144,6 +92,120 @@ public class PetApi { } } + /** + * Fake endpoint to test byte array in body parameter for adding a new pet to the store + * + * @param body Pet object in the form of byte array + * @return void + */ + public void addPetUsingByteArray (byte[] body) throws ApiException { + Object localVarPostBody = body; + + + // create path and map variables + String localVarPath = "/pet?testing_byte_array=true".replaceAll("\\{format\\}","json"); + + // query params + List localVarQueryParams = new ArrayList(); + // header params + Map localVarHeaderParams = new HashMap(); + // form params + Map localVarFormParams = new HashMap(); + + + + + + String[] localVarContentTypes = { + "application/json","application/xml" + }; + String localVarContentType = localVarContentTypes.length > 0 ? localVarContentTypes[0] : "application/json"; + + if (localVarContentType.startsWith("multipart/form-data")) { + // file uploading + MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create(); + + + localVarPostBody = localVarBuilder.build(); + } else { + // normal form params + + } + + try { + String localVarResponse = apiInvoker.invokeAPI(basePath, localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarContentType); + if(localVarResponse != null){ + return ; + } + else { + return ; + } + } catch (ApiException ex) { + throw ex; + } + } + + /** + * Deletes a pet + * + * @param petId Pet id to delete + * @param apiKey + * @return void + */ + 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" + "\\}", apiInvoker.escapeString(petId.toString())); + + // query params + List localVarQueryParams = new ArrayList(); + // header params + Map localVarHeaderParams = new HashMap(); + // form params + Map localVarFormParams = new HashMap(); + + + + + localVarHeaderParams.put("api_key", ApiInvoker.parameterToString(apiKey)); + + + String[] localVarContentTypes = { + + }; + String localVarContentType = localVarContentTypes.length > 0 ? localVarContentTypes[0] : "application/json"; + + if (localVarContentType.startsWith("multipart/form-data")) { + // file uploading + MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create(); + + + localVarPostBody = localVarBuilder.build(); + } else { + // normal form params + + } + + try { + String localVarResponse = apiInvoker.invokeAPI(basePath, localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarContentType); + if(localVarResponse != null){ + return ; + } + else { + return ; + } + } catch (ApiException ex) { + throw ex; + } + } + /** * Finds Pets by status * Multiple status values can be provided with comma separated strings @@ -312,6 +374,175 @@ public class PetApi { } } + /** + * Fake endpoint to test inline arbitrary object return by 'Find pet by ID' + * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + * @param petId ID of pet that needs to be fetched + * @return InlineResponse200 + */ + public InlineResponse200 getPetByIdInObject (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 getPetByIdInObject"); + } + + + // create path and map variables + String localVarPath = "/pet/{petId}?response=inline_arbitrary_object".replaceAll("\\{format\\}","json").replaceAll("\\{" + "petId" + "\\}", apiInvoker.escapeString(petId.toString())); + + // query params + List localVarQueryParams = new ArrayList(); + // header params + Map localVarHeaderParams = new HashMap(); + // form params + Map localVarFormParams = new HashMap(); + + + + + + String[] localVarContentTypes = { + + }; + String localVarContentType = localVarContentTypes.length > 0 ? localVarContentTypes[0] : "application/json"; + + if (localVarContentType.startsWith("multipart/form-data")) { + // file uploading + MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create(); + + + localVarPostBody = localVarBuilder.build(); + } else { + // normal form params + + } + + try { + String localVarResponse = apiInvoker.invokeAPI(basePath, localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarContentType); + if(localVarResponse != null){ + return (InlineResponse200) ApiInvoker.deserialize(localVarResponse, "", InlineResponse200.class); + } + else { + return null; + } + } catch (ApiException ex) { + throw ex; + } + } + + /** + * Fake endpoint to test byte array return by 'Find pet by ID' + * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + * @param petId ID of pet that needs to be fetched + * @return byte[] + */ + public byte[] petPetIdtestingByteArraytrueGet (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 petPetIdtestingByteArraytrueGet"); + } + + + // create path and map variables + String localVarPath = "/pet/{petId}?testing_byte_array=true".replaceAll("\\{format\\}","json").replaceAll("\\{" + "petId" + "\\}", apiInvoker.escapeString(petId.toString())); + + // query params + List localVarQueryParams = new ArrayList(); + // header params + Map localVarHeaderParams = new HashMap(); + // form params + Map localVarFormParams = new HashMap(); + + + + + + String[] localVarContentTypes = { + + }; + String localVarContentType = localVarContentTypes.length > 0 ? localVarContentTypes[0] : "application/json"; + + if (localVarContentType.startsWith("multipart/form-data")) { + // file uploading + MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create(); + + + localVarPostBody = localVarBuilder.build(); + } else { + // normal form params + + } + + try { + String localVarResponse = apiInvoker.invokeAPI(basePath, localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarContentType); + if(localVarResponse != null){ + return (byte[]) ApiInvoker.deserialize(localVarResponse, "", byte[].class); + } + else { + return null; + } + } catch (ApiException ex) { + throw ex; + } + } + + /** + * Update an existing pet + * + * @param body Pet object that needs to be added to the store + * @return void + */ + public void updatePet (Pet body) throws ApiException { + Object localVarPostBody = body; + + + // create path and map variables + String localVarPath = "/pet".replaceAll("\\{format\\}","json"); + + // query params + List localVarQueryParams = new ArrayList(); + // header params + Map localVarHeaderParams = new HashMap(); + // form params + Map localVarFormParams = new HashMap(); + + + + + + String[] localVarContentTypes = { + "application/json","application/xml" + }; + String localVarContentType = localVarContentTypes.length > 0 ? localVarContentTypes[0] : "application/json"; + + if (localVarContentType.startsWith("multipart/form-data")) { + // file uploading + MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create(); + + + localVarPostBody = localVarBuilder.build(); + } else { + // normal form params + + } + + try { + String localVarResponse = apiInvoker.invokeAPI(basePath, localVarPath, "PUT", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarContentType); + if(localVarResponse != null){ + return ; + } + else { + return ; + } + } catch (ApiException ex) { + throw ex; + } + } + /** * Updates a pet in the store with form data * @@ -382,67 +613,6 @@ public class PetApi { } } - /** - * Deletes a pet - * - * @param petId Pet id to delete - * @param apiKey - * @return void - */ - 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" + "\\}", apiInvoker.escapeString(petId.toString())); - - // query params - List localVarQueryParams = new ArrayList(); - // header params - Map localVarHeaderParams = new HashMap(); - // form params - Map localVarFormParams = new HashMap(); - - - - - localVarHeaderParams.put("api_key", ApiInvoker.parameterToString(apiKey)); - - - String[] localVarContentTypes = { - - }; - String localVarContentType = localVarContentTypes.length > 0 ? localVarContentTypes[0] : "application/json"; - - if (localVarContentType.startsWith("multipart/form-data")) { - // file uploading - MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create(); - - - localVarPostBody = localVarBuilder.build(); - } else { - // normal form params - - } - - try { - String localVarResponse = apiInvoker.invokeAPI(basePath, localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarContentType); - if(localVarResponse != null){ - return ; - } - else { - return ; - } - } catch (ApiException ex) { - throw ex; - } - } - /** * uploads an image * @@ -513,115 +683,4 @@ public class PetApi { } } - /** - * Fake endpoint to test byte array return by 'Find pet by ID' - * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions - * @param petId ID of pet that needs to be fetched - * @return byte[] - */ - public byte[] petPetIdtestingByteArraytrueGet (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 petPetIdtestingByteArraytrueGet"); - } - - - // create path and map variables - String localVarPath = "/pet/{petId}?testing_byte_array=true".replaceAll("\\{format\\}","json").replaceAll("\\{" + "petId" + "\\}", apiInvoker.escapeString(petId.toString())); - - // query params - List localVarQueryParams = new ArrayList(); - // header params - Map localVarHeaderParams = new HashMap(); - // form params - Map localVarFormParams = new HashMap(); - - - - - - String[] localVarContentTypes = { - - }; - String localVarContentType = localVarContentTypes.length > 0 ? localVarContentTypes[0] : "application/json"; - - if (localVarContentType.startsWith("multipart/form-data")) { - // file uploading - MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create(); - - - localVarPostBody = localVarBuilder.build(); - } else { - // normal form params - - } - - try { - String localVarResponse = apiInvoker.invokeAPI(basePath, localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarContentType); - if(localVarResponse != null){ - return (byte[]) ApiInvoker.deserialize(localVarResponse, "", byte[].class); - } - else { - return null; - } - } catch (ApiException ex) { - throw ex; - } - } - - /** - * Fake endpoint to test byte array in body parameter for adding a new pet to the store - * - * @param body Pet object in the form of byte array - * @return void - */ - public void addPetUsingByteArray (byte[] body) throws ApiException { - Object localVarPostBody = body; - - - // create path and map variables - String localVarPath = "/pet?testing_byte_array=true".replaceAll("\\{format\\}","json"); - - // query params - List localVarQueryParams = new ArrayList(); - // header params - Map localVarHeaderParams = new HashMap(); - // form params - Map localVarFormParams = new HashMap(); - - - - - - String[] localVarContentTypes = { - "application/json","application/xml" - }; - String localVarContentType = localVarContentTypes.length > 0 ? localVarContentTypes[0] : "application/json"; - - if (localVarContentType.startsWith("multipart/form-data")) { - // file uploading - MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create(); - - - localVarPostBody = localVarBuilder.build(); - } else { - // normal form params - - } - - try { - String localVarResponse = apiInvoker.invokeAPI(basePath, localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarContentType); - if(localVarResponse != null){ - return ; - } - else { - return ; - } - } catch (ApiException ex) { - throw ex; - } - } - } diff --git a/samples/client/petstore/android/default/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/android/default/src/main/java/io/swagger/client/api/StoreApi.java index 6c28905e377..d5ecbca1ab3 100644 --- a/samples/client/petstore/android/default/src/main/java/io/swagger/client/api/StoreApi.java +++ b/samples/client/petstore/android/default/src/main/java/io/swagger/client/api/StoreApi.java @@ -38,6 +38,64 @@ public class 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 + * @return void + */ + 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" + "\\}", apiInvoker.escapeString(orderId.toString())); + + // query params + List localVarQueryParams = new ArrayList(); + // header params + Map localVarHeaderParams = new HashMap(); + // form params + Map localVarFormParams = new HashMap(); + + + + + + String[] localVarContentTypes = { + + }; + String localVarContentType = localVarContentTypes.length > 0 ? localVarContentTypes[0] : "application/json"; + + if (localVarContentType.startsWith("multipart/form-data")) { + // file uploading + MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create(); + + + localVarPostBody = localVarBuilder.build(); + } else { + // normal form params + + } + + try { + String localVarResponse = apiInvoker.invokeAPI(basePath, localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarContentType); + if(localVarResponse != null){ + return ; + } + else { + return ; + } + } catch (ApiException ex) { + throw ex; + } + } + /** * Finds orders by status * A single status value can be provided as a string @@ -146,17 +204,16 @@ public class StoreApi { } /** - * Place an order for a pet - * - * @param body order placed for purchasing the pet - * @return Order + * Fake endpoint to test arbitrary object return by 'Get inventory' + * Returns an arbitrary object which is actually a map of status codes to quantities + * @return Object */ - public Order placeOrder (Order body) throws ApiException { - Object localVarPostBody = body; + public Object getInventoryInObject () throws ApiException { + Object localVarPostBody = null; // create path and map variables - String localVarPath = "/store/order".replaceAll("\\{format\\}","json"); + String localVarPath = "/store/inventory?response=arbitrary_object".replaceAll("\\{format\\}","json"); // query params List localVarQueryParams = new ArrayList(); @@ -186,9 +243,9 @@ public class StoreApi { } try { - String localVarResponse = apiInvoker.invokeAPI(basePath, localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarContentType); + String localVarResponse = apiInvoker.invokeAPI(basePath, localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarContentType); if(localVarResponse != null){ - return (Order) ApiInvoker.deserialize(localVarResponse, "", Order.class); + return (Object) ApiInvoker.deserialize(localVarResponse, "", Object.class); } else { return null; @@ -257,22 +314,17 @@ public class 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 - * @return void + * Place an order for a pet + * + * @param body order placed for purchasing the pet + * @return Order */ - 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"); - } + public Order placeOrder (Order body) throws ApiException { + Object localVarPostBody = body; // create path and map variables - String localVarPath = "/store/order/{orderId}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "orderId" + "\\}", apiInvoker.escapeString(orderId.toString())); + String localVarPath = "/store/order".replaceAll("\\{format\\}","json"); // query params List localVarQueryParams = new ArrayList(); @@ -302,12 +354,12 @@ public class StoreApi { } try { - String localVarResponse = apiInvoker.invokeAPI(basePath, localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarContentType); + String localVarResponse = apiInvoker.invokeAPI(basePath, localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarContentType); if(localVarResponse != null){ - return ; + return (Order) ApiInvoker.deserialize(localVarResponse, "", Order.class); } else { - return ; + return null; } } catch (ApiException ex) { throw ex; diff --git a/samples/client/petstore/android/default/src/main/java/io/swagger/client/api/UserApi.java b/samples/client/petstore/android/default/src/main/java/io/swagger/client/api/UserApi.java index 06934022874..a28410fd0a9 100644 --- a/samples/client/petstore/android/default/src/main/java/io/swagger/client/api/UserApi.java +++ b/samples/client/petstore/android/default/src/main/java/io/swagger/client/api/UserApi.java @@ -197,6 +197,122 @@ public class UserApi { } } + /** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted + * @return void + */ + 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" + "\\}", apiInvoker.escapeString(username.toString())); + + // query params + List localVarQueryParams = new ArrayList(); + // header params + Map localVarHeaderParams = new HashMap(); + // form params + Map localVarFormParams = new HashMap(); + + + + + + String[] localVarContentTypes = { + + }; + String localVarContentType = localVarContentTypes.length > 0 ? localVarContentTypes[0] : "application/json"; + + if (localVarContentType.startsWith("multipart/form-data")) { + // file uploading + MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create(); + + + localVarPostBody = localVarBuilder.build(); + } else { + // normal form params + + } + + try { + String localVarResponse = apiInvoker.invokeAPI(basePath, localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarContentType); + if(localVarResponse != null){ + return ; + } + else { + return ; + } + } catch (ApiException ex) { + throw ex; + } + } + + /** + * Get user by user name + * + * @param username The name that needs to be fetched. Use user1 for testing. + * @return User + */ + 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" + "\\}", apiInvoker.escapeString(username.toString())); + + // query params + List localVarQueryParams = new ArrayList(); + // header params + Map localVarHeaderParams = new HashMap(); + // form params + Map localVarFormParams = new HashMap(); + + + + + + String[] localVarContentTypes = { + + }; + String localVarContentType = localVarContentTypes.length > 0 ? localVarContentTypes[0] : "application/json"; + + if (localVarContentType.startsWith("multipart/form-data")) { + // file uploading + MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create(); + + + localVarPostBody = localVarBuilder.build(); + } else { + // normal form params + + } + + try { + String localVarResponse = apiInvoker.invokeAPI(basePath, localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarContentType); + if(localVarResponse != null){ + return (User) ApiInvoker.deserialize(localVarResponse, "", User.class); + } + else { + return null; + } + } catch (ApiException ex) { + throw ex; + } + } + /** * Logs user into the system * @@ -307,64 +423,6 @@ public class UserApi { } } - /** - * Get user by user name - * - * @param username The name that needs to be fetched. Use user1 for testing. - * @return User - */ - 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" + "\\}", apiInvoker.escapeString(username.toString())); - - // query params - List localVarQueryParams = new ArrayList(); - // header params - Map localVarHeaderParams = new HashMap(); - // form params - Map localVarFormParams = new HashMap(); - - - - - - String[] localVarContentTypes = { - - }; - String localVarContentType = localVarContentTypes.length > 0 ? localVarContentTypes[0] : "application/json"; - - if (localVarContentType.startsWith("multipart/form-data")) { - // file uploading - MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create(); - - - localVarPostBody = localVarBuilder.build(); - } else { - // normal form params - - } - - try { - String localVarResponse = apiInvoker.invokeAPI(basePath, localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarContentType); - if(localVarResponse != null){ - return (User) ApiInvoker.deserialize(localVarResponse, "", User.class); - } - else { - return null; - } - } catch (ApiException ex) { - throw ex; - } - } - /** * Updated user * This can only be done by the logged in user. @@ -424,62 +482,4 @@ public class UserApi { } } - /** - * Delete user - * This can only be done by the logged in user. - * @param username The name that needs to be deleted - * @return void - */ - 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" + "\\}", apiInvoker.escapeString(username.toString())); - - // query params - List localVarQueryParams = new ArrayList(); - // header params - Map localVarHeaderParams = new HashMap(); - // form params - Map localVarFormParams = new HashMap(); - - - - - - String[] localVarContentTypes = { - - }; - String localVarContentType = localVarContentTypes.length > 0 ? localVarContentTypes[0] : "application/json"; - - if (localVarContentType.startsWith("multipart/form-data")) { - // file uploading - MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create(); - - - localVarPostBody = localVarBuilder.build(); - } else { - // normal form params - - } - - try { - String localVarResponse = apiInvoker.invokeAPI(basePath, localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarContentType); - if(localVarResponse != null){ - return ; - } - else { - return ; - } - } catch (ApiException ex) { - throw ex; - } - } - } diff --git a/samples/client/petstore/android/default/src/main/java/io/swagger/client/model/InlineResponse200.java b/samples/client/petstore/android/default/src/main/java/io/swagger/client/model/InlineResponse200.java new file mode 100644 index 00000000000..c4fd8ce357d --- /dev/null +++ b/samples/client/petstore/android/default/src/main/java/io/swagger/client/model/InlineResponse200.java @@ -0,0 +1,112 @@ +package io.swagger.client.model; + +import io.swagger.client.model.Tag; +import java.util.*; + +import io.swagger.annotations.*; +import com.google.gson.annotations.SerializedName; + + +@ApiModel(description = "") +public class InlineResponse200 { + + @SerializedName("tags") + private List tags = null; + @SerializedName("id") + private Long id = null; + @SerializedName("category") + private Object category = null; + public enum StatusEnum { + available, pending, sold, + }; + @SerializedName("status") + private StatusEnum status = null; + @SerializedName("name") + private String name = null; + @SerializedName("photoUrls") + private List photoUrls = null; + + + /** + **/ + @ApiModelProperty(value = "") + public List getTags() { + return tags; + } + public void setTags(List tags) { + this.tags = tags; + } + + + /** + **/ + @ApiModelProperty(required = true, value = "") + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + + /** + **/ + @ApiModelProperty(value = "") + public Object getCategory() { + return category; + } + public void setCategory(Object category) { + this.category = category; + } + + + /** + * pet status in the store + **/ + @ApiModelProperty(value = "pet status in the store") + public StatusEnum getStatus() { + return status; + } + public void setStatus(StatusEnum status) { + this.status = status; + } + + + /** + **/ + @ApiModelProperty(value = "") + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + + + /** + **/ + @ApiModelProperty(value = "") + public List getPhotoUrls() { + return photoUrls; + } + public void setPhotoUrls(List photoUrls) { + this.photoUrls = photoUrls; + } + + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class InlineResponse200 {\n"); + + sb.append(" tags: ").append(tags).append("\n"); + sb.append(" id: ").append(id).append("\n"); + sb.append(" category: ").append(category).append("\n"); + sb.append(" status: ").append(status).append("\n"); + sb.append(" name: ").append(name).append("\n"); + sb.append(" photoUrls: ").append(photoUrls).append("\n"); + sb.append("}\n"); + return sb.toString(); + } +} diff --git a/samples/client/petstore/android/default/src/main/java/io/swagger/client/model/Model200Response.java b/samples/client/petstore/android/default/src/main/java/io/swagger/client/model/Model200Response.java new file mode 100644 index 00000000000..4a6e58b2a5e --- /dev/null +++ b/samples/client/petstore/android/default/src/main/java/io/swagger/client/model/Model200Response.java @@ -0,0 +1,36 @@ +package io.swagger.client.model; + + +import io.swagger.annotations.*; +import com.google.gson.annotations.SerializedName; + + +@ApiModel(description = "") +public class Model200Response { + + @SerializedName("name") + private Integer name = null; + + + /** + **/ + @ApiModelProperty(value = "") + public Integer getName() { + return name; + } + public void setName(Integer name) { + this.name = name; + } + + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Model200Response {\n"); + + sb.append(" name: ").append(name).append("\n"); + sb.append("}\n"); + return sb.toString(); + } +} diff --git a/samples/client/petstore/android/default/src/main/java/io/swagger/client/model/ModelReturn.java b/samples/client/petstore/android/default/src/main/java/io/swagger/client/model/ModelReturn.java new file mode 100644 index 00000000000..24763f3acb4 --- /dev/null +++ b/samples/client/petstore/android/default/src/main/java/io/swagger/client/model/ModelReturn.java @@ -0,0 +1,36 @@ +package io.swagger.client.model; + + +import io.swagger.annotations.*; +import com.google.gson.annotations.SerializedName; + + +@ApiModel(description = "") +public class ModelReturn { + + @SerializedName("return") + private Integer _return = null; + + + /** + **/ + @ApiModelProperty(value = "") + public Integer getReturn() { + return _return; + } + public void setReturn(Integer _return) { + this._return = _return; + } + + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ModelReturn {\n"); + + sb.append(" _return: ").append(_return).append("\n"); + sb.append("}\n"); + return sb.toString(); + } +} diff --git a/samples/client/petstore/android/default/src/main/java/io/swagger/client/model/Name.java b/samples/client/petstore/android/default/src/main/java/io/swagger/client/model/Name.java new file mode 100644 index 00000000000..9763aca7b34 --- /dev/null +++ b/samples/client/petstore/android/default/src/main/java/io/swagger/client/model/Name.java @@ -0,0 +1,50 @@ +package io.swagger.client.model; + + +import io.swagger.annotations.*; +import com.google.gson.annotations.SerializedName; + + +@ApiModel(description = "") +public class Name { + + @SerializedName("name") + private Integer name = null; + @SerializedName("snake_case") + private Integer snakeCase = null; + + + /** + **/ + @ApiModelProperty(value = "") + public Integer getName() { + return name; + } + public void setName(Integer name) { + this.name = name; + } + + + /** + **/ + @ApiModelProperty(value = "") + public Integer getSnakeCase() { + return snakeCase; + } + public void setSnakeCase(Integer snakeCase) { + this.snakeCase = snakeCase; + } + + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Name {\n"); + + sb.append(" name: ").append(name).append("\n"); + sb.append(" snakeCase: ").append(snakeCase).append("\n"); + sb.append("}\n"); + return sb.toString(); + } +} diff --git a/samples/client/petstore/android/default/src/main/java/io/swagger/client/model/SpecialModelName.java b/samples/client/petstore/android/default/src/main/java/io/swagger/client/model/SpecialModelName.java new file mode 100644 index 00000000000..d804bdd8765 --- /dev/null +++ b/samples/client/petstore/android/default/src/main/java/io/swagger/client/model/SpecialModelName.java @@ -0,0 +1,36 @@ +package io.swagger.client.model; + + +import io.swagger.annotations.*; +import com.google.gson.annotations.SerializedName; + + +@ApiModel(description = "") +public class SpecialModelName { + + @SerializedName("$special[property.name]") + private Long specialPropertyName = null; + + + /** + **/ + @ApiModelProperty(value = "") + public Long getSpecialPropertyName() { + return specialPropertyName; + } + public void setSpecialPropertyName(Long specialPropertyName) { + this.specialPropertyName = specialPropertyName; + } + + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class SpecialModelName {\n"); + + sb.append(" specialPropertyName: ").append(specialPropertyName).append("\n"); + sb.append("}\n"); + return sb.toString(); + } +} diff --git a/samples/client/petstore/android/volley/build.gradle b/samples/client/petstore/android/volley/build.gradle index 799f9309a25..e678620cb00 100644 --- a/samples/client/petstore/android/volley/build.gradle +++ b/samples/client/petstore/android/volley/build.gradle @@ -6,9 +6,9 @@ buildscript { jcenter() } dependencies { - classpath 'com.android.tools.build:gradle:1.2.2' + classpath 'com.android.tools.build:gradle:1.5.0' - classpath 'com.github.dcendents:android-maven-plugin:1.2' + classpath 'com.github.dcendents:android-maven-gradle-plugin:1.3' } } 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 0f3dfdc3c55..21ee5f36286 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 @@ -185,25 +185,13 @@ public class ApiInvoker { public static void initializeInstance(Cache cache, Network network, int threadPoolSize, ResponseDelivery delivery, int connectionTimeout) { INSTANCE = new ApiInvoker(cache, network, threadPoolSize, delivery, connectionTimeout); - setUserAgent("Android-Volley-Swagger"); + setUserAgent("Swagger-Codegen/1.0.0/android"); // Setup authentications (key: authentication name, value: authentication). INSTANCE.authentications = new HashMap(); - - - INSTANCE.authentications.put("petstore_auth", new OAuth()); - - - - INSTANCE.authentications.put("test_api_client_id", new ApiKeyAuth("header", "x-test_api_client_id")); - - - - - - INSTANCE.authentications.put("test_api_client_secret", new ApiKeyAuth("header", "x-test_api_client_secret")); + INSTANCE.authentications.put("test_api_key_header", new ApiKeyAuth("header", "test_api_key_header")); @@ -215,15 +203,34 @@ public class ApiInvoker { + + INSTANCE.authentications.put("test_http_basic", new HttpBasicAuth()); + + + + + INSTANCE.authentications.put("test_api_client_secret", new ApiKeyAuth("header", "x-test_api_client_secret")); + + + + + + INSTANCE.authentications.put("test_api_client_id", new ApiKeyAuth("header", "x-test_api_client_id")); + + + + + INSTANCE.authentications.put("test_api_key_query", new ApiKeyAuth("query", "test_api_key_query")); - INSTANCE.authentications.put("test_api_key_header", new ApiKeyAuth("header", "test_api_key_header")); + // TODO: comment out below as OAuth does not exist + //INSTANCE.authentications.put("petstore_auth", new OAuth()); // Prevent the authentications from being modified. 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 8a45f846f19..49ce07a07ae 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 @@ -35,24 +35,44 @@ public class JsonUtil { public static Type getListTypeForDeserialization(Class cls) { String className = cls.getSimpleName(); + if ("Category".equalsIgnoreCase(className)) { + return new TypeToken>(){}.getType(); + } + + if ("InlineResponse200".equalsIgnoreCase(className)) { + return new TypeToken>(){}.getType(); + } + + if ("Model200Response".equalsIgnoreCase(className)) { + return new TypeToken>(){}.getType(); + } + + if ("ModelReturn".equalsIgnoreCase(className)) { + return new TypeToken>(){}.getType(); + } + + if ("Name".equalsIgnoreCase(className)) { + return new TypeToken>(){}.getType(); + } + if ("Order".equalsIgnoreCase(className)) { return new TypeToken>(){}.getType(); } - if ("User".equalsIgnoreCase(className)) { - return new TypeToken>(){}.getType(); + if ("Pet".equalsIgnoreCase(className)) { + return new TypeToken>(){}.getType(); } - if ("Category".equalsIgnoreCase(className)) { - return new TypeToken>(){}.getType(); + if ("SpecialModelName".equalsIgnoreCase(className)) { + return new TypeToken>(){}.getType(); } if ("Tag".equalsIgnoreCase(className)) { return new TypeToken>(){}.getType(); } - if ("Pet".equalsIgnoreCase(className)) { - return new TypeToken>(){}.getType(); + if ("User".equalsIgnoreCase(className)) { + return new TypeToken>(){}.getType(); } return new TypeToken>(){}.getType(); @@ -61,26 +81,46 @@ public class JsonUtil { public static Type getTypeForDeserialization(Class cls) { String className = cls.getSimpleName(); - if ("Order".equalsIgnoreCase(className)) { - return new TypeToken(){}.getType(); - } - - if ("User".equalsIgnoreCase(className)) { - return new TypeToken(){}.getType(); - } - if ("Category".equalsIgnoreCase(className)) { return new TypeToken(){}.getType(); } - if ("Tag".equalsIgnoreCase(className)) { - return new TypeToken(){}.getType(); + if ("InlineResponse200".equalsIgnoreCase(className)) { + return new TypeToken(){}.getType(); + } + + if ("Model200Response".equalsIgnoreCase(className)) { + return new TypeToken(){}.getType(); + } + + if ("ModelReturn".equalsIgnoreCase(className)) { + return new TypeToken(){}.getType(); + } + + if ("Name".equalsIgnoreCase(className)) { + return new TypeToken(){}.getType(); + } + + if ("Order".equalsIgnoreCase(className)) { + return new TypeToken(){}.getType(); } if ("Pet".equalsIgnoreCase(className)) { return new TypeToken(){}.getType(); } + if ("SpecialModelName".equalsIgnoreCase(className)) { + return new TypeToken(){}.getType(); + } + + if ("Tag".equalsIgnoreCase(className)) { + return new TypeToken(){}.getType(); + } + + if ("User".equalsIgnoreCase(className)) { + return new TypeToken(){}.getType(); + } + return new TypeToken(){}.getType(); } 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 e63cd564899..b0a72ab7d8a 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 @@ -12,6 +12,7 @@ import com.android.volley.Response; import com.android.volley.VolleyError; import io.swagger.client.model.Pet; +import io.swagger.client.model.InlineResponse200; import java.io.File; import org.apache.http.HttpEntity; @@ -45,135 +46,6 @@ public class PetApi { } - /** - * Update an existing pet - * - * @param body Pet object that needs to be added to the store - * @return void - */ - public void updatePet (Pet body) throws TimeoutException, ExecutionException, InterruptedException, ApiException { - Object postBody = body; - - - // create path and map variables - String path = "/pet".replaceAll("\\{format\\}","json"); - - // query params - List queryParams = new ArrayList(); - // header params - Map headerParams = new HashMap(); - // form params - Map formParams = new HashMap(); - - - - - - String[] contentTypes = { - "application/json","application/xml" - }; - String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - - if (contentType.startsWith("multipart/form-data")) { - // file uploading - MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create(); - - - HttpEntity httpEntity = localVarBuilder.build(); - postBody = httpEntity; - } else { - // normal form params - - } - - String[] authNames = new String[] { "petstore_auth" }; - - try { - String localVarResponse = apiInvoker.invokeAPI (basePath, path, "PUT", queryParams, postBody, headerParams, formParams, contentType, authNames); - if(localVarResponse != null){ - return ; - } else { - return ; - } - } catch (ApiException ex) { - throw ex; - } catch (InterruptedException ex) { - throw ex; - } catch (ExecutionException ex) { - if(ex.getCause() instanceof VolleyError) { - throw new ApiException(((VolleyError) ex.getCause()).networkResponse.statusCode, ((VolleyError) ex.getCause()).getMessage()); - } - throw ex; - } catch (TimeoutException ex) { - throw ex; - } - } - - /** - * Update an existing pet - * - * @param body Pet object that needs to be added to the store - */ - public void updatePet (Pet body, final Response.Listener responseListener, final Response.ErrorListener errorListener) { - Object postBody = body; - - - - // create path and map variables - String path = "/pet".replaceAll("\\{format\\}","json"); - - // query params - List queryParams = new ArrayList(); - // header params - Map headerParams = new HashMap(); - // form params - Map formParams = new HashMap(); - - - - - - String[] contentTypes = { - "application/json","application/xml" - }; - String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - - if (contentType.startsWith("multipart/form-data")) { - // file uploading - MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create(); - - - HttpEntity httpEntity = localVarBuilder.build(); - postBody = httpEntity; - } else { - // normal form params - - } - - String[] authNames = new String[] { "petstore_auth" }; - - try { - apiInvoker.invokeAPI(basePath, path, "PUT", queryParams, postBody, headerParams, formParams, contentType, authNames, - new Response.Listener() { - @Override - public void onResponse(String localVarResponse) { - - - responseListener.onResponse(localVarResponse); - - - } - }, new Response.ErrorListener() { - @Override - public void onErrorResponse(VolleyError error) { - errorListener.onErrorResponse(error); - } - }); - } catch (ApiException ex) { - errorListener.onErrorResponse(new VolleyError(ex)); - } - } - /** * Add a new pet to the store * @@ -303,6 +175,281 @@ public class PetApi { } } + /** + * Fake endpoint to test byte array in body parameter for adding a new pet to the store + * + * @param body Pet object in the form of byte array + * @return void + */ + public void addPetUsingByteArray (byte[] body) throws TimeoutException, ExecutionException, InterruptedException, ApiException { + Object postBody = body; + + + // create path and map variables + String path = "/pet?testing_byte_array=true".replaceAll("\\{format\\}","json"); + + // query params + List queryParams = new ArrayList(); + // header params + Map headerParams = new HashMap(); + // form params + Map formParams = new HashMap(); + + + + + + String[] contentTypes = { + "application/json","application/xml" + }; + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; + + if (contentType.startsWith("multipart/form-data")) { + // file uploading + MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create(); + + + HttpEntity httpEntity = localVarBuilder.build(); + postBody = httpEntity; + } else { + // normal form params + + } + + String[] authNames = new String[] { "petstore_auth" }; + + try { + String localVarResponse = apiInvoker.invokeAPI (basePath, path, "POST", queryParams, postBody, headerParams, formParams, contentType, authNames); + if(localVarResponse != null){ + return ; + } else { + return ; + } + } catch (ApiException ex) { + throw ex; + } catch (InterruptedException ex) { + throw ex; + } catch (ExecutionException ex) { + if(ex.getCause() instanceof VolleyError) { + throw new ApiException(((VolleyError) ex.getCause()).networkResponse.statusCode, ((VolleyError) ex.getCause()).getMessage()); + } + throw ex; + } catch (TimeoutException ex) { + throw ex; + } + } + + /** + * Fake endpoint to test byte array in body parameter for adding a new pet to the store + * + * @param body Pet object in the form of byte array + */ + public void addPetUsingByteArray (byte[] body, final Response.Listener responseListener, final Response.ErrorListener errorListener) { + Object postBody = body; + + + + // create path and map variables + String path = "/pet?testing_byte_array=true".replaceAll("\\{format\\}","json"); + + // query params + List queryParams = new ArrayList(); + // header params + Map headerParams = new HashMap(); + // form params + Map formParams = new HashMap(); + + + + + + String[] contentTypes = { + "application/json","application/xml" + }; + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; + + if (contentType.startsWith("multipart/form-data")) { + // file uploading + MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create(); + + + HttpEntity httpEntity = localVarBuilder.build(); + postBody = httpEntity; + } else { + // normal form params + + } + + String[] authNames = new String[] { "petstore_auth" }; + + try { + apiInvoker.invokeAPI(basePath, path, "POST", queryParams, postBody, headerParams, formParams, contentType, authNames, + new Response.Listener() { + @Override + public void onResponse(String localVarResponse) { + + + responseListener.onResponse(localVarResponse); + + + } + }, new Response.ErrorListener() { + @Override + public void onErrorResponse(VolleyError error) { + errorListener.onErrorResponse(error); + } + }); + } catch (ApiException ex) { + errorListener.onErrorResponse(new VolleyError(ex)); + } + } + + /** + * Deletes a pet + * + * @param petId Pet id to delete + * @param apiKey + * @return void + */ + public void deletePet (Long petId, String apiKey) throws TimeoutException, ExecutionException, InterruptedException, ApiException { + Object postBody = null; + + // verify the required parameter 'petId' is set + if (petId == null) { + VolleyError error = new VolleyError("Missing the required parameter 'petId' when calling deletePet", + new ApiException(400, "Missing the required parameter 'petId' when calling deletePet")); + } + + + // create path and map variables + String path = "/pet/{petId}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "petId" + "\\}", apiInvoker.escapeString(petId.toString())); + + // query params + List queryParams = new ArrayList(); + // header params + Map headerParams = new HashMap(); + // form params + Map formParams = new HashMap(); + + + + + headerParams.put("api_key", ApiInvoker.parameterToString(apiKey)); + + + String[] contentTypes = { + + }; + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; + + if (contentType.startsWith("multipart/form-data")) { + // file uploading + MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create(); + + + HttpEntity httpEntity = localVarBuilder.build(); + postBody = httpEntity; + } else { + // normal form params + + } + + String[] authNames = new String[] { "petstore_auth" }; + + try { + String localVarResponse = apiInvoker.invokeAPI (basePath, path, "DELETE", queryParams, postBody, headerParams, formParams, contentType, authNames); + if(localVarResponse != null){ + return ; + } else { + return ; + } + } catch (ApiException ex) { + throw ex; + } catch (InterruptedException ex) { + throw ex; + } catch (ExecutionException ex) { + if(ex.getCause() instanceof VolleyError) { + throw new ApiException(((VolleyError) ex.getCause()).networkResponse.statusCode, ((VolleyError) ex.getCause()).getMessage()); + } + throw ex; + } catch (TimeoutException ex) { + throw ex; + } + } + + /** + * Deletes a pet + * + * @param petId Pet id to delete * @param apiKey + */ + public void deletePet (Long petId, String apiKey, final Response.Listener responseListener, final Response.ErrorListener errorListener) { + Object postBody = null; + + + // verify the required parameter 'petId' is set + if (petId == null) { + VolleyError error = new VolleyError("Missing the required parameter 'petId' when calling deletePet", + new ApiException(400, "Missing the required parameter 'petId' when calling deletePet")); + } + + + // create path and map variables + String path = "/pet/{petId}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "petId" + "\\}", apiInvoker.escapeString(petId.toString())); + + // query params + List queryParams = new ArrayList(); + // header params + Map headerParams = new HashMap(); + // form params + Map formParams = new HashMap(); + + + + + headerParams.put("api_key", ApiInvoker.parameterToString(apiKey)); + + + String[] contentTypes = { + + }; + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; + + if (contentType.startsWith("multipart/form-data")) { + // file uploading + MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create(); + + + HttpEntity httpEntity = localVarBuilder.build(); + postBody = httpEntity; + } else { + // normal form params + + } + + String[] authNames = new String[] { "petstore_auth" }; + + try { + apiInvoker.invokeAPI(basePath, path, "DELETE", queryParams, postBody, headerParams, formParams, contentType, authNames, + new Response.Listener() { + @Override + public void onResponse(String localVarResponse) { + + + responseListener.onResponse(localVarResponse); + + + } + }, new Response.ErrorListener() { + @Override + public void onErrorResponse(VolleyError error) { + errorListener.onErrorResponse(error); + } + }); + } catch (ApiException ex) { + errorListener.onErrorResponse(new VolleyError(ex)); + } + } + /** * Finds Pets by status * Multiple status values can be provided with comma separated strings @@ -626,7 +773,7 @@ public class PetApi { } - String[] authNames = new String[] { "petstore_auth", "api_key" }; + String[] authNames = new String[] { "api_key", "petstore_auth" }; try { String localVarResponse = apiInvoker.invokeAPI (basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType, authNames); @@ -696,7 +843,7 @@ public class PetApi { } - String[] authNames = new String[] { "petstore_auth", "api_key" }; + String[] authNames = new String[] { "api_key", "petstore_auth" }; try { apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType, authNames, @@ -725,6 +872,427 @@ public class PetApi { } } + /** + * Fake endpoint to test inline arbitrary object return by 'Find pet by ID' + * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + * @param petId ID of pet that needs to be fetched + * @return InlineResponse200 + */ + public InlineResponse200 getPetByIdInObject (Long petId) throws TimeoutException, ExecutionException, InterruptedException, ApiException { + Object postBody = null; + + // verify the required parameter 'petId' is set + if (petId == null) { + VolleyError error = new VolleyError("Missing the required parameter 'petId' when calling getPetByIdInObject", + new ApiException(400, "Missing the required parameter 'petId' when calling getPetByIdInObject")); + } + + + // create path and map variables + String path = "/pet/{petId}?response=inline_arbitrary_object".replaceAll("\\{format\\}","json").replaceAll("\\{" + "petId" + "\\}", apiInvoker.escapeString(petId.toString())); + + // query params + List queryParams = new ArrayList(); + // header params + Map headerParams = new HashMap(); + // form params + Map formParams = new HashMap(); + + + + + + String[] contentTypes = { + + }; + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; + + if (contentType.startsWith("multipart/form-data")) { + // file uploading + MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create(); + + + HttpEntity httpEntity = localVarBuilder.build(); + postBody = httpEntity; + } else { + // normal form params + + } + + String[] authNames = new String[] { "api_key", "petstore_auth" }; + + try { + String localVarResponse = apiInvoker.invokeAPI (basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType, authNames); + if(localVarResponse != null){ + return (InlineResponse200) ApiInvoker.deserialize(localVarResponse, "", InlineResponse200.class); + } else { + return null; + } + } catch (ApiException ex) { + throw ex; + } catch (InterruptedException ex) { + throw ex; + } catch (ExecutionException ex) { + if(ex.getCause() instanceof VolleyError) { + throw new ApiException(((VolleyError) ex.getCause()).networkResponse.statusCode, ((VolleyError) ex.getCause()).getMessage()); + } + throw ex; + } catch (TimeoutException ex) { + throw ex; + } + } + + /** + * Fake endpoint to test inline arbitrary object return by 'Find pet by ID' + * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + * @param petId ID of pet that needs to be fetched + */ + public void getPetByIdInObject (Long petId, final Response.Listener responseListener, final Response.ErrorListener errorListener) { + Object postBody = null; + + + // verify the required parameter 'petId' is set + if (petId == null) { + VolleyError error = new VolleyError("Missing the required parameter 'petId' when calling getPetByIdInObject", + new ApiException(400, "Missing the required parameter 'petId' when calling getPetByIdInObject")); + } + + + // create path and map variables + String path = "/pet/{petId}?response=inline_arbitrary_object".replaceAll("\\{format\\}","json").replaceAll("\\{" + "petId" + "\\}", apiInvoker.escapeString(petId.toString())); + + // query params + List queryParams = new ArrayList(); + // header params + Map headerParams = new HashMap(); + // form params + Map formParams = new HashMap(); + + + + + + String[] contentTypes = { + + }; + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; + + if (contentType.startsWith("multipart/form-data")) { + // file uploading + MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create(); + + + HttpEntity httpEntity = localVarBuilder.build(); + postBody = httpEntity; + } else { + // normal form params + + } + + String[] authNames = new String[] { "api_key", "petstore_auth" }; + + try { + apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType, authNames, + new Response.Listener() { + @Override + public void onResponse(String localVarResponse) { + + try { + responseListener.onResponse((InlineResponse200) ApiInvoker.deserialize(localVarResponse, "", InlineResponse200.class)); + + + + } catch (ApiException exception) { + errorListener.onErrorResponse(new VolleyError(exception)); + } + + } + }, new Response.ErrorListener() { + @Override + public void onErrorResponse(VolleyError error) { + errorListener.onErrorResponse(error); + } + }); + } catch (ApiException ex) { + errorListener.onErrorResponse(new VolleyError(ex)); + } + } + + /** + * Fake endpoint to test byte array return by 'Find pet by ID' + * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + * @param petId ID of pet that needs to be fetched + * @return byte[] + */ + public byte[] petPetIdtestingByteArraytrueGet (Long petId) throws TimeoutException, ExecutionException, InterruptedException, ApiException { + Object postBody = null; + + // verify the required parameter 'petId' is set + if (petId == null) { + VolleyError error = new VolleyError("Missing the required parameter 'petId' when calling petPetIdtestingByteArraytrueGet", + new ApiException(400, "Missing the required parameter 'petId' when calling petPetIdtestingByteArraytrueGet")); + } + + + // create path and map variables + String path = "/pet/{petId}?testing_byte_array=true".replaceAll("\\{format\\}","json").replaceAll("\\{" + "petId" + "\\}", apiInvoker.escapeString(petId.toString())); + + // query params + List queryParams = new ArrayList(); + // header params + Map headerParams = new HashMap(); + // form params + Map formParams = new HashMap(); + + + + + + String[] contentTypes = { + + }; + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; + + if (contentType.startsWith("multipart/form-data")) { + // file uploading + MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create(); + + + HttpEntity httpEntity = localVarBuilder.build(); + postBody = httpEntity; + } else { + // normal form params + + } + + String[] authNames = new String[] { "api_key", "petstore_auth" }; + + try { + String localVarResponse = apiInvoker.invokeAPI (basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType, authNames); + if(localVarResponse != null){ + return (byte[]) ApiInvoker.deserialize(localVarResponse, "", byte[].class); + } else { + return null; + } + } catch (ApiException ex) { + throw ex; + } catch (InterruptedException ex) { + throw ex; + } catch (ExecutionException ex) { + if(ex.getCause() instanceof VolleyError) { + throw new ApiException(((VolleyError) ex.getCause()).networkResponse.statusCode, ((VolleyError) ex.getCause()).getMessage()); + } + throw ex; + } catch (TimeoutException ex) { + throw ex; + } + } + + /** + * Fake endpoint to test byte array return by 'Find pet by ID' + * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + * @param petId ID of pet that needs to be fetched + */ + public void petPetIdtestingByteArraytrueGet (Long petId, final Response.Listener responseListener, final Response.ErrorListener errorListener) { + Object postBody = null; + + + // verify the required parameter 'petId' is set + if (petId == null) { + VolleyError error = new VolleyError("Missing the required parameter 'petId' when calling petPetIdtestingByteArraytrueGet", + new ApiException(400, "Missing the required parameter 'petId' when calling petPetIdtestingByteArraytrueGet")); + } + + + // create path and map variables + String path = "/pet/{petId}?testing_byte_array=true".replaceAll("\\{format\\}","json").replaceAll("\\{" + "petId" + "\\}", apiInvoker.escapeString(petId.toString())); + + // query params + List queryParams = new ArrayList(); + // header params + Map headerParams = new HashMap(); + // form params + Map formParams = new HashMap(); + + + + + + String[] contentTypes = { + + }; + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; + + if (contentType.startsWith("multipart/form-data")) { + // file uploading + MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create(); + + + HttpEntity httpEntity = localVarBuilder.build(); + postBody = httpEntity; + } else { + // normal form params + + } + + String[] authNames = new String[] { "api_key", "petstore_auth" }; + + try { + apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType, authNames, + new Response.Listener() { + @Override + public void onResponse(String localVarResponse) { + + try { + responseListener.onResponse((byte[]) ApiInvoker.deserialize(localVarResponse, "", byte[].class)); + + + + } catch (ApiException exception) { + errorListener.onErrorResponse(new VolleyError(exception)); + } + + } + }, new Response.ErrorListener() { + @Override + public void onErrorResponse(VolleyError error) { + errorListener.onErrorResponse(error); + } + }); + } catch (ApiException ex) { + errorListener.onErrorResponse(new VolleyError(ex)); + } + } + + /** + * Update an existing pet + * + * @param body Pet object that needs to be added to the store + * @return void + */ + public void updatePet (Pet body) throws TimeoutException, ExecutionException, InterruptedException, ApiException { + Object postBody = body; + + + // create path and map variables + String path = "/pet".replaceAll("\\{format\\}","json"); + + // query params + List queryParams = new ArrayList(); + // header params + Map headerParams = new HashMap(); + // form params + Map formParams = new HashMap(); + + + + + + String[] contentTypes = { + "application/json","application/xml" + }; + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; + + if (contentType.startsWith("multipart/form-data")) { + // file uploading + MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create(); + + + HttpEntity httpEntity = localVarBuilder.build(); + postBody = httpEntity; + } else { + // normal form params + + } + + String[] authNames = new String[] { "petstore_auth" }; + + try { + String localVarResponse = apiInvoker.invokeAPI (basePath, path, "PUT", queryParams, postBody, headerParams, formParams, contentType, authNames); + if(localVarResponse != null){ + return ; + } else { + return ; + } + } catch (ApiException ex) { + throw ex; + } catch (InterruptedException ex) { + throw ex; + } catch (ExecutionException ex) { + if(ex.getCause() instanceof VolleyError) { + throw new ApiException(((VolleyError) ex.getCause()).networkResponse.statusCode, ((VolleyError) ex.getCause()).getMessage()); + } + throw ex; + } catch (TimeoutException ex) { + throw ex; + } + } + + /** + * Update an existing pet + * + * @param body Pet object that needs to be added to the store + */ + public void updatePet (Pet body, final Response.Listener responseListener, final Response.ErrorListener errorListener) { + Object postBody = body; + + + + // create path and map variables + String path = "/pet".replaceAll("\\{format\\}","json"); + + // query params + List queryParams = new ArrayList(); + // header params + Map headerParams = new HashMap(); + // form params + Map formParams = new HashMap(); + + + + + + String[] contentTypes = { + "application/json","application/xml" + }; + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; + + if (contentType.startsWith("multipart/form-data")) { + // file uploading + MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create(); + + + HttpEntity httpEntity = localVarBuilder.build(); + postBody = httpEntity; + } else { + // normal form params + + } + + String[] authNames = new String[] { "petstore_auth" }; + + try { + apiInvoker.invokeAPI(basePath, path, "PUT", queryParams, postBody, headerParams, formParams, contentType, authNames, + new Response.Listener() { + @Override + public void onResponse(String localVarResponse) { + + + responseListener.onResponse(localVarResponse); + + + } + }, new Response.ErrorListener() { + @Override + public void onErrorResponse(VolleyError error) { + errorListener.onErrorResponse(error); + } + }); + } catch (ApiException ex) { + errorListener.onErrorResponse(new VolleyError(ex)); + } + } + /** * Updates a pet in the store with form data * @@ -888,152 +1456,6 @@ public class PetApi { } } - /** - * Deletes a pet - * - * @param petId Pet id to delete - * @param apiKey - * @return void - */ - public void deletePet (Long petId, String apiKey) throws TimeoutException, ExecutionException, InterruptedException, ApiException { - Object postBody = null; - - // verify the required parameter 'petId' is set - if (petId == null) { - VolleyError error = new VolleyError("Missing the required parameter 'petId' when calling deletePet", - new ApiException(400, "Missing the required parameter 'petId' when calling deletePet")); - } - - - // create path and map variables - String path = "/pet/{petId}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "petId" + "\\}", apiInvoker.escapeString(petId.toString())); - - // query params - List queryParams = new ArrayList(); - // header params - Map headerParams = new HashMap(); - // form params - Map formParams = new HashMap(); - - - - - headerParams.put("api_key", ApiInvoker.parameterToString(apiKey)); - - - String[] contentTypes = { - - }; - String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - - if (contentType.startsWith("multipart/form-data")) { - // file uploading - MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create(); - - - HttpEntity httpEntity = localVarBuilder.build(); - postBody = httpEntity; - } else { - // normal form params - - } - - String[] authNames = new String[] { "petstore_auth" }; - - try { - String localVarResponse = apiInvoker.invokeAPI (basePath, path, "DELETE", queryParams, postBody, headerParams, formParams, contentType, authNames); - if(localVarResponse != null){ - return ; - } else { - return ; - } - } catch (ApiException ex) { - throw ex; - } catch (InterruptedException ex) { - throw ex; - } catch (ExecutionException ex) { - if(ex.getCause() instanceof VolleyError) { - throw new ApiException(((VolleyError) ex.getCause()).networkResponse.statusCode, ((VolleyError) ex.getCause()).getMessage()); - } - throw ex; - } catch (TimeoutException ex) { - throw ex; - } - } - - /** - * Deletes a pet - * - * @param petId Pet id to delete * @param apiKey - */ - public void deletePet (Long petId, String apiKey, final Response.Listener responseListener, final Response.ErrorListener errorListener) { - Object postBody = null; - - - // verify the required parameter 'petId' is set - if (petId == null) { - VolleyError error = new VolleyError("Missing the required parameter 'petId' when calling deletePet", - new ApiException(400, "Missing the required parameter 'petId' when calling deletePet")); - } - - - // create path and map variables - String path = "/pet/{petId}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "petId" + "\\}", apiInvoker.escapeString(petId.toString())); - - // query params - List queryParams = new ArrayList(); - // header params - Map headerParams = new HashMap(); - // form params - Map formParams = new HashMap(); - - - - - headerParams.put("api_key", ApiInvoker.parameterToString(apiKey)); - - - String[] contentTypes = { - - }; - String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - - if (contentType.startsWith("multipart/form-data")) { - // file uploading - MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create(); - - - HttpEntity httpEntity = localVarBuilder.build(); - postBody = httpEntity; - } else { - // normal form params - - } - - String[] authNames = new String[] { "petstore_auth" }; - - try { - apiInvoker.invokeAPI(basePath, path, "DELETE", queryParams, postBody, headerParams, formParams, contentType, authNames, - new Response.Listener() { - @Override - public void onResponse(String localVarResponse) { - - - responseListener.onResponse(localVarResponse); - - - } - }, new Response.ErrorListener() { - @Override - public void onErrorResponse(VolleyError error) { - errorListener.onErrorResponse(error); - } - }); - } catch (ApiException ex) { - errorListener.onErrorResponse(new VolleyError(ex)); - } - } - /** * uploads an image * @@ -1197,279 +1619,4 @@ public class PetApi { } } - /** - * Fake endpoint to test byte array return by 'Find pet by ID' - * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions - * @param petId ID of pet that needs to be fetched - * @return byte[] - */ - public byte[] petPetIdtestingByteArraytrueGet (Long petId) throws TimeoutException, ExecutionException, InterruptedException, ApiException { - Object postBody = null; - - // verify the required parameter 'petId' is set - if (petId == null) { - VolleyError error = new VolleyError("Missing the required parameter 'petId' when calling petPetIdtestingByteArraytrueGet", - new ApiException(400, "Missing the required parameter 'petId' when calling petPetIdtestingByteArraytrueGet")); - } - - - // create path and map variables - String path = "/pet/{petId}?testing_byte_array=true".replaceAll("\\{format\\}","json").replaceAll("\\{" + "petId" + "\\}", apiInvoker.escapeString(petId.toString())); - - // query params - List queryParams = new ArrayList(); - // header params - Map headerParams = new HashMap(); - // form params - Map formParams = new HashMap(); - - - - - - String[] contentTypes = { - - }; - String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - - if (contentType.startsWith("multipart/form-data")) { - // file uploading - MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create(); - - - HttpEntity httpEntity = localVarBuilder.build(); - postBody = httpEntity; - } else { - // normal form params - - } - - String[] authNames = new String[] { "petstore_auth", "api_key" }; - - try { - String localVarResponse = apiInvoker.invokeAPI (basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType, authNames); - if(localVarResponse != null){ - return (byte[]) ApiInvoker.deserialize(localVarResponse, "", byte[].class); - } else { - return null; - } - } catch (ApiException ex) { - throw ex; - } catch (InterruptedException ex) { - throw ex; - } catch (ExecutionException ex) { - if(ex.getCause() instanceof VolleyError) { - throw new ApiException(((VolleyError) ex.getCause()).networkResponse.statusCode, ((VolleyError) ex.getCause()).getMessage()); - } - throw ex; - } catch (TimeoutException ex) { - throw ex; - } - } - - /** - * Fake endpoint to test byte array return by 'Find pet by ID' - * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions - * @param petId ID of pet that needs to be fetched - */ - public void petPetIdtestingByteArraytrueGet (Long petId, final Response.Listener responseListener, final Response.ErrorListener errorListener) { - Object postBody = null; - - - // verify the required parameter 'petId' is set - if (petId == null) { - VolleyError error = new VolleyError("Missing the required parameter 'petId' when calling petPetIdtestingByteArraytrueGet", - new ApiException(400, "Missing the required parameter 'petId' when calling petPetIdtestingByteArraytrueGet")); - } - - - // create path and map variables - String path = "/pet/{petId}?testing_byte_array=true".replaceAll("\\{format\\}","json").replaceAll("\\{" + "petId" + "\\}", apiInvoker.escapeString(petId.toString())); - - // query params - List queryParams = new ArrayList(); - // header params - Map headerParams = new HashMap(); - // form params - Map formParams = new HashMap(); - - - - - - String[] contentTypes = { - - }; - String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - - if (contentType.startsWith("multipart/form-data")) { - // file uploading - MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create(); - - - HttpEntity httpEntity = localVarBuilder.build(); - postBody = httpEntity; - } else { - // normal form params - - } - - String[] authNames = new String[] { "petstore_auth", "api_key" }; - - try { - apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType, authNames, - new Response.Listener() { - @Override - public void onResponse(String localVarResponse) { - - try { - responseListener.onResponse((byte[]) ApiInvoker.deserialize(localVarResponse, "", byte[].class)); - - - - } catch (ApiException exception) { - errorListener.onErrorResponse(new VolleyError(exception)); - } - - } - }, new Response.ErrorListener() { - @Override - public void onErrorResponse(VolleyError error) { - errorListener.onErrorResponse(error); - } - }); - } catch (ApiException ex) { - errorListener.onErrorResponse(new VolleyError(ex)); - } - } - - /** - * Fake endpoint to test byte array in body parameter for adding a new pet to the store - * - * @param body Pet object in the form of byte array - * @return void - */ - public void addPetUsingByteArray (byte[] body) throws TimeoutException, ExecutionException, InterruptedException, ApiException { - Object postBody = body; - - - // create path and map variables - String path = "/pet?testing_byte_array=true".replaceAll("\\{format\\}","json"); - - // query params - List queryParams = new ArrayList(); - // header params - Map headerParams = new HashMap(); - // form params - Map formParams = new HashMap(); - - - - - - String[] contentTypes = { - "application/json","application/xml" - }; - String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - - if (contentType.startsWith("multipart/form-data")) { - // file uploading - MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create(); - - - HttpEntity httpEntity = localVarBuilder.build(); - postBody = httpEntity; - } else { - // normal form params - - } - - String[] authNames = new String[] { "petstore_auth" }; - - try { - String localVarResponse = apiInvoker.invokeAPI (basePath, path, "POST", queryParams, postBody, headerParams, formParams, contentType, authNames); - if(localVarResponse != null){ - return ; - } else { - return ; - } - } catch (ApiException ex) { - throw ex; - } catch (InterruptedException ex) { - throw ex; - } catch (ExecutionException ex) { - if(ex.getCause() instanceof VolleyError) { - throw new ApiException(((VolleyError) ex.getCause()).networkResponse.statusCode, ((VolleyError) ex.getCause()).getMessage()); - } - throw ex; - } catch (TimeoutException ex) { - throw ex; - } - } - - /** - * Fake endpoint to test byte array in body parameter for adding a new pet to the store - * - * @param body Pet object in the form of byte array - */ - public void addPetUsingByteArray (byte[] body, final Response.Listener responseListener, final Response.ErrorListener errorListener) { - Object postBody = body; - - - - // create path and map variables - String path = "/pet?testing_byte_array=true".replaceAll("\\{format\\}","json"); - - // query params - List queryParams = new ArrayList(); - // header params - Map headerParams = new HashMap(); - // form params - Map formParams = new HashMap(); - - - - - - String[] contentTypes = { - "application/json","application/xml" - }; - String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - - if (contentType.startsWith("multipart/form-data")) { - // file uploading - MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create(); - - - HttpEntity httpEntity = localVarBuilder.build(); - postBody = httpEntity; - } else { - // normal form params - - } - - String[] authNames = new String[] { "petstore_auth" }; - - try { - apiInvoker.invokeAPI(basePath, path, "POST", queryParams, postBody, headerParams, formParams, contentType, authNames, - new Response.Listener() { - @Override - public void onResponse(String localVarResponse) { - - - responseListener.onResponse(localVarResponse); - - - } - }, new Response.ErrorListener() { - @Override - public void onErrorResponse(VolleyError error) { - errorListener.onErrorResponse(error); - } - }); - } catch (ApiException ex) { - errorListener.onErrorResponse(new VolleyError(ex)); - } - } - } 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 91f04502598..e0aa403200a 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 @@ -45,6 +45,147 @@ public class 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 + * @return void + */ + public void deleteOrder (String orderId) throws TimeoutException, ExecutionException, InterruptedException, ApiException { + Object postBody = null; + + // verify the required parameter 'orderId' is set + if (orderId == null) { + VolleyError error = new VolleyError("Missing the required parameter 'orderId' when calling deleteOrder", + new ApiException(400, "Missing the required parameter 'orderId' when calling deleteOrder")); + } + + + // create path and map variables + String path = "/store/order/{orderId}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "orderId" + "\\}", apiInvoker.escapeString(orderId.toString())); + + // query params + List queryParams = new ArrayList(); + // header params + Map headerParams = new HashMap(); + // form params + Map formParams = new HashMap(); + + + + + + String[] contentTypes = { + + }; + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; + + if (contentType.startsWith("multipart/form-data")) { + // file uploading + MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create(); + + + HttpEntity httpEntity = localVarBuilder.build(); + postBody = httpEntity; + } else { + // normal form params + + } + + String[] authNames = new String[] { }; + + try { + String localVarResponse = apiInvoker.invokeAPI (basePath, path, "DELETE", queryParams, postBody, headerParams, formParams, contentType, authNames); + if(localVarResponse != null){ + return ; + } else { + return ; + } + } catch (ApiException ex) { + throw ex; + } catch (InterruptedException ex) { + throw ex; + } catch (ExecutionException ex) { + if(ex.getCause() instanceof VolleyError) { + throw new ApiException(((VolleyError) ex.getCause()).networkResponse.statusCode, ((VolleyError) ex.getCause()).getMessage()); + } + throw ex; + } catch (TimeoutException ex) { + throw ex; + } + } + + /** + * Delete purchase order by ID + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * @param orderId ID of the order that needs to be deleted + */ + public void deleteOrder (String orderId, final Response.Listener responseListener, final Response.ErrorListener errorListener) { + Object postBody = null; + + + // verify the required parameter 'orderId' is set + if (orderId == null) { + VolleyError error = new VolleyError("Missing the required parameter 'orderId' when calling deleteOrder", + new ApiException(400, "Missing the required parameter 'orderId' when calling deleteOrder")); + } + + + // create path and map variables + String path = "/store/order/{orderId}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "orderId" + "\\}", apiInvoker.escapeString(orderId.toString())); + + // query params + List queryParams = new ArrayList(); + // header params + Map headerParams = new HashMap(); + // form params + Map formParams = new HashMap(); + + + + + + String[] contentTypes = { + + }; + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; + + if (contentType.startsWith("multipart/form-data")) { + // file uploading + MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create(); + + + HttpEntity httpEntity = localVarBuilder.build(); + postBody = httpEntity; + } else { + // normal form params + + } + + String[] authNames = new String[] { }; + + try { + apiInvoker.invokeAPI(basePath, path, "DELETE", queryParams, postBody, headerParams, formParams, contentType, authNames, + new Response.Listener() { + @Override + public void onResponse(String localVarResponse) { + + + responseListener.onResponse(localVarResponse); + + + } + }, new Response.ErrorListener() { + @Override + public void onErrorResponse(VolleyError error) { + errorListener.onErrorResponse(error); + } + }); + } catch (ApiException ex) { + errorListener.onErrorResponse(new VolleyError(ex)); + } + } + /** * Finds orders by status * A single status value can be provided as a string @@ -300,6 +441,285 @@ public class StoreApi { + } catch (ApiException exception) { + errorListener.onErrorResponse(new VolleyError(exception)); + } + + } + }, new Response.ErrorListener() { + @Override + public void onErrorResponse(VolleyError error) { + errorListener.onErrorResponse(error); + } + }); + } catch (ApiException ex) { + errorListener.onErrorResponse(new VolleyError(ex)); + } + } + + /** + * Fake endpoint to test arbitrary object return by 'Get inventory' + * Returns an arbitrary object which is actually a map of status codes to quantities + * @return Object + */ + public Object getInventoryInObject () throws TimeoutException, ExecutionException, InterruptedException, ApiException { + Object postBody = null; + + + // create path and map variables + String path = "/store/inventory?response=arbitrary_object".replaceAll("\\{format\\}","json"); + + // query params + List queryParams = new ArrayList(); + // header params + Map headerParams = new HashMap(); + // form params + Map formParams = new HashMap(); + + + + + + String[] contentTypes = { + + }; + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; + + if (contentType.startsWith("multipart/form-data")) { + // file uploading + MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create(); + + + HttpEntity httpEntity = localVarBuilder.build(); + postBody = httpEntity; + } else { + // normal form params + + } + + String[] authNames = new String[] { "api_key" }; + + try { + String localVarResponse = apiInvoker.invokeAPI (basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType, authNames); + if(localVarResponse != null){ + return (Object) ApiInvoker.deserialize(localVarResponse, "", Object.class); + } else { + return null; + } + } catch (ApiException ex) { + throw ex; + } catch (InterruptedException ex) { + throw ex; + } catch (ExecutionException ex) { + if(ex.getCause() instanceof VolleyError) { + throw new ApiException(((VolleyError) ex.getCause()).networkResponse.statusCode, ((VolleyError) ex.getCause()).getMessage()); + } + throw ex; + } catch (TimeoutException ex) { + throw ex; + } + } + + /** + * Fake endpoint to test arbitrary object return by 'Get inventory' + * Returns an arbitrary object which is actually a map of status codes to quantities + + */ + public void getInventoryInObject (final Response.Listener responseListener, final Response.ErrorListener errorListener) { + Object postBody = null; + + + + // create path and map variables + String path = "/store/inventory?response=arbitrary_object".replaceAll("\\{format\\}","json"); + + // query params + List queryParams = new ArrayList(); + // header params + Map headerParams = new HashMap(); + // form params + Map formParams = new HashMap(); + + + + + + String[] contentTypes = { + + }; + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; + + if (contentType.startsWith("multipart/form-data")) { + // file uploading + MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create(); + + + HttpEntity httpEntity = localVarBuilder.build(); + postBody = httpEntity; + } else { + // normal form params + + } + + String[] authNames = new String[] { "api_key" }; + + try { + apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType, authNames, + new Response.Listener() { + @Override + public void onResponse(String localVarResponse) { + + try { + responseListener.onResponse((Object) ApiInvoker.deserialize(localVarResponse, "", Object.class)); + + + + } catch (ApiException exception) { + errorListener.onErrorResponse(new VolleyError(exception)); + } + + } + }, new Response.ErrorListener() { + @Override + public void onErrorResponse(VolleyError error) { + errorListener.onErrorResponse(error); + } + }); + } catch (ApiException ex) { + errorListener.onErrorResponse(new VolleyError(ex)); + } + } + + /** + * Find purchase order by ID + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * @param orderId ID of pet that needs to be fetched + * @return Order + */ + public Order getOrderById (String orderId) throws TimeoutException, ExecutionException, InterruptedException, ApiException { + Object postBody = null; + + // verify the required parameter 'orderId' is set + if (orderId == null) { + VolleyError error = new VolleyError("Missing the required parameter 'orderId' when calling getOrderById", + new ApiException(400, "Missing the required parameter 'orderId' when calling getOrderById")); + } + + + // create path and map variables + String path = "/store/order/{orderId}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "orderId" + "\\}", apiInvoker.escapeString(orderId.toString())); + + // query params + List queryParams = new ArrayList(); + // header params + Map headerParams = new HashMap(); + // form params + Map formParams = new HashMap(); + + + + + + String[] contentTypes = { + + }; + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; + + if (contentType.startsWith("multipart/form-data")) { + // file uploading + MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create(); + + + HttpEntity httpEntity = localVarBuilder.build(); + postBody = httpEntity; + } else { + // normal form params + + } + + String[] authNames = new String[] { "test_api_key_header", "test_api_key_query" }; + + try { + String localVarResponse = apiInvoker.invokeAPI (basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType, authNames); + if(localVarResponse != null){ + return (Order) ApiInvoker.deserialize(localVarResponse, "", Order.class); + } else { + return null; + } + } catch (ApiException ex) { + throw ex; + } catch (InterruptedException ex) { + throw ex; + } catch (ExecutionException ex) { + if(ex.getCause() instanceof VolleyError) { + throw new ApiException(((VolleyError) ex.getCause()).networkResponse.statusCode, ((VolleyError) ex.getCause()).getMessage()); + } + throw ex; + } catch (TimeoutException ex) { + throw ex; + } + } + + /** + * Find purchase order by ID + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * @param orderId ID of pet that needs to be fetched + */ + public void getOrderById (String orderId, final Response.Listener responseListener, final Response.ErrorListener errorListener) { + Object postBody = null; + + + // verify the required parameter 'orderId' is set + if (orderId == null) { + VolleyError error = new VolleyError("Missing the required parameter 'orderId' when calling getOrderById", + new ApiException(400, "Missing the required parameter 'orderId' when calling getOrderById")); + } + + + // create path and map variables + String path = "/store/order/{orderId}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "orderId" + "\\}", apiInvoker.escapeString(orderId.toString())); + + // query params + List queryParams = new ArrayList(); + // header params + Map headerParams = new HashMap(); + // form params + Map formParams = new HashMap(); + + + + + + String[] contentTypes = { + + }; + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; + + if (contentType.startsWith("multipart/form-data")) { + // file uploading + MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create(); + + + HttpEntity httpEntity = localVarBuilder.build(); + postBody = httpEntity; + } else { + // normal form params + + } + + String[] authNames = new String[] { "test_api_key_header", "test_api_key_query" }; + + try { + apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType, authNames, + new Response.Listener() { + @Override + public void onResponse(String localVarResponse) { + + try { + responseListener.onResponse((Order) ApiInvoker.deserialize(localVarResponse, "", Order.class)); + + + } catch (ApiException exception) { errorListener.onErrorResponse(new VolleyError(exception)); } @@ -450,291 +870,4 @@ public class StoreApi { } } - /** - * Find purchase order by ID - * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - * @param orderId ID of pet that needs to be fetched - * @return Order - */ - public Order getOrderById (String orderId) throws TimeoutException, ExecutionException, InterruptedException, ApiException { - Object postBody = null; - - // verify the required parameter 'orderId' is set - if (orderId == null) { - VolleyError error = new VolleyError("Missing the required parameter 'orderId' when calling getOrderById", - new ApiException(400, "Missing the required parameter 'orderId' when calling getOrderById")); - } - - - // create path and map variables - String path = "/store/order/{orderId}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "orderId" + "\\}", apiInvoker.escapeString(orderId.toString())); - - // query params - List queryParams = new ArrayList(); - // header params - Map headerParams = new HashMap(); - // form params - Map formParams = new HashMap(); - - - - - - String[] contentTypes = { - - }; - String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - - if (contentType.startsWith("multipart/form-data")) { - // file uploading - MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create(); - - - HttpEntity httpEntity = localVarBuilder.build(); - postBody = httpEntity; - } else { - // normal form params - - } - - String[] authNames = new String[] { "test_api_key_query", "test_api_key_header" }; - - try { - String localVarResponse = apiInvoker.invokeAPI (basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType, authNames); - if(localVarResponse != null){ - return (Order) ApiInvoker.deserialize(localVarResponse, "", Order.class); - } else { - return null; - } - } catch (ApiException ex) { - throw ex; - } catch (InterruptedException ex) { - throw ex; - } catch (ExecutionException ex) { - if(ex.getCause() instanceof VolleyError) { - throw new ApiException(((VolleyError) ex.getCause()).networkResponse.statusCode, ((VolleyError) ex.getCause()).getMessage()); - } - throw ex; - } catch (TimeoutException ex) { - throw ex; - } - } - - /** - * Find purchase order by ID - * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - * @param orderId ID of pet that needs to be fetched - */ - public void getOrderById (String orderId, final Response.Listener responseListener, final Response.ErrorListener errorListener) { - Object postBody = null; - - - // verify the required parameter 'orderId' is set - if (orderId == null) { - VolleyError error = new VolleyError("Missing the required parameter 'orderId' when calling getOrderById", - new ApiException(400, "Missing the required parameter 'orderId' when calling getOrderById")); - } - - - // create path and map variables - String path = "/store/order/{orderId}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "orderId" + "\\}", apiInvoker.escapeString(orderId.toString())); - - // query params - List queryParams = new ArrayList(); - // header params - Map headerParams = new HashMap(); - // form params - Map formParams = new HashMap(); - - - - - - String[] contentTypes = { - - }; - String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - - if (contentType.startsWith("multipart/form-data")) { - // file uploading - MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create(); - - - HttpEntity httpEntity = localVarBuilder.build(); - postBody = httpEntity; - } else { - // normal form params - - } - - String[] authNames = new String[] { "test_api_key_query", "test_api_key_header" }; - - try { - apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType, authNames, - new Response.Listener() { - @Override - public void onResponse(String localVarResponse) { - - try { - responseListener.onResponse((Order) ApiInvoker.deserialize(localVarResponse, "", Order.class)); - - - - } catch (ApiException exception) { - errorListener.onErrorResponse(new VolleyError(exception)); - } - - } - }, new Response.ErrorListener() { - @Override - public void onErrorResponse(VolleyError error) { - errorListener.onErrorResponse(error); - } - }); - } catch (ApiException ex) { - errorListener.onErrorResponse(new VolleyError(ex)); - } - } - - /** - * Delete purchase order by ID - * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors - * @param orderId ID of the order that needs to be deleted - * @return void - */ - public void deleteOrder (String orderId) throws TimeoutException, ExecutionException, InterruptedException, ApiException { - Object postBody = null; - - // verify the required parameter 'orderId' is set - if (orderId == null) { - VolleyError error = new VolleyError("Missing the required parameter 'orderId' when calling deleteOrder", - new ApiException(400, "Missing the required parameter 'orderId' when calling deleteOrder")); - } - - - // create path and map variables - String path = "/store/order/{orderId}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "orderId" + "\\}", apiInvoker.escapeString(orderId.toString())); - - // query params - List queryParams = new ArrayList(); - // header params - Map headerParams = new HashMap(); - // form params - Map formParams = new HashMap(); - - - - - - String[] contentTypes = { - - }; - String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - - if (contentType.startsWith("multipart/form-data")) { - // file uploading - MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create(); - - - HttpEntity httpEntity = localVarBuilder.build(); - postBody = httpEntity; - } else { - // normal form params - - } - - String[] authNames = new String[] { }; - - try { - String localVarResponse = apiInvoker.invokeAPI (basePath, path, "DELETE", queryParams, postBody, headerParams, formParams, contentType, authNames); - if(localVarResponse != null){ - return ; - } else { - return ; - } - } catch (ApiException ex) { - throw ex; - } catch (InterruptedException ex) { - throw ex; - } catch (ExecutionException ex) { - if(ex.getCause() instanceof VolleyError) { - throw new ApiException(((VolleyError) ex.getCause()).networkResponse.statusCode, ((VolleyError) ex.getCause()).getMessage()); - } - throw ex; - } catch (TimeoutException ex) { - throw ex; - } - } - - /** - * Delete purchase order by ID - * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors - * @param orderId ID of the order that needs to be deleted - */ - public void deleteOrder (String orderId, final Response.Listener responseListener, final Response.ErrorListener errorListener) { - Object postBody = null; - - - // verify the required parameter 'orderId' is set - if (orderId == null) { - VolleyError error = new VolleyError("Missing the required parameter 'orderId' when calling deleteOrder", - new ApiException(400, "Missing the required parameter 'orderId' when calling deleteOrder")); - } - - - // create path and map variables - String path = "/store/order/{orderId}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "orderId" + "\\}", apiInvoker.escapeString(orderId.toString())); - - // query params - List queryParams = new ArrayList(); - // header params - Map headerParams = new HashMap(); - // form params - Map formParams = new HashMap(); - - - - - - String[] contentTypes = { - - }; - String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - - if (contentType.startsWith("multipart/form-data")) { - // file uploading - MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create(); - - - HttpEntity httpEntity = localVarBuilder.build(); - postBody = httpEntity; - } else { - // normal form params - - } - - String[] authNames = new String[] { }; - - try { - apiInvoker.invokeAPI(basePath, path, "DELETE", queryParams, postBody, headerParams, formParams, contentType, authNames, - new Response.Listener() { - @Override - public void onResponse(String localVarResponse) { - - - responseListener.onResponse(localVarResponse); - - - } - }, new Response.ErrorListener() { - @Override - public void onErrorResponse(VolleyError error) { - errorListener.onErrorResponse(error); - } - }); - } catch (ApiException ex) { - errorListener.onErrorResponse(new VolleyError(ex)); - } - } - } 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 9e7ce84b6f7..0938e600dd2 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 @@ -432,6 +432,293 @@ public class UserApi { } } + /** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted + * @return void + */ + public void deleteUser (String username) throws TimeoutException, ExecutionException, InterruptedException, ApiException { + Object postBody = null; + + // verify the required parameter 'username' is set + if (username == null) { + VolleyError error = new VolleyError("Missing the required parameter 'username' when calling deleteUser", + new ApiException(400, "Missing the required parameter 'username' when calling deleteUser")); + } + + + // create path and map variables + String path = "/user/{username}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "username" + "\\}", apiInvoker.escapeString(username.toString())); + + // query params + List queryParams = new ArrayList(); + // header params + Map headerParams = new HashMap(); + // form params + Map formParams = new HashMap(); + + + + + + String[] contentTypes = { + + }; + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; + + if (contentType.startsWith("multipart/form-data")) { + // file uploading + MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create(); + + + HttpEntity httpEntity = localVarBuilder.build(); + postBody = httpEntity; + } else { + // normal form params + + } + + String[] authNames = new String[] { "test_http_basic" }; + + try { + String localVarResponse = apiInvoker.invokeAPI (basePath, path, "DELETE", queryParams, postBody, headerParams, formParams, contentType, authNames); + if(localVarResponse != null){ + return ; + } else { + return ; + } + } catch (ApiException ex) { + throw ex; + } catch (InterruptedException ex) { + throw ex; + } catch (ExecutionException ex) { + if(ex.getCause() instanceof VolleyError) { + throw new ApiException(((VolleyError) ex.getCause()).networkResponse.statusCode, ((VolleyError) ex.getCause()).getMessage()); + } + throw ex; + } catch (TimeoutException ex) { + throw ex; + } + } + + /** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted + */ + public void deleteUser (String username, final Response.Listener responseListener, final Response.ErrorListener errorListener) { + Object postBody = null; + + + // verify the required parameter 'username' is set + if (username == null) { + VolleyError error = new VolleyError("Missing the required parameter 'username' when calling deleteUser", + new ApiException(400, "Missing the required parameter 'username' when calling deleteUser")); + } + + + // create path and map variables + String path = "/user/{username}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "username" + "\\}", apiInvoker.escapeString(username.toString())); + + // query params + List queryParams = new ArrayList(); + // header params + Map headerParams = new HashMap(); + // form params + Map formParams = new HashMap(); + + + + + + String[] contentTypes = { + + }; + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; + + if (contentType.startsWith("multipart/form-data")) { + // file uploading + MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create(); + + + HttpEntity httpEntity = localVarBuilder.build(); + postBody = httpEntity; + } else { + // normal form params + + } + + String[] authNames = new String[] { "test_http_basic" }; + + try { + apiInvoker.invokeAPI(basePath, path, "DELETE", queryParams, postBody, headerParams, formParams, contentType, authNames, + new Response.Listener() { + @Override + public void onResponse(String localVarResponse) { + + + responseListener.onResponse(localVarResponse); + + + } + }, new Response.ErrorListener() { + @Override + public void onErrorResponse(VolleyError error) { + errorListener.onErrorResponse(error); + } + }); + } catch (ApiException ex) { + errorListener.onErrorResponse(new VolleyError(ex)); + } + } + + /** + * Get user by user name + * + * @param username The name that needs to be fetched. Use user1 for testing. + * @return User + */ + public User getUserByName (String username) throws TimeoutException, ExecutionException, InterruptedException, ApiException { + Object postBody = null; + + // verify the required parameter 'username' is set + if (username == null) { + VolleyError error = new VolleyError("Missing the required parameter 'username' when calling getUserByName", + new ApiException(400, "Missing the required parameter 'username' when calling getUserByName")); + } + + + // create path and map variables + String path = "/user/{username}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "username" + "\\}", apiInvoker.escapeString(username.toString())); + + // query params + List queryParams = new ArrayList(); + // header params + Map headerParams = new HashMap(); + // form params + Map formParams = new HashMap(); + + + + + + String[] contentTypes = { + + }; + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; + + if (contentType.startsWith("multipart/form-data")) { + // file uploading + MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create(); + + + HttpEntity httpEntity = localVarBuilder.build(); + postBody = httpEntity; + } else { + // normal form params + + } + + String[] authNames = new String[] { }; + + try { + String localVarResponse = apiInvoker.invokeAPI (basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType, authNames); + if(localVarResponse != null){ + return (User) ApiInvoker.deserialize(localVarResponse, "", User.class); + } else { + return null; + } + } catch (ApiException ex) { + throw ex; + } catch (InterruptedException ex) { + throw ex; + } catch (ExecutionException ex) { + if(ex.getCause() instanceof VolleyError) { + throw new ApiException(((VolleyError) ex.getCause()).networkResponse.statusCode, ((VolleyError) ex.getCause()).getMessage()); + } + throw ex; + } catch (TimeoutException ex) { + throw ex; + } + } + + /** + * Get user by user name + * + * @param username The name that needs to be fetched. Use user1 for testing. + */ + public void getUserByName (String username, final Response.Listener responseListener, final Response.ErrorListener errorListener) { + Object postBody = null; + + + // verify the required parameter 'username' is set + if (username == null) { + VolleyError error = new VolleyError("Missing the required parameter 'username' when calling getUserByName", + new ApiException(400, "Missing the required parameter 'username' when calling getUserByName")); + } + + + // create path and map variables + String path = "/user/{username}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "username" + "\\}", apiInvoker.escapeString(username.toString())); + + // query params + List queryParams = new ArrayList(); + // header params + Map headerParams = new HashMap(); + // form params + Map formParams = new HashMap(); + + + + + + String[] contentTypes = { + + }; + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; + + if (contentType.startsWith("multipart/form-data")) { + // file uploading + MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create(); + + + HttpEntity httpEntity = localVarBuilder.build(); + postBody = httpEntity; + } else { + // normal form params + + } + + String[] authNames = new String[] { }; + + try { + apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType, authNames, + new Response.Listener() { + @Override + public void onResponse(String localVarResponse) { + + try { + responseListener.onResponse((User) ApiInvoker.deserialize(localVarResponse, "", User.class)); + + + + } catch (ApiException exception) { + errorListener.onErrorResponse(new VolleyError(exception)); + } + + } + }, new Response.ErrorListener() { + @Override + public void onErrorResponse(VolleyError error) { + errorListener.onErrorResponse(error); + } + }); + } catch (ApiException ex) { + errorListener.onErrorResponse(new VolleyError(ex)); + } + } + /** * Logs user into the system * @@ -703,152 +990,6 @@ public class UserApi { } } - /** - * Get user by user name - * - * @param username The name that needs to be fetched. Use user1 for testing. - * @return User - */ - public User getUserByName (String username) throws TimeoutException, ExecutionException, InterruptedException, ApiException { - Object postBody = null; - - // verify the required parameter 'username' is set - if (username == null) { - VolleyError error = new VolleyError("Missing the required parameter 'username' when calling getUserByName", - new ApiException(400, "Missing the required parameter 'username' when calling getUserByName")); - } - - - // create path and map variables - String path = "/user/{username}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "username" + "\\}", apiInvoker.escapeString(username.toString())); - - // query params - List queryParams = new ArrayList(); - // header params - Map headerParams = new HashMap(); - // form params - Map formParams = new HashMap(); - - - - - - String[] contentTypes = { - - }; - String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - - if (contentType.startsWith("multipart/form-data")) { - // file uploading - MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create(); - - - HttpEntity httpEntity = localVarBuilder.build(); - postBody = httpEntity; - } else { - // normal form params - - } - - String[] authNames = new String[] { }; - - try { - String localVarResponse = apiInvoker.invokeAPI (basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType, authNames); - if(localVarResponse != null){ - return (User) ApiInvoker.deserialize(localVarResponse, "", User.class); - } else { - return null; - } - } catch (ApiException ex) { - throw ex; - } catch (InterruptedException ex) { - throw ex; - } catch (ExecutionException ex) { - if(ex.getCause() instanceof VolleyError) { - throw new ApiException(((VolleyError) ex.getCause()).networkResponse.statusCode, ((VolleyError) ex.getCause()).getMessage()); - } - throw ex; - } catch (TimeoutException ex) { - throw ex; - } - } - - /** - * Get user by user name - * - * @param username The name that needs to be fetched. Use user1 for testing. - */ - public void getUserByName (String username, final Response.Listener responseListener, final Response.ErrorListener errorListener) { - Object postBody = null; - - - // verify the required parameter 'username' is set - if (username == null) { - VolleyError error = new VolleyError("Missing the required parameter 'username' when calling getUserByName", - new ApiException(400, "Missing the required parameter 'username' when calling getUserByName")); - } - - - // create path and map variables - String path = "/user/{username}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "username" + "\\}", apiInvoker.escapeString(username.toString())); - - // query params - List queryParams = new ArrayList(); - // header params - Map headerParams = new HashMap(); - // form params - Map formParams = new HashMap(); - - - - - - String[] contentTypes = { - - }; - String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - - if (contentType.startsWith("multipart/form-data")) { - // file uploading - MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create(); - - - HttpEntity httpEntity = localVarBuilder.build(); - postBody = httpEntity; - } else { - // normal form params - - } - - String[] authNames = new String[] { }; - - try { - apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType, authNames, - new Response.Listener() { - @Override - public void onResponse(String localVarResponse) { - - try { - responseListener.onResponse((User) ApiInvoker.deserialize(localVarResponse, "", User.class)); - - - - } catch (ApiException exception) { - errorListener.onErrorResponse(new VolleyError(exception)); - } - - } - }, new Response.ErrorListener() { - @Override - public void onErrorResponse(VolleyError error) { - errorListener.onErrorResponse(error); - } - }); - } catch (ApiException ex) { - errorListener.onErrorResponse(new VolleyError(ex)); - } - } - /** * Updated user * This can only be done by the logged in user. @@ -991,145 +1132,4 @@ public class UserApi { } } - /** - * Delete user - * This can only be done by the logged in user. - * @param username The name that needs to be deleted - * @return void - */ - public void deleteUser (String username) throws TimeoutException, ExecutionException, InterruptedException, ApiException { - Object postBody = null; - - // verify the required parameter 'username' is set - if (username == null) { - VolleyError error = new VolleyError("Missing the required parameter 'username' when calling deleteUser", - new ApiException(400, "Missing the required parameter 'username' when calling deleteUser")); - } - - - // create path and map variables - String path = "/user/{username}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "username" + "\\}", apiInvoker.escapeString(username.toString())); - - // query params - List queryParams = new ArrayList(); - // header params - Map headerParams = new HashMap(); - // form params - Map formParams = new HashMap(); - - - - - - String[] contentTypes = { - - }; - String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - - if (contentType.startsWith("multipart/form-data")) { - // file uploading - MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create(); - - - HttpEntity httpEntity = localVarBuilder.build(); - postBody = httpEntity; - } else { - // normal form params - - } - - String[] authNames = new String[] { }; - - try { - String localVarResponse = apiInvoker.invokeAPI (basePath, path, "DELETE", queryParams, postBody, headerParams, formParams, contentType, authNames); - if(localVarResponse != null){ - return ; - } else { - return ; - } - } catch (ApiException ex) { - throw ex; - } catch (InterruptedException ex) { - throw ex; - } catch (ExecutionException ex) { - if(ex.getCause() instanceof VolleyError) { - throw new ApiException(((VolleyError) ex.getCause()).networkResponse.statusCode, ((VolleyError) ex.getCause()).getMessage()); - } - throw ex; - } catch (TimeoutException ex) { - throw ex; - } - } - - /** - * Delete user - * This can only be done by the logged in user. - * @param username The name that needs to be deleted - */ - public void deleteUser (String username, final Response.Listener responseListener, final Response.ErrorListener errorListener) { - Object postBody = null; - - - // verify the required parameter 'username' is set - if (username == null) { - VolleyError error = new VolleyError("Missing the required parameter 'username' when calling deleteUser", - new ApiException(400, "Missing the required parameter 'username' when calling deleteUser")); - } - - - // create path and map variables - String path = "/user/{username}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "username" + "\\}", apiInvoker.escapeString(username.toString())); - - // query params - List queryParams = new ArrayList(); - // header params - Map headerParams = new HashMap(); - // form params - Map formParams = new HashMap(); - - - - - - String[] contentTypes = { - - }; - String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - - if (contentType.startsWith("multipart/form-data")) { - // file uploading - MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create(); - - - HttpEntity httpEntity = localVarBuilder.build(); - postBody = httpEntity; - } else { - // normal form params - - } - - String[] authNames = new String[] { }; - - try { - apiInvoker.invokeAPI(basePath, path, "DELETE", queryParams, postBody, headerParams, formParams, contentType, authNames, - new Response.Listener() { - @Override - public void onResponse(String localVarResponse) { - - - responseListener.onResponse(localVarResponse); - - - } - }, new Response.ErrorListener() { - @Override - public void onErrorResponse(VolleyError error) { - errorListener.onErrorResponse(error); - } - }); - } catch (ApiException ex) { - errorListener.onErrorResponse(new VolleyError(ex)); - } - } - } diff --git a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/InlineResponse200.java b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/InlineResponse200.java new file mode 100644 index 00000000000..c4fd8ce357d --- /dev/null +++ b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/InlineResponse200.java @@ -0,0 +1,112 @@ +package io.swagger.client.model; + +import io.swagger.client.model.Tag; +import java.util.*; + +import io.swagger.annotations.*; +import com.google.gson.annotations.SerializedName; + + +@ApiModel(description = "") +public class InlineResponse200 { + + @SerializedName("tags") + private List tags = null; + @SerializedName("id") + private Long id = null; + @SerializedName("category") + private Object category = null; + public enum StatusEnum { + available, pending, sold, + }; + @SerializedName("status") + private StatusEnum status = null; + @SerializedName("name") + private String name = null; + @SerializedName("photoUrls") + private List photoUrls = null; + + + /** + **/ + @ApiModelProperty(value = "") + public List getTags() { + return tags; + } + public void setTags(List tags) { + this.tags = tags; + } + + + /** + **/ + @ApiModelProperty(required = true, value = "") + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + + /** + **/ + @ApiModelProperty(value = "") + public Object getCategory() { + return category; + } + public void setCategory(Object category) { + this.category = category; + } + + + /** + * pet status in the store + **/ + @ApiModelProperty(value = "pet status in the store") + public StatusEnum getStatus() { + return status; + } + public void setStatus(StatusEnum status) { + this.status = status; + } + + + /** + **/ + @ApiModelProperty(value = "") + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + + + /** + **/ + @ApiModelProperty(value = "") + public List getPhotoUrls() { + return photoUrls; + } + public void setPhotoUrls(List photoUrls) { + this.photoUrls = photoUrls; + } + + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class InlineResponse200 {\n"); + + sb.append(" tags: ").append(tags).append("\n"); + sb.append(" id: ").append(id).append("\n"); + sb.append(" category: ").append(category).append("\n"); + sb.append(" status: ").append(status).append("\n"); + sb.append(" name: ").append(name).append("\n"); + sb.append(" photoUrls: ").append(photoUrls).append("\n"); + sb.append("}\n"); + return sb.toString(); + } +} diff --git a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/Model200Response.java b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/Model200Response.java new file mode 100644 index 00000000000..4a6e58b2a5e --- /dev/null +++ b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/Model200Response.java @@ -0,0 +1,36 @@ +package io.swagger.client.model; + + +import io.swagger.annotations.*; +import com.google.gson.annotations.SerializedName; + + +@ApiModel(description = "") +public class Model200Response { + + @SerializedName("name") + private Integer name = null; + + + /** + **/ + @ApiModelProperty(value = "") + public Integer getName() { + return name; + } + public void setName(Integer name) { + this.name = name; + } + + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Model200Response {\n"); + + sb.append(" name: ").append(name).append("\n"); + sb.append("}\n"); + return sb.toString(); + } +} diff --git a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/ModelReturn.java b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/ModelReturn.java new file mode 100644 index 00000000000..24763f3acb4 --- /dev/null +++ b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/ModelReturn.java @@ -0,0 +1,36 @@ +package io.swagger.client.model; + + +import io.swagger.annotations.*; +import com.google.gson.annotations.SerializedName; + + +@ApiModel(description = "") +public class ModelReturn { + + @SerializedName("return") + private Integer _return = null; + + + /** + **/ + @ApiModelProperty(value = "") + public Integer getReturn() { + return _return; + } + public void setReturn(Integer _return) { + this._return = _return; + } + + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ModelReturn {\n"); + + sb.append(" _return: ").append(_return).append("\n"); + sb.append("}\n"); + return sb.toString(); + } +} diff --git a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/Name.java b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/Name.java new file mode 100644 index 00000000000..9763aca7b34 --- /dev/null +++ b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/Name.java @@ -0,0 +1,50 @@ +package io.swagger.client.model; + + +import io.swagger.annotations.*; +import com.google.gson.annotations.SerializedName; + + +@ApiModel(description = "") +public class Name { + + @SerializedName("name") + private Integer name = null; + @SerializedName("snake_case") + private Integer snakeCase = null; + + + /** + **/ + @ApiModelProperty(value = "") + public Integer getName() { + return name; + } + public void setName(Integer name) { + this.name = name; + } + + + /** + **/ + @ApiModelProperty(value = "") + public Integer getSnakeCase() { + return snakeCase; + } + public void setSnakeCase(Integer snakeCase) { + this.snakeCase = snakeCase; + } + + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Name {\n"); + + sb.append(" name: ").append(name).append("\n"); + sb.append(" snakeCase: ").append(snakeCase).append("\n"); + sb.append("}\n"); + return sb.toString(); + } +} diff --git a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/SpecialModelName.java b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/SpecialModelName.java new file mode 100644 index 00000000000..d804bdd8765 --- /dev/null +++ b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/model/SpecialModelName.java @@ -0,0 +1,36 @@ +package io.swagger.client.model; + + +import io.swagger.annotations.*; +import com.google.gson.annotations.SerializedName; + + +@ApiModel(description = "") +public class SpecialModelName { + + @SerializedName("$special[property.name]") + private Long specialPropertyName = null; + + + /** + **/ + @ApiModelProperty(value = "") + public Long getSpecialPropertyName() { + return specialPropertyName; + } + public void setSpecialPropertyName(Long specialPropertyName) { + this.specialPropertyName = specialPropertyName; + } + + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class SpecialModelName {\n"); + + sb.append(" specialPropertyName: ").append(specialPropertyName).append("\n"); + sb.append("}\n"); + return sb.toString(); + } +} diff --git a/samples/client/petstore/clojure/.gitignore b/samples/client/petstore/clojure/.gitignore index 055b6ac4772..47fed6c20d9 100644 --- a/samples/client/petstore/clojure/.gitignore +++ b/samples/client/petstore/clojure/.gitignore @@ -1,10 +1,12 @@ -/target -/classes -/checkouts +pom.xml pom.xml.asc -*.jar -*.class -/.lein-* -/.nrepl-port -.hgignore -.hg/ +*jar +/lib/ +/classes/ +/target/ +/checkouts/ +.lein-deps-sum +.lein-repl-history +.lein-plugins/ +.lein-failures +.nrepl-port diff --git a/samples/client/petstore/clojure/git_push.sh b/samples/client/petstore/clojure/git_push.sh new file mode 100644 index 00000000000..1a36388db02 --- /dev/null +++ b/samples/client/petstore/clojure/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="YOUR_GIT_USR_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="YOUR_GIT_REPO_ID" + 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/clojure/src/swagger_petstore/api/pet.clj b/samples/client/petstore/clojure/src/swagger_petstore/api/pet.clj index aaa6e0768e4..a455838c8fc 100644 --- a/samples/client/petstore/clojure/src/swagger_petstore/api/pet.clj +++ b/samples/client/petstore/clojure/src/swagger_petstore/api/pet.clj @@ -2,28 +2,6 @@ (:require [swagger-petstore.core :refer [call-api check-required-params with-collection-format]]) (:import (java.io File))) -(defn update-pet-with-http-info - "Update an existing pet - " - ([] (update-pet-with-http-info nil)) - ([{:keys [body ]}] - (call-api "/pet" :put - {:path-params {} - :header-params {} - :query-params {} - :form-params {} - :body-param body - :content-types ["application/json" "application/xml"] - :accepts ["application/json" "application/xml"] - :auth-names ["petstore_auth"]}))) - -(defn update-pet - "Update an existing pet - " - ([] (update-pet nil)) - ([optional-params] - (:data (update-pet-with-http-info optional-params)))) - (defn add-pet-with-http-info "Add a new pet to the store " @@ -46,6 +24,49 @@ ([optional-params] (:data (add-pet-with-http-info optional-params)))) +(defn add-pet-using-byte-array-with-http-info + "Fake endpoint to test byte array in body parameter for adding a new pet to the store + " + ([] (add-pet-using-byte-array-with-http-info nil)) + ([{:keys [body ]}] + (call-api "/pet?testing_byte_array=true" :post + {:path-params {} + :header-params {} + :query-params {} + :form-params {} + :body-param body + :content-types ["application/json" "application/xml"] + :accepts ["application/json" "application/xml"] + :auth-names ["petstore_auth"]}))) + +(defn add-pet-using-byte-array + "Fake endpoint to test byte array in body parameter for adding a new pet to the store + " + ([] (add-pet-using-byte-array nil)) + ([optional-params] + (:data (add-pet-using-byte-array-with-http-info optional-params)))) + +(defn delete-pet-with-http-info + "Deletes a pet + " + ([pet-id ] (delete-pet-with-http-info pet-id nil)) + ([pet-id {:keys [api-key ]}] + (call-api "/pet/{petId}" :delete + {:path-params {"petId" pet-id } + :header-params {"api_key" api-key } + :query-params {} + :form-params {} + :content-types [] + :accepts ["application/json" "application/xml"] + :auth-names ["petstore_auth"]}))) + +(defn delete-pet + "Deletes a pet + " + ([pet-id ] (delete-pet pet-id nil)) + ([pet-id optional-params] + (:data (delete-pet-with-http-info pet-id optional-params)))) + (defn find-pets-by-status-with-http-info "Finds Pets by status Multiple status values can be provided with comma separated strings" @@ -99,7 +120,7 @@ :form-params {} :content-types [] :accepts ["application/json" "application/xml"] - :auth-names ["petstore_auth" "api_key"]})) + :auth-names ["api_key" "petstore_auth"]})) (defn get-pet-by-id "Find pet by ID @@ -107,6 +128,66 @@ [pet-id ] (:data (get-pet-by-id-with-http-info pet-id))) +(defn get-pet-by-id-in-object-with-http-info + "Fake endpoint to test inline arbitrary object return by 'Find pet by ID' + Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions" + [pet-id ] + (call-api "/pet/{petId}?response=inline_arbitrary_object" :get + {:path-params {"petId" pet-id } + :header-params {} + :query-params {} + :form-params {} + :content-types [] + :accepts ["application/json" "application/xml"] + :auth-names ["api_key" "petstore_auth"]})) + +(defn get-pet-by-id-in-object + "Fake endpoint to test inline arbitrary object return by 'Find pet by ID' + Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions" + [pet-id ] + (:data (get-pet-by-id-in-object-with-http-info pet-id))) + +(defn pet-pet-idtesting-byte-arraytrue-get-with-http-info + "Fake endpoint to test byte array return by 'Find pet by ID' + Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions" + [pet-id ] + (call-api "/pet/{petId}?testing_byte_array=true" :get + {:path-params {"petId" pet-id } + :header-params {} + :query-params {} + :form-params {} + :content-types [] + :accepts ["application/json" "application/xml"] + :auth-names ["api_key" "petstore_auth"]})) + +(defn pet-pet-idtesting-byte-arraytrue-get + "Fake endpoint to test byte array return by 'Find pet by ID' + Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions" + [pet-id ] + (:data (pet-pet-idtesting-byte-arraytrue-get-with-http-info pet-id))) + +(defn update-pet-with-http-info + "Update an existing pet + " + ([] (update-pet-with-http-info nil)) + ([{:keys [body ]}] + (call-api "/pet" :put + {:path-params {} + :header-params {} + :query-params {} + :form-params {} + :body-param body + :content-types ["application/json" "application/xml"] + :accepts ["application/json" "application/xml"] + :auth-names ["petstore_auth"]}))) + +(defn update-pet + "Update an existing pet + " + ([] (update-pet nil)) + ([optional-params] + (:data (update-pet-with-http-info optional-params)))) + (defn update-pet-with-form-with-http-info "Updates a pet in the store with form data " @@ -128,27 +209,6 @@ ([pet-id optional-params] (:data (update-pet-with-form-with-http-info pet-id optional-params)))) -(defn delete-pet-with-http-info - "Deletes a pet - " - ([pet-id ] (delete-pet-with-http-info pet-id nil)) - ([pet-id {:keys [api-key ]}] - (call-api "/pet/{petId}" :delete - {:path-params {"petId" pet-id } - :header-params {"api_key" api-key } - :query-params {} - :form-params {} - :content-types [] - :accepts ["application/json" "application/xml"] - :auth-names ["petstore_auth"]}))) - -(defn delete-pet - "Deletes a pet - " - ([pet-id ] (delete-pet pet-id nil)) - ([pet-id optional-params] - (:data (delete-pet-with-http-info pet-id optional-params)))) - (defn upload-file-with-http-info "uploads an image " @@ -169,44 +229,3 @@ ([pet-id ] (upload-file pet-id nil)) ([pet-id optional-params] (:data (upload-file-with-http-info pet-id optional-params)))) - -(defn pet-pet-idtesting-byte-arraytrue-get-with-http-info - "Fake endpoint to test byte array return by 'Find pet by ID' - Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions" - [pet-id ] - (call-api "/pet/{petId}?testing_byte_array=true" :get - {:path-params {"petId" pet-id } - :header-params {} - :query-params {} - :form-params {} - :content-types [] - :accepts ["application/json" "application/xml"] - :auth-names ["petstore_auth" "api_key"]})) - -(defn pet-pet-idtesting-byte-arraytrue-get - "Fake endpoint to test byte array return by 'Find pet by ID' - Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions" - [pet-id ] - (:data (pet-pet-idtesting-byte-arraytrue-get-with-http-info pet-id))) - -(defn add-pet-using-byte-array-with-http-info - "Fake endpoint to test byte array in body parameter for adding a new pet to the store - " - ([] (add-pet-using-byte-array-with-http-info nil)) - ([{:keys [body ]}] - (call-api "/pet?testing_byte_array=true" :post - {:path-params {} - :header-params {} - :query-params {} - :form-params {} - :body-param body - :content-types ["application/json" "application/xml"] - :accepts ["application/json" "application/xml"] - :auth-names ["petstore_auth"]}))) - -(defn add-pet-using-byte-array - "Fake endpoint to test byte array in body parameter for adding a new pet to the store - " - ([] (add-pet-using-byte-array nil)) - ([optional-params] - (:data (add-pet-using-byte-array-with-http-info optional-params)))) diff --git a/samples/client/petstore/clojure/src/swagger_petstore/api/store.clj b/samples/client/petstore/clojure/src/swagger_petstore/api/store.clj index 1ccf78d4c3b..1e3cc25e4a6 100644 --- a/samples/client/petstore/clojure/src/swagger_petstore/api/store.clj +++ b/samples/client/petstore/clojure/src/swagger_petstore/api/store.clj @@ -2,6 +2,25 @@ (:require [swagger-petstore.core :refer [call-api check-required-params with-collection-format]]) (:import (java.io File))) +(defn delete-order-with-http-info + "Delete purchase order by ID + For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors" + [order-id ] + (call-api "/store/order/{orderId}" :delete + {:path-params {"orderId" order-id } + :header-params {} + :query-params {} + :form-params {} + :content-types [] + :accepts ["application/json" "application/xml"] + :auth-names []})) + +(defn delete-order + "Delete purchase order by ID + For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors" + [order-id ] + (:data (delete-order-with-http-info order-id))) + (defn find-orders-by-status-with-http-info "Finds orders by status A single status value can be provided as a string" @@ -42,6 +61,44 @@ [] (:data (get-inventory-with-http-info))) +(defn get-inventory-in-object-with-http-info + "Fake endpoint to test arbitrary object return by 'Get inventory' + Returns an arbitrary object which is actually a map of status codes to quantities" + [] + (call-api "/store/inventory?response=arbitrary_object" :get + {:path-params {} + :header-params {} + :query-params {} + :form-params {} + :content-types [] + :accepts ["application/json" "application/xml"] + :auth-names ["api_key"]})) + +(defn get-inventory-in-object + "Fake endpoint to test arbitrary object return by 'Get inventory' + Returns an arbitrary object which is actually a map of status codes to quantities" + [] + (:data (get-inventory-in-object-with-http-info))) + +(defn get-order-by-id-with-http-info + "Find purchase order by ID + For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions" + [order-id ] + (call-api "/store/order/{orderId}" :get + {:path-params {"orderId" order-id } + :header-params {} + :query-params {} + :form-params {} + :content-types [] + :accepts ["application/json" "application/xml"] + :auth-names ["test_api_key_header" "test_api_key_query"]})) + +(defn get-order-by-id + "Find purchase order by ID + For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions" + [order-id ] + (:data (get-order-by-id-with-http-info order-id))) + (defn place-order-with-http-info "Place an order for a pet " @@ -63,41 +120,3 @@ ([] (place-order nil)) ([optional-params] (:data (place-order-with-http-info optional-params)))) - -(defn get-order-by-id-with-http-info - "Find purchase order by ID - For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions" - [order-id ] - (call-api "/store/order/{orderId}" :get - {:path-params {"orderId" order-id } - :header-params {} - :query-params {} - :form-params {} - :content-types [] - :accepts ["application/json" "application/xml"] - :auth-names ["test_api_key_query" "test_api_key_header"]})) - -(defn get-order-by-id - "Find purchase order by ID - For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions" - [order-id ] - (:data (get-order-by-id-with-http-info order-id))) - -(defn delete-order-with-http-info - "Delete purchase order by ID - For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors" - [order-id ] - (call-api "/store/order/{orderId}" :delete - {:path-params {"orderId" order-id } - :header-params {} - :query-params {} - :form-params {} - :content-types [] - :accepts ["application/json" "application/xml"] - :auth-names []})) - -(defn delete-order - "Delete purchase order by ID - For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors" - [order-id ] - (:data (delete-order-with-http-info order-id))) diff --git a/samples/client/petstore/clojure/src/swagger_petstore/api/user.clj b/samples/client/petstore/clojure/src/swagger_petstore/api/user.clj index c25d97aa7c4..07b016d641a 100644 --- a/samples/client/petstore/clojure/src/swagger_petstore/api/user.clj +++ b/samples/client/petstore/clojure/src/swagger_petstore/api/user.clj @@ -68,6 +68,44 @@ ([optional-params] (:data (create-users-with-list-input-with-http-info optional-params)))) +(defn delete-user-with-http-info + "Delete user + This can only be done by the logged in user." + [username ] + (call-api "/user/{username}" :delete + {:path-params {"username" username } + :header-params {} + :query-params {} + :form-params {} + :content-types [] + :accepts ["application/json" "application/xml"] + :auth-names []})) + +(defn delete-user + "Delete user + This can only be done by the logged in user." + [username ] + (:data (delete-user-with-http-info username))) + +(defn get-user-by-name-with-http-info + "Get user by user name + " + [username ] + (call-api "/user/{username}" :get + {:path-params {"username" username } + :header-params {} + :query-params {} + :form-params {} + :content-types [] + :accepts ["application/json" "application/xml"] + :auth-names []})) + +(defn get-user-by-name + "Get user by user name + " + [username ] + (:data (get-user-by-name-with-http-info username))) + (defn login-user-with-http-info "Logs user into the system " @@ -108,25 +146,6 @@ [] (:data (logout-user-with-http-info))) -(defn get-user-by-name-with-http-info - "Get user by user name - " - [username ] - (call-api "/user/{username}" :get - {:path-params {"username" username } - :header-params {} - :query-params {} - :form-params {} - :content-types [] - :accepts ["application/json" "application/xml"] - :auth-names []})) - -(defn get-user-by-name - "Get user by user name - " - [username ] - (:data (get-user-by-name-with-http-info username))) - (defn update-user-with-http-info "Updated user This can only be done by the logged in user." @@ -148,22 +167,3 @@ ([username ] (update-user username nil)) ([username optional-params] (:data (update-user-with-http-info username optional-params)))) - -(defn delete-user-with-http-info - "Delete user - This can only be done by the logged in user." - [username ] - (call-api "/user/{username}" :delete - {:path-params {"username" username } - :header-params {} - :query-params {} - :form-params {} - :content-types [] - :accepts ["application/json" "application/xml"] - :auth-names []})) - -(defn delete-user - "Delete user - This can only be done by the logged in user." - [username ] - (:data (delete-user-with-http-info username))) diff --git a/samples/client/petstore/clojure/src/swagger_petstore/core.clj b/samples/client/petstore/clojure/src/swagger_petstore/core.clj index 2d8f596cfc8..f01f3061e0d 100644 --- a/samples/client/petstore/clojure/src/swagger_petstore/core.clj +++ b/samples/client/petstore/clojure/src/swagger_petstore/core.clj @@ -8,12 +8,12 @@ (java.text SimpleDateFormat))) (def auth-definitions - {"petstore_auth" {:type :oauth2} - "test_api_client_id" {:type :api-key :in :header :param-name "x-test_api_client_id"} - "test_api_client_secret" {:type :api-key :in :header :param-name "x-test_api_client_secret"} + {"test_api_key_header" {:type :api-key :in :header :param-name "test_api_key_header"} "api_key" {:type :api-key :in :header :param-name "api_key"} + "test_api_client_secret" {:type :api-key :in :header :param-name "x-test_api_client_secret"} + "test_api_client_id" {:type :api-key :in :header :param-name "x-test_api_client_id"} "test_api_key_query" {:type :api-key :in :query :param-name "test_api_key_query"} - "test_api_key_header" {:type :api-key :in :header :param-name "test_api_key_header"}}) + "petstore_auth" {:type :oauth2}}) (def default-api-context "Default API context." @@ -21,12 +21,12 @@ :date-format "yyyy-MM-dd" :datetime-format "yyyy-MM-dd'T'HH:mm:ss.SSSXXX" :debug false - :auths {"petstore_auth" nil - "test_api_client_id" nil - "test_api_client_secret" nil + :auths {"test_api_key_header" nil "api_key" nil + "test_api_client_secret" nil + "test_api_client_id" nil "test_api_key_query" nil - "test_api_key_header" nil}}) + "petstore_auth" nil}}) (def ^:dynamic *api-context* "Dynamic API context to be applied in API calls." diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient.Test/CategoryTests.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient.Test/CategoryTests.cs index e0216f3fb0f..96e5d946c0b 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient.Test/CategoryTests.cs +++ b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient.Test/CategoryTests.cs @@ -31,7 +31,7 @@ namespace IO.Swagger.Test { instance = new Category(); } - + /// /// Clean up after each test /// @@ -39,7 +39,7 @@ namespace IO.Swagger.Test public void Cleanup() { - } + } /// /// Test an instance of Category @@ -50,25 +50,22 @@ namespace IO.Swagger.Test Assert.IsInstanceOf (instance, "instance is a Category"); } - /// - /// Test the property 'Id' + /// Test the property 'Id' /// [Test] public void IdTest() { - // TODO: unit test for the property 'Id' + // TODO: unit test for the property 'Id' } - /// - /// Test the property 'Name' + /// Test the property 'Name' /// [Test] public void NameTest() { - // TODO: unit test for the property 'Name' + // TODO: unit test for the property 'Name' } - } diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient.Test/InlineResponse200Tests.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient.Test/InlineResponse200Tests.cs new file mode 100644 index 00000000000..4e03a3ef4f9 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient.Test/InlineResponse200Tests.cs @@ -0,0 +1,104 @@ +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 InlineResponse200 + /// + /// + /// This file is automatically generated by Swagger Codegen. + /// Please update the test case below to test the model. + /// + [TestFixture] + public class InlineResponse200Tests + { + private InlineResponse200 instance; + + /// + /// Setup before each test + /// + [SetUp] + public void Init() + { + instance = new InlineResponse200(); + } + + /// + /// Clean up after each test + /// + [TearDown] + public void Cleanup() + { + + } + + /// + /// Test an instance of InlineResponse200 + /// + [Test] + public void InlineResponse200InstanceTest() + { + Assert.IsInstanceOf (instance, "instance is a InlineResponse200"); + } + + /// + /// Test the property 'Tags' + /// + [Test] + public void TagsTest() + { + // TODO: unit test for the property 'Tags' + } + /// + /// 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 'Status' + /// + [Test] + public void StatusTest() + { + // TODO: unit test for the property 'Status' + } + /// + /// 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' + } + + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient.Test/Model200ResponseTests.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient.Test/Model200ResponseTests.cs new file mode 100644 index 00000000000..eb55902a998 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient.Test/Model200ResponseTests.cs @@ -0,0 +1,64 @@ +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 + { + private Model200Response instance; + + /// + /// Setup before each test + /// + [SetUp] + public void Init() + { + instance = new Model200Response(); + } + + /// + /// Clean up after each test + /// + [TearDown] + public void Cleanup() + { + + } + + /// + /// Test an instance of Model200Response + /// + [Test] + public void Model200ResponseInstanceTest() + { + Assert.IsInstanceOf (instance, "instance is a Model200Response"); + } + + /// + /// Test the property 'Name' + /// + [Test] + public void NameTest() + { + // TODO: unit test for the property 'Name' + } + + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient.Test/ModelReturnTests.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient.Test/ModelReturnTests.cs new file mode 100644 index 00000000000..1c620b73241 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient.Test/ModelReturnTests.cs @@ -0,0 +1,64 @@ +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 + { + private ModelReturn instance; + + /// + /// Setup before each test + /// + [SetUp] + public void Init() + { + instance = new ModelReturn(); + } + + /// + /// Clean up after each test + /// + [TearDown] + public void Cleanup() + { + + } + + /// + /// Test an instance of ModelReturn + /// + [Test] + public void ModelReturnInstanceTest() + { + Assert.IsInstanceOf (instance, "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/SwaggerClientTest/Lib/SwaggerClient.Test/NameTests.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient.Test/NameTests.cs new file mode 100644 index 00000000000..896cb8f12bf --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient.Test/NameTests.cs @@ -0,0 +1,72 @@ +using NUnit.Framework; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using IO.Swagger.Api; +using IO.Swagger.Model; +using IO.Swagger.Client; +using System.Reflection; + +namespace IO.Swagger.Test +{ + /// + /// Class for testing Name + /// + /// + /// This file is automatically generated by Swagger Codegen. + /// Please update the test case below to test the model. + /// + [TestFixture] + public class NameTests + { + private Name instance; + + /// + /// Setup before each test + /// + [SetUp] + public void Init() + { + instance = new Name(); + } + + /// + /// Clean up after each test + /// + [TearDown] + public void Cleanup() + { + + } + + /// + /// Test an instance of Name + /// + [Test] + public void NameInstanceTest() + { + Assert.IsInstanceOf (instance, "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' + } + + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient.Test/OrderTests.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient.Test/OrderTests.cs index b9540112766..9363c7409e4 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient.Test/OrderTests.cs +++ b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient.Test/OrderTests.cs @@ -31,7 +31,7 @@ namespace IO.Swagger.Test { instance = new Order(); } - + /// /// Clean up after each test /// @@ -39,7 +39,7 @@ namespace IO.Swagger.Test public void Cleanup() { - } + } /// /// Test an instance of Order @@ -50,61 +50,54 @@ namespace IO.Swagger.Test Assert.IsInstanceOf (instance, "instance is a Order"); } - /// - /// Test the property 'Id' + /// Test the property 'Id' /// [Test] public void IdTest() { - // TODO: unit test for the property 'Id' + // TODO: unit test for the property 'Id' } - /// - /// Test the property 'PetId' + /// Test the property 'PetId' /// [Test] public void PetIdTest() { - // TODO: unit test for the property 'PetId' + // TODO: unit test for the property 'PetId' } - /// - /// Test the property 'Quantity' + /// Test the property 'Quantity' /// [Test] public void QuantityTest() { - // TODO: unit test for the property 'Quantity' + // TODO: unit test for the property 'Quantity' } - /// - /// Test the property 'ShipDate' + /// Test the property 'ShipDate' /// [Test] public void ShipDateTest() { - // TODO: unit test for the property 'ShipDate' + // TODO: unit test for the property 'ShipDate' } - /// - /// Test the property 'Status' + /// Test the property 'Status' /// [Test] public void StatusTest() { - // TODO: unit test for the property 'Status' + // TODO: unit test for the property 'Status' } - /// - /// Test the property 'Complete' + /// Test the property 'Complete' /// [Test] public void CompleteTest() { - // TODO: unit test for the property 'Complete' + // TODO: unit test for the property 'Complete' } - } diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient.Test/PetApiTests.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient.Test/PetApiTests.cs index 77100e04b61..67d8241ee91 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient.Test/PetApiTests.cs +++ b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient.Test/PetApiTests.cs @@ -53,19 +53,6 @@ namespace IO.Swagger.Test } - /// - /// Test UpdatePet - /// - [Test] - public void UpdatePetTest() - { - // TODO: add unit test for the method 'UpdatePet' - Pet body = null; // TODO: replace null with proper value - - instance.UpdatePet(body); - - } - /// /// Test AddPet /// @@ -74,118 +61,8 @@ namespace IO.Swagger.Test { // TODO: add unit test for the method 'AddPet' Pet body = null; // TODO: replace null with proper value - instance.AddPet(body); - - } - - /// - /// Test FindPetsByStatus - /// - [Test] - public void FindPetsByStatusTest() - { - // TODO: add unit test for the method 'FindPetsByStatus' - List status = null; // TODO: replace null with proper value - var response = instance.FindPetsByStatus(status); - Assert.IsInstanceOf> (response, "response is List"); - } - - /// - /// Test FindPetsByTags - /// - [Test] - public void FindPetsByTagsTest() - { - // TODO: add unit test for the method 'FindPetsByTags' - List tags = null; // TODO: replace null with proper value - - var response = instance.FindPetsByTags(tags); - Assert.IsInstanceOf> (response, "response is List"); - } - - /// - /// Test GetPetById - /// - [Test] - public void GetPetByIdTest() - { - // TODO: add unit test for the method 'GetPetById' - long? petId = null; // TODO: replace null with proper value - - var response = instance.GetPetById(petId); - Assert.IsInstanceOf (response, "response is Pet"); - } - - /// - /// Test UpdatePetWithForm - /// - [Test] - public void UpdatePetWithFormTest() - { - // TODO: add unit test for the method 'UpdatePetWithForm' - string petId = null; // TODO: replace null with proper value - string name = null; // TODO: replace null with proper value - string status = null; // TODO: replace null with proper value - - instance.UpdatePetWithForm(petId, name, status); - - } - - /// - /// Test DeletePet - /// - [Test] - public void DeletePetTest() - { - // TODO: add unit test for the method 'DeletePet' - long? petId = null; // TODO: replace null with proper value - string apiKey = null; // TODO: replace null with proper value - - instance.DeletePet(petId, apiKey); - - } - - /// - /// Test UploadFile - /// - [Test] - public void UploadFileTest() - { - // TODO: add unit test for the method 'UploadFile' - long? petId = null; // TODO: replace null with proper value - string additionalMetadata = null; // TODO: replace null with proper value - Stream file = null; // TODO: replace null with proper value - - instance.UploadFile(petId, additionalMetadata, file); - - } - - /// - /// Test GetPetByIdInObject - /// - [Test] - public void GetPetByIdInObjectTest() - { - // TODO: add unit test for the method 'GetPetByIdInObject' - long? petId = null; // TODO: replace null with proper value - - var response = instance.GetPetByIdInObject(petId); - Assert.IsInstanceOf (response, "response is InlineResponse200"); - } - - /// - /// Test PetPetIdtestingByteArraytrueGet - /// - [Test] - public void PetPetIdtestingByteArraytrueGetTest() - { - // TODO: add unit test for the method 'PetPetIdtestingByteArraytrueGet' - long? petId = null; // TODO: replace null with proper value - - var response = instance.PetPetIdtestingByteArraytrueGet(petId); - Assert.IsInstanceOf (response, "response is byte[]"); } /// @@ -196,9 +73,121 @@ namespace IO.Swagger.Test { // TODO: add unit test for the method 'AddPetUsingByteArray' byte[] body = null; // TODO: replace null with proper value - instance.AddPetUsingByteArray(body); - + + } + + /// + /// Test DeletePet + /// + [Test] + public void DeletePetTest() + { + // TODO: add unit test for the method 'DeletePet' + long? petId = null; // TODO: replace null with proper value +string apiKey = null; // TODO: replace null with proper value + instance.DeletePet(petId, apiKey); + + } + + /// + /// Test FindPetsByStatus + /// + [Test] + public void FindPetsByStatusTest() + { + // TODO: add unit test for the method 'FindPetsByStatus' + List status = null; // TODO: replace null with proper value + var response = instance.FindPetsByStatus(status); + Assert.IsInstanceOf> (response, "response is List"); + } + + /// + /// Test FindPetsByTags + /// + [Test] + public void FindPetsByTagsTest() + { + // TODO: add unit test for the method 'FindPetsByTags' + List tags = null; // TODO: replace null with proper value + var response = instance.FindPetsByTags(tags); + Assert.IsInstanceOf> (response, "response is List"); + } + + /// + /// Test GetPetById + /// + [Test] + public void GetPetByIdTest() + { + // TODO: add unit test for the method 'GetPetById' + long? petId = null; // TODO: replace null with proper value + var response = instance.GetPetById(petId); + Assert.IsInstanceOf (response, "response is Pet"); + } + + /// + /// Test GetPetByIdInObject + /// + [Test] + public void GetPetByIdInObjectTest() + { + // TODO: add unit test for the method 'GetPetByIdInObject' + long? petId = null; // TODO: replace null with proper value + var response = instance.GetPetByIdInObject(petId); + Assert.IsInstanceOf (response, "response is InlineResponse200"); + } + + /// + /// Test PetPetIdtestingByteArraytrueGet + /// + [Test] + public void PetPetIdtestingByteArraytrueGetTest() + { + // TODO: add unit test for the method 'PetPetIdtestingByteArraytrueGet' + long? petId = null; // TODO: replace null with proper value + var response = instance.PetPetIdtestingByteArraytrueGet(petId); + Assert.IsInstanceOf (response, "response is byte[]"); + } + + /// + /// Test UpdatePet + /// + [Test] + public void UpdatePetTest() + { + // TODO: add unit test for the method 'UpdatePet' + Pet body = null; // TODO: replace null with proper value + instance.UpdatePet(body); + + } + + /// + /// Test UpdatePetWithForm + /// + [Test] + public void UpdatePetWithFormTest() + { + // TODO: add unit test for the method 'UpdatePetWithForm' + string petId = null; // TODO: replace null with proper value +string name = null; // TODO: replace null with proper value +string status = null; // TODO: replace null with proper value + instance.UpdatePetWithForm(petId, name, status); + + } + + /// + /// Test UploadFile + /// + [Test] + public void UploadFileTest() + { + // TODO: add unit test for the method 'UploadFile' + long? petId = null; // TODO: replace null with proper value +string additionalMetadata = null; // TODO: replace null with proper value +Stream file = null; // TODO: replace null with proper value + instance.UploadFile(petId, additionalMetadata, file); + } } diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient.Test/PetTests.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient.Test/PetTests.cs index ebbf7476264..d016d3500a4 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient.Test/PetTests.cs +++ b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient.Test/PetTests.cs @@ -31,7 +31,7 @@ namespace IO.Swagger.Test { instance = new Pet(); } - + /// /// Clean up after each test /// @@ -39,7 +39,7 @@ namespace IO.Swagger.Test public void Cleanup() { - } + } /// /// Test an instance of Pet @@ -50,61 +50,54 @@ namespace IO.Swagger.Test Assert.IsInstanceOf (instance, "instance is a Pet"); } - /// - /// Test the property 'Id' + /// Test the property 'Id' /// [Test] public void IdTest() { - // TODO: unit test for the property 'Id' + // TODO: unit test for the property 'Id' } - /// - /// Test the property 'Category' + /// Test the property 'Category' /// [Test] public void CategoryTest() { - // TODO: unit test for the property 'Category' + // TODO: unit test for the property 'Category' } - /// - /// Test the property 'Name' + /// Test the property 'Name' /// [Test] public void NameTest() { - // TODO: unit test for the property 'Name' + // TODO: unit test for the property 'Name' } - /// - /// Test the property 'PhotoUrls' + /// Test the property 'PhotoUrls' /// [Test] public void PhotoUrlsTest() { - // TODO: unit test for the property 'PhotoUrls' + // TODO: unit test for the property 'PhotoUrls' } - /// - /// Test the property 'Tags' + /// Test the property 'Tags' /// [Test] public void TagsTest() { - // TODO: unit test for the property 'Tags' + // TODO: unit test for the property 'Tags' } - /// - /// Test the property 'Status' + /// Test the property 'Status' /// [Test] public void StatusTest() { - // TODO: unit test for the property 'Status' + // TODO: unit test for the property 'Status' } - } diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient.Test/SpecialModelNameTests.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient.Test/SpecialModelNameTests.cs new file mode 100644 index 00000000000..21051e71f54 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient.Test/SpecialModelNameTests.cs @@ -0,0 +1,64 @@ +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 + { + private SpecialModelName instance; + + /// + /// Setup before each test + /// + [SetUp] + public void Init() + { + instance = new SpecialModelName(); + } + + /// + /// Clean up after each test + /// + [TearDown] + public void Cleanup() + { + + } + + /// + /// Test an instance of SpecialModelName + /// + [Test] + public void SpecialModelNameInstanceTest() + { + Assert.IsInstanceOf (instance, "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/SwaggerClientTest/Lib/SwaggerClient.Test/StoreApiTests.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient.Test/StoreApiTests.cs index 0b9acfec5e9..1d3e1c53815 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient.Test/StoreApiTests.cs +++ b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient.Test/StoreApiTests.cs @@ -53,6 +53,18 @@ namespace IO.Swagger.Test } + /// + /// Test DeleteOrder + /// + [Test] + public void DeleteOrderTest() + { + // TODO: add unit test for the method 'DeleteOrder' + string orderId = null; // TODO: replace null with proper value + instance.DeleteOrder(orderId); + + } + /// /// Test FindOrdersByStatus /// @@ -61,9 +73,8 @@ namespace IO.Swagger.Test { // TODO: add unit test for the method 'FindOrdersByStatus' string status = null; // TODO: replace null with proper value - var response = instance.FindOrdersByStatus(status); - Assert.IsInstanceOf> (response, "response is List"); + Assert.IsInstanceOf> (response, "response is List"); } /// @@ -73,9 +84,8 @@ namespace IO.Swagger.Test public void GetInventoryTest() { // TODO: add unit test for the method 'GetInventory' - - var response = instance.GetInventory(); - Assert.IsInstanceOf> (response, "response is Dictionary"); + var response = instance.GetInventory(); + Assert.IsInstanceOf> (response, "response is Dictionary"); } /// @@ -85,22 +95,8 @@ namespace IO.Swagger.Test public void GetInventoryInObjectTest() { // TODO: add unit test for the method 'GetInventoryInObject' - - var response = instance.GetInventoryInObject(); - Assert.IsInstanceOf (response, "response is Object"); - } - - /// - /// Test PlaceOrder - /// - [Test] - public void PlaceOrderTest() - { - // TODO: add unit test for the method 'PlaceOrder' - Order body = null; // TODO: replace null with proper value - - var response = instance.PlaceOrder(body); - Assert.IsInstanceOf (response, "response is Order"); + var response = instance.GetInventoryInObject(); + Assert.IsInstanceOf (response, "response is Object"); } /// @@ -111,22 +107,20 @@ namespace IO.Swagger.Test { // TODO: add unit test for the method 'GetOrderById' string orderId = null; // TODO: replace null with proper value - var response = instance.GetOrderById(orderId); - Assert.IsInstanceOf (response, "response is Order"); + Assert.IsInstanceOf (response, "response is Order"); } /// - /// Test DeleteOrder + /// Test PlaceOrder /// [Test] - public void DeleteOrderTest() + public void PlaceOrderTest() { - // TODO: add unit test for the method 'DeleteOrder' - string orderId = null; // TODO: replace null with proper value - - instance.DeleteOrder(orderId); - + // TODO: add unit test for the method 'PlaceOrder' + Order body = null; // TODO: replace null with proper value + var response = instance.PlaceOrder(body); + Assert.IsInstanceOf (response, "response is Order"); } } diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient.Test/TagTests.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient.Test/TagTests.cs index 36ca5b5c0c9..4fff0e4c12d 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient.Test/TagTests.cs +++ b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient.Test/TagTests.cs @@ -31,7 +31,7 @@ namespace IO.Swagger.Test { instance = new Tag(); } - + /// /// Clean up after each test /// @@ -39,7 +39,7 @@ namespace IO.Swagger.Test public void Cleanup() { - } + } /// /// Test an instance of Tag @@ -50,25 +50,22 @@ namespace IO.Swagger.Test Assert.IsInstanceOf (instance, "instance is a Tag"); } - /// - /// Test the property 'Id' + /// Test the property 'Id' /// [Test] public void IdTest() { - // TODO: unit test for the property 'Id' + // TODO: unit test for the property 'Id' } - /// - /// Test the property 'Name' + /// Test the property 'Name' /// [Test] public void NameTest() { - // TODO: unit test for the property 'Name' + // TODO: unit test for the property 'Name' } - } diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient.Test/UserApiTests.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient.Test/UserApiTests.cs index 8764a7773e7..10caebdfe4f 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient.Test/UserApiTests.cs +++ b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient.Test/UserApiTests.cs @@ -61,9 +61,8 @@ namespace IO.Swagger.Test { // TODO: add unit test for the method 'CreateUser' User body = null; // TODO: replace null with proper value - instance.CreateUser(body); - + } /// @@ -74,9 +73,8 @@ namespace IO.Swagger.Test { // TODO: add unit test for the method 'CreateUsersWithArrayInput' List body = null; // TODO: replace null with proper value - instance.CreateUsersWithArrayInput(body); - + } /// @@ -87,62 +85,8 @@ namespace IO.Swagger.Test { // TODO: add unit test for the method 'CreateUsersWithListInput' List body = null; // TODO: replace null with proper value - instance.CreateUsersWithListInput(body); - - } - - /// - /// Test LoginUser - /// - [Test] - public void LoginUserTest() - { - // TODO: add unit test for the method 'LoginUser' - string username = null; // TODO: replace null with proper value - string password = null; // TODO: replace null with proper value - var response = instance.LoginUser(username, password); - Assert.IsInstanceOf (response, "response is string"); - } - - /// - /// Test LogoutUser - /// - [Test] - public void LogoutUserTest() - { - // TODO: add unit test for the method 'LogoutUser' - - instance.LogoutUser(); - - } - - /// - /// Test GetUserByName - /// - [Test] - public void GetUserByNameTest() - { - // TODO: add unit test for the method 'GetUserByName' - string username = null; // TODO: replace null with proper value - - var response = instance.GetUserByName(username); - Assert.IsInstanceOf (response, "response is User"); - } - - /// - /// Test UpdateUser - /// - [Test] - public void UpdateUserTest() - { - // TODO: add unit test for the method 'UpdateUser' - string username = null; // TODO: replace null with proper value - User body = null; // TODO: replace null with proper value - - instance.UpdateUser(username, body); - } /// @@ -153,9 +97,57 @@ namespace IO.Swagger.Test { // TODO: add unit test for the method 'DeleteUser' string username = null; // TODO: replace null with proper value - instance.DeleteUser(username); - + + } + + /// + /// Test GetUserByName + /// + [Test] + public void GetUserByNameTest() + { + // TODO: add unit test for the method 'GetUserByName' + string username = null; // TODO: replace null with proper value + var response = instance.GetUserByName(username); + Assert.IsInstanceOf (response, "response is User"); + } + + /// + /// Test LoginUser + /// + [Test] + public void LoginUserTest() + { + // TODO: add unit test for the method 'LoginUser' + string username = null; // TODO: replace null with proper value +string password = null; // TODO: replace null with proper value + var response = instance.LoginUser(username, password); + Assert.IsInstanceOf (response, "response is string"); + } + + /// + /// Test LogoutUser + /// + [Test] + public void LogoutUserTest() + { + // TODO: add unit test for the method 'LogoutUser' + instance.LogoutUser(); + + } + + /// + /// Test UpdateUser + /// + [Test] + public void UpdateUserTest() + { + // TODO: add unit test for the method 'UpdateUser' + string username = null; // TODO: replace null with proper value +User body = null; // TODO: replace null with proper value + instance.UpdateUser(username, body); + } } diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient.Test/UserTests.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient.Test/UserTests.cs index 645a4a9c69c..38f2667c403 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient.Test/UserTests.cs +++ b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient.Test/UserTests.cs @@ -31,7 +31,7 @@ namespace IO.Swagger.Test { instance = new User(); } - + /// /// Clean up after each test /// @@ -39,7 +39,7 @@ namespace IO.Swagger.Test public void Cleanup() { - } + } /// /// Test an instance of User @@ -50,79 +50,70 @@ namespace IO.Swagger.Test Assert.IsInstanceOf (instance, "instance is a User"); } - /// - /// Test the property 'Id' + /// Test the property 'Id' /// [Test] public void IdTest() { - // TODO: unit test for the property 'Id' + // TODO: unit test for the property 'Id' } - /// - /// Test the property 'Username' + /// Test the property 'Username' /// [Test] public void UsernameTest() { - // TODO: unit test for the property 'Username' + // TODO: unit test for the property 'Username' } - /// - /// Test the property 'FirstName' + /// Test the property 'FirstName' /// [Test] public void FirstNameTest() { - // TODO: unit test for the property 'FirstName' + // TODO: unit test for the property 'FirstName' } - /// - /// Test the property 'LastName' + /// Test the property 'LastName' /// [Test] public void LastNameTest() { - // TODO: unit test for the property 'LastName' + // TODO: unit test for the property 'LastName' } - /// - /// Test the property 'Email' + /// Test the property 'Email' /// [Test] public void EmailTest() { - // TODO: unit test for the property 'Email' + // TODO: unit test for the property 'Email' } - /// - /// Test the property 'Password' + /// Test the property 'Password' /// [Test] public void PasswordTest() { - // TODO: unit test for the property 'Password' + // TODO: unit test for the property 'Password' } - /// - /// Test the property 'Phone' + /// Test the property 'Phone' /// [Test] public void PhoneTest() { - // TODO: unit test for the property 'Phone' + // TODO: unit test for the property 'Phone' } - /// - /// Test the property 'UserStatus' + /// Test the property 'UserStatus' /// [Test] public void UserStatusTest() { - // TODO: unit test for the property 'UserStatus' + // TODO: unit test for the property 'UserStatus' } - } diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/.gitignore b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/.gitignore index 08d9d469ba8..56fef626922 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/.gitignore +++ b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/.gitignore @@ -1,2 +1,185 @@ -vendor/Newtonsoft.Json.8.0.2/ -vendor/RestSharp.105.2.3/ \ No newline at end of file +# Ref: https://gist.github.com/kmorcinek/2710267 +# Download this file using PowerShell v3 under Windows with the following comand +# Invoke-WebRequest https://gist.githubusercontent.com/kmorcinek/2710267/raw/ -OutFile .gitignore + +# User-specific files +*.suo +*.user +*.sln.docstates + +# Build results + +[Dd]ebug/ +[Rr]elease/ +x64/ +build/ +[Bb]in/ +[Oo]bj/ + +# NuGet Packages +*.nupkg +# The packages folder can be ignored because of Package Restore +**/packages/* +# except build/, which is used as an MSBuild target. +!**/packages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/packages/repositories.config + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +*_i.c +*_p.c +*.ilk +*.meta +*.obj +*.pch +*.pdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.log +*.scc + +# OS generated files # +.DS_Store* +ehthumbs.db +Icon? +Thumbs.db + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opensdf +*.sdf +*.cachefile + +# Visual Studio profiler +*.psess +*.vsp +*.vspx + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# NCrunch +*.ncrunch* +.*crunch*.local.xml + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.Publish.xml + +# Windows Azure Build Output +csx +*.build.csdef + +# Windows Store app package directory +AppPackages/ + +# Others +sql/ +*.Cache +ClientBin/ +[Ss]tyle[Cc]op.* +~$* +*~ +*.dbmdl +*.[Pp]ublish.xml +*.pfx +*.publishsettings +modulesbin/ +tempbin/ + +# EPiServer Site file (VPP) +AppData/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file to a newer +# Visual Studio version. Backup files are not needed, because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm + +# vim +*.txt~ +*.swp +*.swo + + # svn + .svn + + # SQL Server files + **/App_Data/*.mdf + **/App_Data/*.ldf + **/App_Data/*.sdf + + + #LightSwitch generated files + GeneratedArtifacts/ + _Pvt_Extensions/ + ModelManifest.xml + + # ========================= + # Windows detritus + # ========================= + + # Windows image file caches + Thumbs.db + ehthumbs.db + + # Folder config file + Desktop.ini + + # Recycle Bin used on file shares + $RECYCLE.BIN/ + + # Mac desktop service store files + .DS_Store + + # SASS Compiler cache + .sass-cache + + # Visual Studio 2014 CTP + **/*.sln.ide diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/compile.bat b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/compile.bat index 0ad14340824..8d07d021131 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/compile.bat +++ b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/compile.bat @@ -1,12 +1,14 @@ -@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 vendor/packages.config -o vendor - -copy vendor/Newtonsoft.Json.8.0.2/lib/net45/Newtonsoft.Json.dll bin/Newtonsoft.Json.dll -copy vendor/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\*.cs /doc:bin/IO.Swagger.xml +@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 vendor/packages.config -o vendor + +if not exist ".\bin" mkdir bin + +copy vendor\Newtonsoft.Json.8.0.2\lib\net45\Newtonsoft.Json.dll bin\Newtonsoft.Json.dll +copy vendor\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\*.cs /doc:bin\IO.Swagger.xml diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/git_push.sh b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/git_push.sh new file mode 100644 index 00000000000..13d463698c5 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/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="YOUR_GIT_USR_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="YOUR_GIT_REPO_ID" + 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/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/PetApi.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/PetApi.cs index 8471bd2141b..12aad1b198e 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/PetApi.cs +++ b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/PetApi.cs @@ -9,36 +9,12 @@ using IO.Swagger.Model; namespace IO.Swagger.Api { - /// /// Represents a collection of functions to interact with the API endpoints /// public interface IPetApi { #region Synchronous Operations - - /// - /// 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 = null); - - /// - /// 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 = null); - /// /// Add a new pet to the store /// @@ -46,10 +22,10 @@ namespace IO.Swagger.Api /// /// /// Thrown when fails to make API call - /// Pet object that needs to be added to the store + /// Pet object that needs to be added to the store (optional) /// void AddPet (Pet body = null); - + /// /// Add a new pet to the store /// @@ -57,10 +33,53 @@ namespace IO.Swagger.Api /// /// /// Thrown when fails to make API call - /// Pet object that needs to be added to the store + /// Pet object that needs to be added to the store (optional) /// ApiResponse of Object(void) ApiResponse AddPetWithHttpInfo (Pet body = null); - + /// + /// Fake endpoint to test byte array in body parameter for adding a new pet to the store + /// + /// + /// + /// + /// Thrown when fails to make API call + /// Pet object in the form of byte array (optional) + /// + void AddPetUsingByteArray (byte[] body = null); + + /// + /// Fake endpoint to test byte array in body parameter for adding a new pet to the store + /// + /// + /// + /// + /// Thrown when fails to make API call + /// Pet object in the form of byte array (optional) + /// ApiResponse of Object(void) + ApiResponse AddPetUsingByteArrayWithHttpInfo (byte[] body = null); + /// + /// 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 /// @@ -68,10 +87,10 @@ namespace IO.Swagger.Api /// 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 query + /// Status values that need to be considered for query (optional, default to available) /// List<Pet> List FindPetsByStatus (List status = null); - + /// /// Finds Pets by status /// @@ -79,10 +98,9 @@ namespace IO.Swagger.Api /// 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 query + /// Status values that need to be considered for query (optional, default to available) /// ApiResponse of List<Pet> ApiResponse> FindPetsByStatusWithHttpInfo (List status = null); - /// /// Finds Pets by tags /// @@ -90,10 +108,10 @@ namespace IO.Swagger.Api /// Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. /// /// Thrown when fails to make API call - /// Tags to filter by + /// Tags to filter by (optional) /// List<Pet> List FindPetsByTags (List tags = null); - + /// /// Finds Pets by tags /// @@ -101,10 +119,9 @@ namespace IO.Swagger.Api /// Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. /// /// Thrown when fails to make API call - /// Tags to filter by + /// Tags to filter by (optional) /// ApiResponse of List<Pet> ApiResponse> FindPetsByTagsWithHttpInfo (List tags = null); - /// /// Find pet by ID /// @@ -115,7 +132,7 @@ namespace IO.Swagger.Api /// ID of pet that needs to be fetched /// Pet Pet GetPetById (long? petId); - + /// /// Find pet by ID /// @@ -126,83 +143,6 @@ namespace IO.Swagger.Api /// ID of pet that needs to be fetched /// ApiResponse of Pet ApiResponse GetPetByIdWithHttpInfo (long? petId); - - /// - /// 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 - /// Updated status of the pet - /// - void UpdatePetWithForm (string 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 - /// Updated status of the pet - /// ApiResponse of Object(void) - ApiResponse UpdatePetWithFormWithHttpInfo (string petId, string name = null, string status = null); - - /// - /// Deletes a pet - /// - /// - /// - /// - /// Thrown when fails to make API call - /// Pet id to delete - /// - /// - void DeletePet (long? petId, string apiKey = null); - - /// - /// Deletes a pet - /// - /// - /// - /// - /// Thrown when fails to make API call - /// Pet id to delete - /// - /// ApiResponse of Object(void) - ApiResponse DeletePetWithHttpInfo (long? petId, string apiKey = null); - - /// - /// uploads an image - /// - /// - /// - /// - /// Thrown when fails to make API call - /// ID of pet to update - /// Additional data to pass to server - /// file to upload - /// - void UploadFile (long? petId, string additionalMetadata = null, Stream file = null); - - /// - /// uploads an image - /// - /// - /// - /// - /// Thrown when fails to make API call - /// ID of pet to update - /// Additional data to pass to server - /// file to upload - /// ApiResponse of Object(void) - ApiResponse UploadFileWithHttpInfo (long? petId, string additionalMetadata = null, Stream file = null); - /// /// Fake endpoint to test inline arbitrary object return by 'Find pet by ID' /// @@ -213,7 +153,7 @@ namespace IO.Swagger.Api /// ID of pet that needs to be fetched /// InlineResponse200 InlineResponse200 GetPetByIdInObject (long? petId); - + /// /// Fake endpoint to test inline arbitrary object return by 'Find pet by ID' /// @@ -224,7 +164,6 @@ namespace IO.Swagger.Api /// ID of pet that needs to be fetched /// ApiResponse of InlineResponse200 ApiResponse GetPetByIdInObjectWithHttpInfo (long? petId); - /// /// Fake endpoint to test byte array return by 'Find pet by ID' /// @@ -235,7 +174,7 @@ namespace IO.Swagger.Api /// ID of pet that needs to be fetched /// byte[] byte[] PetPetIdtestingByteArraytrueGet (long? petId); - + /// /// Fake endpoint to test byte array return by 'Find pet by ID' /// @@ -246,33 +185,6 @@ namespace IO.Swagger.Api /// ID of pet that needs to be fetched /// ApiResponse of byte[] ApiResponse PetPetIdtestingByteArraytrueGetWithHttpInfo (long? petId); - - /// - /// Fake endpoint to test byte array in body parameter for adding a new pet to the store - /// - /// - /// - /// - /// Thrown when fails to make API call - /// Pet object in the form of byte array - /// - void AddPetUsingByteArray (byte[] body = null); - - /// - /// Fake endpoint to test byte array in body parameter for adding a new pet to the store - /// - /// - /// - /// - /// Thrown when fails to make API call - /// Pet object in the form of byte array - /// ApiResponse of Object(void) - ApiResponse AddPetUsingByteArrayWithHttpInfo (byte[] body = null); - - #endregion Synchronous Operations - - #region Asynchronous Operations - /// /// Update an existing pet /// @@ -280,9 +192,9 @@ namespace IO.Swagger.Api /// /// /// 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 = null); + /// Pet object that needs to be added to the store (optional) + /// + void UpdatePet (Pet body = null); /// /// Update an existing pet @@ -291,10 +203,61 @@ namespace IO.Swagger.Api /// /// /// 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 = null); - + /// Pet object that needs to be added to the store (optional) + /// ApiResponse of Object(void) + ApiResponse UpdatePetWithHttpInfo (Pet body = 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) + /// + void UpdatePetWithForm (string 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 (string 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) + /// + void UploadFile (long? petId, string additionalMetadata = null, 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 Object(void) + ApiResponse UploadFileWithHttpInfo (long? petId, string additionalMetadata = null, Stream file = null); + #endregion Synchronous Operations + #region Asynchronous Operations /// /// Add a new pet to the store /// @@ -302,7 +265,7 @@ namespace IO.Swagger.Api /// /// /// Thrown when fails to make API call - /// Pet object that needs to be added to the store + /// Pet object that needs to be added to the store (optional) /// Task of void System.Threading.Tasks.Task AddPetAsync (Pet body = null); @@ -313,10 +276,53 @@ namespace IO.Swagger.Api /// /// /// Thrown when fails to make API call - /// Pet object that needs to be added to the store + /// Pet object that needs to be added to the store (optional) /// Task of ApiResponse System.Threading.Tasks.Task> AddPetAsyncWithHttpInfo (Pet body = null); - + /// + /// Fake endpoint to test byte array in body parameter for adding a new pet to the store + /// + /// + /// + /// + /// Thrown when fails to make API call + /// Pet object in the form of byte array (optional) + /// Task of void + System.Threading.Tasks.Task AddPetUsingByteArrayAsync (byte[] body = null); + + /// + /// Fake endpoint to test byte array in body parameter for adding a new pet to the store + /// + /// + /// + /// + /// Thrown when fails to make API call + /// Pet object in the form of byte array (optional) + /// Task of ApiResponse + System.Threading.Tasks.Task> AddPetUsingByteArrayAsyncWithHttpInfo (byte[] body = null); + /// + /// 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 /// @@ -324,7 +330,7 @@ namespace IO.Swagger.Api /// 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 query + /// Status values that need to be considered for query (optional, default to available) /// Task of List<Pet> System.Threading.Tasks.Task> FindPetsByStatusAsync (List status = null); @@ -335,10 +341,9 @@ namespace IO.Swagger.Api /// 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 query + /// Status values that need to be considered for query (optional, default to available) /// Task of ApiResponse (List<Pet>) System.Threading.Tasks.Task>> FindPetsByStatusAsyncWithHttpInfo (List status = null); - /// /// Finds Pets by tags /// @@ -346,7 +351,7 @@ namespace IO.Swagger.Api /// Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. /// /// Thrown when fails to make API call - /// Tags to filter by + /// Tags to filter by (optional) /// Task of List<Pet> System.Threading.Tasks.Task> FindPetsByTagsAsync (List tags = null); @@ -357,10 +362,9 @@ namespace IO.Swagger.Api /// Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. /// /// Thrown when fails to make API call - /// Tags to filter by + /// Tags to filter by (optional) /// Task of ApiResponse (List<Pet>) System.Threading.Tasks.Task>> FindPetsByTagsAsyncWithHttpInfo (List tags = null); - /// /// Find pet by ID /// @@ -382,83 +386,6 @@ namespace IO.Swagger.Api /// ID of pet that needs to be fetched /// Task of ApiResponse (Pet) System.Threading.Tasks.Task> GetPetByIdAsyncWithHttpInfo (long? petId); - - /// - /// 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 - /// Updated status of the pet - /// Task of void - System.Threading.Tasks.Task UpdatePetWithFormAsync (string 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 - /// Updated status of the pet - /// Task of ApiResponse - System.Threading.Tasks.Task> UpdatePetWithFormAsyncWithHttpInfo (string petId, string name = null, string status = null); - - /// - /// Deletes a pet - /// - /// - /// - /// - /// Thrown when fails to make API call - /// Pet id to delete - /// - /// 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 - /// - /// Task of ApiResponse - System.Threading.Tasks.Task> DeletePetAsyncWithHttpInfo (long? petId, string apiKey = null); - - /// - /// uploads an image - /// - /// - /// - /// - /// Thrown when fails to make API call - /// ID of pet to update - /// Additional data to pass to server - /// file to upload - /// Task of void - System.Threading.Tasks.Task UploadFileAsync (long? petId, string additionalMetadata = null, Stream file = null); - - /// - /// uploads an image - /// - /// - /// - /// - /// Thrown when fails to make API call - /// ID of pet to update - /// Additional data to pass to server - /// file to upload - /// Task of ApiResponse - System.Threading.Tasks.Task> UploadFileAsyncWithHttpInfo (long? petId, string additionalMetadata = null, Stream file = null); - /// /// Fake endpoint to test inline arbitrary object return by 'Find pet by ID' /// @@ -480,7 +407,6 @@ namespace IO.Swagger.Api /// ID of pet that needs to be fetched /// Task of ApiResponse (InlineResponse200) System.Threading.Tasks.Task> GetPetByIdInObjectAsyncWithHttpInfo (long? petId); - /// /// Fake endpoint to test byte array return by 'Find pet by ID' /// @@ -502,33 +428,80 @@ namespace IO.Swagger.Api /// ID of pet that needs to be fetched /// Task of ApiResponse (byte[]) System.Threading.Tasks.Task> PetPetIdtestingByteArraytrueGetAsyncWithHttpInfo (long? petId); - /// - /// Fake endpoint to test byte array in body parameter for adding a new pet to the store + /// Update an existing pet /// /// /// /// /// Thrown when fails to make API call - /// Pet object in the form of byte array + /// Pet object that needs to be added to the store (optional) /// Task of void - System.Threading.Tasks.Task AddPetUsingByteArrayAsync (byte[] body = null); + System.Threading.Tasks.Task UpdatePetAsync (Pet body = null); /// - /// Fake endpoint to test byte array in body parameter for adding a new pet to the store + /// Update an existing pet /// /// /// /// /// Thrown when fails to make API call - /// Pet object in the form of byte array + /// Pet object that needs to be added to the store (optional) /// Task of ApiResponse - System.Threading.Tasks.Task> AddPetUsingByteArrayAsyncWithHttpInfo (byte[] body = null); - + System.Threading.Tasks.Task> UpdatePetAsyncWithHttpInfo (Pet body = 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 + System.Threading.Tasks.Task UpdatePetWithFormAsync (string 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 (string 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 void + System.Threading.Tasks.Task UploadFileAsync (long? petId, string additionalMetadata = null, 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 + System.Threading.Tasks.Task> UploadFileAsyncWithHttpInfo (long? petId, string additionalMetadata = null, Stream file = null); #endregion Asynchronous Operations - } - + /// /// Represents a collection of functions to interact with the API endpoints /// @@ -541,8 +514,14 @@ namespace IO.Swagger.Api public PetApi(String basePath) { this.Configuration = new Configuration(new ApiClient(basePath)); + + // ensure API client has configuration ready + if (Configuration.ApiClient.Configuration == null) + { + this.Configuration.ApiClient.Configuration = this.Configuration; + } } - + /// /// Initializes a new instance of the class /// using Configuration object @@ -552,9 +531,15 @@ namespace IO.Swagger.Api public PetApi(Configuration configuration = null) { if (configuration == null) // use the default one in Configuration - this.Configuration = Configuration.Default; + this.Configuration = Configuration.Default; else this.Configuration = configuration; + + // ensure API client has configuration ready + if (Configuration.ApiClient.Configuration == null) + { + this.Configuration.ApiClient.Configuration = this.Configuration; + } } /// @@ -575,7 +560,7 @@ namespace IO.Swagger.Api { // do nothing } - + /// /// Gets or sets the configuration object /// @@ -603,190 +588,12 @@ namespace IO.Swagger.Api { this.Configuration.AddDefaultHeader(key, value); } - - - /// - /// 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 = null) - { - 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 = null) - { - - - 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/json", "application/xml" - }; - 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.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 (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling UpdatePet: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling UpdatePet: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); - - - 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 = null) - { - 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 = null) - { - - - 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/json", "application/xml" - }; - 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.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 (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling UpdatePet: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling UpdatePet: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); - - - 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 + /// Pet object that needs to be added to the store (optional) /// public void AddPet (Pet body = null) { @@ -797,14 +604,14 @@ namespace IO.Swagger.Api /// Add a new pet to the store /// /// Thrown when fails to make API call - /// Pet object that needs to be added to the store + /// Pet object that needs to be added to the store (optional) /// ApiResponse of Object(void) public ApiResponse AddPetWithHttpInfo (Pet body = null) { - + var localVarPath = "/pet"; - + var localVarPathParams = new Dictionary(); var localVarQueryParams = new Dictionary(); var localVarHeaderParams = new Dictionary(Configuration.DefaultHeader); @@ -829,11 +636,7 @@ namespace IO.Swagger.Api // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); - - - - - if (body.GetType() != typeof(byte[])) + if (body.GetType() != typeof(byte[])) { localVarPostBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter } @@ -849,32 +652,30 @@ namespace IO.Swagger.Api { localVarHeaderParams["Authorization"] = "Bearer " + Configuration.AccessToken; } - - + // make the HTTP request - IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, + IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; - + if (localVarStatusCode >= 400) throw new ApiException (localVarStatusCode, "Error calling AddPet: " + localVarResponse.Content, localVarResponse.Content); else if (localVarStatusCode == 0) throw new ApiException (localVarStatusCode, "Error calling AddPet: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); - + 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 + /// Pet object that needs to be added to the store (optional) /// Task of void public async System.Threading.Tasks.Task AddPetAsync (Pet body = null) { @@ -886,14 +687,14 @@ namespace IO.Swagger.Api /// Add a new pet to the store /// /// Thrown when fails to make API call - /// Pet object that needs to be added to the store + /// Pet object that needs to be added to the store (optional) /// Task of ApiResponse public async System.Threading.Tasks.Task> AddPetAsyncWithHttpInfo (Pet body = null) { - + var localVarPath = "/pet"; - + var localVarPathParams = new Dictionary(); var localVarQueryParams = new Dictionary(); var localVarHeaderParams = new Dictionary(Configuration.DefaultHeader); @@ -918,11 +719,7 @@ namespace IO.Swagger.Api // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); - - - - - if (body.GetType() != typeof(byte[])) + if (body.GetType() != typeof(byte[])) { localVarPostBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter } @@ -931,7 +728,6 @@ namespace IO.Swagger.Api localVarPostBody = body; // byte array } - // authentication (petstore_auth) required // oauth required @@ -939,15 +735,14 @@ namespace IO.Swagger.Api { localVarHeaderParams["Authorization"] = "Bearer " + Configuration.AccessToken; } - // make the HTTP request - IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath, - Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, + IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath, + Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; - + if (localVarStatusCode >= 400) throw new ApiException (localVarStatusCode, "Error calling AddPet: " + localVarResponse.Content, localVarResponse.Content); else if (localVarStatusCode == 0) @@ -958,31 +753,29 @@ namespace IO.Swagger.Api 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 + /// Fake endpoint to test byte array in body parameter for adding a new pet to the store /// /// Thrown when fails to make API call - /// Status values that need to be considered for query - /// List<Pet> - public List FindPetsByStatus (List status = null) + /// Pet object in the form of byte array (optional) + /// + public void AddPetUsingByteArray (byte[] body = null) { - ApiResponse> localVarResponse = FindPetsByStatusWithHttpInfo(status); - return localVarResponse.Data; + AddPetUsingByteArrayWithHttpInfo(body); } /// - /// Finds Pets by status Multiple status values can be provided with comma separated strings + /// Fake endpoint to test byte array in body parameter for adding a new pet to the store /// /// Thrown when fails to make API call - /// Status values that need to be considered for query - /// ApiResponse of List<Pet> - public ApiResponse< List > FindPetsByStatusWithHttpInfo (List status = null) + /// Pet object in the form of byte array (optional) + /// ApiResponse of Object(void) + public ApiResponse AddPetUsingByteArrayWithHttpInfo (byte[] body = null) { - - var localVarPath = "/pet/findByStatus"; - + + var localVarPath = "/pet?testing_byte_array=true"; + var localVarPathParams = new Dictionary(); var localVarQueryParams = new Dictionary(); var localVarHeaderParams = new Dictionary(Configuration.DefaultHeader); @@ -992,7 +785,7 @@ namespace IO.Swagger.Api // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { - + "application/json", "application/xml" }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); @@ -1007,12 +800,14 @@ namespace IO.Swagger.Api // 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 - - - - + if (body.GetType() != typeof(byte[])) + { + localVarPostBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter + } + else + { + localVarPostBody = body; // byte array + } // authentication (petstore_auth) required @@ -1021,52 +816,49 @@ namespace IO.Swagger.Api { localVarHeaderParams["Authorization"] = "Bearer " + Configuration.AccessToken; } - - + // make the HTTP request - IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, - Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, + IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, + Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; - + if (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling FindPetsByStatus: " + localVarResponse.Content, localVarResponse.Content); + throw new ApiException (localVarStatusCode, "Error calling AddPetUsingByteArray: " + localVarResponse.Content, localVarResponse.Content); else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling FindPetsByStatus: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); - - return new ApiResponse>(localVarStatusCode, + throw new ApiException (localVarStatusCode, "Error calling AddPetUsingByteArray: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + + + return new ApiResponse(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), - (List) Configuration.ApiClient.Deserialize(localVarResponse, typeof(List))); - + null); } - /// - /// Finds Pets by status Multiple status values can be provided with comma separated strings + /// Fake endpoint to test byte array in body parameter for adding a new pet to the store /// /// Thrown when fails to make API call - /// Status values that need to be considered for query - /// Task of List<Pet> - public async System.Threading.Tasks.Task> FindPetsByStatusAsync (List status = null) + /// Pet object in the form of byte array (optional) + /// Task of void + public async System.Threading.Tasks.Task AddPetUsingByteArrayAsync (byte[] body = null) { - ApiResponse> localVarResponse = await FindPetsByStatusAsyncWithHttpInfo(status); - return localVarResponse.Data; + await AddPetUsingByteArrayAsyncWithHttpInfo(body); } /// - /// Finds Pets by status Multiple status values can be provided with comma separated strings + /// Fake endpoint to test byte array in body parameter for adding a new pet to the store /// /// Thrown when fails to make API call - /// Status values that need to be considered for query - /// Task of ApiResponse (List<Pet>) - public async System.Threading.Tasks.Task>> FindPetsByStatusAsyncWithHttpInfo (List status = null) + /// Pet object in the form of byte array (optional) + /// Task of ApiResponse + public async System.Threading.Tasks.Task> AddPetUsingByteArrayAsyncWithHttpInfo (byte[] body = null) { - - var localVarPath = "/pet/findByStatus"; - + + var localVarPath = "/pet?testing_byte_array=true"; + var localVarPathParams = new Dictionary(); var localVarQueryParams = new Dictionary(); var localVarHeaderParams = new Dictionary(Configuration.DefaultHeader); @@ -1076,7 +868,7 @@ namespace IO.Swagger.Api // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { - + "application/json", "application/xml" }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); @@ -1091,95 +883,14 @@ namespace IO.Swagger.Api // 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)) + if (body.GetType() != typeof(byte[])) { - localVarHeaderParams["Authorization"] = "Bearer " + Configuration.AccessToken; + 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.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, - localVarPathParams, localVarHttpContentType); - - int localVarStatusCode = (int) localVarResponse.StatusCode; - - if (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling FindPetsByStatus: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling FindPetsByStatus: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); - - 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 Muliple tags can be provided with comma seperated 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 = null) - { - ApiResponse> localVarResponse = FindPetsByTagsWithHttpInfo(tags); - return localVarResponse.Data; - } - - /// - /// Finds Pets by tags Muliple tags can be provided with comma seperated 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 = null) - { - - - 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/json", "application/xml" - }; - 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 @@ -1188,139 +899,53 @@ namespace IO.Swagger.Api { localVarHeaderParams["Authorization"] = "Bearer " + Configuration.AccessToken; } - - + // make the HTTP request - IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, - Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, + IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath, + Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; - + if (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling FindPetsByTags: " + localVarResponse.Content, localVarResponse.Content); + throw new ApiException (localVarStatusCode, "Error calling AddPetUsingByteArray: " + localVarResponse.Content, localVarResponse.Content); else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling FindPetsByTags: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); - - return new ApiResponse>(localVarStatusCode, + throw new ApiException (localVarStatusCode, "Error calling AddPetUsingByteArray: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + + + return new ApiResponse(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), - (List) Configuration.ApiClient.Deserialize(localVarResponse, typeof(List))); - + null); } - - /// - /// Finds Pets by tags Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + /// Deletes a pet /// /// Thrown when fails to make API call - /// Tags to filter by - /// Task of List<Pet> - public async System.Threading.Tasks.Task> FindPetsByTagsAsync (List tags = null) + /// Pet id to delete + /// (optional) + /// + public void DeletePet (long? petId, string apiKey = null) { - ApiResponse> localVarResponse = await FindPetsByTagsAsyncWithHttpInfo(tags); - return localVarResponse.Data; - + DeletePetWithHttpInfo(petId, apiKey); } /// - /// Finds Pets by tags Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + /// Deletes a pet /// /// 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 = null) - { - - - 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/json", "application/xml" - }; - 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 (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling FindPetsByTags: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling FindPetsByTags: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); - - 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 pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions - /// - /// Thrown when fails to make API call - /// ID of pet that needs to be fetched - /// Pet - public Pet GetPetById (long? petId) - { - ApiResponse localVarResponse = GetPetByIdWithHttpInfo(petId); - return localVarResponse.Data; - } - - /// - /// Find pet by ID Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions - /// - /// Thrown when fails to make API call - /// ID of pet that needs to be fetched - /// ApiResponse of Pet - public ApiResponse< Pet > GetPetByIdWithHttpInfo (long? petId) + /// 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->GetPetById"); + 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); @@ -1346,18 +971,9 @@ namespace IO.Swagger.Api // 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 (api_key) required - - if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("api_key"))) - { - localVarHeaderParams["api_key"] = Configuration.GetApiKeyWithPrefix("api_key"); - } // authentication (petstore_auth) required // oauth required @@ -1365,27 +981,501 @@ namespace IO.Swagger.Api { localVarHeaderParams["Authorization"] = "Bearer " + Configuration.AccessToken; } - - + // make the HTTP request - IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, + IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, + Method.DELETE, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, + localVarPathParams, localVarHttpContentType); + + int localVarStatusCode = (int) localVarResponse.StatusCode; + + if (localVarStatusCode >= 400) + throw new ApiException (localVarStatusCode, "Error calling DeletePet: " + localVarResponse.Content, localVarResponse.Content); + else if (localVarStatusCode == 0) + throw new ApiException (localVarStatusCode, "Error calling DeletePet: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + + + 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 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/json", "application/xml" + }; + 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 (localVarStatusCode >= 400) + throw new ApiException (localVarStatusCode, "Error calling DeletePet: " + localVarResponse.Content, localVarResponse.Content); + else if (localVarStatusCode == 0) + throw new ApiException (localVarStatusCode, "Error calling DeletePet: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + + + 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 query (optional, default to available) + /// List<Pet> + public List FindPetsByStatus (List status = null) + { + 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 query (optional, default to available) + /// ApiResponse of List<Pet> + public ApiResponse< List > FindPetsByStatusWithHttpInfo (List status = null) + { + + + 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/json", "application/xml" + }; + 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 (localVarStatusCode >= 400) + throw new ApiException (localVarStatusCode, "Error calling FindPetsByStatus: " + localVarResponse.Content, localVarResponse.Content); + else if (localVarStatusCode == 0) + throw new ApiException (localVarStatusCode, "Error calling FindPetsByStatus: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + + 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 query (optional, default to available) + /// Task of List<Pet> + public async System.Threading.Tasks.Task> FindPetsByStatusAsync (List status = null) + { + 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 query (optional, default to available) + /// Task of ApiResponse (List<Pet>) + public async System.Threading.Tasks.Task>> FindPetsByStatusAsyncWithHttpInfo (List status = null) + { + + + 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/json", "application/xml" + }; + 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 (localVarStatusCode >= 400) + throw new ApiException (localVarStatusCode, "Error calling FindPetsByStatus: " + localVarResponse.Content, localVarResponse.Content); + else if (localVarStatusCode == 0) + throw new ApiException (localVarStatusCode, "Error calling FindPetsByStatus: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + + 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 Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + /// + /// Thrown when fails to make API call + /// Tags to filter by (optional) + /// List<Pet> + public List FindPetsByTags (List tags = null) + { + ApiResponse> localVarResponse = FindPetsByTagsWithHttpInfo(tags); + return localVarResponse.Data; + } + + /// + /// Finds Pets by tags Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + /// + /// Thrown when fails to make API call + /// Tags to filter by (optional) + /// ApiResponse of List<Pet> + public ApiResponse< List > FindPetsByTagsWithHttpInfo (List tags = null) + { + + + 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/json", "application/xml" + }; + 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 (localVarStatusCode >= 400) + throw new ApiException (localVarStatusCode, "Error calling FindPetsByTags: " + localVarResponse.Content, localVarResponse.Content); + else if (localVarStatusCode == 0) + throw new ApiException (localVarStatusCode, "Error calling FindPetsByTags: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + + 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 Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + /// + /// Thrown when fails to make API call + /// Tags to filter by (optional) + /// Task of List<Pet> + public async System.Threading.Tasks.Task> FindPetsByTagsAsync (List tags = null) + { + ApiResponse> localVarResponse = await FindPetsByTagsAsyncWithHttpInfo(tags); + return localVarResponse.Data; + + } + + /// + /// Finds Pets by tags Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + /// + /// Thrown when fails to make API call + /// Tags to filter by (optional) + /// Task of ApiResponse (List<Pet>) + public async System.Threading.Tasks.Task>> FindPetsByTagsAsyncWithHttpInfo (List tags = null) + { + + + 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/json", "application/xml" + }; + 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 (localVarStatusCode >= 400) + throw new ApiException (localVarStatusCode, "Error calling FindPetsByTags: " + localVarResponse.Content, localVarResponse.Content); + else if (localVarStatusCode == 0) + throw new ApiException (localVarStatusCode, "Error calling FindPetsByTags: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + + 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 pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + /// + /// Thrown when fails to make API call + /// ID of pet that needs to be fetched + /// Pet + public Pet GetPetById (long? petId) + { + ApiResponse localVarResponse = GetPetByIdWithHttpInfo(petId); + return localVarResponse.Data; + } + + /// + /// Find pet by ID Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + /// + /// Thrown when fails to make API call + /// ID of pet that needs to be fetched + /// 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/json", "application/xml" + }; + 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"); + } +// 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 (localVarStatusCode >= 400) throw new ApiException (localVarStatusCode, "Error calling GetPetById: " + localVarResponse.Content, localVarResponse.Content); else if (localVarStatusCode == 0) throw new ApiException (localVarStatusCode, "Error calling GetPetById: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); - + 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 pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions /// @@ -1410,9 +1500,9 @@ namespace IO.Swagger.Api // verify the required parameter 'petId' is set if (petId == null) throw new ApiException(400, "Missing required parameter 'petId' when calling GetPetById"); - + var localVarPath = "/pet/{petId}"; - + var localVarPathParams = new Dictionary(); var localVarQueryParams = new Dictionary(); var localVarHeaderParams = new Dictionary(Configuration.DefaultHeader); @@ -1438,20 +1528,14 @@ namespace IO.Swagger.Api // 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"); } - // authentication (petstore_auth) required // oauth required @@ -1459,15 +1543,14 @@ namespace IO.Swagger.Api { localVarHeaderParams["Authorization"] = "Bearer " + Configuration.AccessToken; } - // make the HTTP request - IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath, - Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, + IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath, + Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; - + if (localVarStatusCode >= 400) throw new ApiException (localVarStatusCode, "Error calling GetPetById: " + localVarResponse.Content, localVarResponse.Content); else if (localVarStatusCode == 0) @@ -1478,555 +1561,11 @@ namespace IO.Swagger.Api (Pet) Configuration.ApiClient.Deserialize(localVarResponse, typeof(Pet))); } - - /// - /// 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 - /// Updated status of the pet - /// - public void UpdatePetWithForm (string 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 - /// Updated status of the pet - /// ApiResponse of Object(void) - public ApiResponse UpdatePetWithFormWithHttpInfo (string 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/json", "application/xml" - }; - 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 (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling UpdatePetWithForm: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling UpdatePetWithForm: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); - - - 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 - /// Updated status of the pet - /// Task of void - public async System.Threading.Tasks.Task UpdatePetWithFormAsync (string 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 - /// Updated status of the pet - /// Task of ApiResponse - public async System.Threading.Tasks.Task> UpdatePetWithFormAsyncWithHttpInfo (string 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 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/json", "application/xml" - }; - 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 (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling UpdatePetWithForm: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling UpdatePetWithForm: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); - - - 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 - /// - /// - 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 - /// - /// 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/json", "application/xml" - }; - 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 (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling DeletePet: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling DeletePet: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); - - - 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 - /// - /// 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 - /// - /// 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 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/json", "application/xml" - }; - 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 (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling DeletePet: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling DeletePet: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); - - - 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 - /// file to upload - /// - public void UploadFile (long? petId, string additionalMetadata = null, Stream file = null) - { - UploadFileWithHttpInfo(petId, additionalMetadata, file); - } - - /// - /// uploads an image - /// - /// Thrown when fails to make API call - /// ID of pet to update - /// Additional data to pass to server - /// file to upload - /// ApiResponse of Object(void) - public ApiResponse UploadFileWithHttpInfo (long? petId, string additionalMetadata = null, 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", "application/xml" - }; - 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 (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling UploadFile: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling UploadFile: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); - - - 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 - /// file to upload - /// Task of void - public async System.Threading.Tasks.Task UploadFileAsync (long? petId, string additionalMetadata = null, Stream file = null) - { - await UploadFileAsyncWithHttpInfo(petId, additionalMetadata, file); - - } - - /// - /// uploads an image - /// - /// Thrown when fails to make API call - /// ID of pet to update - /// Additional data to pass to server - /// file to upload - /// Task of ApiResponse - public async System.Threading.Tasks.Task> UploadFileAsyncWithHttpInfo (long? petId, string additionalMetadata = null, Stream file = null) - { - // verify the required parameter 'petId' is set - if (petId == null) throw new ApiException(400, "Missing required parameter 'petId' when calling 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", "application/xml" - }; - 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 (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling UploadFile: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling UploadFile: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); - - - return new ApiResponse(localVarStatusCode, - localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), - null); - } - /// /// Fake endpoint to test inline arbitrary object return by 'Find pet by ID' Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions /// /// Thrown when fails to make API call - /// ID of pet that needs to be fetched + /// ID of pet that needs to be fetched /// InlineResponse200 public InlineResponse200 GetPetByIdInObject (long? petId) { @@ -2038,7 +1577,7 @@ namespace IO.Swagger.Api /// Fake endpoint to test inline arbitrary object return by 'Find pet by ID' Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions /// /// Thrown when fails to make API call - /// ID of pet that needs to be fetched + /// ID of pet that needs to be fetched /// ApiResponse of InlineResponse200 public ApiResponse< InlineResponse200 > GetPetByIdInObjectWithHttpInfo (long? petId) { @@ -2047,9 +1586,9 @@ namespace IO.Swagger.Api if (petId == null) throw new ApiException(400, "Missing required parameter 'petId' when calling PetApi->GetPetByIdInObject"); - - var localVarPath = "/pet/{petId}?response=inline_arbitrary_object"; - + + var localVarPath = "/pet/{petId}?response=inline_arbitrary_object"; + var localVarPathParams = new Dictionary(); var localVarQueryParams = new Dictionary(); var localVarHeaderParams = new Dictionary(Configuration.DefaultHeader); @@ -2075,11 +1614,7 @@ namespace IO.Swagger.Api // 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 @@ -2087,34 +1622,32 @@ namespace IO.Swagger.Api { localVarHeaderParams["api_key"] = Configuration.GetApiKeyWithPrefix("api_key"); } - // authentication (petstore_auth) required +// 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, + IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; - + if (localVarStatusCode >= 400) throw new ApiException (localVarStatusCode, "Error calling GetPetByIdInObject: " + localVarResponse.Content, localVarResponse.Content); else if (localVarStatusCode == 0) throw new ApiException (localVarStatusCode, "Error calling GetPetByIdInObject: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); - + return new ApiResponse(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (InlineResponse200) Configuration.ApiClient.Deserialize(localVarResponse, typeof(InlineResponse200))); } - /// /// Fake endpoint to test inline arbitrary object return by 'Find pet by ID' Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions /// @@ -2139,9 +1672,9 @@ namespace IO.Swagger.Api // verify the required parameter 'petId' is set if (petId == null) throw new ApiException(400, "Missing required parameter 'petId' when calling GetPetByIdInObject"); - - var localVarPath = "/pet/{petId}?response=inline_arbitrary_object"; - + + var localVarPath = "/pet/{petId}?response=inline_arbitrary_object"; + var localVarPathParams = new Dictionary(); var localVarQueryParams = new Dictionary(); var localVarHeaderParams = new Dictionary(Configuration.DefaultHeader); @@ -2167,20 +1700,14 @@ namespace IO.Swagger.Api // 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"); } - // authentication (petstore_auth) required // oauth required @@ -2188,15 +1715,14 @@ namespace IO.Swagger.Api { localVarHeaderParams["Authorization"] = "Bearer " + Configuration.AccessToken; } - // make the HTTP request - IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath, - Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, + IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath, + Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; - + if (localVarStatusCode >= 400) throw new ApiException (localVarStatusCode, "Error calling GetPetByIdInObject: " + localVarResponse.Content, localVarResponse.Content); else if (localVarStatusCode == 0) @@ -2207,12 +1733,11 @@ namespace IO.Swagger.Api (InlineResponse200) Configuration.ApiClient.Deserialize(localVarResponse, typeof(InlineResponse200))); } - /// /// Fake endpoint to test byte array return by 'Find pet by ID' Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions /// /// Thrown when fails to make API call - /// ID of pet that needs to be fetched + /// ID of pet that needs to be fetched /// byte[] public byte[] PetPetIdtestingByteArraytrueGet (long? petId) { @@ -2224,7 +1749,7 @@ namespace IO.Swagger.Api /// Fake endpoint to test byte array return by 'Find pet by ID' Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions /// /// Thrown when fails to make API call - /// ID of pet that needs to be fetched + /// ID of pet that needs to be fetched /// ApiResponse of byte[] public ApiResponse< byte[] > PetPetIdtestingByteArraytrueGetWithHttpInfo (long? petId) { @@ -2233,9 +1758,9 @@ namespace IO.Swagger.Api if (petId == null) throw new ApiException(400, "Missing required parameter 'petId' when calling PetApi->PetPetIdtestingByteArraytrueGet"); - - var localVarPath = "/pet/{petId}?testing_byte_array=true"; - + + var localVarPath = "/pet/{petId}?testing_byte_array=true"; + var localVarPathParams = new Dictionary(); var localVarQueryParams = new Dictionary(); var localVarHeaderParams = new Dictionary(Configuration.DefaultHeader); @@ -2261,11 +1786,7 @@ namespace IO.Swagger.Api // 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 @@ -2273,34 +1794,32 @@ namespace IO.Swagger.Api { localVarHeaderParams["api_key"] = Configuration.GetApiKeyWithPrefix("api_key"); } - // authentication (petstore_auth) required +// 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, + IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; - + if (localVarStatusCode >= 400) throw new ApiException (localVarStatusCode, "Error calling PetPetIdtestingByteArraytrueGet: " + localVarResponse.Content, localVarResponse.Content); else if (localVarStatusCode == 0) throw new ApiException (localVarStatusCode, "Error calling PetPetIdtestingByteArraytrueGet: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); - + return new ApiResponse(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (byte[]) Configuration.ApiClient.Deserialize(localVarResponse, typeof(byte[]))); } - /// /// Fake endpoint to test byte array return by 'Find pet by ID' Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions /// @@ -2325,9 +1844,9 @@ namespace IO.Swagger.Api // verify the required parameter 'petId' is set if (petId == null) throw new ApiException(400, "Missing required parameter 'petId' when calling PetPetIdtestingByteArraytrueGet"); - - var localVarPath = "/pet/{petId}?testing_byte_array=true"; - + + var localVarPath = "/pet/{petId}?testing_byte_array=true"; + var localVarPathParams = new Dictionary(); var localVarQueryParams = new Dictionary(); var localVarHeaderParams = new Dictionary(Configuration.DefaultHeader); @@ -2353,20 +1872,14 @@ namespace IO.Swagger.Api // 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"); } - // authentication (petstore_auth) required // oauth required @@ -2374,15 +1887,14 @@ namespace IO.Swagger.Api { localVarHeaderParams["Authorization"] = "Bearer " + Configuration.AccessToken; } - // make the HTTP request - IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath, - Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, + IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath, + Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; - + if (localVarStatusCode >= 400) throw new ApiException (localVarStatusCode, "Error calling PetPetIdtestingByteArraytrueGet: " + localVarResponse.Content, localVarResponse.Content); else if (localVarStatusCode == 0) @@ -2393,30 +1905,29 @@ namespace IO.Swagger.Api (byte[]) Configuration.ApiClient.Deserialize(localVarResponse, typeof(byte[]))); } - /// - /// Fake endpoint to test byte array in body parameter for adding a new pet to the store + /// Update an existing pet /// /// Thrown when fails to make API call - /// Pet object in the form of byte array + /// Pet object that needs to be added to the store (optional) /// - public void AddPetUsingByteArray (byte[] body = null) + public void UpdatePet (Pet body = null) { - AddPetUsingByteArrayWithHttpInfo(body); + UpdatePetWithHttpInfo(body); } /// - /// Fake endpoint to test byte array in body parameter for adding a new pet to the store + /// Update an existing pet /// /// Thrown when fails to make API call - /// Pet object in the form of byte array + /// Pet object that needs to be added to the store (optional) /// ApiResponse of Object(void) - public ApiResponse AddPetUsingByteArrayWithHttpInfo (byte[] body = null) + public ApiResponse UpdatePetWithHttpInfo (Pet body = null) { - - var localVarPath = "/pet?testing_byte_array=true"; - + + var localVarPath = "/pet"; + var localVarPathParams = new Dictionary(); var localVarQueryParams = new Dictionary(); var localVarHeaderParams = new Dictionary(Configuration.DefaultHeader); @@ -2441,11 +1952,7 @@ namespace IO.Swagger.Api // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); - - - - - if (body.GetType() != typeof(byte[])) + if (body.GetType() != typeof(byte[])) { localVarPostBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter } @@ -2461,51 +1968,223 @@ namespace IO.Swagger.Api { localVarHeaderParams["Authorization"] = "Bearer " + Configuration.AccessToken; } - - + // make the HTTP request - IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, + IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, + Method.PUT, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, + localVarPathParams, localVarHttpContentType); + + int localVarStatusCode = (int) localVarResponse.StatusCode; + + if (localVarStatusCode >= 400) + throw new ApiException (localVarStatusCode, "Error calling UpdatePet: " + localVarResponse.Content, localVarResponse.Content); + else if (localVarStatusCode == 0) + throw new ApiException (localVarStatusCode, "Error calling UpdatePet: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + + + 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 (optional) + /// Task of void + public async System.Threading.Tasks.Task UpdatePetAsync (Pet body = null) + { + await UpdatePetAsyncWithHttpInfo(body); + + } + + /// + /// Update an existing pet + /// + /// Thrown when fails to make API call + /// Pet object that needs to be added to the store (optional) + /// Task of ApiResponse + public async System.Threading.Tasks.Task> UpdatePetAsyncWithHttpInfo (Pet body = null) + { + + + 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/json", "application/xml" + }; + 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.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 (localVarStatusCode >= 400) + throw new ApiException (localVarStatusCode, "Error calling UpdatePet: " + localVarResponse.Content, localVarResponse.Content); + else if (localVarStatusCode == 0) + throw new ApiException (localVarStatusCode, "Error calling UpdatePet: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + + + 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 (string 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 (string 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/json", "application/xml" + }; + 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 (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling AddPetUsingByteArray: " + localVarResponse.Content, localVarResponse.Content); + throw new ApiException (localVarStatusCode, "Error calling UpdatePetWithForm: " + localVarResponse.Content, localVarResponse.Content); else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling AddPetUsingByteArray: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); - + throw new ApiException (localVarStatusCode, "Error calling UpdatePetWithForm: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + return new ApiResponse(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), null); } - /// - /// Fake endpoint to test byte array in body parameter for adding a new pet to the store + /// Updates a pet in the store with form data /// /// Thrown when fails to make API call - /// Pet object in the form of byte array + /// 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 AddPetUsingByteArrayAsync (byte[] body = null) + public async System.Threading.Tasks.Task UpdatePetWithFormAsync (string petId, string name = null, string status = null) { - await AddPetUsingByteArrayAsyncWithHttpInfo(body); + await UpdatePetWithFormAsyncWithHttpInfo(petId, name, status); } /// - /// Fake endpoint to test byte array in body parameter for adding a new pet to the store + /// Updates a pet in the store with form data /// /// Thrown when fails to make API call - /// Pet object in the form of byte array + /// 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> AddPetUsingByteArrayAsyncWithHttpInfo (byte[] body = null) + public async System.Threading.Tasks.Task> UpdatePetWithFormAsyncWithHttpInfo (string 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 UpdatePetWithForm"); - - var localVarPath = "/pet?testing_byte_array=true"; - + + var localVarPath = "/pet/{petId}"; + var localVarPathParams = new Dictionary(); var localVarQueryParams = new Dictionary(); var localVarHeaderParams = new Dictionary(Configuration.DefaultHeader); @@ -2515,7 +2194,7 @@ namespace IO.Swagger.Api // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { - "application/json", "application/xml" + "application/x-www-form-urlencoded" }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); @@ -2530,20 +2209,11 @@ namespace IO.Swagger.Api // 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 - - - - if (body.GetType() != typeof(byte[])) - { - localVarPostBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter - } - else - { - localVarPostBody = body; // byte array - } - // authentication (petstore_auth) required // oauth required @@ -2551,26 +2221,193 @@ namespace IO.Swagger.Api { localVarHeaderParams["Authorization"] = "Bearer " + Configuration.AccessToken; } - // make the HTTP request - IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath, - Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, + IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath, + Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; - + if (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling AddPetUsingByteArray: " + localVarResponse.Content, localVarResponse.Content); + throw new ApiException (localVarStatusCode, "Error calling UpdatePetWithForm: " + localVarResponse.Content, localVarResponse.Content); else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling AddPetUsingByteArray: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + throw new ApiException (localVarStatusCode, "Error calling UpdatePetWithForm: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + + + 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) + /// + public void UploadFile (long? petId, string additionalMetadata = null, Stream file = null) + { + UploadFileWithHttpInfo(petId, additionalMetadata, file); + } + + /// + /// 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 Object(void) + public ApiResponse UploadFileWithHttpInfo (long? petId, string additionalMetadata = null, 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", "application/xml" + }; + 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 (localVarStatusCode >= 400) + throw new ApiException (localVarStatusCode, "Error calling UploadFile: " + localVarResponse.Content, localVarResponse.Content); + else if (localVarStatusCode == 0) + throw new ApiException (localVarStatusCode, "Error calling UploadFile: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + + + 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) + /// Task of void + public async System.Threading.Tasks.Task UploadFileAsync (long? petId, string additionalMetadata = null, Stream file = null) + { + await UploadFileAsyncWithHttpInfo(petId, additionalMetadata, file); + + } + + /// + /// 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> UploadFileAsyncWithHttpInfo (long? petId, string additionalMetadata = null, Stream file = null) + { + // verify the required parameter 'petId' is set + if (petId == null) throw new ApiException(400, "Missing required parameter 'petId' when calling 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", "application/xml" + }; + 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 (localVarStatusCode >= 400) + throw new ApiException (localVarStatusCode, "Error calling UploadFile: " + localVarResponse.Content, localVarResponse.Content); + else if (localVarStatusCode == 0) + throw new ApiException (localVarStatusCode, "Error calling UploadFile: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); return new ApiResponse(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), null); } - } - } diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/StoreApi.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/StoreApi.cs index 4000f9b754c..bd611798c6c 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/StoreApi.cs +++ b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/StoreApi.cs @@ -9,120 +9,12 @@ using IO.Swagger.Model; namespace IO.Swagger.Api { - /// /// Represents a collection of functions to interact with the API endpoints /// public interface IStoreApi { #region Synchronous Operations - - /// - /// Finds orders by status - /// - /// - /// A single status value can be provided as a string - /// - /// Thrown when fails to make API call - /// Status value that needs to be considered for query - /// List<Order> - List FindOrdersByStatus (string status = null); - - /// - /// Finds orders by status - /// - /// - /// A single status value can be provided as a string - /// - /// Thrown when fails to make API call - /// Status value that needs to be considered for query - /// ApiResponse of List<Order> - ApiResponse> FindOrdersByStatusWithHttpInfo (string status = null); - - /// - /// 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 (); - - /// - /// Fake endpoint to test arbitrary object return by 'Get inventory' - /// - /// - /// Returns an arbitrary object which is actually a map of status codes to quantities - /// - /// Thrown when fails to make API call - /// Object - Object GetInventoryInObject (); - - /// - /// Fake endpoint to test arbitrary object return by 'Get inventory' - /// - /// - /// Returns an arbitrary object which is actually a map of status codes to quantities - /// - /// Thrown when fails to make API call - /// ApiResponse of Object - ApiResponse GetInventoryInObjectWithHttpInfo (); - - /// - /// Place an order for a pet - /// - /// - /// - /// - /// Thrown when fails to make API call - /// order placed for purchasing the pet - /// Order - Order PlaceOrder (Order body = null); - - /// - /// 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 = null); - - /// - /// 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 (string 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 (string orderId); - /// /// Delete purchase order by ID /// @@ -133,7 +25,7 @@ namespace IO.Swagger.Api /// ID of the order that needs to be deleted /// void DeleteOrder (string orderId); - + /// /// Delete purchase order by ID /// @@ -144,117 +36,109 @@ namespace IO.Swagger.Api /// ID of the order that needs to be deleted /// ApiResponse of Object(void) ApiResponse DeleteOrderWithHttpInfo (string orderId); - + /// + /// Finds orders by status + /// + /// + /// A single status value can be provided as a string + /// + /// Thrown when fails to make API call + /// Status value that needs to be considered for query (optional, default to placed) + /// List<Order> + List FindOrdersByStatus (string status = null); + + /// + /// Finds orders by status + /// + /// + /// A single status value can be provided as a string + /// + /// Thrown when fails to make API call + /// Status value that needs to be considered for query (optional, default to placed) + /// ApiResponse of List<Order> + ApiResponse> FindOrdersByStatusWithHttpInfo (string status = null); + /// + /// 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 (); + /// + /// Fake endpoint to test arbitrary object return by 'Get inventory' + /// + /// + /// Returns an arbitrary object which is actually a map of status codes to quantities + /// + /// Thrown when fails to make API call + /// Object + Object GetInventoryInObject (); + + /// + /// Fake endpoint to test arbitrary object return by 'Get inventory' + /// + /// + /// Returns an arbitrary object which is actually a map of status codes to quantities + /// + /// Thrown when fails to make API call + /// ApiResponse of Object + ApiResponse GetInventoryInObjectWithHttpInfo (); + /// + /// 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 (string 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 (string orderId); + /// + /// Place an order for a pet + /// + /// + /// + /// + /// Thrown when fails to make API call + /// order placed for purchasing the pet (optional) + /// Order + Order PlaceOrder (Order body = null); + + /// + /// Place an order for a pet + /// + /// + /// + /// + /// Thrown when fails to make API call + /// order placed for purchasing the pet (optional) + /// ApiResponse of Order + ApiResponse PlaceOrderWithHttpInfo (Order body = null); #endregion Synchronous Operations - #region Asynchronous Operations - - /// - /// Finds orders by status - /// - /// - /// A single status value can be provided as a string - /// - /// Thrown when fails to make API call - /// Status value that needs to be considered for query - /// Task of List<Order> - System.Threading.Tasks.Task> FindOrdersByStatusAsync (string status = null); - - /// - /// Finds orders by status - /// - /// - /// A single status value can be provided as a string - /// - /// Thrown when fails to make API call - /// Status value that needs to be considered for query - /// Task of ApiResponse (List<Order>) - System.Threading.Tasks.Task>> FindOrdersByStatusAsyncWithHttpInfo (string status = null); - - /// - /// 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 (); - - /// - /// Fake endpoint to test arbitrary object return by 'Get inventory' - /// - /// - /// Returns an arbitrary object which is actually a map of status codes to quantities - /// - /// Thrown when fails to make API call - /// Task of Object - System.Threading.Tasks.Task GetInventoryInObjectAsync (); - - /// - /// Fake endpoint to test arbitrary object return by 'Get inventory' - /// - /// - /// Returns an arbitrary object which is actually a map of status codes to quantities - /// - /// Thrown when fails to make API call - /// Task of ApiResponse (Object) - System.Threading.Tasks.Task> GetInventoryInObjectAsyncWithHttpInfo (); - - /// - /// 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 = null); - - /// - /// 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 = null); - - /// - /// 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 (string 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 (string orderId); - /// /// Delete purchase order by ID /// @@ -276,11 +160,110 @@ namespace IO.Swagger.Api /// ID of the order that needs to be deleted /// Task of ApiResponse System.Threading.Tasks.Task> DeleteOrderAsyncWithHttpInfo (string orderId); - + /// + /// Finds orders by status + /// + /// + /// A single status value can be provided as a string + /// + /// Thrown when fails to make API call + /// Status value that needs to be considered for query (optional, default to placed) + /// Task of List<Order> + System.Threading.Tasks.Task> FindOrdersByStatusAsync (string status = null); + + /// + /// Finds orders by status + /// + /// + /// A single status value can be provided as a string + /// + /// Thrown when fails to make API call + /// Status value that needs to be considered for query (optional, default to placed) + /// Task of ApiResponse (List<Order>) + System.Threading.Tasks.Task>> FindOrdersByStatusAsyncWithHttpInfo (string status = null); + /// + /// 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 (); + /// + /// Fake endpoint to test arbitrary object return by 'Get inventory' + /// + /// + /// Returns an arbitrary object which is actually a map of status codes to quantities + /// + /// Thrown when fails to make API call + /// Task of Object + System.Threading.Tasks.Task GetInventoryInObjectAsync (); + + /// + /// Fake endpoint to test arbitrary object return by 'Get inventory' + /// + /// + /// Returns an arbitrary object which is actually a map of status codes to quantities + /// + /// Thrown when fails to make API call + /// Task of ApiResponse (Object) + System.Threading.Tasks.Task> GetInventoryInObjectAsyncWithHttpInfo (); + /// + /// 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 (string 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 (string orderId); + /// + /// Place an order for a pet + /// + /// + /// + /// + /// Thrown when fails to make API call + /// order placed for purchasing the pet (optional) + /// Task of Order + System.Threading.Tasks.Task PlaceOrderAsync (Order body = null); + + /// + /// Place an order for a pet + /// + /// + /// + /// + /// Thrown when fails to make API call + /// order placed for purchasing the pet (optional) + /// Task of ApiResponse (Order) + System.Threading.Tasks.Task> PlaceOrderAsyncWithHttpInfo (Order body = null); #endregion Asynchronous Operations - } - + /// /// Represents a collection of functions to interact with the API endpoints /// @@ -293,8 +276,14 @@ namespace IO.Swagger.Api public StoreApi(String basePath) { this.Configuration = new Configuration(new ApiClient(basePath)); + + // ensure API client has configuration ready + if (Configuration.ApiClient.Configuration == null) + { + this.Configuration.ApiClient.Configuration = this.Configuration; + } } - + /// /// Initializes a new instance of the class /// using Configuration object @@ -304,9 +293,15 @@ namespace IO.Swagger.Api public StoreApi(Configuration configuration = null) { if (configuration == null) // use the default one in Configuration - this.Configuration = Configuration.Default; + this.Configuration = Configuration.Default; else this.Configuration = configuration; + + // ensure API client has configuration ready + if (Configuration.ApiClient.Configuration == null) + { + this.Configuration.ApiClient.Configuration = this.Configuration; + } } /// @@ -327,7 +322,7 @@ namespace IO.Swagger.Api { // do nothing } - + /// /// Gets or sets the configuration object /// @@ -355,883 +350,12 @@ namespace IO.Swagger.Api { this.Configuration.AddDefaultHeader(key, value); } - - - /// - /// Finds orders by status A single status value can be provided as a string - /// - /// Thrown when fails to make API call - /// Status value that needs to be considered for query - /// List<Order> - public List FindOrdersByStatus (string status = null) - { - ApiResponse> localVarResponse = FindOrdersByStatusWithHttpInfo(status); - return localVarResponse.Data; - } - /// - /// Finds orders by status A single status value can be provided as a string - /// - /// Thrown when fails to make API call - /// Status value that needs to be considered for query - /// ApiResponse of List<Order> - public ApiResponse< List > FindOrdersByStatusWithHttpInfo (string status = null) - { - - - var localVarPath = "/store/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/json", "application/xml" - }; - 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 (test_api_client_id) required - - if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("x-test_api_client_id"))) - { - localVarHeaderParams["x-test_api_client_id"] = Configuration.GetApiKeyWithPrefix("x-test_api_client_id"); - } - // authentication (test_api_client_secret) required - - if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("x-test_api_client_secret"))) - { - localVarHeaderParams["x-test_api_client_secret"] = Configuration.GetApiKeyWithPrefix("x-test_api_client_secret"); - } - - - // 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 (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling FindOrdersByStatus: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling FindOrdersByStatus: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); - - return new ApiResponse>(localVarStatusCode, - localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), - (List) Configuration.ApiClient.Deserialize(localVarResponse, typeof(List))); - - } - - - /// - /// Finds orders by status A single status value can be provided as a string - /// - /// Thrown when fails to make API call - /// Status value that needs to be considered for query - /// Task of List<Order> - public async System.Threading.Tasks.Task> FindOrdersByStatusAsync (string status = null) - { - ApiResponse> localVarResponse = await FindOrdersByStatusAsyncWithHttpInfo(status); - return localVarResponse.Data; - - } - - /// - /// Finds orders by status A single status value can be provided as a string - /// - /// Thrown when fails to make API call - /// Status value that needs to be considered for query - /// Task of ApiResponse (List<Order>) - public async System.Threading.Tasks.Task>> FindOrdersByStatusAsyncWithHttpInfo (string status = null) - { - - - var localVarPath = "/store/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/json", "application/xml" - }; - 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 (test_api_client_id) required - - if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("x-test_api_client_id"))) - { - localVarHeaderParams["x-test_api_client_id"] = Configuration.GetApiKeyWithPrefix("x-test_api_client_id"); - } - - // authentication (test_api_client_secret) required - - if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("x-test_api_client_secret"))) - { - localVarHeaderParams["x-test_api_client_secret"] = Configuration.GetApiKeyWithPrefix("x-test_api_client_secret"); - } - - - // 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 (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling FindOrdersByStatus: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling FindOrdersByStatus: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); - - return new ApiResponse>(localVarStatusCode, - localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), - (List) Configuration.ApiClient.Deserialize(localVarResponse, typeof(List))); - - } - - /// - /// 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", "application/xml" - }; - 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 (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling GetInventory: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling GetInventory: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); - - 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", "application/xml" - }; - 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 (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling GetInventory: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling GetInventory: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); - - return new ApiResponse>(localVarStatusCode, - localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), - (Dictionary) Configuration.ApiClient.Deserialize(localVarResponse, typeof(Dictionary))); - - } - - /// - /// Fake endpoint to test arbitrary object return by 'Get inventory' Returns an arbitrary object which is actually a map of status codes to quantities - /// - /// Thrown when fails to make API call - /// Object - public Object GetInventoryInObject () - { - ApiResponse localVarResponse = GetInventoryInObjectWithHttpInfo(); - return localVarResponse.Data; - } - - /// - /// Fake endpoint to test arbitrary object return by 'Get inventory' Returns an arbitrary object which is actually a map of status codes to quantities - /// - /// Thrown when fails to make API call - /// ApiResponse of Object - public ApiResponse< Object > GetInventoryInObjectWithHttpInfo () - { - - - var localVarPath = "/store/inventory?response=arbitrary_object"; - - 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", "application/xml" - }; - 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 (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling GetInventoryInObject: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling GetInventoryInObject: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); - - return new ApiResponse(localVarStatusCode, - localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), - (Object) Configuration.ApiClient.Deserialize(localVarResponse, typeof(Object))); - - } - - - /// - /// Fake endpoint to test arbitrary object return by 'Get inventory' Returns an arbitrary object which is actually a map of status codes to quantities - /// - /// Thrown when fails to make API call - /// Task of Object - public async System.Threading.Tasks.Task GetInventoryInObjectAsync () - { - ApiResponse localVarResponse = await GetInventoryInObjectAsyncWithHttpInfo(); - return localVarResponse.Data; - - } - - /// - /// Fake endpoint to test arbitrary object return by 'Get inventory' Returns an arbitrary object which is actually a map of status codes to quantities - /// - /// Thrown when fails to make API call - /// Task of ApiResponse (Object) - public async System.Threading.Tasks.Task> GetInventoryInObjectAsyncWithHttpInfo () - { - - - var localVarPath = "/store/inventory?response=arbitrary_object"; - - 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", "application/xml" - }; - 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 (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling GetInventoryInObject: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling GetInventoryInObject: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); - - return new ApiResponse(localVarStatusCode, - localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), - (Object) Configuration.ApiClient.Deserialize(localVarResponse, typeof(Object))); - - } - - /// - /// 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 = null) - { - 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 = null) - { - - - 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/json", "application/xml" - }; - 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.GetType() != typeof(byte[])) - { - localVarPostBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter - } - else - { - localVarPostBody = body; // byte array - } - - // authentication (test_api_client_id) required - - if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("x-test_api_client_id"))) - { - localVarHeaderParams["x-test_api_client_id"] = Configuration.GetApiKeyWithPrefix("x-test_api_client_id"); - } - // authentication (test_api_client_secret) required - - if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("x-test_api_client_secret"))) - { - localVarHeaderParams["x-test_api_client_secret"] = Configuration.GetApiKeyWithPrefix("x-test_api_client_secret"); - } - - - // make the HTTP request - IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, - Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, - localVarPathParams, localVarHttpContentType); - - int localVarStatusCode = (int) localVarResponse.StatusCode; - - if (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling PlaceOrder: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling PlaceOrder: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); - - 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 = null) - { - 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 = null) - { - - - 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/json", "application/xml" - }; - 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.GetType() != typeof(byte[])) - { - localVarPostBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter - } - else - { - localVarPostBody = body; // byte array - } - - - // authentication (test_api_client_id) required - - if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("x-test_api_client_id"))) - { - localVarHeaderParams["x-test_api_client_id"] = Configuration.GetApiKeyWithPrefix("x-test_api_client_id"); - } - - // authentication (test_api_client_secret) required - - if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("x-test_api_client_secret"))) - { - localVarHeaderParams["x-test_api_client_secret"] = Configuration.GetApiKeyWithPrefix("x-test_api_client_secret"); - } - - - // make the HTTP request - IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath, - Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, - localVarPathParams, localVarHttpContentType); - - int localVarStatusCode = (int) localVarResponse.StatusCode; - - if (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling PlaceOrder: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling PlaceOrder: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); - - 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 - /// Order - public Order GetOrderById (string 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 (string 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/json", "application/xml" - }; - 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 - - - - - - - // authentication (test_api_key_header) required - - if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("test_api_key_header"))) - { - localVarHeaderParams["test_api_key_header"] = Configuration.GetApiKeyWithPrefix("test_api_key_header"); - } - // authentication (test_api_key_query) required - - if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("test_api_key_query"))) - { - localVarQueryParams["test_api_key_query"] = Configuration.GetApiKeyWithPrefix("test_api_key_query"); - } - - - // 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 (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling GetOrderById: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling GetOrderById: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); - - 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 (string 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 (string orderId) - { - // verify the required parameter 'orderId' is set - if (orderId == null) throw new ApiException(400, "Missing required parameter 'orderId' when calling 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/json", "application/xml" - }; - 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 - - - - - - - - // authentication (test_api_key_header) required - - if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("test_api_key_header"))) - { - localVarHeaderParams["test_api_key_header"] = Configuration.GetApiKeyWithPrefix("test_api_key_header"); - } - - // authentication (test_api_key_query) required - - if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("test_api_key_query"))) - { - localVarQueryParams["test_api_key_query"] = Configuration.GetApiKeyWithPrefix("test_api_key_query"); - } - - - // 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 (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling GetOrderById: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling GetOrderById: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); - - return new ApiResponse(localVarStatusCode, - localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), - (Order) Configuration.ApiClient.Deserialize(localVarResponse, typeof(Order))); - - } - /// /// 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 + /// ID of the order that needs to be deleted /// public void DeleteOrder (string orderId) { @@ -1242,7 +366,7 @@ namespace IO.Swagger.Api /// 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 + /// ID of the order that needs to be deleted /// ApiResponse of Object(void) public ApiResponse DeleteOrderWithHttpInfo (string orderId) { @@ -1251,9 +375,9 @@ namespace IO.Swagger.Api 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); @@ -1279,33 +403,27 @@ namespace IO.Swagger.Api // 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, + IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, Method.DELETE, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; - + if (localVarStatusCode >= 400) throw new ApiException (localVarStatusCode, "Error calling DeleteOrder: " + localVarResponse.Content, localVarResponse.Content); else if (localVarStatusCode == 0) throw new ApiException (localVarStatusCode, "Error calling DeleteOrder: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); - + 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 /// @@ -1329,9 +447,9 @@ namespace IO.Swagger.Api // verify the required parameter 'orderId' is set if (orderId == null) throw new ApiException(400, "Missing required parameter 'orderId' when calling DeleteOrder"); - + var localVarPath = "/store/order/{orderId}"; - + var localVarPathParams = new Dictionary(); var localVarQueryParams = new Dictionary(); var localVarHeaderParams = new Dictionary(Configuration.DefaultHeader); @@ -1357,21 +475,16 @@ namespace IO.Swagger.Api // 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, + IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath, + Method.DELETE, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; - + if (localVarStatusCode >= 400) throw new ApiException (localVarStatusCode, "Error calling DeleteOrder: " + localVarResponse.Content, localVarResponse.Content); else if (localVarStatusCode == 0) @@ -1382,7 +495,807 @@ namespace IO.Swagger.Api localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), null); } - + /// + /// Finds orders by status A single status value can be provided as a string + /// + /// Thrown when fails to make API call + /// Status value that needs to be considered for query (optional, default to placed) + /// List<Order> + public List FindOrdersByStatus (string status = null) + { + ApiResponse> localVarResponse = FindOrdersByStatusWithHttpInfo(status); + return localVarResponse.Data; + } + + /// + /// Finds orders by status A single status value can be provided as a string + /// + /// Thrown when fails to make API call + /// Status value that needs to be considered for query (optional, default to placed) + /// ApiResponse of List<Order> + public ApiResponse< List > FindOrdersByStatusWithHttpInfo (string status = null) + { + + + var localVarPath = "/store/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/json", "application/xml" + }; + 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 (test_api_client_id) required + + if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("x-test_api_client_id"))) + { + localVarHeaderParams["x-test_api_client_id"] = Configuration.GetApiKeyWithPrefix("x-test_api_client_id"); + } +// authentication (test_api_client_secret) required + + if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("x-test_api_client_secret"))) + { + localVarHeaderParams["x-test_api_client_secret"] = Configuration.GetApiKeyWithPrefix("x-test_api_client_secret"); + } + + // 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 (localVarStatusCode >= 400) + throw new ApiException (localVarStatusCode, "Error calling FindOrdersByStatus: " + localVarResponse.Content, localVarResponse.Content); + else if (localVarStatusCode == 0) + throw new ApiException (localVarStatusCode, "Error calling FindOrdersByStatus: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + + return new ApiResponse>(localVarStatusCode, + localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), + (List) Configuration.ApiClient.Deserialize(localVarResponse, typeof(List))); + + } + + /// + /// Finds orders by status A single status value can be provided as a string + /// + /// Thrown when fails to make API call + /// Status value that needs to be considered for query (optional, default to placed) + /// Task of List<Order> + public async System.Threading.Tasks.Task> FindOrdersByStatusAsync (string status = null) + { + ApiResponse> localVarResponse = await FindOrdersByStatusAsyncWithHttpInfo(status); + return localVarResponse.Data; + + } + + /// + /// Finds orders by status A single status value can be provided as a string + /// + /// Thrown when fails to make API call + /// Status value that needs to be considered for query (optional, default to placed) + /// Task of ApiResponse (List<Order>) + public async System.Threading.Tasks.Task>> FindOrdersByStatusAsyncWithHttpInfo (string status = null) + { + + + var localVarPath = "/store/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/json", "application/xml" + }; + 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 (test_api_client_id) required + + if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("x-test_api_client_id"))) + { + localVarHeaderParams["x-test_api_client_id"] = Configuration.GetApiKeyWithPrefix("x-test_api_client_id"); + } + // authentication (test_api_client_secret) required + + if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("x-test_api_client_secret"))) + { + localVarHeaderParams["x-test_api_client_secret"] = Configuration.GetApiKeyWithPrefix("x-test_api_client_secret"); + } + + // 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 (localVarStatusCode >= 400) + throw new ApiException (localVarStatusCode, "Error calling FindOrdersByStatus: " + localVarResponse.Content, localVarResponse.Content); + else if (localVarStatusCode == 0) + throw new ApiException (localVarStatusCode, "Error calling FindOrdersByStatus: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + + return new ApiResponse>(localVarStatusCode, + localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), + (List) Configuration.ApiClient.Deserialize(localVarResponse, typeof(List))); + + } + /// + /// 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", "application/xml" + }; + 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 (localVarStatusCode >= 400) + throw new ApiException (localVarStatusCode, "Error calling GetInventory: " + localVarResponse.Content, localVarResponse.Content); + else if (localVarStatusCode == 0) + throw new ApiException (localVarStatusCode, "Error calling GetInventory: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + + 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", "application/xml" + }; + 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 (localVarStatusCode >= 400) + throw new ApiException (localVarStatusCode, "Error calling GetInventory: " + localVarResponse.Content, localVarResponse.Content); + else if (localVarStatusCode == 0) + throw new ApiException (localVarStatusCode, "Error calling GetInventory: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + + return new ApiResponse>(localVarStatusCode, + localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), + (Dictionary) Configuration.ApiClient.Deserialize(localVarResponse, typeof(Dictionary))); + + } + /// + /// Fake endpoint to test arbitrary object return by 'Get inventory' Returns an arbitrary object which is actually a map of status codes to quantities + /// + /// Thrown when fails to make API call + /// Object + public Object GetInventoryInObject () + { + ApiResponse localVarResponse = GetInventoryInObjectWithHttpInfo(); + return localVarResponse.Data; + } + + /// + /// Fake endpoint to test arbitrary object return by 'Get inventory' Returns an arbitrary object which is actually a map of status codes to quantities + /// + /// Thrown when fails to make API call + /// ApiResponse of Object + public ApiResponse< Object > GetInventoryInObjectWithHttpInfo () + { + + + var localVarPath = "/store/inventory?response=arbitrary_object"; + + 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", "application/xml" + }; + 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 (localVarStatusCode >= 400) + throw new ApiException (localVarStatusCode, "Error calling GetInventoryInObject: " + localVarResponse.Content, localVarResponse.Content); + else if (localVarStatusCode == 0) + throw new ApiException (localVarStatusCode, "Error calling GetInventoryInObject: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + + return new ApiResponse(localVarStatusCode, + localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), + (Object) Configuration.ApiClient.Deserialize(localVarResponse, typeof(Object))); + + } + + /// + /// Fake endpoint to test arbitrary object return by 'Get inventory' Returns an arbitrary object which is actually a map of status codes to quantities + /// + /// Thrown when fails to make API call + /// Task of Object + public async System.Threading.Tasks.Task GetInventoryInObjectAsync () + { + ApiResponse localVarResponse = await GetInventoryInObjectAsyncWithHttpInfo(); + return localVarResponse.Data; + + } + + /// + /// Fake endpoint to test arbitrary object return by 'Get inventory' Returns an arbitrary object which is actually a map of status codes to quantities + /// + /// Thrown when fails to make API call + /// Task of ApiResponse (Object) + public async System.Threading.Tasks.Task> GetInventoryInObjectAsyncWithHttpInfo () + { + + + var localVarPath = "/store/inventory?response=arbitrary_object"; + + 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", "application/xml" + }; + 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 (localVarStatusCode >= 400) + throw new ApiException (localVarStatusCode, "Error calling GetInventoryInObject: " + localVarResponse.Content, localVarResponse.Content); + else if (localVarStatusCode == 0) + throw new ApiException (localVarStatusCode, "Error calling GetInventoryInObject: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + + return new ApiResponse(localVarStatusCode, + localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), + (Object) Configuration.ApiClient.Deserialize(localVarResponse, typeof(Object))); + + } + /// + /// 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 (string 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 (string 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/json", "application/xml" + }; + 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 + + + // authentication (test_api_key_header) required + + if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("test_api_key_header"))) + { + localVarHeaderParams["test_api_key_header"] = Configuration.GetApiKeyWithPrefix("test_api_key_header"); + } +// authentication (test_api_key_query) required + + if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("test_api_key_query"))) + { + localVarQueryParams["test_api_key_query"] = Configuration.GetApiKeyWithPrefix("test_api_key_query"); + } + + // 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 (localVarStatusCode >= 400) + throw new ApiException (localVarStatusCode, "Error calling GetOrderById: " + localVarResponse.Content, localVarResponse.Content); + else if (localVarStatusCode == 0) + throw new ApiException (localVarStatusCode, "Error calling GetOrderById: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + + 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 (string 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 (string orderId) + { + // verify the required parameter 'orderId' is set + if (orderId == null) throw new ApiException(400, "Missing required parameter 'orderId' when calling 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/json", "application/xml" + }; + 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 + + + // authentication (test_api_key_header) required + + if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("test_api_key_header"))) + { + localVarHeaderParams["test_api_key_header"] = Configuration.GetApiKeyWithPrefix("test_api_key_header"); + } + // authentication (test_api_key_query) required + + if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("test_api_key_query"))) + { + localVarQueryParams["test_api_key_query"] = Configuration.GetApiKeyWithPrefix("test_api_key_query"); + } + + // 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 (localVarStatusCode >= 400) + throw new ApiException (localVarStatusCode, "Error calling GetOrderById: " + localVarResponse.Content, localVarResponse.Content); + else if (localVarStatusCode == 0) + throw new ApiException (localVarStatusCode, "Error calling GetOrderById: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + + 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 (optional) + /// Order + public Order PlaceOrder (Order body = null) + { + 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 (optional) + /// ApiResponse of Order + public ApiResponse< Order > PlaceOrderWithHttpInfo (Order body = null) + { + + + 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/json", "application/xml" + }; + 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.GetType() != typeof(byte[])) + { + localVarPostBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter + } + else + { + localVarPostBody = body; // byte array + } + + // authentication (test_api_client_id) required + + if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("x-test_api_client_id"))) + { + localVarHeaderParams["x-test_api_client_id"] = Configuration.GetApiKeyWithPrefix("x-test_api_client_id"); + } +// authentication (test_api_client_secret) required + + if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("x-test_api_client_secret"))) + { + localVarHeaderParams["x-test_api_client_secret"] = Configuration.GetApiKeyWithPrefix("x-test_api_client_secret"); + } + + // make the HTTP request + IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, + Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, + localVarPathParams, localVarHttpContentType); + + int localVarStatusCode = (int) localVarResponse.StatusCode; + + if (localVarStatusCode >= 400) + throw new ApiException (localVarStatusCode, "Error calling PlaceOrder: " + localVarResponse.Content, localVarResponse.Content); + else if (localVarStatusCode == 0) + throw new ApiException (localVarStatusCode, "Error calling PlaceOrder: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + + 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 (optional) + /// Task of Order + public async System.Threading.Tasks.Task PlaceOrderAsync (Order body = null) + { + 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 (optional) + /// Task of ApiResponse (Order) + public async System.Threading.Tasks.Task> PlaceOrderAsyncWithHttpInfo (Order body = null) + { + + + 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/json", "application/xml" + }; + 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.GetType() != typeof(byte[])) + { + localVarPostBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter + } + else + { + localVarPostBody = body; // byte array + } + + // authentication (test_api_client_id) required + + if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("x-test_api_client_id"))) + { + localVarHeaderParams["x-test_api_client_id"] = Configuration.GetApiKeyWithPrefix("x-test_api_client_id"); + } + // authentication (test_api_client_secret) required + + if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("x-test_api_client_secret"))) + { + localVarHeaderParams["x-test_api_client_secret"] = Configuration.GetApiKeyWithPrefix("x-test_api_client_secret"); + } + + // make the HTTP request + IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath, + Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, + localVarPathParams, localVarHttpContentType); + + int localVarStatusCode = (int) localVarResponse.StatusCode; + + if (localVarStatusCode >= 400) + throw new ApiException (localVarStatusCode, "Error calling PlaceOrder: " + localVarResponse.Content, localVarResponse.Content); + else if (localVarStatusCode == 0) + throw new ApiException (localVarStatusCode, "Error calling PlaceOrder: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + + 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/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/UserApi.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/UserApi.cs index 193cc501a85..80297f069db 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/UserApi.cs +++ b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/UserApi.cs @@ -9,14 +9,12 @@ using IO.Swagger.Model; namespace IO.Swagger.Api { - /// /// Represents a collection of functions to interact with the API endpoints /// public interface IUserApi { #region Synchronous Operations - /// /// Create user /// @@ -24,10 +22,10 @@ namespace IO.Swagger.Api /// This can only be done by the logged in user. /// /// Thrown when fails to make API call - /// Created user object + /// Created user object (optional) /// void CreateUser (User body = null); - + /// /// Create user /// @@ -35,10 +33,9 @@ namespace IO.Swagger.Api /// This can only be done by the logged in user. /// /// Thrown when fails to make API call - /// Created user object + /// Created user object (optional) /// ApiResponse of Object(void) ApiResponse CreateUserWithHttpInfo (User body = null); - /// /// Creates list of users with given input array /// @@ -46,10 +43,10 @@ namespace IO.Swagger.Api /// /// /// Thrown when fails to make API call - /// List of user object + /// List of user object (optional) /// void CreateUsersWithArrayInput (List body = null); - + /// /// Creates list of users with given input array /// @@ -57,10 +54,9 @@ namespace IO.Swagger.Api /// /// /// Thrown when fails to make API call - /// List of user object + /// List of user object (optional) /// ApiResponse of Object(void) ApiResponse CreateUsersWithArrayInputWithHttpInfo (List body = null); - /// /// Creates list of users with given input array /// @@ -68,10 +64,10 @@ namespace IO.Swagger.Api /// /// /// Thrown when fails to make API call - /// List of user object + /// List of user object (optional) /// void CreateUsersWithListInput (List body = null); - + /// /// Creates list of users with given input array /// @@ -79,100 +75,9 @@ namespace IO.Swagger.Api /// /// /// Thrown when fails to make API call - /// List of user object + /// List of user object (optional) /// ApiResponse of Object(void) ApiResponse CreateUsersWithListInputWithHttpInfo (List body = null); - - /// - /// 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 = null, string password = null); - - /// - /// 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 = null, string password = null); - - /// - /// 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 (); - - /// - /// 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); - - /// - /// 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 = 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 - /// ApiResponse of Object(void) - ApiResponse UpdateUserWithHttpInfo (string username, User body = null); - /// /// Delete user /// @@ -183,7 +88,7 @@ namespace IO.Swagger.Api /// The name that needs to be deleted /// void DeleteUser (string username); - + /// /// Delete user /// @@ -194,11 +99,94 @@ namespace IO.Swagger.Api /// 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 (optional) + /// The password for login in clear text (optional) + /// string + string LoginUser (string username = null, string password = null); + + /// + /// Logs user into the system + /// + /// + /// + /// + /// Thrown when fails to make API call + /// The user name for login (optional) + /// The password for login in clear text (optional) + /// ApiResponse of string + ApiResponse LoginUserWithHttpInfo (string username = null, string password = null); + /// + /// 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 (optional) + /// + void UpdateUser (string username, User body = 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 (optional) + /// ApiResponse of Object(void) + ApiResponse UpdateUserWithHttpInfo (string username, User body = null); #endregion Synchronous Operations - #region Asynchronous Operations - /// /// Create user /// @@ -206,7 +194,7 @@ namespace IO.Swagger.Api /// This can only be done by the logged in user. /// /// Thrown when fails to make API call - /// Created user object + /// Created user object (optional) /// Task of void System.Threading.Tasks.Task CreateUserAsync (User body = null); @@ -217,10 +205,9 @@ namespace IO.Swagger.Api /// This can only be done by the logged in user. /// /// Thrown when fails to make API call - /// Created user object + /// Created user object (optional) /// Task of ApiResponse System.Threading.Tasks.Task> CreateUserAsyncWithHttpInfo (User body = null); - /// /// Creates list of users with given input array /// @@ -228,7 +215,7 @@ namespace IO.Swagger.Api /// /// /// Thrown when fails to make API call - /// List of user object + /// List of user object (optional) /// Task of void System.Threading.Tasks.Task CreateUsersWithArrayInputAsync (List body = null); @@ -239,10 +226,9 @@ namespace IO.Swagger.Api /// /// /// Thrown when fails to make API call - /// List of user object + /// List of user object (optional) /// Task of ApiResponse System.Threading.Tasks.Task> CreateUsersWithArrayInputAsyncWithHttpInfo (List body = null); - /// /// Creates list of users with given input array /// @@ -250,7 +236,7 @@ namespace IO.Swagger.Api /// /// /// Thrown when fails to make API call - /// List of user object + /// List of user object (optional) /// Task of void System.Threading.Tasks.Task CreateUsersWithListInputAsync (List body = null); @@ -261,100 +247,9 @@ namespace IO.Swagger.Api /// /// /// Thrown when fails to make API call - /// List of user object + /// List of user object (optional) /// Task of ApiResponse System.Threading.Tasks.Task> CreateUsersWithListInputAsyncWithHttpInfo (List body = null); - - /// - /// 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 = null, string password = null); - - /// - /// 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 = null, string password = null); - - /// - /// 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 (); - - /// - /// 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); - - /// - /// 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 = 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 ApiResponse - System.Threading.Tasks.Task> UpdateUserAsyncWithHttpInfo (string username, User body = null); - /// /// Delete user /// @@ -376,11 +271,95 @@ namespace IO.Swagger.Api /// 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 (optional) + /// The password for login in clear text (optional) + /// Task of string + System.Threading.Tasks.Task LoginUserAsync (string username = null, string password = null); + + /// + /// Logs user into the system + /// + /// + /// + /// + /// Thrown when fails to make API call + /// The user name for login (optional) + /// The password for login in clear text (optional) + /// Task of ApiResponse (string) + System.Threading.Tasks.Task> LoginUserAsyncWithHttpInfo (string username = null, string password = null); + /// + /// 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 (optional) + /// Task of void + System.Threading.Tasks.Task UpdateUserAsync (string username, User body = 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 (optional) + /// Task of ApiResponse + System.Threading.Tasks.Task> UpdateUserAsyncWithHttpInfo (string username, User body = null); #endregion Asynchronous Operations - } - + /// /// Represents a collection of functions to interact with the API endpoints /// @@ -393,8 +372,14 @@ namespace IO.Swagger.Api public UserApi(String basePath) { this.Configuration = new Configuration(new ApiClient(basePath)); + + // ensure API client has configuration ready + if (Configuration.ApiClient.Configuration == null) + { + this.Configuration.ApiClient.Configuration = this.Configuration; + } } - + /// /// Initializes a new instance of the class /// using Configuration object @@ -404,9 +389,15 @@ namespace IO.Swagger.Api public UserApi(Configuration configuration = null) { if (configuration == null) // use the default one in Configuration - this.Configuration = Configuration.Default; + this.Configuration = Configuration.Default; else this.Configuration = configuration; + + // ensure API client has configuration ready + if (Configuration.ApiClient.Configuration == null) + { + this.Configuration.ApiClient.Configuration = this.Configuration; + } } /// @@ -427,7 +418,7 @@ namespace IO.Swagger.Api { // do nothing } - + /// /// Gets or sets the configuration object /// @@ -455,13 +446,12 @@ namespace IO.Swagger.Api { 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 + /// Created user object (optional) /// public void CreateUser (User body = null) { @@ -472,14 +462,14 @@ namespace IO.Swagger.Api /// Create user This can only be done by the logged in user. /// /// Thrown when fails to make API call - /// Created user object + /// Created user object (optional) /// ApiResponse of Object(void) public ApiResponse CreateUserWithHttpInfo (User body = null) { - + var localVarPath = "/user"; - + var localVarPathParams = new Dictionary(); var localVarQueryParams = new Dictionary(); var localVarHeaderParams = new Dictionary(Configuration.DefaultHeader); @@ -504,11 +494,7 @@ namespace IO.Swagger.Api // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); - - - - - if (body.GetType() != typeof(byte[])) + if (body.GetType() != typeof(byte[])) { localVarPostBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter } @@ -518,31 +504,29 @@ namespace IO.Swagger.Api } - // make the HTTP request - IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, + IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; - + if (localVarStatusCode >= 400) throw new ApiException (localVarStatusCode, "Error calling CreateUser: " + localVarResponse.Content, localVarResponse.Content); else if (localVarStatusCode == 0) throw new ApiException (localVarStatusCode, "Error calling CreateUser: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); - + 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 + /// Created user object (optional) /// Task of void public async System.Threading.Tasks.Task CreateUserAsync (User body = null) { @@ -554,14 +538,14 @@ namespace IO.Swagger.Api /// Create user This can only be done by the logged in user. /// /// Thrown when fails to make API call - /// Created user object + /// Created user object (optional) /// Task of ApiResponse public async System.Threading.Tasks.Task> CreateUserAsyncWithHttpInfo (User body = null) { - + var localVarPath = "/user"; - + var localVarPathParams = new Dictionary(); var localVarQueryParams = new Dictionary(); var localVarHeaderParams = new Dictionary(Configuration.DefaultHeader); @@ -586,11 +570,7 @@ namespace IO.Swagger.Api // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); - - - - - if (body.GetType() != typeof(byte[])) + if (body.GetType() != typeof(byte[])) { localVarPostBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter } @@ -599,15 +579,14 @@ namespace IO.Swagger.Api localVarPostBody = body; // byte array } - // make the HTTP request - IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath, - Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, + IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath, + Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; - + if (localVarStatusCode >= 400) throw new ApiException (localVarStatusCode, "Error calling CreateUser: " + localVarResponse.Content, localVarResponse.Content); else if (localVarStatusCode == 0) @@ -618,12 +597,11 @@ namespace IO.Swagger.Api 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 + /// List of user object (optional) /// public void CreateUsersWithArrayInput (List body = null) { @@ -634,14 +612,14 @@ namespace IO.Swagger.Api /// Creates list of users with given input array /// /// Thrown when fails to make API call - /// List of user object + /// List of user object (optional) /// ApiResponse of Object(void) public ApiResponse CreateUsersWithArrayInputWithHttpInfo (List body = null) { - + var localVarPath = "/user/createWithArray"; - + var localVarPathParams = new Dictionary(); var localVarQueryParams = new Dictionary(); var localVarHeaderParams = new Dictionary(Configuration.DefaultHeader); @@ -666,11 +644,7 @@ namespace IO.Swagger.Api // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); - - - - - if (body.GetType() != typeof(byte[])) + if (body.GetType() != typeof(byte[])) { localVarPostBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter } @@ -680,31 +654,29 @@ namespace IO.Swagger.Api } - // make the HTTP request - IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, + IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; - + if (localVarStatusCode >= 400) throw new ApiException (localVarStatusCode, "Error calling CreateUsersWithArrayInput: " + localVarResponse.Content, localVarResponse.Content); else if (localVarStatusCode == 0) throw new ApiException (localVarStatusCode, "Error calling CreateUsersWithArrayInput: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); - + 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 + /// List of user object (optional) /// Task of void public async System.Threading.Tasks.Task CreateUsersWithArrayInputAsync (List body = null) { @@ -716,14 +688,14 @@ namespace IO.Swagger.Api /// Creates list of users with given input array /// /// Thrown when fails to make API call - /// List of user object + /// List of user object (optional) /// Task of ApiResponse public async System.Threading.Tasks.Task> CreateUsersWithArrayInputAsyncWithHttpInfo (List body = null) { - + var localVarPath = "/user/createWithArray"; - + var localVarPathParams = new Dictionary(); var localVarQueryParams = new Dictionary(); var localVarHeaderParams = new Dictionary(Configuration.DefaultHeader); @@ -748,11 +720,7 @@ namespace IO.Swagger.Api // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); - - - - - if (body.GetType() != typeof(byte[])) + if (body.GetType() != typeof(byte[])) { localVarPostBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter } @@ -761,15 +729,14 @@ namespace IO.Swagger.Api localVarPostBody = body; // byte array } - // make the HTTP request - IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath, - Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, + IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath, + Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; - + if (localVarStatusCode >= 400) throw new ApiException (localVarStatusCode, "Error calling CreateUsersWithArrayInput: " + localVarResponse.Content, localVarResponse.Content); else if (localVarStatusCode == 0) @@ -780,12 +747,11 @@ namespace IO.Swagger.Api 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 + /// List of user object (optional) /// public void CreateUsersWithListInput (List body = null) { @@ -796,14 +762,14 @@ namespace IO.Swagger.Api /// Creates list of users with given input array /// /// Thrown when fails to make API call - /// List of user object + /// List of user object (optional) /// ApiResponse of Object(void) public ApiResponse CreateUsersWithListInputWithHttpInfo (List body = null) { - + var localVarPath = "/user/createWithList"; - + var localVarPathParams = new Dictionary(); var localVarQueryParams = new Dictionary(); var localVarHeaderParams = new Dictionary(Configuration.DefaultHeader); @@ -828,11 +794,7 @@ namespace IO.Swagger.Api // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); - - - - - if (body.GetType() != typeof(byte[])) + if (body.GetType() != typeof(byte[])) { localVarPostBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter } @@ -842,31 +804,29 @@ namespace IO.Swagger.Api } - // make the HTTP request - IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, + IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; - + if (localVarStatusCode >= 400) throw new ApiException (localVarStatusCode, "Error calling CreateUsersWithListInput: " + localVarResponse.Content, localVarResponse.Content); else if (localVarStatusCode == 0) throw new ApiException (localVarStatusCode, "Error calling CreateUsersWithListInput: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); - + 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 + /// List of user object (optional) /// Task of void public async System.Threading.Tasks.Task CreateUsersWithListInputAsync (List body = null) { @@ -878,14 +838,14 @@ namespace IO.Swagger.Api /// Creates list of users with given input array /// /// Thrown when fails to make API call - /// List of user object + /// List of user object (optional) /// Task of ApiResponse public async System.Threading.Tasks.Task> CreateUsersWithListInputAsyncWithHttpInfo (List body = null) { - + var localVarPath = "/user/createWithList"; - + var localVarPathParams = new Dictionary(); var localVarQueryParams = new Dictionary(); var localVarHeaderParams = new Dictionary(Configuration.DefaultHeader); @@ -910,11 +870,7 @@ namespace IO.Swagger.Api // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); - - - - - if (body.GetType() != typeof(byte[])) + if (body.GetType() != typeof(byte[])) { localVarPostBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter } @@ -923,15 +879,14 @@ namespace IO.Swagger.Api localVarPostBody = body; // byte array } - // make the HTTP request - IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath, - Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, + IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath, + Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; - + if (localVarStatusCode >= 400) throw new ApiException (localVarStatusCode, "Error calling CreateUsersWithListInput: " + localVarResponse.Content, localVarResponse.Content); else if (localVarStatusCode == 0) @@ -942,646 +897,11 @@ namespace IO.Swagger.Api localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), null); } - - /// - /// 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 = null, string password = null) - { - 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 = null, string password = null) - { - - - 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/json", "application/xml" - }; - 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 (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling LoginUser: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling LoginUser: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); - - 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 = null, string password = null) - { - 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 = null, string password = null) - { - - - 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/json", "application/xml" - }; - 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 (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling LoginUser: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling LoginUser: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); - - 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/json", "application/xml" - }; - 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 (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling LogoutUser: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling LogoutUser: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); - - - 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/json", "application/xml" - }; - 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 (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling LogoutUser: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling LogoutUser: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); - - - 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/json", "application/xml" - }; - 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 (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling GetUserByName: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling GetUserByName: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); - - 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 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/json", "application/xml" - }; - 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 (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling GetUserByName: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling GetUserByName: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); - - return new ApiResponse(localVarStatusCode, - localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), - (User) Configuration.ApiClient.Deserialize(localVarResponse, typeof(User))); - - } - - /// - /// 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 = null) - { - 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 = null) - { - - // verify the required parameter 'username' is set - if (username == null) - throw new ApiException(400, "Missing required parameter 'username' 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/json", "application/xml" - }; - 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.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 (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling UpdateUser: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling UpdateUser: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); - - - 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 = null) - { - 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 = null) - { - // verify the required parameter 'username' is set - if (username == null) throw new ApiException(400, "Missing required parameter 'username' when calling 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/json", "application/xml" - }; - 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.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 (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling UpdateUser: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling UpdateUser: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); - - - 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 + /// The name that needs to be deleted /// public void DeleteUser (string username) { @@ -1592,7 +912,7 @@ namespace IO.Swagger.Api /// 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 + /// The name that needs to be deleted /// ApiResponse of Object(void) public ApiResponse DeleteUserWithHttpInfo (string username) { @@ -1601,9 +921,9 @@ namespace IO.Swagger.Api 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); @@ -1629,33 +949,34 @@ namespace IO.Swagger.Api // 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 - - - - - + + // authentication (test_http_basic) 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, + IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, Method.DELETE, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; - + if (localVarStatusCode >= 400) throw new ApiException (localVarStatusCode, "Error calling DeleteUser: " + localVarResponse.Content, localVarResponse.Content); else if (localVarStatusCode == 0) throw new ApiException (localVarStatusCode, "Error calling DeleteUser: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); - + 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. /// @@ -1679,9 +1000,9 @@ namespace IO.Swagger.Api // verify the required parameter 'username' is set if (username == null) throw new ApiException(400, "Missing required parameter 'username' when calling DeleteUser"); - + var localVarPath = "/user/{username}"; - + var localVarPathParams = new Dictionary(); var localVarQueryParams = new Dictionary(); var localVarHeaderParams = new Dictionary(Configuration.DefaultHeader); @@ -1707,21 +1028,23 @@ namespace IO.Swagger.Api // 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 - - - - - + + // authentication (test_http_basic) 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.DELETE, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, + IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath, + Method.DELETE, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; - + if (localVarStatusCode >= 400) throw new ApiException (localVarStatusCode, "Error calling DeleteUser: " + localVarResponse.Content, localVarResponse.Content); else if (localVarStatusCode == 0) @@ -1732,7 +1055,591 @@ namespace IO.Swagger.Api 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/json", "application/xml" + }; + 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 (localVarStatusCode >= 400) + throw new ApiException (localVarStatusCode, "Error calling GetUserByName: " + localVarResponse.Content, localVarResponse.Content); + else if (localVarStatusCode == 0) + throw new ApiException (localVarStatusCode, "Error calling GetUserByName: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + + 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 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/json", "application/xml" + }; + 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 (localVarStatusCode >= 400) + throw new ApiException (localVarStatusCode, "Error calling GetUserByName: " + localVarResponse.Content, localVarResponse.Content); + else if (localVarStatusCode == 0) + throw new ApiException (localVarStatusCode, "Error calling GetUserByName: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + + 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 (optional) + /// The password for login in clear text (optional) + /// string + public string LoginUser (string username = null, string password = null) + { + 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 (optional) + /// The password for login in clear text (optional) + /// ApiResponse of string + public ApiResponse< string > LoginUserWithHttpInfo (string username = null, string password = null) + { + + + 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/json", "application/xml" + }; + 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 (localVarStatusCode >= 400) + throw new ApiException (localVarStatusCode, "Error calling LoginUser: " + localVarResponse.Content, localVarResponse.Content); + else if (localVarStatusCode == 0) + throw new ApiException (localVarStatusCode, "Error calling LoginUser: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + + 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 (optional) + /// The password for login in clear text (optional) + /// Task of string + public async System.Threading.Tasks.Task LoginUserAsync (string username = null, string password = null) + { + 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 (optional) + /// The password for login in clear text (optional) + /// Task of ApiResponse (string) + public async System.Threading.Tasks.Task> LoginUserAsyncWithHttpInfo (string username = null, string password = null) + { + + + 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/json", "application/xml" + }; + 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 (localVarStatusCode >= 400) + throw new ApiException (localVarStatusCode, "Error calling LoginUser: " + localVarResponse.Content, localVarResponse.Content); + else if (localVarStatusCode == 0) + throw new ApiException (localVarStatusCode, "Error calling LoginUser: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + + 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/json", "application/xml" + }; + 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 (localVarStatusCode >= 400) + throw new ApiException (localVarStatusCode, "Error calling LogoutUser: " + localVarResponse.Content, localVarResponse.Content); + else if (localVarStatusCode == 0) + throw new ApiException (localVarStatusCode, "Error calling LogoutUser: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + + + 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/json", "application/xml" + }; + 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 (localVarStatusCode >= 400) + throw new ApiException (localVarStatusCode, "Error calling LogoutUser: " + localVarResponse.Content, localVarResponse.Content); + else if (localVarStatusCode == 0) + throw new ApiException (localVarStatusCode, "Error calling LogoutUser: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + + + 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 (optional) + /// + public void UpdateUser (string username, User body = null) + { + 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 (optional) + /// ApiResponse of Object(void) + public ApiResponse UpdateUserWithHttpInfo (string username, User body = null) + { + + // verify the required parameter 'username' is set + if (username == null) + throw new ApiException(400, "Missing required parameter 'username' 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/json", "application/xml" + }; + 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.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 (localVarStatusCode >= 400) + throw new ApiException (localVarStatusCode, "Error calling UpdateUser: " + localVarResponse.Content, localVarResponse.Content); + else if (localVarStatusCode == 0) + throw new ApiException (localVarStatusCode, "Error calling UpdateUser: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + + + 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 (optional) + /// Task of void + public async System.Threading.Tasks.Task UpdateUserAsync (string username, User body = null) + { + 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 (optional) + /// Task of ApiResponse + public async System.Threading.Tasks.Task> UpdateUserAsyncWithHttpInfo (string username, User body = null) + { + // verify the required parameter 'username' is set + if (username == null) throw new ApiException(400, "Missing required parameter 'username' when calling 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/json", "application/xml" + }; + 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.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 (localVarStatusCode >= 400) + throw new ApiException (localVarStatusCode, "Error calling UpdateUser: " + localVarResponse.Content, localVarResponse.Content); + else if (localVarStatusCode == 0) + throw new ApiException (localVarStatusCode, "Error calling UpdateUser: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + + + return new ApiResponse(localVarStatusCode, + localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), + null); + } } - } diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Client/ApiClient.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Client/ApiClient.cs index ac2c7eda793..ec9c793b7d3 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Client/ApiClient.cs +++ b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Client/ApiClient.cs @@ -63,7 +63,7 @@ namespace IO.Swagger.Client /// The default API client. [Obsolete("ApiClient.Default is deprecated, please use 'Configuration.Default.ApiClient' instead.")] public static ApiClient Default; - + /// /// Gets or sets the Configuration. /// @@ -75,7 +75,7 @@ namespace IO.Swagger.Client /// /// 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, @@ -84,10 +84,10 @@ namespace IO.Swagger.Client 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); + request.AddParameter(param.Key, param.Value, ParameterType.UrlSegment); // add header parameter, if any foreach(var param in headerParams) @@ -116,7 +116,7 @@ namespace IO.Swagger.Client request.AddParameter(contentType, postBody, ParameterType.RequestBody); } } - + return request; } @@ -143,10 +143,14 @@ namespace IO.Swagger.Client path, method, queryParams, postBody, headerParams, formParams, fileParams, pathParams, contentType); + // set timeout + RestClient.Timeout = Configuration.Timeout; + // set user agent + RestClient.UserAgent = Configuration.UserAgent; + var response = RestClient.Execute(request); return (Object) response; } - /// /// Makes the asynchronous HTTP request. /// @@ -172,7 +176,7 @@ namespace IO.Swagger.Client var response = await RestClient.ExecuteTaskAsync(request); return (Object)response; } - + /// /// Escape string (url-encoded). /// @@ -182,7 +186,7 @@ namespace IO.Swagger.Client { return UrlEncode(str); } - + /// /// Create FileParameter based on Stream. /// @@ -196,7 +200,7 @@ namespace IO.Swagger.Client 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 ",". @@ -217,7 +221,7 @@ namespace IO.Swagger.Client // 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); + return ((DateTimeOffset)obj).ToString (Configuration.DateTimeFormat); else if (obj is IList) { var flattenedString = new StringBuilder(); @@ -232,7 +236,7 @@ namespace IO.Swagger.Client else return Convert.ToString (obj); } - + /// /// Deserialize the JSON string into a proper object. /// @@ -277,9 +281,9 @@ namespace IO.Swagger.Client if (type == typeof(String) || type.Name.StartsWith("System.Nullable")) // return primitive type { - return ConvertType(response.Content, type); + return ConvertType(response.Content, type); } - + // at this point, it must be a model (json) try { @@ -290,7 +294,7 @@ namespace IO.Swagger.Client throw new ApiException(500, e.Message); } } - + /// /// Serialize an input (model) into JSON string /// @@ -307,7 +311,7 @@ namespace IO.Swagger.Client 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; @@ -343,7 +347,7 @@ namespace IO.Swagger.Client return String.Join(",", accepts); } - + /// /// Encode string in base64 format. /// @@ -353,7 +357,7 @@ namespace IO.Swagger.Client { 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 diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Client/ApiException.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Client/ApiException.cs index 2410626602c..7b7a11721df 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Client/ApiException.cs +++ b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Client/ApiException.cs @@ -12,18 +12,18 @@ namespace IO.Swagger.Client /// /// 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. /// @@ -33,7 +33,7 @@ namespace IO.Swagger.Client { this.ErrorCode = errorCode; } - + /// /// Initializes a new instance of the class. /// @@ -46,5 +46,5 @@ namespace IO.Swagger.Client this.ErrorContent = errorContent; } } - + } diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Client/ApiResponse.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Client/ApiResponse.cs index 651d3609c22..808837b4aa1 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Client/ApiResponse.cs +++ b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Client/ApiResponse.cs @@ -13,19 +13,19 @@ namespace IO.Swagger.Client /// /// 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. /// @@ -38,7 +38,7 @@ namespace IO.Swagger.Client this.Headers = headers; this.Data = data; } - + } - + } diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Client/Configuration.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Client/Configuration.cs index 2622a9b11fc..acbaee1e688 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Client/Configuration.cs +++ b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Client/Configuration.cs @@ -25,6 +25,7 @@ namespace IO.Swagger.Client /// 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, @@ -34,7 +35,8 @@ namespace IO.Swagger.Client Dictionary apiKeyPrefix = null, string tempFolderPath = null, string dateTimeFormat = null, - int timeout = 100000 + int timeout = 100000, + string userAgent = "Swagger-Codegen/1.0.0/csharp" ) { setApiClientUsingDefault(apiClient); @@ -42,6 +44,7 @@ namespace IO.Swagger.Client Username = username; Password = password; AccessToken = accessToken; + UserAgent = userAgent; if (defaultHeader != null) DefaultHeader = defaultHeader; @@ -84,7 +87,7 @@ namespace IO.Swagger.Client { get { return ApiClient.RestClient.Timeout; } - set + set { if (ApiClient != null) ApiClient.RestClient.Timeout = value; @@ -146,6 +149,12 @@ namespace IO.Swagger.Client _defaultHeaderMap.Add(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). /// @@ -211,7 +220,7 @@ namespace IO.Swagger.Client } // create the directory if it does not exist - if (!Directory.Exists(value)) + if (!Directory.Exists(value)) Directory.CreateDirectory(value); // check if the path contains directory separator at the end diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Animal.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Animal.cs new file mode 100644 index 00000000000..b2db1964a52 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Animal.cs @@ -0,0 +1,118 @@ +using System; +using System.Linq; +using System.IO; +using System.Text; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Runtime.Serialization; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; + +namespace IO.Swagger.Model +{ + /// + /// + /// + [DataContract] + public partial class Animal : IEquatable + { + + /// + /// Initializes a new instance of the class. + /// Initializes a new instance of the class. + /// + /// ClassName (required). + + public Animal(string ClassName = 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; + } + + } + + + /// + /// Gets or Sets ClassName + /// + [DataMember(Name="className", EmitDefaultValue=false)] + public string ClassName { 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("}\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) + ); + } + + /// + /// 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(); + return hash; + } + } + + } +} diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Cat.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Cat.cs new file mode 100644 index 00000000000..7fe58ce7f38 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Cat.cs @@ -0,0 +1,134 @@ +using System; +using System.Linq; +using System.IO; +using System.Text; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Runtime.Serialization; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; + +namespace IO.Swagger.Model +{ + /// + /// + /// + [DataContract] + public partial class Cat : Animal, IEquatable + { + + /// + /// Initializes a new instance of the class. + /// Initializes a new instance of the class. + /// + /// ClassName (required). + /// Declawed. + + public Cat(string ClassName = 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; + } + this.Declawed = Declawed; + + } + + + /// + /// Gets or Sets ClassName + /// + [DataMember(Name="className", EmitDefaultValue=false)] + public string ClassName { 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(" 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.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.Declawed != null) + hash = hash * 59 + this.Declawed.GetHashCode(); + return hash; + } + } + + } +} diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Category.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Category.cs index 80683074e9f..ded3e525318 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Category.cs +++ b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Category.cs @@ -31,7 +31,7 @@ namespace IO.Swagger.Model this.Name = Name; } - + /// /// Gets or Sets Id @@ -54,12 +54,11 @@ namespace IO.Swagger.Model var sb = new StringBuilder(); sb.Append("class Category {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); - sb.Append(" Name: ").Append(Name).Append("\n"); - +sb.Append(" Name: ").Append(Name).Append("\n"); sb.Append("}\n"); return sb.ToString(); } - + /// /// Returns the JSON string presentation of the object /// @@ -115,13 +114,10 @@ namespace IO.Swagger.Model { 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; } } diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Dog.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Dog.cs new file mode 100644 index 00000000000..5e40e848243 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Dog.cs @@ -0,0 +1,134 @@ +using System; +using System.Linq; +using System.IO; +using System.Text; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Runtime.Serialization; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; + +namespace IO.Swagger.Model +{ + /// + /// + /// + [DataContract] + public partial class Dog : Animal, IEquatable + { + + /// + /// Initializes a new instance of the class. + /// Initializes a new instance of the class. + /// + /// ClassName (required). + /// Breed. + + public Dog(string ClassName = 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; + } + this.Breed = Breed; + + } + + + /// + /// Gets or Sets ClassName + /// + [DataMember(Name="className", EmitDefaultValue=false)] + public string ClassName { 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(" 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.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.Breed != null) + hash = hash * 59 + this.Breed.GetHashCode(); + return hash; + } + } + + } +} diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/FormatTest.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/FormatTest.cs new file mode 100644 index 00000000000..4985f365053 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/FormatTest.cs @@ -0,0 +1,278 @@ +using System; +using System.Linq; +using System.IO; +using System.Text; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Runtime.Serialization; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; + +namespace IO.Swagger.Model +{ + /// + /// + /// + [DataContract] + public partial class FormatTest : IEquatable + { + + /// + /// Initializes a new instance of the class. + /// Initializes a new instance of the class. + /// + /// Integer. + /// Int32. + /// Int64. + /// Number (required). + /// _Float. + /// _Double. + /// _String. + /// _Byte. + /// Binary. + /// Date. + /// DateTime. + + public FormatTest(int? Integer = null, int? Int32 = null, long? Int64 = null, double? Number = null, float? _Float = null, double? _Double = null, string _String = null, byte[] _Byte = null, byte[] Binary = null, DateTime? Date = null, string DateTime = 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; + } + this.Integer = Integer; + this.Int32 = Int32; + this.Int64 = Int64; + this._Float = _Float; + this._Double = _Double; + this._String = _String; + this._Byte = _Byte; + this.Binary = Binary; + this.Date = Date; + this.DateTime = DateTime; + + } + + + /// + /// 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 double? 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 string DateTime { 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("}\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) + ); + } + + /// + /// 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(); + return hash; + } + } + + } +} diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/InlineResponse200.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/InlineResponse200.cs index 53d161c1ab6..e58dd38354d 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/InlineResponse200.cs +++ b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/InlineResponse200.cs @@ -17,7 +17,11 @@ namespace IO.Swagger.Model [DataContract] public partial class InlineResponse200 : IEquatable { - + + /// + /// pet status in the store + /// + /// pet status in the store [JsonConverter(typeof(StringEnumConverter))] public enum StatusEnum { @@ -30,6 +34,7 @@ namespace IO.Swagger.Model [EnumMember(Value = "sold")] Sold } + /// /// pet status in the store @@ -67,7 +72,7 @@ namespace IO.Swagger.Model this.PhotoUrls = PhotoUrls; } - + /// /// Gets or Sets Tags @@ -108,16 +113,15 @@ namespace IO.Swagger.Model var sb = new StringBuilder(); sb.Append("class InlineResponse200 {\n"); sb.Append(" Tags: ").Append(Tags).Append("\n"); - sb.Append(" Id: ").Append(Id).Append("\n"); - sb.Append(" Category: ").Append(Category).Append("\n"); - sb.Append(" Status: ").Append(Status).Append("\n"); - sb.Append(" Name: ").Append(Name).Append("\n"); - sb.Append(" PhotoUrls: ").Append(PhotoUrls).Append("\n"); - +sb.Append(" Id: ").Append(Id).Append("\n"); +sb.Append(" Category: ").Append(Category).Append("\n"); +sb.Append(" Status: ").Append(Status).Append("\n"); +sb.Append(" Name: ").Append(Name).Append("\n"); +sb.Append(" PhotoUrls: ").Append(PhotoUrls).Append("\n"); sb.Append("}\n"); return sb.ToString(); } - + /// /// Returns the JSON string presentation of the object /// @@ -193,25 +197,18 @@ namespace IO.Swagger.Model { int hash = 41; // Suitable nullity checks etc, of course :) - if (this.Tags != null) hash = hash * 59 + this.Tags.GetHashCode(); - if (this.Id != null) hash = hash * 59 + this.Id.GetHashCode(); - if (this.Category != null) hash = hash * 59 + this.Category.GetHashCode(); - if (this.Status != null) hash = hash * 59 + this.Status.GetHashCode(); - if (this.Name != null) hash = hash * 59 + this.Name.GetHashCode(); - if (this.PhotoUrls != null) hash = hash * 59 + this.PhotoUrls.GetHashCode(); - return hash; } } diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Model200Response.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Model200Response.cs new file mode 100644 index 00000000000..9199732c8e7 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Model200Response.cs @@ -0,0 +1,110 @@ +using System; +using System.Linq; +using System.IO; +using System.Text; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Runtime.Serialization; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; + +namespace IO.Swagger.Model +{ + /// + /// Model for testing model name starting with number + /// + [DataContract] + public partial class Model200Response : IEquatable + { + + /// + /// Initializes a new instance of the class. + /// Initializes a new instance of the class. + /// + /// Name. + + public Model200Response(int? Name = null) + { + this.Name = Name; + + } + + + /// + /// Gets or Sets Name + /// + [DataMember(Name="name", EmitDefaultValue=false)] + public int? 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 Model200Response {\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 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) + ); + } + + /// + /// 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(); + return hash; + } + } + + } +} diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/ModelReturn.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/ModelReturn.cs new file mode 100644 index 00000000000..a65c1430953 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/ModelReturn.cs @@ -0,0 +1,110 @@ +using System; +using System.Linq; +using System.IO; +using System.Text; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Runtime.Serialization; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; + +namespace IO.Swagger.Model +{ + /// + /// Model for testing reserved words + /// + [DataContract] + public partial class ModelReturn : IEquatable + { + + /// + /// Initializes a new instance of the class. + /// 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; + } + } + + } +} diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Name.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Name.cs new file mode 100644 index 00000000000..663e9d88e4c --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Name.cs @@ -0,0 +1,132 @@ +using System; +using System.Linq; +using System.IO; +using System.Text; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Runtime.Serialization; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; + +namespace IO.Swagger.Model +{ + /// + /// Model for testing model name same as property name + /// + [DataContract] + public partial class Name : IEquatable + { + + /// + /// Initializes a new instance of the class. + /// Initializes a new instance of the class. + /// + /// _Name (required). + + public Name(int? _Name = 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; + } + + } + + + /// + /// 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; } + + /// + /// 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("}\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) + ); + } + + /// + /// 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(); + return hash; + } + } + + } +} diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Order.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Order.cs index 4fc561c6786..7942042e0e0 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Order.cs +++ b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Order.cs @@ -17,7 +17,11 @@ namespace IO.Swagger.Model [DataContract] public partial class Order : IEquatable { - + + /// + /// Order Status + /// + /// Order Status [JsonConverter(typeof(StringEnumConverter))] public enum StatusEnum { @@ -30,6 +34,7 @@ namespace IO.Swagger.Model [EnumMember(Value = "delivered")] Delivered } + /// /// Order Status @@ -57,7 +62,7 @@ namespace IO.Swagger.Model this.Complete = Complete; } - + /// /// Gets or Sets Id @@ -98,16 +103,15 @@ namespace IO.Swagger.Model var sb = new StringBuilder(); sb.Append("class Order {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); - sb.Append(" PetId: ").Append(PetId).Append("\n"); - sb.Append(" Quantity: ").Append(Quantity).Append("\n"); - sb.Append(" ShipDate: ").Append(ShipDate).Append("\n"); - sb.Append(" Status: ").Append(Status).Append("\n"); - sb.Append(" Complete: ").Append(Complete).Append("\n"); - +sb.Append(" PetId: ").Append(PetId).Append("\n"); +sb.Append(" Quantity: ").Append(Quantity).Append("\n"); +sb.Append(" ShipDate: ").Append(ShipDate).Append("\n"); +sb.Append(" Status: ").Append(Status).Append("\n"); +sb.Append(" Complete: ").Append(Complete).Append("\n"); sb.Append("}\n"); return sb.ToString(); } - + /// /// Returns the JSON string presentation of the object /// @@ -183,25 +187,18 @@ namespace IO.Swagger.Model { 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; } } diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Pet.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Pet.cs index b206c3fa550..534dd6fd42d 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Pet.cs +++ b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Pet.cs @@ -17,7 +17,11 @@ namespace IO.Swagger.Model [DataContract] public partial class Pet : IEquatable { - + + /// + /// pet status in the store + /// + /// pet status in the store [JsonConverter(typeof(StringEnumConverter))] public enum StatusEnum { @@ -30,6 +34,7 @@ namespace IO.Swagger.Model [EnumMember(Value = "sold")] Sold } + /// /// pet status in the store @@ -75,7 +80,7 @@ namespace IO.Swagger.Model this.Status = Status; } - + /// /// Gets or Sets Id @@ -116,16 +121,15 @@ namespace IO.Swagger.Model var sb = new StringBuilder(); sb.Append("class Pet {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); - sb.Append(" Category: ").Append(Category).Append("\n"); - sb.Append(" Name: ").Append(Name).Append("\n"); - sb.Append(" PhotoUrls: ").Append(PhotoUrls).Append("\n"); - sb.Append(" Tags: ").Append(Tags).Append("\n"); - sb.Append(" Status: ").Append(Status).Append("\n"); - +sb.Append(" Category: ").Append(Category).Append("\n"); +sb.Append(" Name: ").Append(Name).Append("\n"); +sb.Append(" PhotoUrls: ").Append(PhotoUrls).Append("\n"); +sb.Append(" Tags: ").Append(Tags).Append("\n"); +sb.Append(" Status: ").Append(Status).Append("\n"); sb.Append("}\n"); return sb.ToString(); } - + /// /// Returns the JSON string presentation of the object /// @@ -201,25 +205,18 @@ namespace IO.Swagger.Model { 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; } } diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/SpecialModelName.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/SpecialModelName.cs index 4424503f008..7912fffa1fc 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/SpecialModelName.cs +++ b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/SpecialModelName.cs @@ -29,7 +29,7 @@ namespace IO.Swagger.Model this.SpecialPropertyName = SpecialPropertyName; } - + /// /// Gets or Sets SpecialPropertyName @@ -46,11 +46,10 @@ namespace IO.Swagger.Model 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 /// @@ -101,10 +100,8 @@ namespace IO.Swagger.Model { int hash = 41; // Suitable nullity checks etc, of course :) - if (this.SpecialPropertyName != null) hash = hash * 59 + this.SpecialPropertyName.GetHashCode(); - return hash; } } diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Tag.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Tag.cs index 8b511075d56..84b6091bf7a 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Tag.cs +++ b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Tag.cs @@ -31,7 +31,7 @@ namespace IO.Swagger.Model this.Name = Name; } - + /// /// Gets or Sets Id @@ -54,12 +54,11 @@ namespace IO.Swagger.Model var sb = new StringBuilder(); sb.Append("class Tag {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); - sb.Append(" Name: ").Append(Name).Append("\n"); - +sb.Append(" Name: ").Append(Name).Append("\n"); sb.Append("}\n"); return sb.ToString(); } - + /// /// Returns the JSON string presentation of the object /// @@ -115,13 +114,10 @@ namespace IO.Swagger.Model { 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; } } diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Task.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Task.cs new file mode 100644 index 00000000000..b2182f2f712 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Task.cs @@ -0,0 +1,113 @@ +using System; +using System.Linq; +using System.IO; +using System.Text; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Runtime.Serialization; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; + +namespace IO.Swagger.Model +{ + /// + /// + /// + [DataContract] + public partial class Task : IEquatable + { + + /// + /// Initializes a new instance of the class. + /// Initializes a new instance of the class. + /// + /// _Return. + + public Task(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 Task {\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 Task); + } + + /// + /// Returns true if Task instances are equal + /// + /// Instance of Task to be compared + /// Boolean + public bool Equals(Task 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; + } + } + + } +} diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/User.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/User.cs index 2216619c0bf..3563543b81c 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/User.cs +++ b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/User.cs @@ -43,7 +43,7 @@ namespace IO.Swagger.Model this.UserStatus = UserStatus; } - + /// /// Gets or Sets Id @@ -103,18 +103,17 @@ namespace IO.Swagger.Model var sb = new StringBuilder(); sb.Append("class User {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); - sb.Append(" Username: ").Append(Username).Append("\n"); - sb.Append(" FirstName: ").Append(FirstName).Append("\n"); - sb.Append(" LastName: ").Append(LastName).Append("\n"); - sb.Append(" Email: ").Append(Email).Append("\n"); - sb.Append(" Password: ").Append(Password).Append("\n"); - sb.Append(" Phone: ").Append(Phone).Append("\n"); - sb.Append(" UserStatus: ").Append(UserStatus).Append("\n"); - +sb.Append(" Username: ").Append(Username).Append("\n"); +sb.Append(" FirstName: ").Append(FirstName).Append("\n"); +sb.Append(" LastName: ").Append(LastName).Append("\n"); +sb.Append(" Email: ").Append(Email).Append("\n"); +sb.Append(" Password: ").Append(Password).Append("\n"); +sb.Append(" Phone: ").Append(Phone).Append("\n"); +sb.Append(" UserStatus: ").Append(UserStatus).Append("\n"); sb.Append("}\n"); return sb.ToString(); } - + /// /// Returns the JSON string presentation of the object /// @@ -200,31 +199,22 @@ namespace IO.Swagger.Model { 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; } } diff --git a/samples/client/petstore/csharp/SwaggerClientTest/SwaggerClientTest.csproj b/samples/client/petstore/csharp/SwaggerClientTest/SwaggerClientTest.csproj index fad04017f7a..67c8e73b6e5 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/SwaggerClientTest.csproj +++ b/samples/client/petstore/csharp/SwaggerClientTest/SwaggerClientTest.csproj @@ -62,6 +62,14 @@ + + + + + + + + diff --git a/samples/client/petstore/csharp/SwaggerClientTest/SwaggerClientTest.userprefs b/samples/client/petstore/csharp/SwaggerClientTest/SwaggerClientTest.userprefs index e6c1146e4f5..d261de4844c 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/SwaggerClientTest.userprefs +++ b/samples/client/petstore/csharp/SwaggerClientTest/SwaggerClientTest.userprefs @@ -1,17 +1,12 @@  - + - - + + + + - - - - - - - diff --git a/samples/client/petstore/csharp/SwaggerClientTest/TestPet.cs b/samples/client/petstore/csharp/SwaggerClientTest/TestPet.cs index 5c30360ee0f..0b04ca72b05 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/TestPet.cs +++ b/samples/client/petstore/csharp/SwaggerClientTest/TestPet.cs @@ -136,7 +136,7 @@ namespace SwaggerClientTest.TestPet public void TestGetPetById () { // set timeout to 10 seconds - Configuration c1 = new Configuration (timeout: 10000); + Configuration c1 = new Configuration (timeout: 10000, userAgent: "TEST_USER_AGENT"); PetApi petApi = new PetApi (c1); Pet response = petApi.GetPetById (petId); diff --git a/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.csproj.FilesWrittenAbsolute.txt b/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.csproj.FilesWrittenAbsolute.txt index 07693d3494d..323cad108c6 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.csproj.FilesWrittenAbsolute.txt +++ b/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.csproj.FilesWrittenAbsolute.txt @@ -7,12 +7,3 @@ /Users/williamcheng/Code/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/Newtonsoft.Json.dll /Users/williamcheng/Code/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/nunit.framework.dll /Users/williamcheng/Code/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/RestSharp.dll -/Users/williamcheng/Code/wing328/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/.NETFramework,Version=v4.5.AssemblyAttribute.cs -/Users/williamcheng/Code/wing328/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.swagger-logo.png -/Users/williamcheng/Code/wing328/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/SwaggerClientTest.dll.mdb -/Users/williamcheng/Code/wing328/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/SwaggerClientTest.dll -/Users/williamcheng/Code/wing328/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.dll -/Users/williamcheng/Code/wing328/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.dll.mdb -/Users/williamcheng/Code/wing328/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/Newtonsoft.Json.dll -/Users/williamcheng/Code/wing328/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/nunit.framework.dll -/Users/williamcheng/Code/wing328/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/RestSharp.dll diff --git a/samples/client/petstore/go/.gitignore b/samples/client/petstore/go/.gitignore new file mode 100644 index 00000000000..daf913b1b34 --- /dev/null +++ b/samples/client/petstore/go/.gitignore @@ -0,0 +1,24 @@ +# Compiled Object files, Static and Dynamic libs (Shared Objects) +*.o +*.a +*.so + +# Folders +_obj +_test + +# Architecture specific extensions/prefixes +*.[568vq] +[568vq].out + +*.cgo1.go +*.cgo2.c +_cgo_defun.c +_cgo_gotypes.go +_cgo_export.* + +_testmain.go + +*.exe +*.test +*.prof diff --git a/samples/client/petstore/go/git_push.sh b/samples/client/petstore/go/git_push.sh new file mode 100644 index 00000000000..1a36388db02 --- /dev/null +++ b/samples/client/petstore/go/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="YOUR_GIT_USR_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="YOUR_GIT_REPO_ID" + 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/go/petStore_test.go b/samples/client/petstore/go/petStore_test.go new file mode 100644 index 00000000000..e3df602c3b8 --- /dev/null +++ b/samples/client/petstore/go/petStore_test.go @@ -0,0 +1,52 @@ +package main + +import ( + "testing" + + sw "./swagger" + "github.com/stretchr/testify/assert" +) + +func TestAddPet(t *testing.T) { + t.Log("Testing TestAddPet...") + s := sw.NewPetApi() + newPet := (sw.Pet{Id: 12830, Name: "gopher", + PhotoUrls: []string{"http://1.com", "http://2.com"}, Status: "pending"}) + + err := s.AddPet(newPet) + + if err != nil { + t.Errorf("Error while adding pet") + t.Log(err) + } +} + +func TestGetPetById(t *testing.T) { + assert := assert.New(t) + t.Log("Testing TestGetPetById...") + + s := sw.NewPetApi() + resp, err := s.GetPetById(12830) + if err != nil { + t.Errorf("Error while getting pet by id") + t.Log(err) + } else { + assert.Equal(resp.Id, 12830, "Pet id should be equal") + assert.Equal(resp.Name, "gopher", "Pet name should be gopher") + assert.Equal(resp.Status, "pending", "Pet status should be pending") + + t.Log(resp) + } +} + +func TestUpdatePetWithForm(t *testing.T) { + t.Log("Testing UpdatePetWithForm...") + + s := sw.NewPetApi() + err := s.UpdatePetWithForm("12830", "golang", "available") + + if err != nil { + t.Errorf("Error while updating pet by id") + t.Log(err) + } +} diff --git a/samples/client/petstore/go/swagger/Category.go b/samples/client/petstore/go/swagger/Category.go index 0268f62488a..c150c0d2599 100644 --- a/samples/client/petstore/go/swagger/Category.go +++ b/samples/client/petstore/go/swagger/Category.go @@ -5,6 +5,5 @@ import ( type Category struct { Id int64 `json:"id,omitempty"` - Name string `json:"name,omitempty"` - +Name string `json:"name,omitempty"` } diff --git a/samples/client/petstore/go/swagger/Configuration.go b/samples/client/petstore/go/swagger/Configuration.go new file mode 100644 index 00000000000..7535db5e67f --- /dev/null +++ b/samples/client/petstore/go/swagger/Configuration.go @@ -0,0 +1,25 @@ +package swagger + +import ( + +) + +type Configuration struct { + UserName string `json:"userName,omitempty"` + ApiKey string `json:"apiKey,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"` +} + +func NewConfiguration() *Configuration { + return &Configuration{ + BasePath: "http://petstore.swagger.io/v2", + UserName: "", + Debug: false, + } +} \ No newline at end of file diff --git a/samples/client/petstore/go/swagger/ModelReturn.go b/samples/client/petstore/go/swagger/ModelReturn.go new file mode 100644 index 00000000000..daac97e1763 --- /dev/null +++ b/samples/client/petstore/go/swagger/ModelReturn.go @@ -0,0 +1,9 @@ +package swagger + +import ( +) + +type ModelReturn struct { + Return_ int32 `json:"return,omitempty"` + +} diff --git a/samples/client/petstore/go/swagger/Name.go b/samples/client/petstore/go/swagger/Name.go new file mode 100644 index 00000000000..5c0d7bc6d44 --- /dev/null +++ b/samples/client/petstore/go/swagger/Name.go @@ -0,0 +1,9 @@ +package swagger + +import ( +) + +type Name struct { + Name int32 `json:"name,omitempty"` + +} diff --git a/samples/client/petstore/go/swagger/Order.go b/samples/client/petstore/go/swagger/Order.go index 9db0f945110..a5a4852d1dd 100644 --- a/samples/client/petstore/go/swagger/Order.go +++ b/samples/client/petstore/go/swagger/Order.go @@ -6,10 +6,9 @@ import ( type Order struct { Id int64 `json:"id,omitempty"` - PetId int64 `json:"petId,omitempty"` - Quantity int32 `json:"quantity,omitempty"` - ShipDate time.Time `json:"shipDate,omitempty"` - Status string `json:"status,omitempty"` - Complete bool `json:"complete,omitempty"` - +PetId int64 `json:"petId,omitempty"` +Quantity int32 `json:"quantity,omitempty"` +ShipDate time.Time `json:"shipDate,omitempty"` +Status string `json:"status,omitempty"` +Complete bool `json:"complete,omitempty"` } diff --git a/samples/client/petstore/go/swagger/Pet.go b/samples/client/petstore/go/swagger/Pet.go index 7544eed6384..5f1f3c06d51 100644 --- a/samples/client/petstore/go/swagger/Pet.go +++ b/samples/client/petstore/go/swagger/Pet.go @@ -5,10 +5,9 @@ import ( type Pet struct { Id int64 `json:"id,omitempty"` - Category Category `json:"category,omitempty"` - Name string `json:"name,omitempty"` - PhotoUrls []string `json:"photoUrls,omitempty"` - Tags []Tag `json:"tags,omitempty"` - Status string `json:"status,omitempty"` - +Category Category `json:"category,omitempty"` +Name string `json:"name,omitempty"` +PhotoUrls []string `json:"photoUrls,omitempty"` +Tags []Tag `json:"tags,omitempty"` +Status string `json:"status,omitempty"` } diff --git a/samples/client/petstore/go/swagger/PetApi.go b/samples/client/petstore/go/swagger/PetApi.go index 51b32061e0f..41353aac741 100644 --- a/samples/client/petstore/go/swagger/PetApi.go +++ b/samples/client/petstore/go/swagger/PetApi.go @@ -3,68 +3,42 @@ package swagger import ( "strings" "fmt" + "encoding/json" + "errors" "github.com/dghubble/sling" "os" ) type PetApi struct { - basePath string + Configuration Configuration } func NewPetApi() *PetApi{ + configuration := NewConfiguration() return &PetApi { - basePath: "http://petstore.swagger.io/v2", + Configuration: *configuration, } } func NewPetApiWithBasePath(basePath string) *PetApi{ + configuration := NewConfiguration() + configuration.BasePath = basePath + return &PetApi { - basePath: basePath, + Configuration: *configuration, } } -/** - * Update an existing pet - * - * @param Body Pet object that needs to be added to the store - * @return void - */ -//func (a PetApi) UpdatePet (Body Pet) (error) { -func (a PetApi) UpdatePet (Body Pet) (error) { - - _sling := sling.New().Put(a.basePath) - - // create path and map variables - path := "/v2/pet" - - _sling = _sling.Path(path) - - // accept header - accepts := []string { "application/json", "application/xml" } - for key := range accepts { - _sling = _sling.Set("Accept", accepts[key]) - break // only use the first Accept - } - -// body params - _sling = _sling.BodyJSON(Body) - - - - _, err := _sling.ReceiveSuccess(nil) - //fmt.Println("UpdatePet response: void, ", resp, err) - return err -} /** * Add a new pet to the store * - * @param Body Pet object that needs to be added to the store + * @param body Pet object that needs to be added to the store * @return void */ -//func (a PetApi) AddPet (Body Pet) (error) { -func (a PetApi) AddPet (Body Pet) (error) { +//func (a PetApi) AddPet (body Pet) (error) { +func (a PetApi) AddPet (body Pet) (error) { - _sling := sling.New().Post(a.basePath) + _sling := sling.New().Post(a.Configuration.BasePath) // create path and map variables path := "/v2/pet" @@ -72,31 +46,121 @@ func (a PetApi) AddPet (Body Pet) (error) { _sling = _sling.Path(path) // accept header - accepts := []string { "application/json", "application/xml" } + accepts := []string { "application/xml", "application/json" } for key := range accepts { _sling = _sling.Set("Accept", accepts[key]) break // only use the first Accept } // body params - _sling = _sling.BodyJSON(Body) + _sling = _sling.BodyJSON(body) - _, err := _sling.ReceiveSuccess(nil) - //fmt.Println("AddPet response: void, ", resp, err) - return err + // We use this map (below) so that any arbitrary error JSON can be handled. + // FIXME: This is in the absence of this Go generator honoring the non-2xx + // response (error) models, which needs to be implemented at some point. + var failurePayload map[string]interface{} + + httpResponse, err := _sling.Receive(nil, &failurePayload) + + if err == nil { + // err == nil only means that there wasn't a sub-application-layer error (e.g. no network error) + if failurePayload != nil { + // If the failurePayload is present, there likely was some kind of non-2xx status + // returned (and a JSON payload error present) + var str []byte + str, err = json.Marshal(failurePayload) + if err == nil { // For safety, check for an error marshalling... probably superfluous + // This will return the JSON error body as a string + err = errors.New(string(str)) + } + } else { + // So, there was no network-type error, and nothing in the failure payload, + // but we should still check the status code + if httpResponse == nil { + // This should never happen... + err = errors.New("No HTTP Response received.") + } else if code := httpResponse.StatusCode; 200 > code || code > 299 { + err = errors.New("HTTP Error: " + string(httpResponse.StatusCode)) + } + } + } + + return err +} +/** + * Deletes a pet + * + * @param petId Pet id to delete + * @param apiKey + * @return void + */ +//func (a PetApi) DeletePet (petId int64, apiKey string) (error) { +func (a PetApi) DeletePet (petId int64, apiKey string) (error) { + + _sling := sling.New().Delete(a.Configuration.BasePath) + + // create path and map variables + path := "/v2/pet/{petId}" + path = strings.Replace(path, "{" + "petId" + "}", fmt.Sprintf("%v", petId), -1) + + _sling = _sling.Path(path) + + // accept header + accepts := []string { "application/xml", "application/json" } + for key := range accepts { + _sling = _sling.Set("Accept", accepts[key]) + break // only use the first Accept + } + // header params "api_key" + _sling = _sling.Set("api_key", apiKey) + + + + + // We use this map (below) so that any arbitrary error JSON can be handled. + // FIXME: This is in the absence of this Go generator honoring the non-2xx + // response (error) models, which needs to be implemented at some point. + var failurePayload map[string]interface{} + + httpResponse, err := _sling.Receive(nil, &failurePayload) + + if err == nil { + // err == nil only means that there wasn't a sub-application-layer error (e.g. no network error) + if failurePayload != nil { + // If the failurePayload is present, there likely was some kind of non-2xx status + // returned (and a JSON payload error present) + var str []byte + str, err = json.Marshal(failurePayload) + if err == nil { // For safety, check for an error marshalling... probably superfluous + // This will return the JSON error body as a string + err = errors.New(string(str)) + } + } else { + // So, there was no network-type error, and nothing in the failure payload, + // but we should still check the status code + if httpResponse == nil { + // This should never happen... + err = errors.New("No HTTP Response received.") + } else if code := httpResponse.StatusCode; 200 > code || code > 299 { + err = errors.New("HTTP Error: " + string(httpResponse.StatusCode)) + } + } + } + + return err } /** * Finds Pets by status - * Multiple status values can be provided with comma seperated strings - * @param Status Status values that need to be considered for filter + * Multiple status values can be provided with comma separated strings + * @param status Status values that need to be considered for filter * @return []Pet */ -//func (a PetApi) FindPetsByStatus (Status []string) ([]Pet, error) { -func (a PetApi) FindPetsByStatus (Status []string) ([]Pet, error) { +//func (a PetApi) FindPetsByStatus (status []string) ([]Pet, error) { +func (a PetApi) FindPetsByStatus (status []string) ([]Pet, error) { - _sling := sling.New().Get(a.basePath) + _sling := sling.New().Get(a.Configuration.BasePath) // create path and map variables path := "/v2/pet/findByStatus" @@ -104,34 +168,61 @@ func (a PetApi) FindPetsByStatus (Status []string) ([]Pet, error) { _sling = _sling.Path(path) type QueryParams struct { - Status []string `url:"status,omitempty"` - + status []string `url:"status,omitempty"` } - _sling = _sling.QueryStruct(&QueryParams{ Status: Status }) + _sling = _sling.QueryStruct(&QueryParams{ status: status }) // accept header - accepts := []string { "application/json", "application/xml" } + accepts := []string { "application/xml", "application/json" } for key := range accepts { _sling = _sling.Set("Accept", accepts[key]) break // only use the first Accept } + var successPayload = new([]Pet) - response := new([]Pet) - _, err := _sling.ReceiveSuccess(response) - //fmt.Println("FindPetsByStatus response: ", response, resp, err) - return *response, err + // We use this map (below) so that any arbitrary error JSON can be handled. + // FIXME: This is in the absence of this Go generator honoring the non-2xx + // response (error) models, which needs to be implemented at some point. + var failurePayload map[string]interface{} + + httpResponse, err := _sling.Receive(successPayload, &failurePayload) + + if err == nil { + // err == nil only means that there wasn't a sub-application-layer error (e.g. no network error) + if failurePayload != nil { + // If the failurePayload is present, there likely was some kind of non-2xx status + // returned (and a JSON payload error present) + var str []byte + str, err = json.Marshal(failurePayload) + if err == nil { // For safety, check for an error marshalling... probably superfluous + // This will return the JSON error body as a string + err = errors.New(string(str)) + } + } else { + // So, there was no network-type error, and nothing in the failure payload, + // but we should still check the status code + if httpResponse == nil { + // This should never happen... + err = errors.New("No HTTP Response received.") + } else if code := httpResponse.StatusCode; 200 > code || code > 299 { + err = errors.New("HTTP Error: " + string(httpResponse.StatusCode)) + } + } + } + + return *successPayload, err } /** * Finds Pets by tags - * Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. - * @param Tags Tags to filter by + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * @param tags Tags to filter by * @return []Pet */ -//func (a PetApi) FindPetsByTags (Tags []string) ([]Pet, error) { -func (a PetApi) FindPetsByTags (Tags []string) ([]Pet, error) { +//func (a PetApi) FindPetsByTags (tags []string) ([]Pet, error) { +func (a PetApi) FindPetsByTags (tags []string) ([]Pet, error) { - _sling := sling.New().Get(a.basePath) + _sling := sling.New().Get(a.Configuration.BasePath) // create path and map variables path := "/v2/pet/findByTags" @@ -139,191 +230,299 @@ func (a PetApi) FindPetsByTags (Tags []string) ([]Pet, error) { _sling = _sling.Path(path) type QueryParams struct { - Tags []string `url:"tags,omitempty"` - + tags []string `url:"tags,omitempty"` } - _sling = _sling.QueryStruct(&QueryParams{ Tags: Tags }) + _sling = _sling.QueryStruct(&QueryParams{ tags: tags }) // accept header - accepts := []string { "application/json", "application/xml" } + accepts := []string { "application/xml", "application/json" } for key := range accepts { _sling = _sling.Set("Accept", accepts[key]) break // only use the first Accept } + var successPayload = new([]Pet) - response := new([]Pet) - _, err := _sling.ReceiveSuccess(response) - //fmt.Println("FindPetsByTags response: ", response, resp, err) - return *response, err + // We use this map (below) so that any arbitrary error JSON can be handled. + // FIXME: This is in the absence of this Go generator honoring the non-2xx + // response (error) models, which needs to be implemented at some point. + var failurePayload map[string]interface{} + + httpResponse, err := _sling.Receive(successPayload, &failurePayload) + + if err == nil { + // err == nil only means that there wasn't a sub-application-layer error (e.g. no network error) + if failurePayload != nil { + // If the failurePayload is present, there likely was some kind of non-2xx status + // returned (and a JSON payload error present) + var str []byte + str, err = json.Marshal(failurePayload) + if err == nil { // For safety, check for an error marshalling... probably superfluous + // This will return the JSON error body as a string + err = errors.New(string(str)) + } + } else { + // So, there was no network-type error, and nothing in the failure payload, + // but we should still check the status code + if httpResponse == nil { + // This should never happen... + err = errors.New("No HTTP Response received.") + } else if code := httpResponse.StatusCode; 200 > code || code > 299 { + err = errors.New("HTTP Error: " + string(httpResponse.StatusCode)) + } + } + } + + return *successPayload, err } /** * Find pet by ID - * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions - * @param PetId ID of pet that needs to be fetched + * Returns a single pet + * @param petId ID of pet to return * @return Pet */ -//func (a PetApi) GetPetById (PetId int64) (Pet, error) { -func (a PetApi) GetPetById (PetId int64) (Pet, error) { +//func (a PetApi) GetPetById (petId int64) (Pet, error) { +func (a PetApi) GetPetById (petId int64) (Pet, error) { - _sling := sling.New().Get(a.basePath) + _sling := sling.New().Get(a.Configuration.BasePath) // create path and map variables path := "/v2/pet/{petId}" - path = strings.Replace(path, "{" + "petId" + "}", fmt.Sprintf("%v", PetId), -1) + path = strings.Replace(path, "{" + "petId" + "}", fmt.Sprintf("%v", petId), -1) _sling = _sling.Path(path) // accept header - accepts := []string { "application/json", "application/xml" } + accepts := []string { "application/xml", "application/json" } for key := range accepts { _sling = _sling.Set("Accept", accepts[key]) break // only use the first Accept } + var successPayload = new(Pet) - response := new(Pet) - _, err := _sling.ReceiveSuccess(response) - //fmt.Println("GetPetById response: ", response, resp, err) - return *response, err + // We use this map (below) so that any arbitrary error JSON can be handled. + // FIXME: This is in the absence of this Go generator honoring the non-2xx + // response (error) models, which needs to be implemented at some point. + var failurePayload map[string]interface{} + + httpResponse, err := _sling.Receive(successPayload, &failurePayload) + + if err == nil { + // err == nil only means that there wasn't a sub-application-layer error (e.g. no network error) + if failurePayload != nil { + // If the failurePayload is present, there likely was some kind of non-2xx status + // returned (and a JSON payload error present) + var str []byte + str, err = json.Marshal(failurePayload) + if err == nil { // For safety, check for an error marshalling... probably superfluous + // This will return the JSON error body as a string + err = errors.New(string(str)) + } + } else { + // So, there was no network-type error, and nothing in the failure payload, + // but we should still check the status code + if httpResponse == nil { + // This should never happen... + err = errors.New("No HTTP Response received.") + } else if code := httpResponse.StatusCode; 200 > code || code > 299 { + err = errors.New("HTTP Error: " + string(httpResponse.StatusCode)) + } + } + } + + return *successPayload, err +} +/** + * Update an existing pet + * + * @param body Pet object that needs to be added to the store + * @return void + */ +//func (a PetApi) UpdatePet (body Pet) (error) { +func (a PetApi) UpdatePet (body Pet) (error) { + + _sling := sling.New().Put(a.Configuration.BasePath) + + // create path and map variables + path := "/v2/pet" + + _sling = _sling.Path(path) + + // accept header + accepts := []string { "application/xml", "application/json" } + for key := range accepts { + _sling = _sling.Set("Accept", accepts[key]) + break // only use the first Accept + } + +// body params + _sling = _sling.BodyJSON(body) + + + + // We use this map (below) so that any arbitrary error JSON can be handled. + // FIXME: This is in the absence of this Go generator honoring the non-2xx + // response (error) models, which needs to be implemented at some point. + var failurePayload map[string]interface{} + + httpResponse, err := _sling.Receive(nil, &failurePayload) + + if err == nil { + // err == nil only means that there wasn't a sub-application-layer error (e.g. no network error) + if failurePayload != nil { + // If the failurePayload is present, there likely was some kind of non-2xx status + // returned (and a JSON payload error present) + var str []byte + str, err = json.Marshal(failurePayload) + if err == nil { // For safety, check for an error marshalling... probably superfluous + // This will return the JSON error body as a string + err = errors.New(string(str)) + } + } else { + // So, there was no network-type error, and nothing in the failure payload, + // but we should still check the status code + if httpResponse == nil { + // This should never happen... + err = errors.New("No HTTP Response received.") + } else if code := httpResponse.StatusCode; 200 > code || code > 299 { + err = errors.New("HTTP Error: " + string(httpResponse.StatusCode)) + } + } + } + + return err } /** * Updates a pet in the store with form data * - * @param PetId ID of pet that needs to be updated - * @param Name Updated name of the pet - * @param Status Updated status of the pet + * @param petId ID of pet that needs to be updated + * @param name Updated name of the pet + * @param status Updated status of the pet * @return void */ -//func (a PetApi) UpdatePetWithForm (PetId string, Name string, Status string) (error) { -func (a PetApi) UpdatePetWithForm (PetId string, Name string, Status string) (error) { +//func (a PetApi) UpdatePetWithForm (petId int64, name string, status string) (error) { +func (a PetApi) UpdatePetWithForm (petId int64, name string, status string) (error) { - _sling := sling.New().Post(a.basePath) + _sling := sling.New().Post(a.Configuration.BasePath) // create path and map variables path := "/v2/pet/{petId}" - path = strings.Replace(path, "{" + "petId" + "}", fmt.Sprintf("%v", PetId), -1) + path = strings.Replace(path, "{" + "petId" + "}", fmt.Sprintf("%v", petId), -1) _sling = _sling.Path(path) // accept header - accepts := []string { "application/json", "application/xml" } + accepts := []string { "application/xml", "application/json" } for key := range accepts { _sling = _sling.Set("Accept", accepts[key]) break // only use the first Accept } type FormParams struct { - Name string `url:"name,omitempty"` - Status string `url:"status,omitempty"` + name string `url:"name,omitempty"` + status string `url:"status,omitempty"` } - _sling = _sling.BodyForm(&FormParams{ Name: Name,Status: Status }) + _sling = _sling.BodyForm(&FormParams{ name: name,status: status }) - _, err := _sling.ReceiveSuccess(nil) - //fmt.Println("UpdatePetWithForm response: void, ", resp, err) - return err -} -/** - * Deletes a pet - * - * @param PetId Pet id to delete - * @param ApiKey - * @return void - */ -//func (a PetApi) DeletePet (PetId int64, ApiKey string) (error) { -func (a PetApi) DeletePet (PetId int64, ApiKey string) (error) { + // We use this map (below) so that any arbitrary error JSON can be handled. + // FIXME: This is in the absence of this Go generator honoring the non-2xx + // response (error) models, which needs to be implemented at some point. + var failurePayload map[string]interface{} - _sling := sling.New().Delete(a.basePath) + httpResponse, err := _sling.Receive(nil, &failurePayload) - // create path and map variables - path := "/v2/pet/{petId}" - path = strings.Replace(path, "{" + "petId" + "}", fmt.Sprintf("%v", PetId), -1) - - _sling = _sling.Path(path) - - // accept header - accepts := []string { "application/json", "application/xml" } - for key := range accepts { - _sling = _sling.Set("Accept", accepts[key]) - break // only use the first Accept + if err == nil { + // err == nil only means that there wasn't a sub-application-layer error (e.g. no network error) + if failurePayload != nil { + // If the failurePayload is present, there likely was some kind of non-2xx status + // returned (and a JSON payload error present) + var str []byte + str, err = json.Marshal(failurePayload) + if err == nil { // For safety, check for an error marshalling... probably superfluous + // This will return the JSON error body as a string + err = errors.New(string(str)) + } + } else { + // So, there was no network-type error, and nothing in the failure payload, + // but we should still check the status code + if httpResponse == nil { + // This should never happen... + err = errors.New("No HTTP Response received.") + } else if code := httpResponse.StatusCode; 200 > code || code > 299 { + err = errors.New("HTTP Error: " + string(httpResponse.StatusCode)) + } } - // header params "api_key" - _sling = _sling.Set("api_key", ApiKey) + } - - - - _, err := _sling.ReceiveSuccess(nil) - //fmt.Println("DeletePet response: void, ", resp, err) - return err -} -/** - * downloads an image - * - * @return *os.File - */ -//func (a PetApi) DownloadFile () (*os.File, error) { -func (a PetApi) DownloadFile () (*os.File, error) { - - _sling := sling.New().Get(a.basePath) - - // create path and map variables - path := "/v2/pet/{petId}/downloadImage" - - _sling = _sling.Path(path) - - // accept header - accepts := []string { "application/octet-stream" } - for key := range accepts { - _sling = _sling.Set("Accept", accepts[key]) - break // only use the first Accept - } - - - - response := new(*os.File) - _, err := _sling.ReceiveSuccess(response) - //fmt.Println("DownloadFile response: ", response, resp, err) - return *response, err + return err } /** * uploads an image * - * @param PetId ID of pet to update - * @param AdditionalMetadata Additional data to pass to server - * @param File file to upload - * @return void + * @param petId ID of pet to update + * @param additionalMetadata Additional data to pass to server + * @param file file to upload + * @return ApiResponse */ -//func (a PetApi) UploadFile (PetId int64, AdditionalMetadata string, File *os.File) (error) { -func (a PetApi) UploadFile (PetId int64, AdditionalMetadata string, File *os.File) (error) { +//func (a PetApi) UploadFile (petId int64, additionalMetadata string, file *os.File) (ApiResponse, error) { +func (a PetApi) UploadFile (petId int64, additionalMetadata string, file *os.File) (ApiResponse, error) { - _sling := sling.New().Post(a.basePath) + _sling := sling.New().Post(a.Configuration.BasePath) // create path and map variables path := "/v2/pet/{petId}/uploadImage" - path = strings.Replace(path, "{" + "petId" + "}", fmt.Sprintf("%v", PetId), -1) + path = strings.Replace(path, "{" + "petId" + "}", fmt.Sprintf("%v", petId), -1) _sling = _sling.Path(path) // accept header - accepts := []string { "application/json", "application/xml" } + accepts := []string { "application/json" } for key := range accepts { _sling = _sling.Set("Accept", accepts[key]) break // only use the first Accept } type FormParams struct { - AdditionalMetadata string `url:"additionalMetadata,omitempty"` - File *os.File `url:"file,omitempty"` + additionalMetadata string `url:"additionalMetadata,omitempty"` + file *os.File `url:"file,omitempty"` } - _sling = _sling.BodyForm(&FormParams{ AdditionalMetadata: AdditionalMetadata,File: File }) + _sling = _sling.BodyForm(&FormParams{ additionalMetadata: additionalMetadata,file: file }) + var successPayload = new(ApiResponse) + // We use this map (below) so that any arbitrary error JSON can be handled. + // FIXME: This is in the absence of this Go generator honoring the non-2xx + // response (error) models, which needs to be implemented at some point. + var failurePayload map[string]interface{} - _, err := _sling.ReceiveSuccess(nil) - //fmt.Println("UploadFile response: void, ", resp, err) - return err + httpResponse, err := _sling.Receive(successPayload, &failurePayload) + + if err == nil { + // err == nil only means that there wasn't a sub-application-layer error (e.g. no network error) + if failurePayload != nil { + // If the failurePayload is present, there likely was some kind of non-2xx status + // returned (and a JSON payload error present) + var str []byte + str, err = json.Marshal(failurePayload) + if err == nil { // For safety, check for an error marshalling... probably superfluous + // This will return the JSON error body as a string + err = errors.New(string(str)) + } + } else { + // So, there was no network-type error, and nothing in the failure payload, + // but we should still check the status code + if httpResponse == nil { + // This should never happen... + err = errors.New("No HTTP Response received.") + } else if code := httpResponse.StatusCode; 200 > code || code > 299 { + err = errors.New("HTTP Error: " + string(httpResponse.StatusCode)) + } + } + } + + return *successPayload, err } diff --git a/samples/client/petstore/go/swagger/StoreApi.go b/samples/client/petstore/go/swagger/StoreApi.go index c43d320077c..8d3e41e71e1 100644 --- a/samples/client/petstore/go/swagger/StoreApi.go +++ b/samples/client/petstore/go/swagger/StoreApi.go @@ -3,25 +3,90 @@ package swagger import ( "strings" "fmt" + "encoding/json" + "errors" "github.com/dghubble/sling" ) type StoreApi struct { - basePath string + Configuration Configuration } func NewStoreApi() *StoreApi{ + configuration := NewConfiguration() return &StoreApi { - basePath: "http://petstore.swagger.io/v2", + Configuration: *configuration, } } func NewStoreApiWithBasePath(basePath string) *StoreApi{ + configuration := NewConfiguration() + configuration.BasePath = basePath + return &StoreApi { - basePath: basePath, + Configuration: *configuration, } } +/** + * Delete purchase order by ID + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * @param orderId ID of the order that needs to be deleted + * @return void + */ +//func (a StoreApi) DeleteOrder (orderId string) (error) { +func (a StoreApi) DeleteOrder (orderId string) (error) { + + _sling := sling.New().Delete(a.Configuration.BasePath) + + // create path and map variables + path := "/v2/store/order/{orderId}" + path = strings.Replace(path, "{" + "orderId" + "}", fmt.Sprintf("%v", orderId), -1) + + _sling = _sling.Path(path) + + // accept header + accepts := []string { "application/xml", "application/json" } + for key := range accepts { + _sling = _sling.Set("Accept", accepts[key]) + break // only use the first Accept + } + + + + + // We use this map (below) so that any arbitrary error JSON can be handled. + // FIXME: This is in the absence of this Go generator honoring the non-2xx + // response (error) models, which needs to be implemented at some point. + var failurePayload map[string]interface{} + + httpResponse, err := _sling.Receive(nil, &failurePayload) + + if err == nil { + // err == nil only means that there wasn't a sub-application-layer error (e.g. no network error) + if failurePayload != nil { + // If the failurePayload is present, there likely was some kind of non-2xx status + // returned (and a JSON payload error present) + var str []byte + str, err = json.Marshal(failurePayload) + if err == nil { // For safety, check for an error marshalling... probably superfluous + // This will return the JSON error body as a string + err = errors.New(string(str)) + } + } else { + // So, there was no network-type error, and nothing in the failure payload, + // but we should still check the status code + if httpResponse == nil { + // This should never happen... + err = errors.New("No HTTP Response received.") + } else if code := httpResponse.StatusCode; 200 > code || code > 299 { + err = errors.New("HTTP Error: " + string(httpResponse.StatusCode)) + } + } + } + + return err +} /** * Returns pet inventories by status * Returns a map of status codes to quantities @@ -30,7 +95,7 @@ func NewStoreApiWithBasePath(basePath string) *StoreApi{ //func (a StoreApi) GetInventory () (map[string]int32, error) { func (a StoreApi) GetInventory () (map[string]int32, error) { - _sling := sling.New().Get(a.basePath) + _sling := sling.New().Get(a.Configuration.BasePath) // create path and map variables path := "/v2/store/inventory" @@ -38,29 +103,116 @@ func (a StoreApi) GetInventory () (map[string]int32, error) { _sling = _sling.Path(path) // accept header - accepts := []string { "application/json", "application/xml" } + accepts := []string { "application/json" } for key := range accepts { _sling = _sling.Set("Accept", accepts[key]) break // only use the first Accept } + var successPayload = new(map[string]int32) - response := new(map[string]int32) - _, err := _sling.ReceiveSuccess(response) - //fmt.Println("GetInventory response: ", response, resp, err) - return *response, err + // We use this map (below) so that any arbitrary error JSON can be handled. + // FIXME: This is in the absence of this Go generator honoring the non-2xx + // response (error) models, which needs to be implemented at some point. + var failurePayload map[string]interface{} + + httpResponse, err := _sling.Receive(successPayload, &failurePayload) + + if err == nil { + // err == nil only means that there wasn't a sub-application-layer error (e.g. no network error) + if failurePayload != nil { + // If the failurePayload is present, there likely was some kind of non-2xx status + // returned (and a JSON payload error present) + var str []byte + str, err = json.Marshal(failurePayload) + if err == nil { // For safety, check for an error marshalling... probably superfluous + // This will return the JSON error body as a string + err = errors.New(string(str)) + } + } else { + // So, there was no network-type error, and nothing in the failure payload, + // but we should still check the status code + if httpResponse == nil { + // This should never happen... + err = errors.New("No HTTP Response received.") + } else if code := httpResponse.StatusCode; 200 > code || code > 299 { + err = errors.New("HTTP Error: " + string(httpResponse.StatusCode)) + } + } + } + + return *successPayload, err +} +/** + * Find purchase order by ID + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * @param orderId ID of pet that needs to be fetched + * @return Order + */ +//func (a StoreApi) GetOrderById (orderId int64) (Order, error) { +func (a StoreApi) GetOrderById (orderId int64) (Order, error) { + + _sling := sling.New().Get(a.Configuration.BasePath) + + // create path and map variables + path := "/v2/store/order/{orderId}" + path = strings.Replace(path, "{" + "orderId" + "}", fmt.Sprintf("%v", orderId), -1) + + _sling = _sling.Path(path) + + // accept header + accepts := []string { "application/xml", "application/json" } + for key := range accepts { + _sling = _sling.Set("Accept", accepts[key]) + break // only use the first Accept + } + + + var successPayload = new(Order) + + // We use this map (below) so that any arbitrary error JSON can be handled. + // FIXME: This is in the absence of this Go generator honoring the non-2xx + // response (error) models, which needs to be implemented at some point. + var failurePayload map[string]interface{} + + httpResponse, err := _sling.Receive(successPayload, &failurePayload) + + if err == nil { + // err == nil only means that there wasn't a sub-application-layer error (e.g. no network error) + if failurePayload != nil { + // If the failurePayload is present, there likely was some kind of non-2xx status + // returned (and a JSON payload error present) + var str []byte + str, err = json.Marshal(failurePayload) + if err == nil { // For safety, check for an error marshalling... probably superfluous + // This will return the JSON error body as a string + err = errors.New(string(str)) + } + } else { + // So, there was no network-type error, and nothing in the failure payload, + // but we should still check the status code + if httpResponse == nil { + // This should never happen... + err = errors.New("No HTTP Response received.") + } else if code := httpResponse.StatusCode; 200 > code || code > 299 { + err = errors.New("HTTP Error: " + string(httpResponse.StatusCode)) + } + } + } + + return *successPayload, err } /** * Place an order for a pet * - * @param Body order placed for purchasing the pet + * @param body order placed for purchasing the pet * @return Order */ -//func (a StoreApi) PlaceOrder (Body Order) (Order, error) { -func (a StoreApi) PlaceOrder (Body Order) (Order, error) { +//func (a StoreApi) PlaceOrder (body Order) (Order, error) { +func (a StoreApi) PlaceOrder (body Order) (Order, error) { - _sling := sling.New().Post(a.basePath) + _sling := sling.New().Post(a.Configuration.BasePath) // create path and map variables path := "/v2/store/order" @@ -68,80 +220,46 @@ func (a StoreApi) PlaceOrder (Body Order) (Order, error) { _sling = _sling.Path(path) // accept header - accepts := []string { "application/json", "application/xml" } + accepts := []string { "application/xml", "application/json" } for key := range accepts { _sling = _sling.Set("Accept", accepts[key]) break // only use the first Accept } // body params - _sling = _sling.BodyJSON(Body) + _sling = _sling.BodyJSON(body) + var successPayload = new(Order) - response := new(Order) - _, err := _sling.ReceiveSuccess(response) - //fmt.Println("PlaceOrder response: ", response, resp, err) - return *response, err -} -/** - * Find purchase order by ID - * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - * @param OrderId ID of pet that needs to be fetched - * @return Order - */ -//func (a StoreApi) GetOrderById (OrderId string) (Order, error) { -func (a StoreApi) GetOrderById (OrderId string) (Order, error) { + // We use this map (below) so that any arbitrary error JSON can be handled. + // FIXME: This is in the absence of this Go generator honoring the non-2xx + // response (error) models, which needs to be implemented at some point. + var failurePayload map[string]interface{} - _sling := sling.New().Get(a.basePath) + httpResponse, err := _sling.Receive(successPayload, &failurePayload) - // create path and map variables - path := "/v2/store/order/{orderId}" - path = strings.Replace(path, "{" + "orderId" + "}", fmt.Sprintf("%v", OrderId), -1) - - _sling = _sling.Path(path) - - // accept header - accepts := []string { "application/json", "application/xml" } - for key := range accepts { - _sling = _sling.Set("Accept", accepts[key]) - break // only use the first Accept + if err == nil { + // err == nil only means that there wasn't a sub-application-layer error (e.g. no network error) + if failurePayload != nil { + // If the failurePayload is present, there likely was some kind of non-2xx status + // returned (and a JSON payload error present) + var str []byte + str, err = json.Marshal(failurePayload) + if err == nil { // For safety, check for an error marshalling... probably superfluous + // This will return the JSON error body as a string + err = errors.New(string(str)) + } + } else { + // So, there was no network-type error, and nothing in the failure payload, + // but we should still check the status code + if httpResponse == nil { + // This should never happen... + err = errors.New("No HTTP Response received.") + } else if code := httpResponse.StatusCode; 200 > code || code > 299 { + err = errors.New("HTTP Error: " + string(httpResponse.StatusCode)) + } } + } - - - response := new(Order) - _, err := _sling.ReceiveSuccess(response) - //fmt.Println("GetOrderById response: ", response, resp, err) - return *response, err -} -/** - * Delete purchase order by ID - * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors - * @param OrderId ID of the order that needs to be deleted - * @return void - */ -//func (a StoreApi) DeleteOrder (OrderId string) (error) { -func (a StoreApi) DeleteOrder (OrderId string) (error) { - - _sling := sling.New().Delete(a.basePath) - - // create path and map variables - path := "/v2/store/order/{orderId}" - path = strings.Replace(path, "{" + "orderId" + "}", fmt.Sprintf("%v", OrderId), -1) - - _sling = _sling.Path(path) - - // accept header - accepts := []string { "application/json", "application/xml" } - for key := range accepts { - _sling = _sling.Set("Accept", accepts[key]) - break // only use the first Accept - } - - - - - _, err := _sling.ReceiveSuccess(nil) - //fmt.Println("DeleteOrder response: void, ", resp, err) - return err + return *successPayload, err } diff --git a/samples/client/petstore/go/swagger/Tag.go b/samples/client/petstore/go/swagger/Tag.go index 6b505272a15..bb27c61b39c 100644 --- a/samples/client/petstore/go/swagger/Tag.go +++ b/samples/client/petstore/go/swagger/Tag.go @@ -5,6 +5,5 @@ import ( type Tag struct { Id int64 `json:"id,omitempty"` - Name string `json:"name,omitempty"` - +Name string `json:"name,omitempty"` } diff --git a/samples/client/petstore/go/swagger/User.go b/samples/client/petstore/go/swagger/User.go index e7f26d1d10c..e34ad81ec8c 100644 --- a/samples/client/petstore/go/swagger/User.go +++ b/samples/client/petstore/go/swagger/User.go @@ -5,12 +5,11 @@ import ( type User struct { Id int64 `json:"id,omitempty"` - Username string `json:"username,omitempty"` - FirstName string `json:"firstName,omitempty"` - LastName string `json:"lastName,omitempty"` - Email string `json:"email,omitempty"` - Password string `json:"password,omitempty"` - Phone string `json:"phone,omitempty"` - UserStatus int32 `json:"userStatus,omitempty"` - +Username string `json:"username,omitempty"` +FirstName string `json:"firstName,omitempty"` +LastName string `json:"lastName,omitempty"` +Email string `json:"email,omitempty"` +Password string `json:"password,omitempty"` +Phone string `json:"phone,omitempty"` +UserStatus int32 `json:"userStatus,omitempty"` } diff --git a/samples/client/petstore/go/swagger/UserApi.go b/samples/client/petstore/go/swagger/UserApi.go index 9907453bd39..f8c8581aa3b 100644 --- a/samples/client/petstore/go/swagger/UserApi.go +++ b/samples/client/petstore/go/swagger/UserApi.go @@ -3,35 +3,41 @@ package swagger import ( "strings" "fmt" + "encoding/json" + "errors" "github.com/dghubble/sling" ) type UserApi struct { - basePath string + Configuration Configuration } func NewUserApi() *UserApi{ + configuration := NewConfiguration() return &UserApi { - basePath: "http://petstore.swagger.io/v2", + Configuration: *configuration, } } func NewUserApiWithBasePath(basePath string) *UserApi{ + configuration := NewConfiguration() + configuration.BasePath = basePath + return &UserApi { - basePath: basePath, + Configuration: *configuration, } } /** * Create user * This can only be done by the logged in user. - * @param Body Created user object + * @param body Created user object * @return void */ -//func (a UserApi) CreateUser (Body User) (error) { -func (a UserApi) CreateUser (Body User) (error) { +//func (a UserApi) CreateUser (body User) (error) { +func (a UserApi) CreateUser (body User) (error) { - _sling := sling.New().Post(a.basePath) + _sling := sling.New().Post(a.Configuration.BasePath) // create path and map variables path := "/v2/user" @@ -39,31 +45,59 @@ func (a UserApi) CreateUser (Body User) (error) { _sling = _sling.Path(path) // accept header - accepts := []string { "application/json", "application/xml" } + accepts := []string { "application/xml", "application/json" } for key := range accepts { _sling = _sling.Set("Accept", accepts[key]) break // only use the first Accept } // body params - _sling = _sling.BodyJSON(Body) + _sling = _sling.BodyJSON(body) - _, err := _sling.ReceiveSuccess(nil) - //fmt.Println("CreateUser response: void, ", resp, err) - return err + // We use this map (below) so that any arbitrary error JSON can be handled. + // FIXME: This is in the absence of this Go generator honoring the non-2xx + // response (error) models, which needs to be implemented at some point. + var failurePayload map[string]interface{} + + httpResponse, err := _sling.Receive(nil, &failurePayload) + + if err == nil { + // err == nil only means that there wasn't a sub-application-layer error (e.g. no network error) + if failurePayload != nil { + // If the failurePayload is present, there likely was some kind of non-2xx status + // returned (and a JSON payload error present) + var str []byte + str, err = json.Marshal(failurePayload) + if err == nil { // For safety, check for an error marshalling... probably superfluous + // This will return the JSON error body as a string + err = errors.New(string(str)) + } + } else { + // So, there was no network-type error, and nothing in the failure payload, + // but we should still check the status code + if httpResponse == nil { + // This should never happen... + err = errors.New("No HTTP Response received.") + } else if code := httpResponse.StatusCode; 200 > code || code > 299 { + err = errors.New("HTTP Error: " + string(httpResponse.StatusCode)) + } + } + } + + return err } /** * Creates list of users with given input array * - * @param Body List of user object + * @param body List of user object * @return void */ -//func (a UserApi) CreateUsersWithArrayInput (Body []User) (error) { -func (a UserApi) CreateUsersWithArrayInput (Body []User) (error) { +//func (a UserApi) CreateUsersWithArrayInput (body []User) (error) { +func (a UserApi) CreateUsersWithArrayInput (body []User) (error) { - _sling := sling.New().Post(a.basePath) + _sling := sling.New().Post(a.Configuration.BasePath) // create path and map variables path := "/v2/user/createWithArray" @@ -71,31 +105,59 @@ func (a UserApi) CreateUsersWithArrayInput (Body []User) (error) { _sling = _sling.Path(path) // accept header - accepts := []string { "application/json", "application/xml" } + accepts := []string { "application/xml", "application/json" } for key := range accepts { _sling = _sling.Set("Accept", accepts[key]) break // only use the first Accept } // body params - _sling = _sling.BodyJSON(Body) + _sling = _sling.BodyJSON(body) - _, err := _sling.ReceiveSuccess(nil) - //fmt.Println("CreateUsersWithArrayInput response: void, ", resp, err) - return err + // We use this map (below) so that any arbitrary error JSON can be handled. + // FIXME: This is in the absence of this Go generator honoring the non-2xx + // response (error) models, which needs to be implemented at some point. + var failurePayload map[string]interface{} + + httpResponse, err := _sling.Receive(nil, &failurePayload) + + if err == nil { + // err == nil only means that there wasn't a sub-application-layer error (e.g. no network error) + if failurePayload != nil { + // If the failurePayload is present, there likely was some kind of non-2xx status + // returned (and a JSON payload error present) + var str []byte + str, err = json.Marshal(failurePayload) + if err == nil { // For safety, check for an error marshalling... probably superfluous + // This will return the JSON error body as a string + err = errors.New(string(str)) + } + } else { + // So, there was no network-type error, and nothing in the failure payload, + // but we should still check the status code + if httpResponse == nil { + // This should never happen... + err = errors.New("No HTTP Response received.") + } else if code := httpResponse.StatusCode; 200 > code || code > 299 { + err = errors.New("HTTP Error: " + string(httpResponse.StatusCode)) + } + } + } + + return err } /** * Creates list of users with given input array * - * @param Body List of user object + * @param body List of user object * @return void */ -//func (a UserApi) CreateUsersWithListInput (Body []User) (error) { -func (a UserApi) CreateUsersWithListInput (Body []User) (error) { +//func (a UserApi) CreateUsersWithListInput (body []User) (error) { +func (a UserApi) CreateUsersWithListInput (body []User) (error) { - _sling := sling.New().Post(a.basePath) + _sling := sling.New().Post(a.Configuration.BasePath) // create path and map variables path := "/v2/user/createWithList" @@ -103,32 +165,178 @@ func (a UserApi) CreateUsersWithListInput (Body []User) (error) { _sling = _sling.Path(path) // accept header - accepts := []string { "application/json", "application/xml" } + accepts := []string { "application/xml", "application/json" } for key := range accepts { _sling = _sling.Set("Accept", accepts[key]) break // only use the first Accept } // body params - _sling = _sling.BodyJSON(Body) + _sling = _sling.BodyJSON(body) - _, err := _sling.ReceiveSuccess(nil) - //fmt.Println("CreateUsersWithListInput response: void, ", resp, err) - return err + // We use this map (below) so that any arbitrary error JSON can be handled. + // FIXME: This is in the absence of this Go generator honoring the non-2xx + // response (error) models, which needs to be implemented at some point. + var failurePayload map[string]interface{} + + httpResponse, err := _sling.Receive(nil, &failurePayload) + + if err == nil { + // err == nil only means that there wasn't a sub-application-layer error (e.g. no network error) + if failurePayload != nil { + // If the failurePayload is present, there likely was some kind of non-2xx status + // returned (and a JSON payload error present) + var str []byte + str, err = json.Marshal(failurePayload) + if err == nil { // For safety, check for an error marshalling... probably superfluous + // This will return the JSON error body as a string + err = errors.New(string(str)) + } + } else { + // So, there was no network-type error, and nothing in the failure payload, + // but we should still check the status code + if httpResponse == nil { + // This should never happen... + err = errors.New("No HTTP Response received.") + } else if code := httpResponse.StatusCode; 200 > code || code > 299 { + err = errors.New("HTTP Error: " + string(httpResponse.StatusCode)) + } + } + } + + return err +} +/** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted + * @return void + */ +//func (a UserApi) DeleteUser (username string) (error) { +func (a UserApi) DeleteUser (username string) (error) { + + _sling := sling.New().Delete(a.Configuration.BasePath) + + // create path and map variables + path := "/v2/user/{username}" + path = strings.Replace(path, "{" + "username" + "}", fmt.Sprintf("%v", username), -1) + + _sling = _sling.Path(path) + + // accept header + accepts := []string { "application/xml", "application/json" } + for key := range accepts { + _sling = _sling.Set("Accept", accepts[key]) + break // only use the first Accept + } + + + + + // We use this map (below) so that any arbitrary error JSON can be handled. + // FIXME: This is in the absence of this Go generator honoring the non-2xx + // response (error) models, which needs to be implemented at some point. + var failurePayload map[string]interface{} + + httpResponse, err := _sling.Receive(nil, &failurePayload) + + if err == nil { + // err == nil only means that there wasn't a sub-application-layer error (e.g. no network error) + if failurePayload != nil { + // If the failurePayload is present, there likely was some kind of non-2xx status + // returned (and a JSON payload error present) + var str []byte + str, err = json.Marshal(failurePayload) + if err == nil { // For safety, check for an error marshalling... probably superfluous + // This will return the JSON error body as a string + err = errors.New(string(str)) + } + } else { + // So, there was no network-type error, and nothing in the failure payload, + // but we should still check the status code + if httpResponse == nil { + // This should never happen... + err = errors.New("No HTTP Response received.") + } else if code := httpResponse.StatusCode; 200 > code || code > 299 { + err = errors.New("HTTP Error: " + string(httpResponse.StatusCode)) + } + } + } + + return err +} +/** + * Get user by user name + * + * @param username The name that needs to be fetched. Use user1 for testing. + * @return User + */ +//func (a UserApi) GetUserByName (username string) (User, error) { +func (a UserApi) GetUserByName (username string) (User, error) { + + _sling := sling.New().Get(a.Configuration.BasePath) + + // create path and map variables + path := "/v2/user/{username}" + path = strings.Replace(path, "{" + "username" + "}", fmt.Sprintf("%v", username), -1) + + _sling = _sling.Path(path) + + // accept header + accepts := []string { "application/xml", "application/json" } + for key := range accepts { + _sling = _sling.Set("Accept", accepts[key]) + break // only use the first Accept + } + + + var successPayload = new(User) + + // We use this map (below) so that any arbitrary error JSON can be handled. + // FIXME: This is in the absence of this Go generator honoring the non-2xx + // response (error) models, which needs to be implemented at some point. + var failurePayload map[string]interface{} + + httpResponse, err := _sling.Receive(successPayload, &failurePayload) + + if err == nil { + // err == nil only means that there wasn't a sub-application-layer error (e.g. no network error) + if failurePayload != nil { + // If the failurePayload is present, there likely was some kind of non-2xx status + // returned (and a JSON payload error present) + var str []byte + str, err = json.Marshal(failurePayload) + if err == nil { // For safety, check for an error marshalling... probably superfluous + // This will return the JSON error body as a string + err = errors.New(string(str)) + } + } else { + // So, there was no network-type error, and nothing in the failure payload, + // but we should still check the status code + if httpResponse == nil { + // This should never happen... + err = errors.New("No HTTP Response received.") + } else if code := httpResponse.StatusCode; 200 > code || code > 299 { + err = errors.New("HTTP Error: " + string(httpResponse.StatusCode)) + } + } + } + + return *successPayload, err } /** * Logs user into the system * - * @param Username The user name for login - * @param Password The password for login in clear text + * @param username The user name for login + * @param password The password for login in clear text * @return string */ -//func (a UserApi) LoginUser (Username string, Password string) (string, error) { -func (a UserApi) LoginUser (Username string, Password string) (string, error) { +//func (a UserApi) LoginUser (username string, password string) (string, error) { +func (a UserApi) LoginUser (username string, password string) (string, error) { - _sling := sling.New().Get(a.basePath) + _sling := sling.New().Get(a.Configuration.BasePath) // create path and map variables path := "/v2/user/login" @@ -136,24 +344,51 @@ func (a UserApi) LoginUser (Username string, Password string) (string, error) { _sling = _sling.Path(path) type QueryParams struct { - Username string `url:"username,omitempty"` - Password string `url:"password,omitempty"` - + username string `url:"username,omitempty"` +password string `url:"password,omitempty"` } - _sling = _sling.QueryStruct(&QueryParams{ Username: Username,Password: Password }) + _sling = _sling.QueryStruct(&QueryParams{ username: username,password: password }) // accept header - accepts := []string { "application/json", "application/xml" } + accepts := []string { "application/xml", "application/json" } for key := range accepts { _sling = _sling.Set("Accept", accepts[key]) break // only use the first Accept } + var successPayload = new(string) - response := new(string) - _, err := _sling.ReceiveSuccess(response) - //fmt.Println("LoginUser response: ", response, resp, err) - return *response, err + // We use this map (below) so that any arbitrary error JSON can be handled. + // FIXME: This is in the absence of this Go generator honoring the non-2xx + // response (error) models, which needs to be implemented at some point. + var failurePayload map[string]interface{} + + httpResponse, err := _sling.Receive(successPayload, &failurePayload) + + if err == nil { + // err == nil only means that there wasn't a sub-application-layer error (e.g. no network error) + if failurePayload != nil { + // If the failurePayload is present, there likely was some kind of non-2xx status + // returned (and a JSON payload error present) + var str []byte + str, err = json.Marshal(failurePayload) + if err == nil { // For safety, check for an error marshalling... probably superfluous + // This will return the JSON error body as a string + err = errors.New(string(str)) + } + } else { + // So, there was no network-type error, and nothing in the failure payload, + // but we should still check the status code + if httpResponse == nil { + // This should never happen... + err = errors.New("No HTTP Response received.") + } else if code := httpResponse.StatusCode; 200 > code || code > 299 { + err = errors.New("HTTP Error: " + string(httpResponse.StatusCode)) + } + } + } + + return *successPayload, err } /** * Logs out current logged in user session @@ -163,7 +398,7 @@ func (a UserApi) LoginUser (Username string, Password string) (string, error) { //func (a UserApi) LogoutUser () (error) { func (a UserApi) LogoutUser () (error) { - _sling := sling.New().Get(a.basePath) + _sling := sling.New().Get(a.Configuration.BasePath) // create path and map variables path := "/v2/user/logout" @@ -171,7 +406,7 @@ func (a UserApi) LogoutUser () (error) { _sling = _sling.Path(path) // accept header - accepts := []string { "application/json", "application/xml" } + accepts := []string { "application/xml", "application/json" } for key := range accepts { _sling = _sling.Set("Accept", accepts[key]) break // only use the first Accept @@ -180,103 +415,97 @@ func (a UserApi) LogoutUser () (error) { - _, err := _sling.ReceiveSuccess(nil) - //fmt.Println("LogoutUser response: void, ", resp, err) - return err -} -/** - * Get user by user name - * - * @param Username The name that needs to be fetched. Use user1 for testing. - * @return User - */ -//func (a UserApi) GetUserByName (Username string) (User, error) { -func (a UserApi) GetUserByName (Username string) (User, error) { + // We use this map (below) so that any arbitrary error JSON can be handled. + // FIXME: This is in the absence of this Go generator honoring the non-2xx + // response (error) models, which needs to be implemented at some point. + var failurePayload map[string]interface{} - _sling := sling.New().Get(a.basePath) + httpResponse, err := _sling.Receive(nil, &failurePayload) - // create path and map variables - path := "/v2/user/{username}" - path = strings.Replace(path, "{" + "username" + "}", fmt.Sprintf("%v", Username), -1) - - _sling = _sling.Path(path) - - // accept header - accepts := []string { "application/json", "application/xml" } - for key := range accepts { - _sling = _sling.Set("Accept", accepts[key]) - break // only use the first Accept + if err == nil { + // err == nil only means that there wasn't a sub-application-layer error (e.g. no network error) + if failurePayload != nil { + // If the failurePayload is present, there likely was some kind of non-2xx status + // returned (and a JSON payload error present) + var str []byte + str, err = json.Marshal(failurePayload) + if err == nil { // For safety, check for an error marshalling... probably superfluous + // This will return the JSON error body as a string + err = errors.New(string(str)) + } + } else { + // So, there was no network-type error, and nothing in the failure payload, + // but we should still check the status code + if httpResponse == nil { + // This should never happen... + err = errors.New("No HTTP Response received.") + } else if code := httpResponse.StatusCode; 200 > code || code > 299 { + err = errors.New("HTTP Error: " + string(httpResponse.StatusCode)) + } } + } - - - response := new(User) - _, err := _sling.ReceiveSuccess(response) - //fmt.Println("GetUserByName response: ", response, resp, err) - return *response, err + return err } /** * Updated user * This can only be done by the logged in user. - * @param Username name that need to be deleted - * @param Body Updated user object + * @param username name that need to be deleted + * @param body Updated user object * @return void */ -//func (a UserApi) UpdateUser (Username string, Body User) (error) { -func (a UserApi) UpdateUser (Username string, Body User) (error) { +//func (a UserApi) UpdateUser (username string, body User) (error) { +func (a UserApi) UpdateUser (username string, body User) (error) { - _sling := sling.New().Put(a.basePath) + _sling := sling.New().Put(a.Configuration.BasePath) // create path and map variables path := "/v2/user/{username}" - path = strings.Replace(path, "{" + "username" + "}", fmt.Sprintf("%v", Username), -1) + path = strings.Replace(path, "{" + "username" + "}", fmt.Sprintf("%v", username), -1) _sling = _sling.Path(path) // accept header - accepts := []string { "application/json", "application/xml" } + accepts := []string { "application/xml", "application/json" } for key := range accepts { _sling = _sling.Set("Accept", accepts[key]) break // only use the first Accept } // body params - _sling = _sling.BodyJSON(Body) + _sling = _sling.BodyJSON(body) - _, err := _sling.ReceiveSuccess(nil) - //fmt.Println("UpdateUser response: void, ", resp, err) - return err -} -/** - * Delete user - * This can only be done by the logged in user. - * @param Username The name that needs to be deleted - * @return void - */ -//func (a UserApi) DeleteUser (Username string) (error) { -func (a UserApi) DeleteUser (Username string) (error) { + // We use this map (below) so that any arbitrary error JSON can be handled. + // FIXME: This is in the absence of this Go generator honoring the non-2xx + // response (error) models, which needs to be implemented at some point. + var failurePayload map[string]interface{} - _sling := sling.New().Delete(a.basePath) + httpResponse, err := _sling.Receive(nil, &failurePayload) - // create path and map variables - path := "/v2/user/{username}" - path = strings.Replace(path, "{" + "username" + "}", fmt.Sprintf("%v", Username), -1) - - _sling = _sling.Path(path) - - // accept header - accepts := []string { "application/json", "application/xml" } - for key := range accepts { - _sling = _sling.Set("Accept", accepts[key]) - break // only use the first Accept + if err == nil { + // err == nil only means that there wasn't a sub-application-layer error (e.g. no network error) + if failurePayload != nil { + // If the failurePayload is present, there likely was some kind of non-2xx status + // returned (and a JSON payload error present) + var str []byte + str, err = json.Marshal(failurePayload) + if err == nil { // For safety, check for an error marshalling... probably superfluous + // This will return the JSON error body as a string + err = errors.New(string(str)) + } + } else { + // So, there was no network-type error, and nothing in the failure payload, + // but we should still check the status code + if httpResponse == nil { + // This should never happen... + err = errors.New("No HTTP Response received.") + } else if code := httpResponse.StatusCode; 200 > code || code > 299 { + err = errors.New("HTTP Error: " + string(httpResponse.StatusCode)) + } } + } - - - - _, err := _sling.ReceiveSuccess(nil) - //fmt.Println("DeleteUser response: void, ", resp, err) - return err + return err } diff --git a/samples/client/petstore/go/test.go b/samples/client/petstore/go/test.go index d65e70575fc..f742307196b 100644 --- a/samples/client/petstore/go/test.go +++ b/samples/client/petstore/go/test.go @@ -19,7 +19,7 @@ func main() { s.AddPet(newPet) // test POST(form) - s.UpdatePetWithForm("12830", "golang", "available") + s.UpdatePetWithForm(12830, "golang", "available") // test GET resp, err := s.GetPetById(12830) diff --git a/samples/client/petstore/java/default/.gitignore b/samples/client/petstore/java/default/.gitignore new file mode 100644 index 00000000000..32858aad3c3 --- /dev/null +++ b/samples/client/petstore/java/default/.gitignore @@ -0,0 +1,12 @@ +*.class + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.ear + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* diff --git a/samples/client/petstore/java/default/git_push.sh b/samples/client/petstore/java/default/git_push.sh new file mode 100644 index 00000000000..1a36388db02 --- /dev/null +++ b/samples/client/petstore/java/default/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="YOUR_GIT_USR_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="YOUR_GIT_REPO_ID" + 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/default/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/ApiClient.java index a8ab7a8f853..50c0e8db641 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/ApiClient.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/ApiClient.java @@ -41,7 +41,7 @@ import io.swagger.client.auth.HttpBasicAuth; import io.swagger.client.auth.ApiKeyAuth; import io.swagger.client.auth.OAuth; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-02-18T20:04:40.386+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-03-17T15:55:38.841+08:00") public class ApiClient { private Map defaultHeaderMap = new HashMap(); private String basePath = "http://petstore.swagger.io/v2"; @@ -71,7 +71,7 @@ public class ApiClient { dateFormat = ApiClient.buildDefaultDateFormat(); // Set default User-Agent. - setUserAgent("Java-Swagger"); + setUserAgent("Swagger-Codegen/1.0.0/java"); // Setup authentications (key: authentication name, value: authentication). authentications = new HashMap(); @@ -79,6 +79,7 @@ public class ApiClient { authentications.put("test_api_client_id", new ApiKeyAuth("header", "x-test_api_client_id")); authentications.put("test_api_client_secret", new ApiKeyAuth("header", "x-test_api_client_secret")); authentications.put("api_key", new ApiKeyAuth("header", "api_key")); + authentications.put("test_http_basic", new HttpBasicAuth()); authentications.put("test_api_key_query", new ApiKeyAuth("query", "test_api_key_query")); authentications.put("test_api_key_header", new ApiKeyAuth("header", "test_api_key_header")); // Prevent the authentications from being modified. diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/ApiException.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/ApiException.java index c8e07238179..27395e86ba9 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/ApiException.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/ApiException.java @@ -3,7 +3,7 @@ package io.swagger.client; import java.util.Map; import java.util.List; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-02-12T18:48:10.013-08:00") + public class ApiException extends Exception { private int code = 0; private Map> responseHeaders = null; diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/Configuration.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/Configuration.java index 8a28d5f194c..19b0ebeae4e 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/Configuration.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/Configuration.java @@ -1,6 +1,6 @@ package io.swagger.client; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-02-12T18:48:10.013-08:00") + public class Configuration { private static ApiClient defaultApiClient = new ApiClient(); diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/Pair.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/Pair.java index 4c08f122623..d8d32210b10 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/Pair.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/Pair.java @@ -1,6 +1,6 @@ package io.swagger.client; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-02-12T18:48:10.013-08:00") + public class Pair { private String name = ""; private String value = ""; diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/StringUtil.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/StringUtil.java index ab175012239..1383dd0decb 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/StringUtil.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/StringUtil.java @@ -1,6 +1,6 @@ package io.swagger.client; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-02-12T18:48:10.013-08:00") + public class StringUtil { /** * Check if the given array contains the given value (with case-insensitive comparison). diff --git a/samples/client/petstore/java/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 index d9a63413546..00bd52b9a6f 100644 --- 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 @@ -8,15 +8,15 @@ import io.swagger.client.Configuration; import io.swagger.client.Pair; import io.swagger.client.model.Pet; -import java.io.File; import io.swagger.client.model.InlineResponse200; +import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-03-03T10:59:23.243+08:00") + public class PetApi { private ApiClient apiClient; @@ -37,50 +37,10 @@ public class PetApi { } - /** - * Update an existing pet - * - * @param body Pet object that needs to be added to the store - * @throws ApiException if fails to make API call - */ - public void updatePet(Pet body) throws ApiException { - Object localVarPostBody = body; - - // 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/json", "application/xml" - }; - 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); - - } - /** * Add a new pet to the store * - * @param body Pet object that needs to be added to the store + * @param body Pet object that needs to be added to the store (optional) * @throws ApiException if fails to make API call */ public void addPet(Pet body) throws ApiException { @@ -117,10 +77,99 @@ public class PetApi { } + /** + * Fake endpoint to test byte array in body parameter for adding a new pet to the store + * + * @param body Pet object in the form of byte array (optional) + * @throws ApiException if fails to make API call + */ + public void addPetUsingByteArray(byte[] body) throws ApiException { + Object localVarPostBody = body; + + // create path and map variables + String localVarPath = "/pet?testing_byte_array=true".replaceAll("\\{format\\}","json"); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + + + + final String[] localVarAccepts = { + "application/json", "application/xml" + }; + 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/json", "application/xml" + }; + 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 query + * @param status Status values that need to be considered for query (optional, default to available) * @return List * @throws ApiException if fails to make API call */ @@ -164,7 +213,7 @@ public class PetApi { /** * Finds Pets by tags * Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. - * @param tags Tags to filter by + * @param tags Tags to filter by (optional) * @return List * @throws ApiException if fails to make API call */ @@ -208,7 +257,7 @@ public class PetApi { /** * Find pet by ID * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions - * @param petId ID of pet that needs to be fetched + * @param petId ID of pet that needs to be fetched (required) * @return Pet * @throws ApiException if fails to make API call */ @@ -245,7 +294,7 @@ public class PetApi { }; final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - String[] localVarAuthNames = new String[] { "petstore_auth", "api_key" }; + String[] localVarAuthNames = new String[] { "api_key", "petstore_auth" }; GenericType localVarReturnType = new GenericType() {}; @@ -253,12 +302,148 @@ public class PetApi { } + /** + * Fake endpoint to test inline arbitrary object return by 'Find pet by ID' + * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + * @param petId ID of pet that needs to be fetched (required) + * @return InlineResponse200 + * @throws ApiException if fails to make API call + */ + public InlineResponse200 getPetByIdInObject(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 getPetByIdInObject"); + } + + // create path and map variables + String localVarPath = "/pet/{petId}?response=inline_arbitrary_object".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/json", "application/xml" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "api_key", "petstore_auth" }; + + + GenericType localVarReturnType = new GenericType() {}; + return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + + } + + /** + * Fake endpoint to test byte array return by 'Find pet by ID' + * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + * @param petId ID of pet that needs to be fetched (required) + * @return byte[] + * @throws ApiException if fails to make API call + */ + public byte[] petPetIdtestingByteArraytrueGet(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 petPetIdtestingByteArraytrueGet"); + } + + // create path and map variables + String localVarPath = "/pet/{petId}?testing_byte_array=true".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/json", "application/xml" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "api_key", "petstore_auth" }; + + + 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 (optional) + * @throws ApiException if fails to make API call + */ + public void updatePet(Pet body) throws ApiException { + Object localVarPostBody = body; + + // 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/json", "application/xml" + }; + 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 - * @param name Updated name of the pet - * @param status Updated status of the pet + * @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(String petId, String name, String status) throws ApiException { @@ -305,61 +490,12 @@ public class PetApi { } - /** - * Deletes a pet - * - * @param petId Pet id to delete - * @param apiKey - * @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/json", "application/xml" - }; - 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); - - } - /** * uploads an image * - * @param petId ID of pet to update - * @param additionalMetadata Additional data to pass to server - * @param file file to upload + * @param petId ID of pet to update (required) + * @param additionalMetadata Additional data to pass to server (optional) + * @param file file to upload (optional) * @throws ApiException if fails to make API call */ public void uploadFile(Long petId, String additionalMetadata, File file) throws ApiException { @@ -402,142 +538,6 @@ public class PetApi { String[] localVarAuthNames = new String[] { "petstore_auth" }; - apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); - - } - - /** - * Fake endpoint to test inline arbitrary object return by 'Find pet by ID' - * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions - * @param petId ID of pet that needs to be fetched - * @return InlineResponse200 - * @throws ApiException if fails to make API call - */ - public InlineResponse200 getPetByIdInObject(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 getPetByIdInObject"); - } - - // create path and map variables - String localVarPath = "/pet/{petId}?response=inline_arbitrary_object".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/json", "application/xml" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { "petstore_auth", "api_key" }; - - - GenericType localVarReturnType = new GenericType() {}; - return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); - - } - - /** - * Fake endpoint to test byte array return by 'Find pet by ID' - * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions - * @param petId ID of pet that needs to be fetched - * @return byte[] - * @throws ApiException if fails to make API call - */ - public byte[] petPetIdtestingByteArraytrueGet(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 petPetIdtestingByteArraytrueGet"); - } - - // create path and map variables - String localVarPath = "/pet/{petId}?testing_byte_array=true".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/json", "application/xml" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { "petstore_auth", "api_key" }; - - - GenericType localVarReturnType = new GenericType() {}; - return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); - - } - - /** - * Fake endpoint to test byte array in body parameter for adding a new pet to the store - * - * @param body Pet object in the form of byte array - * @throws ApiException if fails to make API call - */ - public void addPetUsingByteArray(byte[] body) throws ApiException { - Object localVarPostBody = body; - - // create path and map variables - String localVarPath = "/pet?testing_byte_array=true".replaceAll("\\{format\\}","json"); - - // query params - List localVarQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - - - - - - - final String[] localVarAccepts = { - "application/json", "application/xml" - }; - 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); } 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 index 5b900ac15d3..7e8bccd8da3 100644 --- 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 @@ -14,7 +14,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-03-03T11:57:06.886+08:00") + public class StoreApi { private ApiClient apiClient; @@ -35,10 +35,56 @@ public class 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) + * @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/json", "application/xml" + }; + 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); + + } + /** * Finds orders by status * A single status value can be provided as a string - * @param status Status value that needs to be considered for query + * @param status Status value that needs to be considered for query (optional, default to placed) * @return List * @throws ApiException if fails to make API call */ @@ -161,10 +207,58 @@ public class StoreApi { } + /** + * 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(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 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/json", "application/xml" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "test_api_key_header", "test_api_key_query" }; + + + 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 + * @param body order placed for purchasing the pet (optional) * @return Order * @throws ApiException if fails to make API call */ @@ -203,98 +297,4 @@ public class StoreApi { } - /** - * Find purchase order by ID - * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - * @param orderId ID of pet that needs to be fetched - * @return Order - * @throws ApiException if fails to make API call - */ - public Order getOrderById(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 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/json", "application/xml" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { "test_api_key_query", "test_api_key_header" }; - - - GenericType localVarReturnType = new GenericType() {}; - return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); - - } - - /** - * 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 - * @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/json", "application/xml" - }; - 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); - - } - } 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 index 79cc99f69a7..848ec58ce17 100644 --- 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 @@ -14,7 +14,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-02-29T12:55:35.772+08:00") + public class UserApi { private ApiClient apiClient; @@ -38,7 +38,7 @@ public class UserApi { /** * Create user * This can only be done by the logged in user. - * @param body Created user object + * @param body Created user object (optional) * @throws ApiException if fails to make API call */ public void createUser(User body) throws ApiException { @@ -78,7 +78,7 @@ public class UserApi { /** * Creates list of users with given input array * - * @param body List of user object + * @param body List of user object (optional) * @throws ApiException if fails to make API call */ public void createUsersWithArrayInput(List body) throws ApiException { @@ -118,7 +118,7 @@ public class UserApi { /** * Creates list of users with given input array * - * @param body List of user object + * @param body List of user object (optional) * @throws ApiException if fails to make API call */ public void createUsersWithListInput(List body) throws ApiException { @@ -155,11 +155,105 @@ public class UserApi { } + /** + * 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/json", "application/xml" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "test_http_basic" }; + + + 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/json", "application/xml" + }; + 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 - * @param password The password for login in clear text + * @param username The user name for login (optional) + * @param password The password for login in clear text (optional) * @return String * @throws ApiException if fails to make API call */ @@ -241,59 +335,11 @@ public class UserApi { } - /** - * Get user by user name - * - * @param username The name that needs to be fetched. Use user1 for testing. - * @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/json", "application/xml" - }; - 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); - - } - /** * Updated user * This can only be done by the logged in user. - * @param username name that need to be deleted - * @param body Updated user object + * @param username name that need to be deleted (required) + * @param body Updated user object (optional) * @throws ApiException if fails to make API call */ public void updateUser(String username, User body) throws ApiException { @@ -336,50 +382,4 @@ public class UserApi { } - /** - * Delete user - * This can only be done by the logged in user. - * @param username The name that needs to be deleted - * @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/json", "application/xml" - }; - 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); - - } - } diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/ApiKeyAuth.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/ApiKeyAuth.java index 0a38c196bee..6882dbc41c0 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/ApiKeyAuth.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/ApiKeyAuth.java @@ -5,7 +5,7 @@ import io.swagger.client.Pair; import java.util.Map; import java.util.List; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-02-12T18:48:10.013-08:00") + public class ApiKeyAuth implements Authentication { private final String location; private final String paramName; diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/HttpBasicAuth.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/HttpBasicAuth.java index d85b6418867..64f2c887377 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/HttpBasicAuth.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/HttpBasicAuth.java @@ -9,7 +9,7 @@ import java.util.List; import java.io.UnsupportedEncodingException; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-02-12T18:48:10.013-08:00") + public class HttpBasicAuth implements Authentication { private String username; private String password; diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/OAuth.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/OAuth.java index 38187f5511c..76d2917f24e 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/OAuth.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/OAuth.java @@ -5,7 +5,7 @@ import io.swagger.client.Pair; import java.util.Map; import java.util.List; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-02-12T18:48:10.013-08:00") + public class OAuth implements Authentication { private String accessToken; 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 index a2c1e6dfbc9..3289c469672 100644 --- 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 @@ -9,7 +9,7 @@ import io.swagger.annotations.ApiModelProperty; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-02-22T14:59:49.052+08:00") + public class Category { private Long id = null; diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/InlineResponse200.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/InlineResponse200.java index ae04afd1f11..c7d3c155657 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/InlineResponse200.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/InlineResponse200.java @@ -2,35 +2,62 @@ package io.swagger.client.model; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonValue; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; +import io.swagger.client.model.Tag; +import java.util.ArrayList; +import java.util.List; + -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-03-03T10:48:49.300+08:00") public class InlineResponse200 { - private String name = null; + private List tags = new ArrayList(); private Long id = null; private Object category = null; + + 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; + private String name = null; + private List photoUrls = new ArrayList(); + /** **/ - public InlineResponse200 name(String name) { - this.name = name; + public InlineResponse200 tags(List tags) { + this.tags = tags; return this; } - @ApiModelProperty(example = "doggie", value = "") - @JsonProperty("name") - public String getName() { - return name; + @ApiModelProperty(example = "null", value = "") + @JsonProperty("tags") + public List getTags() { + return tags; } - public void setName(String name) { - this.name = name; + public void setTags(List tags) { + this.tags = tags; } @@ -68,6 +95,58 @@ public class InlineResponse200 { } + /** + * pet status in the store + **/ + public InlineResponse200 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; + } + + + /** + **/ + public InlineResponse200 name(String name) { + this.name = name; + return this; + } + + @ApiModelProperty(example = "doggie", value = "") + @JsonProperty("name") + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + + + /** + **/ + public InlineResponse200 photoUrls(List photoUrls) { + this.photoUrls = photoUrls; + return this; + } + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("photoUrls") + public List getPhotoUrls() { + return photoUrls; + } + public void setPhotoUrls(List photoUrls) { + this.photoUrls = photoUrls; + } + + @Override public boolean equals(java.lang.Object o) { @@ -78,14 +157,17 @@ public class InlineResponse200 { return false; } InlineResponse200 inlineResponse200 = (InlineResponse200) o; - return Objects.equals(this.name, inlineResponse200.name) && + return Objects.equals(this.tags, inlineResponse200.tags) && Objects.equals(this.id, inlineResponse200.id) && - Objects.equals(this.category, inlineResponse200.category); + Objects.equals(this.category, inlineResponse200.category) && + Objects.equals(this.status, inlineResponse200.status) && + Objects.equals(this.name, inlineResponse200.name) && + Objects.equals(this.photoUrls, inlineResponse200.photoUrls); } @Override public int hashCode() { - return Objects.hash(name, id, category); + return Objects.hash(tags, id, category, status, name, photoUrls); } @Override @@ -93,9 +175,12 @@ public class InlineResponse200 { StringBuilder sb = new StringBuilder(); sb.append("class InlineResponse200 {\n"); - sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" tags: ").append(toIndentedString(tags)).append("\n"); sb.append(" id: ").append(toIndentedString(id)).append("\n"); sb.append(" category: ").append(toIndentedString(category)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" photoUrls: ").append(toIndentedString(photoUrls)).append("\n"); sb.append("}"); return sb.toString(); } 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 new file mode 100644 index 00000000000..fb24ee29a3f --- /dev/null +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Model200Response.java @@ -0,0 +1,74 @@ +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + + + + + + +public class Model200Response { + + private Integer name = 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; + } + + + + @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); + } + + @Override + public int hashCode() { + return Objects.hash(name); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Model200Response {\n"); + + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(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 new file mode 100644 index 00000000000..fbb4135ce27 --- /dev/null +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/ModelReturn.java @@ -0,0 +1,74 @@ +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + + + + + + +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 new file mode 100644 index 00000000000..512289310c7 --- /dev/null +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Name.java @@ -0,0 +1,94 @@ +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + + + + + + +public class Name { + + private Integer name = null; + private Integer snakeCase = null; + + + /** + **/ + public Name 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 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; + } + + + + @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); + } + + @Override + public int hashCode() { + return Objects.hash(name, snakeCase); + } + + @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("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the 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 index b571d5d9580..77df445af66 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Order.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Order.java @@ -11,7 +11,7 @@ import java.util.Date; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-02-22T14:59:49.052+08:00") + public class Order { private Long id = null; 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 index 9d183a547a5..42c23a9db0e 100644 --- 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 @@ -14,7 +14,7 @@ import java.util.List; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-02-22T14:59:49.052+08:00") + public class Pet { private Long id = null; 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 new file mode 100644 index 00000000000..7fa91b8827c --- /dev/null +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/SpecialModelName.java @@ -0,0 +1,74 @@ +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + + + + + + +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 index 070136e0718..4e6055c1410 100644 --- 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 @@ -9,7 +9,7 @@ import io.swagger.annotations.ApiModelProperty; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-02-22T14:59:49.052+08:00") + public class Tag { private Long id = null; 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 index fe65e0dfe9e..272ec6d3843 100644 --- 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 @@ -9,7 +9,7 @@ import io.swagger.annotations.ApiModelProperty; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-02-22T14:59:49.052+08:00") + public class User { private Long id = null; diff --git a/samples/client/petstore/java/default/src/test/java/io/swagger/client/ApiClientTest.java b/samples/client/petstore/java/default/src/test/java/io/swagger/client/ApiClientTest.java index 9fa51a06baa..47f004c283b 100644 --- a/samples/client/petstore/java/default/src/test/java/io/swagger/client/ApiClientTest.java +++ b/samples/client/petstore/java/default/src/test/java/io/swagger/client/ApiClientTest.java @@ -112,21 +112,25 @@ public class ApiClientTest { } @Test - public void testSetUsername() { - try { - apiClient.setUsername("my-username"); - fail("there should be no HTTP basic authentications"); - } catch (RuntimeException e) { + 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); - @Test - public void testSetPassword() { - try { - apiClient.setPassword("my-password"); - fail("there should be no HTTP basic authentications"); - } catch (RuntimeException e) { - } + 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 diff --git a/samples/client/petstore/java/feign/.gitignore b/samples/client/petstore/java/feign/.gitignore new file mode 100644 index 00000000000..32858aad3c3 --- /dev/null +++ b/samples/client/petstore/java/feign/.gitignore @@ -0,0 +1,12 @@ +*.class + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.ear + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* diff --git a/samples/client/petstore/java/feign/git_push.sh b/samples/client/petstore/java/feign/git_push.sh new file mode 100644 index 00000000000..1a36388db02 --- /dev/null +++ b/samples/client/petstore/java/feign/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="YOUR_GIT_USR_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="YOUR_GIT_REPO_ID" + 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/feign/src/main/java/io/swagger/client/FormAwareEncoder.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/FormAwareEncoder.java index 40f6af65150..f8c7170f44e 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/FormAwareEncoder.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/FormAwareEncoder.java @@ -14,7 +14,7 @@ import feign.codec.EncodeException; import feign.codec.Encoder; import feign.RequestTemplate; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-11T21:48:33.457Z") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-03-14T22:17:50.356+08:00") public class FormAwareEncoder implements Encoder { public static final String UTF_8 = "utf-8"; private static final String LINE_FEED = "\r\n"; diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/StringUtil.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/StringUtil.java index a7299767d3f..88aff61bf68 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/StringUtil.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/StringUtil.java @@ -1,6 +1,6 @@ package io.swagger.client; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-11T21:48:33.457Z") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-03-14T22:17:50.356+08:00") public class StringUtil { /** * Check if the given array contains the given value (with case-insensitive comparison). diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/PetApi.java index 1ef43cc376d..51f6c2358c7 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/PetApi.java @@ -3,36 +3,26 @@ package io.swagger.client.api; import io.swagger.client.ApiClient; import io.swagger.client.model.Pet; -import java.io.File; import io.swagger.client.model.InlineResponse200; +import java.io.File; + + import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; + import feign.*; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-03-03T12:04:41.120+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-03-19T15:53:31.820+08:00") public interface PetApi extends ApiClient.Api { - /** - * Update an existing pet - * - * @param body Pet object that needs to be added to the store - * @return void - */ - @RequestLine("PUT /pet") - @Headers({ - "Content-type: application/json", - "Accepts: application/json", - }) - void updatePet(Pet body); - /** * Add a new pet to the store * - * @param body Pet object that needs to be added to the store + * @param body Pet object that needs to be added to the store (optional) * @return void */ @RequestLine("POST /pet") @@ -42,10 +32,38 @@ public interface PetApi extends ApiClient.Api { }) void addPet(Pet body); + /** + * Fake endpoint to test byte array in body parameter for adding a new pet to the store + * + * @param body Pet object in the form of byte array (optional) + * @return void + */ + @RequestLine("POST /pet?testing_byte_array=true") + @Headers({ + "Content-type: application/json", + "Accepts: application/json", + }) + void addPetUsingByteArray(byte[] body); + + /** + * Deletes a pet + * + * @param petId Pet id to delete (required) + * @param apiKey (optional) + * @return void + */ + @RequestLine("DELETE /pet/{petId}") + @Headers({ + "Content-type: application/json", + "Accepts: application/json", + "apiKey: {apiKey}" + }) + void deletePet(@Param("petId") Long petId, @Param("apiKey") 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 query + * @param status Status values that need to be considered for query (optional, default to available) * @return List */ @RequestLine("GET /pet/findByStatus?status={status}") @@ -58,7 +76,7 @@ public interface PetApi extends ApiClient.Api { /** * Finds Pets by tags * Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. - * @param tags Tags to filter by + * @param tags Tags to filter by (optional) * @return List */ @RequestLine("GET /pet/findByTags?tags={tags}") @@ -71,7 +89,7 @@ public interface PetApi extends ApiClient.Api { /** * Find pet by ID * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions - * @param petId ID of pet that needs to be fetched + * @param petId ID of pet that needs to be fetched (required) * @return Pet */ @RequestLine("GET /pet/{petId}") @@ -81,55 +99,10 @@ public interface PetApi extends ApiClient.Api { }) Pet getPetById(@Param("petId") Long petId); - /** - * Updates a pet in the store with form data - * - * @param petId ID of pet that needs to be updated - * @param name Updated name of the pet - * @param status Updated status of the pet - * @return void - */ - @RequestLine("POST /pet/{petId}") - @Headers({ - "Content-type: application/x-www-form-urlencoded", - "Accepts: application/json", - }) - void updatePetWithForm(@Param("petId") String petId, @Param("name") String name, @Param("status") String status); - - /** - * Deletes a pet - * - * @param petId Pet id to delete - * @param apiKey - * @return void - */ - @RequestLine("DELETE /pet/{petId}") - @Headers({ - "Content-type: application/json", - "Accepts: application/json", - "apiKey: {apiKey}" - }) - void deletePet(@Param("petId") Long petId, @Param("apiKey") String apiKey); - - /** - * uploads an image - * - * @param petId ID of pet to update - * @param additionalMetadata Additional data to pass to server - * @param file file to upload - * @return void - */ - @RequestLine("POST /pet/{petId}/uploadImage") - @Headers({ - "Content-type: multipart/form-data", - "Accepts: application/json", - }) - void uploadFile(@Param("petId") Long petId, @Param("additionalMetadata") String additionalMetadata, @Param("file") File file); - /** * Fake endpoint to test inline arbitrary object return by 'Find pet by ID' * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions - * @param petId ID of pet that needs to be fetched + * @param petId ID of pet that needs to be fetched (required) * @return InlineResponse200 */ @RequestLine("GET /pet/{petId}?response=inline_arbitrary_object") @@ -142,7 +115,7 @@ public interface PetApi extends ApiClient.Api { /** * Fake endpoint to test byte array return by 'Find pet by ID' * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions - * @param petId ID of pet that needs to be fetched + * @param petId ID of pet that needs to be fetched (required) * @return byte[] */ @RequestLine("GET /pet/{petId}?testing_byte_array=true") @@ -153,16 +126,47 @@ public interface PetApi extends ApiClient.Api { byte[] petPetIdtestingByteArraytrueGet(@Param("petId") Long petId); /** - * Fake endpoint to test byte array in body parameter for adding a new pet to the store + * Update an existing pet * - * @param body Pet object in the form of byte array + * @param body Pet object that needs to be added to the store (optional) * @return void */ - @RequestLine("POST /pet?testing_byte_array=true") + @RequestLine("PUT /pet") @Headers({ "Content-type: application/json", "Accepts: application/json", }) - void addPetUsingByteArray(byte[] body); + void updatePet(Pet body); + /** + * 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 void + */ + @RequestLine("POST /pet/{petId}") + @Headers({ + "Content-type: application/x-www-form-urlencoded", + "Accepts: application/json", + }) + void updatePetWithForm(@Param("petId") String petId, @Param("name") String name, @Param("status") String status); + + /** + * 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 void + */ + @RequestLine("POST /pet/{petId}/uploadImage") + @Headers({ + "Content-type: multipart/form-data", + "Accepts: application/json", + }) + void uploadFile(@Param("petId") Long petId, @Param("additionalMetadata") String additionalMetadata, @Param("file") File file); + + } diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/StoreApi.java index cb70916ae6b..97c3ad3ec16 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/StoreApi.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/StoreApi.java @@ -4,20 +4,36 @@ import io.swagger.client.ApiClient; import io.swagger.client.model.Order; + + import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; + import feign.*; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-03-03T12:04:41.120+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-03-19T15:53:31.820+08:00") public interface StoreApi extends ApiClient.Api { + /** + * 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 void + */ + @RequestLine("DELETE /store/order/{orderId}") + @Headers({ + "Content-type: application/json", + "Accepts: application/json", + }) + void deleteOrder(@Param("orderId") String orderId); + /** * Finds orders by status * A single status value can be provided as a string - * @param status Status value that needs to be considered for query + * @param status Status value that needs to be considered for query (optional, default to placed) * @return List */ @RequestLine("GET /store/findByStatus?status={status}") @@ -51,23 +67,10 @@ public interface StoreApi extends ApiClient.Api { }) Object getInventoryInObject(); - /** - * Place an order for a pet - * - * @param body order placed for purchasing the pet - * @return Order - */ - @RequestLine("POST /store/order") - @Headers({ - "Content-type: application/json", - "Accepts: application/json", - }) - Order placeOrder(Order body); - /** * Find purchase order by ID * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - * @param orderId ID of pet that needs to be fetched + * @param orderId ID of pet that needs to be fetched (required) * @return Order */ @RequestLine("GET /store/order/{orderId}") @@ -78,16 +81,17 @@ public interface StoreApi extends ApiClient.Api { Order getOrderById(@Param("orderId") 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 - * @param orderId ID of the order that needs to be deleted - * @return void + * Place an order for a pet + * + * @param body order placed for purchasing the pet (optional) + * @return Order */ - @RequestLine("DELETE /store/order/{orderId}") + @RequestLine("POST /store/order") @Headers({ "Content-type: application/json", "Accepts: application/json", }) - void deleteOrder(@Param("orderId") String orderId); + Order placeOrder(Order body); + } diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/UserApi.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/UserApi.java index e6fec19f35c..3fef00a41f0 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/UserApi.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/UserApi.java @@ -4,20 +4,23 @@ import io.swagger.client.ApiClient; import io.swagger.client.model.User; + + import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; + import feign.*; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-11T21:48:33.457Z") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-03-19T15:53:31.820+08:00") public interface UserApi extends ApiClient.Api { /** * Create user * This can only be done by the logged in user. - * @param body Created user object + * @param body Created user object (optional) * @return void */ @RequestLine("POST /user") @@ -30,7 +33,7 @@ public interface UserApi extends ApiClient.Api { /** * Creates list of users with given input array * - * @param body List of user object + * @param body List of user object (optional) * @return void */ @RequestLine("POST /user/createWithArray") @@ -43,7 +46,7 @@ public interface UserApi extends ApiClient.Api { /** * Creates list of users with given input array * - * @param body List of user object + * @param body List of user object (optional) * @return void */ @RequestLine("POST /user/createWithList") @@ -53,11 +56,37 @@ public interface UserApi extends ApiClient.Api { }) void createUsersWithListInput(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 void + */ + @RequestLine("DELETE /user/{username}") + @Headers({ + "Content-type: application/json", + "Accepts: application/json", + }) + void deleteUser(@Param("username") String username); + + /** + * Get user by user name + * + * @param username The name that needs to be fetched. Use user1 for testing. (required) + * @return User + */ + @RequestLine("GET /user/{username}") + @Headers({ + "Content-type: application/json", + "Accepts: application/json", + }) + User getUserByName(@Param("username") String username); + /** * Logs user into the system * - * @param username The user name for login - * @param password The password for login in clear text + * @param username The user name for login (optional) + * @param password The password for login in clear text (optional) * @return String */ @RequestLine("GET /user/login?username={username}&password={password}") @@ -79,24 +108,11 @@ public interface UserApi extends ApiClient.Api { }) void logoutUser(); - /** - * Get user by user name - * - * @param username The name that needs to be fetched. Use user1 for testing. - * @return User - */ - @RequestLine("GET /user/{username}") - @Headers({ - "Content-type: application/json", - "Accepts: application/json", - }) - User getUserByName(@Param("username") String username); - /** * Updated user * This can only be done by the logged in user. - * @param username name that need to be deleted - * @param body Updated user object + * @param username name that need to be deleted (required) + * @param body Updated user object (optional) * @return void */ @RequestLine("PUT /user/{username}") @@ -106,17 +122,5 @@ public interface UserApi extends ApiClient.Api { }) void updateUser(@Param("username") String username, User body); - /** - * Delete user - * This can only be done by the logged in user. - * @param username The name that needs to be deleted - * @return void - */ - @RequestLine("DELETE /user/{username}") - @Headers({ - "Content-type: application/json", - "Accepts: application/json", - }) - void deleteUser(@Param("username") String username); - + } 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 05753abc4bf..ca030ff6c48 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 @@ -9,7 +9,7 @@ import io.swagger.annotations.ApiModelProperty; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-02-22T15:32:23.465+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-03-14T22:17:50.356+08:00") public class Category { private Long id = null; diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/InlineResponse200.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/InlineResponse200.java index 3cdf734a806..117d23f61f6 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/InlineResponse200.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/InlineResponse200.java @@ -2,19 +2,65 @@ package io.swagger.client.model; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonValue; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; +import io.swagger.client.model.Tag; +import java.util.ArrayList; +import java.util.List; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-03-03T12:04:41.120+08:00") + + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-03-19T15:53:31.820+08:00") public class InlineResponse200 { + private List photoUrls = new ArrayList(); private String name = null; private Long id = null; private Object category = null; + 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 InlineResponse200 photoUrls(List photoUrls) { + this.photoUrls = photoUrls; + return this; + } + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("photoUrls") + public List getPhotoUrls() { + return photoUrls; + } + public void setPhotoUrls(List photoUrls) { + this.photoUrls = photoUrls; + } /** @@ -68,6 +114,41 @@ public class InlineResponse200 { } + /** + **/ + public InlineResponse200 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 InlineResponse200 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) { @@ -78,14 +159,17 @@ public class InlineResponse200 { return false; } InlineResponse200 inlineResponse200 = (InlineResponse200) o; - return Objects.equals(this.name, inlineResponse200.name) && + return Objects.equals(this.photoUrls, inlineResponse200.photoUrls) && + Objects.equals(this.name, inlineResponse200.name) && Objects.equals(this.id, inlineResponse200.id) && - Objects.equals(this.category, inlineResponse200.category); + Objects.equals(this.category, inlineResponse200.category) && + Objects.equals(this.tags, inlineResponse200.tags) && + Objects.equals(this.status, inlineResponse200.status); } @Override public int hashCode() { - return Objects.hash(name, id, category); + return Objects.hash(photoUrls, name, id, category, tags, status); } @Override @@ -93,9 +177,12 @@ public class InlineResponse200 { StringBuilder sb = new StringBuilder(); sb.append("class InlineResponse200 {\n"); + sb.append(" photoUrls: ").append(toIndentedString(photoUrls)).append("\n"); sb.append(" name: ").append(toIndentedString(name)).append("\n"); sb.append(" id: ").append(toIndentedString(id)).append("\n"); sb.append(" category: ").append(toIndentedString(category)).append("\n"); + sb.append(" tags: ").append(toIndentedString(tags)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); sb.append("}"); return sb.toString(); } @@ -112,3 +199,5 @@ public class InlineResponse200 { } } + + 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 new file mode 100644 index 00000000000..882dd6017c9 --- /dev/null +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Model200Response.java @@ -0,0 +1,78 @@ +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + + + + + + + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-03-19T15:53:31.820+08:00") +public class Model200Response { + + private Integer name = 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; + } + + + + @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); + } + + @Override + public int hashCode() { + return Objects.hash(name); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Model200Response {\n"); + + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(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/ModelReturn.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ModelReturn.java new file mode 100644 index 00000000000..d4be9479686 --- /dev/null +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ModelReturn.java @@ -0,0 +1,78 @@ +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + + + + + + + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-03-19T15:53:31.820+08:00") +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/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 new file mode 100644 index 00000000000..a10c13ef806 --- /dev/null +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Name.java @@ -0,0 +1,98 @@ +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + + + + + + + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-03-19T15:53:31.820+08:00") +public class Name { + + private Integer name = null; + private Integer snakeCase = null; + + + /** + **/ + public Name 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 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; + } + + + + @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); + } + + @Override + public int hashCode() { + return Objects.hash(name, snakeCase); + } + + @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("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the 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 a82b360d4fb..a6ae8c7aea8 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 @@ -11,7 +11,7 @@ import java.util.Date; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-02-22T15:32:23.465+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-03-14T22:17:50.356+08:00") public class Order { private Long id = null; 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 9cdfabd89dd..af5ed59eba3 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 @@ -14,7 +14,7 @@ import java.util.List; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-02-22T15:32:23.465+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-03-14T22:17:50.356+08:00") public class Pet { private Long id = null; 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 new file mode 100644 index 00000000000..254f9be4828 --- /dev/null +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/SpecialModelName.java @@ -0,0 +1,78 @@ +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + + + + + + + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-03-19T15:53:31.820+08:00") +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/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 497f1c8424d..30263bf28ae 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 @@ -9,7 +9,7 @@ import io.swagger.annotations.ApiModelProperty; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-02-22T15:32:23.465+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-03-14T22:17:50.356+08:00") public class Tag { private Long id = null; diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/User.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/User.java index 75039e3f237..b3c1d22d367 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 @@ -9,7 +9,7 @@ import io.swagger.annotations.ApiModelProperty; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-02-22T15:32:23.465+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-03-14T22:17:50.356+08:00") public class User { private Long id = null; diff --git a/samples/client/petstore/java/jersey2/.gitignore b/samples/client/petstore/java/jersey2/.gitignore new file mode 100644 index 00000000000..32858aad3c3 --- /dev/null +++ b/samples/client/petstore/java/jersey2/.gitignore @@ -0,0 +1,12 @@ +*.class + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.ear + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* diff --git a/samples/client/petstore/java/jersey2/git_push.sh b/samples/client/petstore/java/jersey2/git_push.sh new file mode 100644 index 00000000000..1a36388db02 --- /dev/null +++ b/samples/client/petstore/java/jersey2/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="YOUR_GIT_USR_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="YOUR_GIT_REPO_ID" + 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/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiClient.java index 77bcbef413c..bc43cfe670e 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiClient.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiClient.java @@ -48,7 +48,7 @@ import io.swagger.client.auth.HttpBasicAuth; import io.swagger.client.auth.ApiKeyAuth; import io.swagger.client.auth.OAuth; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-02-17T17:16:21.885+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-03-17T17:22:31.147+08:00") public class ApiClient { private Map defaultHeaderMap = new HashMap(); private String basePath = "http://petstore.swagger.io/v2"; @@ -80,7 +80,7 @@ public class ApiClient { this.json.setDateFormat((DateFormat) dateFormat.clone()); // Set default User-Agent. - setUserAgent("Java-Swagger"); + setUserAgent("Swagger-Codegen/1.0.0/java"); // Setup authentications (key: authentication name, value: authentication). authentications = new HashMap(); @@ -88,6 +88,7 @@ public class ApiClient { authentications.put("test_api_client_id", new ApiKeyAuth("header", "x-test_api_client_id")); authentications.put("test_api_client_secret", new ApiKeyAuth("header", "x-test_api_client_secret")); authentications.put("api_key", new ApiKeyAuth("header", "api_key")); + authentications.put("test_http_basic", new HttpBasicAuth()); authentications.put("test_api_key_query", new ApiKeyAuth("query", "test_api_key_query")); authentications.put("test_api_key_header", new ApiKeyAuth("header", "test_api_key_header")); // Prevent the authentications from being modified. 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 a5793c1d0de..2f7ef6e3286 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 @@ -3,7 +3,7 @@ package io.swagger.client; import java.util.Map; import java.util.List; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-28T16:23:25.238+01:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-03-14T22:17:48.808+08:00") public class ApiException extends Exception { private int code = 0; private Map> responseHeaders = null; 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 c316be8c331..b06f6a4f6a4 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 @@ package io.swagger.client; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-28T16:23:25.238+01:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-03-14T22:17:48.808+08:00") public class Configuration { private static ApiClient defaultApiClient = new ApiClient(); diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/JSON.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/JSON.java index 0bd23b63091..ff3a5cb782a 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/JSON.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/JSON.java @@ -8,7 +8,7 @@ import java.text.DateFormat; import javax.ws.rs.ext.ContextResolver; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-28T16:23:25.238+01:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-03-14T22:17:48.808+08:00") public class JSON implements ContextResolver { private ObjectMapper mapper; diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/Pair.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/Pair.java index 69e856d15fb..a83256c3b3d 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 @@ package io.swagger.client; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-28T16:23:25.238+01:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-03-14T22:17:48.808+08:00") public class Pair { private String name = ""; private String value = ""; diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/StringUtil.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/StringUtil.java index 98258bfaf15..513c655bd4d 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 @@ package io.swagger.client; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-28T16:23:25.238+01:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-03-14T22:17:48.808+08:00") public class StringUtil { /** * Check if the given array contains the given value (with case-insensitive comparison). diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/PetApi.java index e661539eaba..dff33b11fc4 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,15 +8,15 @@ import io.swagger.client.Pair; import javax.ws.rs.core.GenericType; import io.swagger.client.model.Pet; -import java.io.File; import io.swagger.client.model.InlineResponse200; +import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-03-03T12:04:39.601+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-03-17T16:00:50.657+08:00") public class PetApi { private ApiClient apiClient; @@ -37,50 +37,10 @@ public class PetApi { } - /** - * Update an existing pet - * - * @param body Pet object that needs to be added to the store - * @throws ApiException if fails to make API call - */ - public void updatePet(Pet body) throws ApiException { - Object localVarPostBody = body; - - // 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/json", "application/xml" - }; - 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); - - } - /** * Add a new pet to the store * - * @param body Pet object that needs to be added to the store + * @param body Pet object that needs to be added to the store (optional) * @throws ApiException if fails to make API call */ public void addPet(Pet body) throws ApiException { @@ -118,160 +78,16 @@ public class PetApi { } /** - * Finds Pets by status - * Multiple status values can be provided with comma separated strings - * @param status Status values that need to be considered for query - * @return List - * @throws ApiException if fails to make API call - */ - public List findPetsByStatus(List status) throws ApiException { - Object localVarPostBody = null; - - // 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("multi", "status", status)); - - - - - - - final String[] localVarAccepts = { - "application/json", "application/xml" - }; - 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 - * Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. - * @param tags Tags to filter by - * @return List - * @throws ApiException if fails to make API call - */ - public List findPetsByTags(List tags) throws ApiException { - Object localVarPostBody = null; - - // 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("multi", "tags", tags)); - - - - - - - final String[] localVarAccepts = { - "application/json", "application/xml" - }; - 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 pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions - * @param petId ID of pet that needs to be fetched - * @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/json", "application/xml" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { "petstore_auth", "api_key" }; - - - GenericType localVarReturnType = new GenericType() {}; - return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); - - } - - /** - * Updates a pet in the store with form data + * Fake endpoint to test byte array in body parameter for adding a new pet to the store * - * @param petId ID of pet that needs to be updated - * @param name Updated name of the pet - * @param status Updated status of the pet + * @param body Pet object in the form of byte array (optional) * @throws ApiException if fails to make API call */ - public void updatePetWithForm(String 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"); - } + public void addPetUsingByteArray(byte[] body) throws ApiException { + Object localVarPostBody = body; // create path and map variables - String localVarPath = "/pet/{petId}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); + String localVarPath = "/pet?testing_byte_array=true".replaceAll("\\{format\\}","json"); // query params List localVarQueryParams = new ArrayList(); @@ -282,10 +98,6 @@ public class PetApi { - if (name != null) - localVarFormParams.put("name", name); - if (status != null) - localVarFormParams.put("status", status); final String[] localVarAccepts = { @@ -294,7 +106,7 @@ public class PetApi { final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] localVarContentTypes = { - "application/x-www-form-urlencoded" + "application/json", "application/xml" }; final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); @@ -308,8 +120,8 @@ public class PetApi { /** * Deletes a pet * - * @param petId Pet id to delete - * @param apiKey + * @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 { @@ -355,23 +167,110 @@ public class PetApi { } /** - * uploads an image - * - * @param petId ID of pet to update - * @param additionalMetadata Additional data to pass to server - * @param file file to upload + * Finds Pets by status + * Multiple status values can be provided with comma separated strings + * @param status Status values that need to be considered for query (optional, default to available) + * @return List * @throws ApiException if fails to make API call */ - public void uploadFile(Long petId, String additionalMetadata, File file) throws ApiException { + public List findPetsByStatus(List status) throws ApiException { + Object localVarPostBody = null; + + // 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("multi", "status", status)); + + + + + + + final String[] localVarAccepts = { + "application/json", "application/xml" + }; + 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 + * Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + * @param tags Tags to filter by (optional) + * @return List + * @throws ApiException if fails to make API call + */ + public List findPetsByTags(List tags) throws ApiException { + Object localVarPostBody = null; + + // 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("multi", "tags", tags)); + + + + + + + final String[] localVarAccepts = { + "application/json", "application/xml" + }; + 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 pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + * @param petId ID of pet that needs to be fetched (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 uploadFile"); + throw new ApiException(400, "Missing the required parameter 'petId' when calling getPetById"); } // create path and map variables - String localVarPath = "/pet/{petId}/uploadImage".replaceAll("\\{format\\}","json") + String localVarPath = "/pet/{petId}".replaceAll("\\{format\\}","json") .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); // query params @@ -383,10 +282,6 @@ public class PetApi { - if (additionalMetadata != null) - localVarFormParams.put("additionalMetadata", additionalMetadata); - if (file != null) - localVarFormParams.put("file", file); final String[] localVarAccepts = { @@ -395,21 +290,22 @@ public class PetApi { final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] localVarContentTypes = { - "multipart/form-data" + }; final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - String[] localVarAuthNames = new String[] { "petstore_auth" }; + String[] localVarAuthNames = new String[] { "petstore_auth", "api_key" }; - apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); + GenericType localVarReturnType = new GenericType() {}; + return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); } /** * Fake endpoint to test inline arbitrary object return by 'Find pet by ID' * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions - * @param petId ID of pet that needs to be fetched + * @param petId ID of pet that needs to be fetched (required) * @return InlineResponse200 * @throws ApiException if fails to make API call */ @@ -457,7 +353,7 @@ public class PetApi { /** * Fake endpoint to test byte array return by 'Find pet by ID' * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions - * @param petId ID of pet that needs to be fetched + * @param petId ID of pet that needs to be fetched (required) * @return byte[] * @throws ApiException if fails to make API call */ @@ -503,16 +399,16 @@ public class PetApi { } /** - * Fake endpoint to test byte array in body parameter for adding a new pet to the store + * Update an existing pet * - * @param body Pet object in the form of byte array + * @param body Pet object that needs to be added to the store (optional) * @throws ApiException if fails to make API call */ - public void addPetUsingByteArray(byte[] body) throws ApiException { + public void updatePet(Pet body) throws ApiException { Object localVarPostBody = body; // create path and map variables - String localVarPath = "/pet?testing_byte_array=true".replaceAll("\\{format\\}","json"); + String localVarPath = "/pet".replaceAll("\\{format\\}","json"); // query params List localVarQueryParams = new ArrayList(); @@ -538,6 +434,110 @@ public class PetApi { 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(String 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/json", "application/xml" + }; + 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) + * @throws ApiException if fails to make API call + */ + public void 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", "application/xml" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + "multipart/form-data" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + + apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/StoreApi.java index 73801be33da..9b7bf83fea4 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/StoreApi.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/StoreApi.java @@ -14,7 +14,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-03-03T12:04:39.601+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-03-17T16:00:50.657+08:00") public class StoreApi { private ApiClient apiClient; @@ -35,10 +35,56 @@ public class 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) + * @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/json", "application/xml" + }; + 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); + + } + /** * Finds orders by status * A single status value can be provided as a string - * @param status Status value that needs to be considered for query + * @param status Status value that needs to be considered for query (optional, default to placed) * @return List * @throws ApiException if fails to make API call */ @@ -161,52 +207,10 @@ public class StoreApi { } - /** - * Place an order for a pet - * - * @param body order placed for purchasing the pet - * @return Order - * @throws ApiException if fails to make API call - */ - public Order placeOrder(Order body) throws ApiException { - Object localVarPostBody = body; - - // 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/json", "application/xml" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { "test_api_client_id", "test_api_client_secret" }; - - - GenericType localVarReturnType = new GenericType() {}; - return apiClient.invokeAPI(localVarPath, "POST", 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 + * @param orderId ID of pet that needs to be fetched (required) * @return Order * @throws ApiException if fails to make API call */ @@ -252,22 +256,17 @@ public class 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 + * Place an order for a pet + * + * @param body order placed for purchasing the pet (optional) + * @return Order * @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"); - } + public Order placeOrder(Order body) throws ApiException { + Object localVarPostBody = body; // create path and map variables - String localVarPath = "/store/order/{orderId}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.toString())); + String localVarPath = "/store/order".replaceAll("\\{format\\}","json"); // query params List localVarQueryParams = new ArrayList(); @@ -290,10 +289,11 @@ public class StoreApi { }; final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - String[] localVarAuthNames = new String[] { }; + String[] localVarAuthNames = new String[] { "test_api_client_id", "test_api_client_secret" }; - apiClient.invokeAPI(localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); + 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/src/main/java/io/swagger/client/api/UserApi.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/UserApi.java index 267c1396285..47334096488 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/UserApi.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/UserApi.java @@ -14,7 +14,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-02-29T12:55:37.248+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-03-17T16:00:50.657+08:00") public class UserApi { private ApiClient apiClient; @@ -38,7 +38,7 @@ public class UserApi { /** * Create user * This can only be done by the logged in user. - * @param body Created user object + * @param body Created user object (optional) * @throws ApiException if fails to make API call */ public void createUser(User body) throws ApiException { @@ -78,7 +78,7 @@ public class UserApi { /** * Creates list of users with given input array * - * @param body List of user object + * @param body List of user object (optional) * @throws ApiException if fails to make API call */ public void createUsersWithArrayInput(List body) throws ApiException { @@ -118,7 +118,7 @@ public class UserApi { /** * Creates list of users with given input array * - * @param body List of user object + * @param body List of user object (optional) * @throws ApiException if fails to make API call */ public void createUsersWithListInput(List body) throws ApiException { @@ -155,11 +155,105 @@ public class UserApi { } + /** + * 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/json", "application/xml" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "test_http_basic" }; + + + 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/json", "application/xml" + }; + 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 - * @param password The password for login in clear text + * @param username The user name for login (optional) + * @param password The password for login in clear text (optional) * @return String * @throws ApiException if fails to make API call */ @@ -241,59 +335,11 @@ public class UserApi { } - /** - * Get user by user name - * - * @param username The name that needs to be fetched. Use user1 for testing. - * @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/json", "application/xml" - }; - 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); - - } - /** * Updated user * This can only be done by the logged in user. - * @param username name that need to be deleted - * @param body Updated user object + * @param username name that need to be deleted (required) + * @param body Updated user object (optional) * @throws ApiException if fails to make API call */ public void updateUser(String username, User body) throws ApiException { @@ -336,50 +382,4 @@ public class UserApi { } - /** - * Delete user - * This can only be done by the logged in user. - * @param username The name that needs to be deleted - * @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/json", "application/xml" - }; - 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); - - } - } 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 36168ed506f..4687d6782e1 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 @@ -5,7 +5,7 @@ import io.swagger.client.Pair; import java.util.Map; import java.util.List; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-28T16:23:25.238+01:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-03-14T22:17:48.808+08:00") public class ApiKeyAuth implements Authentication { private final String location; private final String paramName; diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/HttpBasicAuth.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/HttpBasicAuth.java index cfc36fc4777..0b20480ec95 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 @@ -9,7 +9,7 @@ import java.util.List; import java.io.UnsupportedEncodingException; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-28T16:23:25.238+01:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-03-14T22:17:48.808+08:00") public class HttpBasicAuth implements Authentication { private String username; private String password; diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/OAuth.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/OAuth.java index 4586e3f1879..15a655f826c 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 @@ -5,7 +5,7 @@ import io.swagger.client.Pair; import java.util.Map; import java.util.List; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-28T16:23:25.238+01:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-03-14T22:17:48.808+08:00") public class OAuth implements Authentication { private String accessToken; 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 cb9ca56b44f..0a81b468c6e 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 @@ -9,7 +9,7 @@ import io.swagger.annotations.ApiModelProperty; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-02-22T15:34:25.436+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-03-14T22:17:48.808+08:00") public class Category { private Long id = null; diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/InlineResponse200.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/InlineResponse200.java index a966f51c800..36019aa9c4b 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/InlineResponse200.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/InlineResponse200.java @@ -2,35 +2,62 @@ package io.swagger.client.model; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonValue; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; +import io.swagger.client.model.Tag; +import java.util.ArrayList; +import java.util.List; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-03-03T12:04:39.601+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-03-14T22:17:48.808+08:00") public class InlineResponse200 { - private String name = null; + private List tags = new ArrayList(); private Long id = null; private Object category = null; + + 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; + private String name = null; + private List photoUrls = new ArrayList(); + /** **/ - public InlineResponse200 name(String name) { - this.name = name; + public InlineResponse200 tags(List tags) { + this.tags = tags; return this; } - @ApiModelProperty(example = "doggie", value = "") - @JsonProperty("name") - public String getName() { - return name; + @ApiModelProperty(example = "null", value = "") + @JsonProperty("tags") + public List getTags() { + return tags; } - public void setName(String name) { - this.name = name; + public void setTags(List tags) { + this.tags = tags; } @@ -68,6 +95,58 @@ public class InlineResponse200 { } + /** + * pet status in the store + **/ + public InlineResponse200 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; + } + + + /** + **/ + public InlineResponse200 name(String name) { + this.name = name; + return this; + } + + @ApiModelProperty(example = "doggie", value = "") + @JsonProperty("name") + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + + + /** + **/ + public InlineResponse200 photoUrls(List photoUrls) { + this.photoUrls = photoUrls; + return this; + } + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("photoUrls") + public List getPhotoUrls() { + return photoUrls; + } + public void setPhotoUrls(List photoUrls) { + this.photoUrls = photoUrls; + } + + @Override public boolean equals(java.lang.Object o) { @@ -78,14 +157,17 @@ public class InlineResponse200 { return false; } InlineResponse200 inlineResponse200 = (InlineResponse200) o; - return Objects.equals(this.name, inlineResponse200.name) && + return Objects.equals(this.tags, inlineResponse200.tags) && Objects.equals(this.id, inlineResponse200.id) && - Objects.equals(this.category, inlineResponse200.category); + Objects.equals(this.category, inlineResponse200.category) && + Objects.equals(this.status, inlineResponse200.status) && + Objects.equals(this.name, inlineResponse200.name) && + Objects.equals(this.photoUrls, inlineResponse200.photoUrls); } @Override public int hashCode() { - return Objects.hash(name, id, category); + return Objects.hash(tags, id, category, status, name, photoUrls); } @Override @@ -93,9 +175,12 @@ public class InlineResponse200 { StringBuilder sb = new StringBuilder(); sb.append("class InlineResponse200 {\n"); - sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" tags: ").append(toIndentedString(tags)).append("\n"); sb.append(" id: ").append(toIndentedString(id)).append("\n"); sb.append(" category: ").append(toIndentedString(category)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" photoUrls: ").append(toIndentedString(photoUrls)).append("\n"); sb.append("}"); return sb.toString(); } 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 new file mode 100644 index 00000000000..a05d493feb6 --- /dev/null +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Model200Response.java @@ -0,0 +1,74 @@ +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + + + + + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-03-17T16:00:50.657+08:00") +public class Model200Response { + + private Integer name = 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; + } + + + + @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); + } + + @Override + public int hashCode() { + return Objects.hash(name); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Model200Response {\n"); + + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(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/ModelReturn.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ModelReturn.java new file mode 100644 index 00000000000..e2e95fd0f77 --- /dev/null +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ModelReturn.java @@ -0,0 +1,74 @@ +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + + + + + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-03-17T16:00:50.657+08:00") +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/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 new file mode 100644 index 00000000000..fc0985915ce --- /dev/null +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Name.java @@ -0,0 +1,74 @@ +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + + + + + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-03-17T16:00:50.657+08:00") +public class Name { + + private Integer name = null; + + + /** + **/ + public Name 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; + } + + + + @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); + } + + @Override + public int hashCode() { + return Objects.hash(name); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Name {\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/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 3f29f00fab3..943ddd37306 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 @@ -11,7 +11,7 @@ import java.util.Date; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-02-22T15:34:25.436+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-03-14T22:17:48.808+08:00") public class Order { private Long id = null; 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 7f3418d5bd9..1c434aa687d 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 @@ -14,7 +14,7 @@ import java.util.List; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-02-22T15:34:25.436+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-03-14T22:17:48.808+08:00") public class Pet { private Long id = null; 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 new file mode 100644 index 00000000000..0349889b190 --- /dev/null +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/SpecialModelName.java @@ -0,0 +1,74 @@ +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + + + + + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-03-17T16:00:50.657+08:00") +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/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 76e9f52750a..437b42c44be 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 @@ -9,7 +9,7 @@ import io.swagger.annotations.ApiModelProperty; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-02-22T15:34:25.436+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-03-14T22:17:48.808+08:00") public class Tag { private Long id = null; diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/User.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/User.java index dd91724f652..f6299149305 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 @@ -9,7 +9,7 @@ import io.swagger.annotations.ApiModelProperty; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-02-22T15:34:25.436+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-03-14T22:17:48.808+08:00") public class User { private Long id = null; diff --git a/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/ApiClientTest.java b/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/ApiClientTest.java index 9fa51a06baa..47f004c283b 100644 --- a/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/ApiClientTest.java +++ b/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/ApiClientTest.java @@ -112,21 +112,25 @@ public class ApiClientTest { } @Test - public void testSetUsername() { - try { - apiClient.setUsername("my-username"); - fail("there should be no HTTP basic authentications"); - } catch (RuntimeException e) { + 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); - @Test - public void testSetPassword() { - try { - apiClient.setPassword("my-password"); - fail("there should be no HTTP basic authentications"); - } catch (RuntimeException e) { - } + 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 diff --git a/samples/client/petstore/java/okhttp-gson/.gitignore b/samples/client/petstore/java/okhttp-gson/.gitignore new file mode 100644 index 00000000000..32858aad3c3 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/.gitignore @@ -0,0 +1,12 @@ +*.class + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.ear + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* diff --git a/samples/client/petstore/java/okhttp-gson/git_push.sh b/samples/client/petstore/java/okhttp-gson/git_push.sh new file mode 100644 index 00000000000..1a36388db02 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/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="YOUR_GIT_USR_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="YOUR_GIT_REPO_ID" + 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/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiClient.java index 0f853388744..ef5ae6fa25d 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 @@ -141,7 +141,7 @@ public class ApiClient { this.lenientDatetimeFormat = true; // Set default User-Agent. - setUserAgent("Java-Swagger"); + setUserAgent("Swagger-Codegen/1.0.0/java"); // Setup authentications (key: authentication name, value: authentication). authentications = new HashMap(); @@ -149,6 +149,7 @@ public class ApiClient { authentications.put("test_api_client_id", new ApiKeyAuth("header", "x-test_api_client_id")); authentications.put("test_api_client_secret", new ApiKeyAuth("header", "x-test_api_client_secret")); authentications.put("api_key", new ApiKeyAuth("header", "api_key")); + authentications.put("test_http_basic", new HttpBasicAuth()); authentications.put("test_api_key_query", new ApiKeyAuth("query", "test_api_key_query")); authentications.put("test_api_key_header", new ApiKeyAuth("header", "test_api_key_header")); // Prevent the authentications from being modified. diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiException.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiException.java index 5355f1a187e..529f9fff8dd 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiException.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiException.java @@ -3,7 +3,7 @@ package io.swagger.client; import java.util.Map; import java.util.List; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-02-15T18:20:42.151+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-03-14T22:17:51.831+08:00") public class ApiException extends Exception { private int code = 0; private Map> responseHeaders = null; diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/Configuration.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/Configuration.java index 6be94b99493..c4c80febb52 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/Configuration.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/Configuration.java @@ -1,6 +1,6 @@ package io.swagger.client; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-02-15T18:20:42.151+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-03-14T22:17:51.831+08:00") public class Configuration { private static ApiClient defaultApiClient = new ApiClient(); diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/Pair.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/Pair.java index 5017f33d152..86d8f1de128 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/Pair.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/Pair.java @@ -1,6 +1,6 @@ package io.swagger.client; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-02-15T18:20:42.151+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-03-14T22:17:51.831+08:00") public class Pair { private String name = ""; private String value = ""; diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/StringUtil.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/StringUtil.java index 9e910ae1b10..f9f52549100 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/StringUtil.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/StringUtil.java @@ -1,6 +1,6 @@ package io.swagger.client; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-02-15T18:20:42.151+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-03-14T22:17:51.831+08:00") public class StringUtil { /** * Check if the given array contains the given value (with case-insensitive comparison). diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/PetApi.java index df64a903099..507f838e341 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/PetApi.java @@ -18,8 +18,8 @@ import com.squareup.okhttp.Response; import java.io.IOException; import io.swagger.client.model.Pet; -import java.io.File; import io.swagger.client.model.InlineResponse200; +import java.io.File; import java.lang.reflect.Type; import java.util.ArrayList; @@ -47,104 +47,6 @@ public class PetApi { } - /* Build call for updatePet */ - private Call updatePetCall(Pet body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = body; - - - // create path and map variables - String localVarPath = "/pet".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/json", "application/xml" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - "application/json", "application/xml" - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new Interceptor() { - @Override - public Response intercept(Interceptor.Chain chain) throws IOException { - Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - 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 - * @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 - * @return ApiResponse - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse updatePetWithHttpInfo(Pet body) throws ApiException { - Call call = updatePetCall(body, null, null); - return apiClient.execute(call); - } - - /** - * Update an existing pet (asynchronously) - * - * @param body Pet object that needs to be added to the store - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public Call updatePetAsync(Pet body, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - Call call = updatePetCall(body, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } - /* Build call for addPet */ private Call addPetCall(Pet body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object localVarPostBody = body; @@ -190,7 +92,7 @@ public class PetApi { /** * Add a new pet to the store * - * @param body Pet object that needs to be added to the store + * @param body Pet object that needs to be added to the store (optional) * @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 { @@ -200,7 +102,7 @@ public class PetApi { /** * Add a new pet to the store * - * @param body Pet object that needs to be added to the store + * @param body Pet object that needs to be added to the store (optional) * @return ApiResponse * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ @@ -212,7 +114,7 @@ public class PetApi { /** * Add a new pet to the store (asynchronously) * - * @param body Pet object that needs to be added to the store + * @param body Pet object that needs to be added to the store (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 @@ -243,6 +145,213 @@ public class PetApi { return call; } + /* Build call for addPetUsingByteArray */ + private Call addPetUsingByteArrayCall(byte[] body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = body; + + + // create path and map variables + String localVarPath = "/pet?testing_byte_array=true".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/json", "application/xml" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + "application/json", "application/xml" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new Interceptor() { + @Override + public Response intercept(Interceptor.Chain chain) throws IOException { + Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Fake endpoint to test byte array in body parameter for adding a new pet to the store + * + * @param body Pet object in the form of byte array (optional) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void addPetUsingByteArray(byte[] body) throws ApiException { + addPetUsingByteArrayWithHttpInfo(body); + } + + /** + * Fake endpoint to test byte array in body parameter for adding a new pet to the store + * + * @param body Pet object in the form of byte array (optional) + * @return ApiResponse + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse addPetUsingByteArrayWithHttpInfo(byte[] body) throws ApiException { + Call call = addPetUsingByteArrayCall(body, null, null); + return apiClient.execute(call); + } + + /** + * Fake endpoint to test byte array in body parameter for adding a new pet to the store (asynchronously) + * + * @param body Pet object in the form of byte array (optional) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public Call addPetUsingByteArrayAsync(byte[] 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); + } + }; + } + + Call call = addPetUsingByteArrayCall(body, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + + /* Build call for deletePet */ + private Call deletePetCall(Long petId, String apiKey, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException("Missing the required parameter 'petId' when calling deletePet(Async)"); + } + + + // create path and map variables + String localVarPath = "/pet/{petId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + if (apiKey != null) + localVarHeaderParams.put("api_key", apiClient.parameterToString(apiKey)); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/json", "application/xml" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new Interceptor() { + @Override + public Response intercept(Interceptor.Chain chain) throws IOException { + Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + return apiClient.buildCall(localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Deletes a pet + * + * @param petId Pet id to delete (required) + * @param apiKey (optional) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void deletePet(Long petId, String apiKey) throws ApiException { + deletePetWithHttpInfo(petId, apiKey); + } + + /** + * Deletes a pet + * + * @param petId Pet id to delete (required) + * @param apiKey (optional) + * @return ApiResponse + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse deletePetWithHttpInfo(Long petId, String apiKey) throws ApiException { + Call call = deletePetCall(petId, apiKey, null, null); + return apiClient.execute(call); + } + + /** + * Deletes a pet (asynchronously) + * + * @param petId Pet id to delete (required) + * @param apiKey (optional) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public Call deletePetAsync(Long petId, String apiKey, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + Call call = deletePetCall(petId, apiKey, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for findPetsByStatus */ private Call findPetsByStatusCall(List status, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object localVarPostBody = null; @@ -290,7 +399,7 @@ public class PetApi { /** * Finds Pets by status * Multiple status values can be provided with comma separated strings - * @param status Status values that need to be considered for query + * @param status Status values that need to be considered for query (optional, default to available) * @return List * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ @@ -302,7 +411,7 @@ public class PetApi { /** * Finds Pets by status * Multiple status values can be provided with comma separated strings - * @param status Status values that need to be considered for query + * @param status Status values that need to be considered for query (optional, default to available) * @return ApiResponse> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ @@ -315,7 +424,7 @@ public class PetApi { /** * 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 query + * @param status Status values that need to be considered for query (optional, default to available) * @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 @@ -394,7 +503,7 @@ public class PetApi { /** * Finds Pets by tags * Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. - * @param tags Tags to filter by + * @param tags Tags to filter by (optional) * @return List * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ @@ -406,7 +515,7 @@ public class PetApi { /** * Finds Pets by tags * Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. - * @param tags Tags to filter by + * @param tags Tags to filter by (optional) * @return ApiResponse> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ @@ -419,7 +528,7 @@ public class PetApi { /** * Finds Pets by tags (asynchronously) * Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. - * @param tags Tags to filter by + * @param tags Tags to filter by (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 @@ -502,7 +611,7 @@ public class PetApi { /** * Find pet by ID * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions - * @param petId ID of pet that needs to be fetched + * @param petId ID of pet that needs to be fetched (required) * @return Pet * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ @@ -514,7 +623,7 @@ public class PetApi { /** * Find pet by ID * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions - * @param petId ID of pet that needs to be fetched + * @param petId ID of pet that needs to be fetched (required) * @return ApiResponse * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ @@ -527,7 +636,7 @@ public class PetApi { /** * Find pet by ID (asynchronously) * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions - * @param petId ID of pet that needs to be fetched + * @param petId 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 @@ -559,343 +668,6 @@ public class PetApi { return call; } - /* Build call for updatePetWithForm */ - private Call updatePetWithFormCall(String 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/json", "application/xml" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - "application/x-www-form-urlencoded" - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new Interceptor() { - @Override - public Response intercept(Interceptor.Chain chain) throws IOException { - Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - 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 - * @param name Updated name of the pet - * @param status Updated status of the pet - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void updatePetWithForm(String 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 - * @param name Updated name of the pet - * @param status Updated status of the pet - * @return ApiResponse - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse updatePetWithFormWithHttpInfo(String petId, String name, String status) throws ApiException { - 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 - * @param name Updated name of the pet - * @param status Updated status of the pet - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public Call updatePetWithFormAsync(String 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); - } - }; - } - - Call call = updatePetWithFormCall(petId, name, status, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } - - /* Build call for deletePet */ - private Call deletePetCall(Long petId, String apiKey, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'petId' is set - if (petId == null) { - throw new ApiException("Missing the required parameter 'petId' when calling deletePet(Async)"); - } - - - // create path and map variables - String localVarPath = "/pet/{petId}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - if (apiKey != null) - localVarHeaderParams.put("api_key", apiClient.parameterToString(apiKey)); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/json", "application/xml" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new Interceptor() { - @Override - public Response intercept(Interceptor.Chain chain) throws IOException { - Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - 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 - * @param apiKey - * @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 - * @param apiKey - * @return ApiResponse - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse deletePetWithHttpInfo(Long petId, String apiKey) throws ApiException { - Call call = deletePetCall(petId, apiKey, null, null); - return apiClient.execute(call); - } - - /** - * Deletes a pet (asynchronously) - * - * @param petId Pet id to delete - * @param apiKey - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public Call deletePetAsync(Long petId, String apiKey, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - Call call = deletePetCall(petId, apiKey, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } - - /* Build call for uploadFile */ - private Call uploadFileCall(Long petId, String additionalMetadata, File file, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'petId' is set - if (petId == null) { - throw new ApiException("Missing the required parameter 'petId' when calling uploadFile(Async)"); - } - - - // create path and map variables - String localVarPath = "/pet/{petId}/uploadImage".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - if (additionalMetadata != null) - localVarFormParams.put("additionalMetadata", additionalMetadata); - if (file != null) - localVarFormParams.put("file", file); - - final String[] localVarAccepts = { - "application/json", "application/xml" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - "multipart/form-data" - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new Interceptor() { - @Override - public Response intercept(Interceptor.Chain chain) throws IOException { - Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - 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 - * @param additionalMetadata Additional data to pass to server - * @param file file to upload - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void uploadFile(Long petId, String additionalMetadata, File file) throws ApiException { - uploadFileWithHttpInfo(petId, additionalMetadata, file); - } - - /** - * uploads an image - * - * @param petId ID of pet to update - * @param additionalMetadata Additional data to pass to server - * @param file file to upload - * @return ApiResponse - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse uploadFileWithHttpInfo(Long petId, String additionalMetadata, File file) throws ApiException { - Call call = uploadFileCall(petId, additionalMetadata, file, null, null); - return apiClient.execute(call); - } - - /** - * uploads an image (asynchronously) - * - * @param petId ID of pet to update - * @param additionalMetadata Additional data to pass to server - * @param file file to upload - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public Call uploadFileAsync(Long petId, String additionalMetadata, File file, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - Call call = uploadFileCall(petId, additionalMetadata, file, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } - /* Build call for getPetByIdInObject */ private Call getPetByIdInObjectCall(Long petId, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object localVarPostBody = null; @@ -947,7 +719,7 @@ public class PetApi { /** * Fake endpoint to test inline arbitrary object return by 'Find pet by ID' * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions - * @param petId ID of pet that needs to be fetched + * @param petId ID of pet that needs to be fetched (required) * @return InlineResponse200 * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ @@ -959,7 +731,7 @@ public class PetApi { /** * Fake endpoint to test inline arbitrary object return by 'Find pet by ID' * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions - * @param petId ID of pet that needs to be fetched + * @param petId ID of pet that needs to be fetched (required) * @return ApiResponse * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ @@ -972,7 +744,7 @@ public class PetApi { /** * Fake endpoint to test inline arbitrary object return by 'Find pet by ID' (asynchronously) * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions - * @param petId ID of pet that needs to be fetched + * @param petId 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 @@ -1055,7 +827,7 @@ public class PetApi { /** * Fake endpoint to test byte array return by 'Find pet by ID' * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions - * @param petId ID of pet that needs to be fetched + * @param petId ID of pet that needs to be fetched (required) * @return byte[] * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ @@ -1067,7 +839,7 @@ public class PetApi { /** * Fake endpoint to test byte array return by 'Find pet by ID' * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions - * @param petId ID of pet that needs to be fetched + * @param petId ID of pet that needs to be fetched (required) * @return ApiResponse * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ @@ -1080,7 +852,7 @@ public class PetApi { /** * Fake endpoint to test byte array return by 'Find pet by ID' (asynchronously) * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions - * @param petId ID of pet that needs to be fetched + * @param petId 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 @@ -1112,13 +884,13 @@ public class PetApi { return call; } - /* Build call for addPetUsingByteArray */ - private Call addPetUsingByteArrayCall(byte[] body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + /* Build call for updatePet */ + private Call updatePetCall(Pet body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object localVarPostBody = body; // create path and map variables - String localVarPath = "/pet?testing_byte_array=true".replaceAll("\\{format\\}","json"); + String localVarPath = "/pet".replaceAll("\\{format\\}","json"); List localVarQueryParams = new ArrayList(); @@ -1151,40 +923,40 @@ public class PetApi { } String[] localVarAuthNames = new String[] { "petstore_auth" }; - return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + return apiClient.buildCall(localVarPath, "PUT", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } /** - * Fake endpoint to test byte array in body parameter for adding a new pet to the store + * Update an existing pet * - * @param body Pet object in the form of byte array + * @param body Pet object that needs to be added to the store (optional) * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ - public void addPetUsingByteArray(byte[] body) throws ApiException { - addPetUsingByteArrayWithHttpInfo(body); + public void updatePet(Pet body) throws ApiException { + updatePetWithHttpInfo(body); } /** - * Fake endpoint to test byte array in body parameter for adding a new pet to the store + * Update an existing pet * - * @param body Pet object in the form of byte array + * @param body Pet object that needs to be added to the store (optional) * @return ApiResponse * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ - public ApiResponse addPetUsingByteArrayWithHttpInfo(byte[] body) throws ApiException { - Call call = addPetUsingByteArrayCall(body, null, null); + public ApiResponse updatePetWithHttpInfo(Pet body) throws ApiException { + Call call = updatePetCall(body, null, null); return apiClient.execute(call); } /** - * Fake endpoint to test byte array in body parameter for adding a new pet to the store (asynchronously) + * Update an existing pet (asynchronously) * - * @param body Pet object in the form of byte array + * @param body Pet object that needs to be added to the store (optional) * @param callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object */ - public Call addPetUsingByteArrayAsync(byte[] body, final ApiCallback callback) throws ApiException { + public Call updatePetAsync(Pet body, final ApiCallback callback) throws ApiException { ProgressResponseBody.ProgressListener progressListener = null; ProgressRequestBody.ProgressRequestListener progressRequestListener = null; @@ -1205,7 +977,235 @@ public class PetApi { }; } - Call call = addPetUsingByteArrayCall(body, progressListener, progressRequestListener); + Call call = updatePetCall(body, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + + /* Build call for updatePetWithForm */ + private Call updatePetWithFormCall(String 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/json", "application/xml" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + "application/x-www-form-urlencoded" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new Interceptor() { + @Override + public Response intercept(Interceptor.Chain chain) throws IOException { + Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + 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(String 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 + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse updatePetWithFormWithHttpInfo(String petId, String name, String status) throws ApiException { + 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 Call updatePetWithFormAsync(String 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); + } + }; + } + + Call call = updatePetWithFormCall(petId, name, status, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + + /* Build call for uploadFile */ + private Call uploadFileCall(Long petId, String additionalMetadata, File file, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException("Missing the required parameter 'petId' when calling uploadFile(Async)"); + } + + + // create path and map variables + String localVarPath = "/pet/{petId}/uploadImage".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + if (additionalMetadata != null) + localVarFormParams.put("additionalMetadata", additionalMetadata); + if (file != null) + localVarFormParams.put("file", file); + + final String[] localVarAccepts = { + "application/json", "application/xml" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + "multipart/form-data" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new Interceptor() { + @Override + public Response intercept(Interceptor.Chain chain) throws IOException { + Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + 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) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void uploadFile(Long petId, String additionalMetadata, File file) throws ApiException { + uploadFileWithHttpInfo(petId, additionalMetadata, file); + } + + /** + * uploads an image + * + * @param petId ID of pet to update (required) + * @param additionalMetadata Additional data to pass to server (optional) + * @param file file to upload (optional) + * @return ApiResponse + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse uploadFileWithHttpInfo(Long petId, String additionalMetadata, File file) throws ApiException { + Call call = uploadFileCall(petId, additionalMetadata, file, null, null); + return apiClient.execute(call); + } + + /** + * uploads an image (asynchronously) + * + * @param petId ID of pet to update (required) + * @param additionalMetadata Additional data to pass to server (optional) + * @param file file to upload (optional) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public Call uploadFileAsync(Long petId, String additionalMetadata, File file, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + Call call = uploadFileCall(petId, additionalMetadata, file, progressListener, progressRequestListener); apiClient.executeAsync(call, callback); return call; } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/StoreApi.java index 7625fae65b9..086db3000d8 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/StoreApi.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/StoreApi.java @@ -45,6 +45,110 @@ public class StoreApi { } + /* Build call for deleteOrder */ + private Call deleteOrderCall(String orderId, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'orderId' is set + if (orderId == null) { + throw new ApiException("Missing the required parameter 'orderId' when calling deleteOrder(Async)"); + } + + + // create path and map variables + String localVarPath = "/store/order/{orderId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.toString())); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/json", "application/xml" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new Interceptor() { + @Override + public Response intercept(Interceptor.Chain chain) throws IOException { + Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Delete purchase order by ID + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * @param orderId ID of the order that needs to be deleted (required) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void deleteOrder(String orderId) throws ApiException { + deleteOrderWithHttpInfo(orderId); + } + + /** + * Delete purchase order by ID + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * @param orderId ID of the order that needs to be deleted (required) + * @return ApiResponse + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse deleteOrderWithHttpInfo(String orderId) throws ApiException { + Call call = deleteOrderCall(orderId, null, null); + return apiClient.execute(call); + } + + /** + * Delete purchase order by ID (asynchronously) + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * @param orderId ID of the order that needs to be deleted (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public Call deleteOrderAsync(String orderId, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + Call call = deleteOrderCall(orderId, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for findOrdersByStatus */ private Call findOrdersByStatusCall(String status, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object localVarPostBody = null; @@ -92,7 +196,7 @@ public class StoreApi { /** * Finds orders by status * A single status value can be provided as a string - * @param status Status value that needs to be considered for query + * @param status Status value that needs to be considered for query (optional, default to placed) * @return List * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ @@ -104,7 +208,7 @@ public class StoreApi { /** * Finds orders by status * A single status value can be provided as a string - * @param status Status value that needs to be considered for query + * @param status Status value that needs to be considered for query (optional, default to placed) * @return ApiResponse> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ @@ -117,7 +221,7 @@ public class StoreApi { /** * Finds orders by status (asynchronously) * A single status value can be provided as a string - * @param status Status value that needs to be considered for query + * @param status Status value that needs to be considered for query (optional, default to placed) * @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 @@ -347,108 +451,6 @@ public class StoreApi { return call; } - /* Build call for placeOrder */ - private Call placeOrderCall(Order body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = body; - - - // create path and map variables - String localVarPath = "/store/order".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/json", "application/xml" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new Interceptor() { - @Override - public Response intercept(Interceptor.Chain chain) throws IOException { - Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { "test_api_client_id", "test_api_client_secret" }; - 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 - * @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 - * @return ApiResponse - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse placeOrderWithHttpInfo(Order body) throws ApiException { - Call call = placeOrderCall(body, null, null); - Type localVarReturnType = new TypeToken(){}.getType(); - return apiClient.execute(call, localVarReturnType); - } - - /** - * Place an order for a pet (asynchronously) - * - * @param body order placed for purchasing the pet - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public Call placeOrderAsync(Order body, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - Call call = placeOrderCall(body, progressListener, progressRequestListener); - Type localVarReturnType = new TypeToken(){}.getType(); - apiClient.executeAsync(call, localVarReturnType, callback); - return call; - } - /* Build call for getOrderById */ private Call getOrderByIdCall(String orderId, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object localVarPostBody = null; @@ -500,7 +502,7 @@ public class StoreApi { /** * 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 + * @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 */ @@ -512,7 +514,7 @@ public class StoreApi { /** * 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 + * @param orderId ID of pet that needs to be fetched (required) * @return ApiResponse * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ @@ -525,7 +527,7 @@ public class StoreApi { /** * 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 + * @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 @@ -557,19 +559,13 @@ public class StoreApi { return call; } - /* Build call for deleteOrder */ - private Call deleteOrderCall(String orderId, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'orderId' is set - if (orderId == null) { - throw new ApiException("Missing the required parameter 'orderId' when calling deleteOrder(Async)"); - } + /* Build call for placeOrder */ + private Call placeOrderCall(Order body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = body; // create path and map variables - String localVarPath = "/store/order/{orderId}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.toString())); + String localVarPath = "/store/order".replaceAll("\\{format\\}","json"); List localVarQueryParams = new ArrayList(); @@ -601,41 +597,44 @@ public class StoreApi { }); } - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + String[] localVarAuthNames = new String[] { "test_api_client_id", "test_api_client_secret" }; + return apiClient.buildCall(localVarPath, "POST", 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 + * Place an order for a pet + * + * @param body order placed for purchasing the pet (optional) + * @return Order * @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); + public Order placeOrder(Order body) throws ApiException { + ApiResponse resp = placeOrderWithHttpInfo(body); + return resp.getData(); } /** - * Delete purchase order by ID - * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors - * @param orderId ID of the order that needs to be deleted - * @return ApiResponse + * Place an order for a pet + * + * @param body order placed for purchasing the pet (optional) + * @return ApiResponse * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ - public ApiResponse deleteOrderWithHttpInfo(String orderId) throws ApiException { - Call call = deleteOrderCall(orderId, null, null); - return apiClient.execute(call); + public ApiResponse placeOrderWithHttpInfo(Order body) throws ApiException { + Call call = placeOrderCall(body, null, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return apiClient.execute(call, localVarReturnType); } /** - * 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 + * Place an order for a pet (asynchronously) + * + * @param body order placed for purchasing the pet (optional) * @param callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object */ - public Call deleteOrderAsync(String orderId, final ApiCallback callback) throws ApiException { + public Call placeOrderAsync(Order body, final ApiCallback callback) throws ApiException { ProgressResponseBody.ProgressListener progressListener = null; ProgressRequestBody.ProgressRequestListener progressRequestListener = null; @@ -656,8 +655,9 @@ public class StoreApi { }; } - Call call = deleteOrderCall(orderId, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); + Call call = placeOrderCall(body, progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); return call; } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/UserApi.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/UserApi.java index 57b3550c1af..6da2483722b 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/UserApi.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/UserApi.java @@ -90,7 +90,7 @@ public class UserApi { /** * Create user * This can only be done by the logged in user. - * @param body Created user object + * @param body Created user object (optional) * @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 { @@ -100,7 +100,7 @@ public class UserApi { /** * Create user * This can only be done by the logged in user. - * @param body Created user object + * @param body Created user object (optional) * @return ApiResponse * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ @@ -112,7 +112,7 @@ public class UserApi { /** * Create user (asynchronously) * This can only be done by the logged in user. - * @param body Created user object + * @param body Created user object (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 @@ -188,7 +188,7 @@ public class UserApi { /** * Creates list of users with given input array * - * @param body List of user object + * @param body List of user object (optional) * @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 { @@ -198,7 +198,7 @@ public class UserApi { /** * Creates list of users with given input array * - * @param body List of user object + * @param body List of user object (optional) * @return ApiResponse * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ @@ -210,7 +210,7 @@ public class UserApi { /** * Creates list of users with given input array (asynchronously) * - * @param body List of user object + * @param body List of user object (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 @@ -286,7 +286,7 @@ public class UserApi { /** * Creates list of users with given input array * - * @param body List of user object + * @param body List of user object (optional) * @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 { @@ -296,7 +296,7 @@ public class UserApi { /** * Creates list of users with given input array * - * @param body List of user object + * @param body List of user object (optional) * @return ApiResponse * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ @@ -308,7 +308,7 @@ public class UserApi { /** * Creates list of users with given input array (asynchronously) * - * @param body List of user object + * @param body List of user object (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 @@ -339,6 +339,218 @@ public class UserApi { return call; } + /* Build call for deleteUser */ + private Call deleteUserCall(String username, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'username' is set + if (username == null) { + throw new ApiException("Missing the required parameter 'username' when calling deleteUser(Async)"); + } + + + // create path and map variables + String localVarPath = "/user/{username}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/json", "application/xml" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new Interceptor() { + @Override + public Response intercept(Interceptor.Chain chain) throws IOException { + Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "test_http_basic" }; + 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 + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse deleteUserWithHttpInfo(String username) throws ApiException { + Call call = deleteUserCall(username, null, null); + return apiClient.execute(call); + } + + /** + * Delete user (asynchronously) + * This can only be done by the logged in user. + * @param username The name that needs to be deleted (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public Call deleteUserAsync(String username, final ApiCallback callback) throws ApiException { + + 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); + } + }; + } + + Call call = deleteUserCall(username, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + + /* Build call for getUserByName */ + private Call getUserByNameCall(String username, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'username' is set + if (username == null) { + throw new ApiException("Missing the required parameter 'username' when calling getUserByName(Async)"); + } + + + // create path and map variables + String localVarPath = "/user/{username}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/json", "application/xml" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new Interceptor() { + @Override + public Response intercept(Interceptor.Chain chain) throws IOException { + Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + 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 + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse getUserByNameWithHttpInfo(String username) throws ApiException { + Call call = getUserByNameCall(username, null, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return apiClient.execute(call, localVarReturnType); + } + + /** + * Get user by user name (asynchronously) + * + * @param username The name that needs to be fetched. Use user1 for testing. (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public Call getUserByNameAsync(String username, final ApiCallback callback) throws ApiException { + + 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); + } + }; + } + + Call call = getUserByNameCall(username, progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; + } + /* Build call for loginUser */ private Call loginUserCall(String username, String password, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object localVarPostBody = null; @@ -388,8 +600,8 @@ public class UserApi { /** * Logs user into the system * - * @param username The user name for login - * @param password The password for login in clear text + * @param username The user name for login (optional) + * @param password The password for login in clear text (optional) * @return String * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ @@ -401,8 +613,8 @@ public class UserApi { /** * Logs user into the system * - * @param username The user name for login - * @param password The password for login in clear text + * @param username The user name for login (optional) + * @param password The password for login in clear text (optional) * @return ApiResponse * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ @@ -415,8 +627,8 @@ public class UserApi { /** * Logs user into the system (asynchronously) * - * @param username The user name for login - * @param password The password for login in clear text + * @param username The user name for login (optional) + * @param password The password for login in clear text (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 @@ -543,114 +755,6 @@ public class UserApi { return call; } - /* Build call for getUserByName */ - private Call getUserByNameCall(String username, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'username' is set - if (username == null) { - throw new ApiException("Missing the required parameter 'username' when calling getUserByName(Async)"); - } - - - // create path and map variables - String localVarPath = "/user/{username}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/json", "application/xml" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new Interceptor() { - @Override - public Response intercept(Interceptor.Chain chain) throws IOException { - Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - 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. - * @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. - * @return ApiResponse - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse getUserByNameWithHttpInfo(String username) throws ApiException { - Call call = getUserByNameCall(username, null, null); - Type localVarReturnType = new TypeToken(){}.getType(); - return apiClient.execute(call, localVarReturnType); - } - - /** - * Get user by user name (asynchronously) - * - * @param username The name that needs to be fetched. Use user1 for testing. - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public Call getUserByNameAsync(String username, final ApiCallback callback) throws ApiException { - - 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); - } - }; - } - - Call call = getUserByNameCall(username, progressListener, progressRequestListener); - Type localVarReturnType = new TypeToken(){}.getType(); - apiClient.executeAsync(call, localVarReturnType, callback); - return call; - } - /* Build call for updateUser */ private Call updateUserCall(String username, User body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object localVarPostBody = body; @@ -702,8 +806,8 @@ public class UserApi { /** * Updated user * This can only be done by the logged in user. - * @param username name that need to be deleted - * @param body Updated user object + * @param username name that need to be deleted (required) + * @param body Updated user object (optional) * @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 { @@ -713,8 +817,8 @@ public class UserApi { /** * Updated user * This can only be done by the logged in user. - * @param username name that need to be deleted - * @param body Updated user object + * @param username name that need to be deleted (required) + * @param body Updated user object (optional) * @return ApiResponse * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ @@ -726,8 +830,8 @@ public class UserApi { /** * Updated user (asynchronously) * This can only be done by the logged in user. - * @param username name that need to be deleted - * @param body Updated user object + * @param username name that need to be deleted (required) + * @param body Updated user object (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 @@ -758,108 +862,4 @@ public class UserApi { return call; } - /* Build call for deleteUser */ - private Call deleteUserCall(String username, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'username' is set - if (username == null) { - throw new ApiException("Missing the required parameter 'username' when calling deleteUser(Async)"); - } - - - // create path and map variables - String localVarPath = "/user/{username}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/json", "application/xml" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new Interceptor() { - @Override - public Response intercept(Interceptor.Chain chain) throws IOException { - Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - 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 - * @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 - * @return ApiResponse - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse deleteUserWithHttpInfo(String username) throws ApiException { - Call call = deleteUserCall(username, null, null); - return apiClient.execute(call); - } - - /** - * Delete user (asynchronously) - * This can only be done by the logged in user. - * @param username The name that needs to be deleted - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public Call deleteUserAsync(String username, final ApiCallback callback) throws ApiException { - - 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); - } - }; - } - - Call call = deleteUserCall(username, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } - } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/ApiKeyAuth.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/ApiKeyAuth.java index b8b1e69d7ff..491c9ec75b8 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/ApiKeyAuth.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/ApiKeyAuth.java @@ -5,7 +5,7 @@ import io.swagger.client.Pair; import java.util.Map; import java.util.List; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-02-15T18:20:42.151+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-03-14T22:17:51.831+08:00") public class ApiKeyAuth implements Authentication { private final String location; private final String paramName; diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/OAuth.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/OAuth.java index bdfa1d9563f..03e1e10cce1 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/OAuth.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/OAuth.java @@ -5,7 +5,7 @@ import io.swagger.client.Pair; import java.util.Map; import java.util.List; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-02-15T18:20:42.151+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-03-14T22:17:51.831+08:00") public class OAuth implements Authentication { private String accessToken; diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Category.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Category.java index e7052e47170..5aa82b23415 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 @@ -9,7 +9,7 @@ import com.google.gson.annotations.SerializedName; -@ApiModel(description = "") + public class Category { @SerializedName("id") diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/InlineResponse200.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/InlineResponse200.java index 2093866e063..41d02b8a23f 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/InlineResponse200.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/InlineResponse200.java @@ -3,15 +3,21 @@ package io.swagger.client.model; import java.util.Objects; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; +import io.swagger.client.model.Tag; +import java.util.ArrayList; +import java.util.List; import com.google.gson.annotations.SerializedName; -@ApiModel(description = "") + public class InlineResponse200 { + @SerializedName("photoUrls") + private List photoUrls = new ArrayList(); + @SerializedName("name") private String name = null; @@ -21,6 +27,46 @@ public class InlineResponse200 { @SerializedName("category") private Object category = null; + @SerializedName("tags") + private List tags = new ArrayList(); + + +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 value; + } +} + + @SerializedName("status") + private StatusEnum status = null; + + + + /** + **/ + @ApiModelProperty(value = "") + public List getPhotoUrls() { + return photoUrls; + } + public void setPhotoUrls(List photoUrls) { + this.photoUrls = photoUrls; + } /** @@ -56,6 +102,29 @@ public class InlineResponse200 { } + /** + **/ + @ApiModelProperty(value = "") + public List getTags() { + return tags; + } + public void setTags(List tags) { + this.tags = tags; + } + + + /** + * pet status in the store + **/ + @ApiModelProperty(value = "pet status in the store") + public StatusEnum getStatus() { + return status; + } + public void setStatus(StatusEnum status) { + this.status = status; + } + + @Override public boolean equals(Object o) { @@ -66,14 +135,17 @@ public class InlineResponse200 { return false; } InlineResponse200 inlineResponse200 = (InlineResponse200) o; - return Objects.equals(this.name, inlineResponse200.name) && + return Objects.equals(this.photoUrls, inlineResponse200.photoUrls) && + Objects.equals(this.name, inlineResponse200.name) && Objects.equals(this.id, inlineResponse200.id) && - Objects.equals(this.category, inlineResponse200.category); + Objects.equals(this.category, inlineResponse200.category) && + Objects.equals(this.tags, inlineResponse200.tags) && + Objects.equals(this.status, inlineResponse200.status); } @Override public int hashCode() { - return Objects.hash(name, id, category); + return Objects.hash(photoUrls, name, id, category, tags, status); } @Override @@ -81,9 +153,12 @@ public class InlineResponse200 { StringBuilder sb = new StringBuilder(); sb.append("class InlineResponse200 {\n"); + sb.append(" photoUrls: ").append(toIndentedString(photoUrls)).append("\n"); sb.append(" name: ").append(toIndentedString(name)).append("\n"); sb.append(" id: ").append(toIndentedString(id)).append("\n"); sb.append(" category: ").append(toIndentedString(category)).append("\n"); + sb.append(" tags: ").append(toIndentedString(tags)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); sb.append("}"); return sb.toString(); } 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 new file mode 100644 index 00000000000..3afae36dbfe --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Model200Response.java @@ -0,0 +1,69 @@ +package io.swagger.client.model; + +import java.util.Objects; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +import com.google.gson.annotations.SerializedName; + + + + + +public class Model200Response { + + @SerializedName("name") + private Integer name = null; + + + + /** + **/ + @ApiModelProperty(value = "") + public Integer getName() { + return name; + } + public void setName(Integer name) { + this.name = name; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Model200Response _200Response = (Model200Response) o; + return Objects.equals(this.name, _200Response.name); + } + + @Override + public int hashCode() { + return Objects.hash(name); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Model200Response {\n"); + + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ModelReturn.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ModelReturn.java new file mode 100644 index 00000000000..60da9b8e181 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ModelReturn.java @@ -0,0 +1,69 @@ +package io.swagger.client.model; + +import java.util.Objects; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +import com.google.gson.annotations.SerializedName; + + + + + +public class ModelReturn { + + @SerializedName("return") + private Integer _return = null; + + + + /** + **/ + @ApiModelProperty(value = "") + public Integer getReturn() { + return _return; + } + public void setReturn(Integer _return) { + this._return = _return; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + 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(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/Name.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Name.java new file mode 100644 index 00000000000..a65b8fda614 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Name.java @@ -0,0 +1,69 @@ +package io.swagger.client.model; + +import java.util.Objects; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +import com.google.gson.annotations.SerializedName; + + + + + +public class Name { + + @SerializedName("name") + private Integer name = null; + + + + /** + **/ + @ApiModelProperty(value = "") + public Integer getName() { + return name; + } + public void setName(Integer name) { + this.name = name; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Name name = (Name) o; + return Objects.equals(this.name, name.name); + } + + @Override + public int hashCode() { + return Objects.hash(name); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Name {\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/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 b0e4e246c11..31097ea438d 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 @@ -10,7 +10,7 @@ import com.google.gson.annotations.SerializedName; -@ApiModel(description = "") + public class Order { @SerializedName("id") 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 854b72195f6..7895e23ba13 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 @@ -13,7 +13,7 @@ import com.google.gson.annotations.SerializedName; -@ApiModel(description = "") + public class Pet { @SerializedName("id") 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 new file mode 100644 index 00000000000..9a0c166186c --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/SpecialModelName.java @@ -0,0 +1,69 @@ +package io.swagger.client.model; + +import java.util.Objects; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +import com.google.gson.annotations.SerializedName; + + + + + +public class SpecialModelName { + + @SerializedName("$special[property.name]") + private Long specialPropertyName = null; + + + + /** + **/ + @ApiModelProperty(value = "") + public Long getSpecialPropertyName() { + return specialPropertyName; + } + public void setSpecialPropertyName(Long specialPropertyName) { + this.specialPropertyName = specialPropertyName; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + 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(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/Tag.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Tag.java index 4f8217b7678..f5a148ecc36 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 @@ -9,7 +9,7 @@ import com.google.gson.annotations.SerializedName; -@ApiModel(description = "") + public class Tag { @SerializedName("id") 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 bcec1fc0a1c..9b71b457d15 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 @@ -9,7 +9,7 @@ import com.google.gson.annotations.SerializedName; -@ApiModel(description = "") + public class User { @SerializedName("id") diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/ApiClientTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/ApiClientTest.java index 9e6d5f42642..000dbd96bfb 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/ApiClientTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/ApiClientTest.java @@ -151,21 +151,25 @@ public class ApiClientTest { } @Test - public void testSetUsername() { - try { - apiClient.setUsername("my-username"); - fail("there should be no HTTP basic authentications"); - } catch (RuntimeException e) { + 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); - @Test - public void testSetPassword() { - try { - apiClient.setPassword("my-password"); - fail("there should be no HTTP basic authentications"); - } catch (RuntimeException e) { - } + 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 diff --git a/samples/client/petstore/java/retrofit/.gitignore b/samples/client/petstore/java/retrofit/.gitignore new file mode 100644 index 00000000000..32858aad3c3 --- /dev/null +++ b/samples/client/petstore/java/retrofit/.gitignore @@ -0,0 +1,12 @@ +*.class + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.ear + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* diff --git a/samples/client/petstore/java/retrofit/git_push.sh b/samples/client/petstore/java/retrofit/git_push.sh new file mode 100644 index 00000000000..1a36388db02 --- /dev/null +++ b/samples/client/petstore/java/retrofit/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="YOUR_GIT_USR_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="YOUR_GIT_REPO_ID" + 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/retrofit/src/main/java/io/swagger/client/StringUtil.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/StringUtil.java index de61255cb25..0eec085e2a4 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 @@ package io.swagger.client; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-05T14:39:21.255+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-03-14T22:17:53.252+08:00") public class StringUtil { /** * Check if the given array contains the given value (with case-insensitive comparison). diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/PetApi.java index af1172aa9db..92147932bac 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/PetApi.java @@ -7,47 +7,25 @@ import retrofit.http.*; import retrofit.mime.*; import io.swagger.client.model.Pet; -import java.io.File; import io.swagger.client.model.InlineResponse200; +import java.io.File; + + import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; -public interface PetApi { - - /** - * Update an existing pet - * Sync method - * - * @param body Pet object that needs to be added to the store - * @return Void - */ - - @PUT("/pet") - Void updatePet( - @Body Pet body - ); - /** - * Update an existing pet - * Async method - * @param body Pet object that needs to be added to the store - * @param cb callback method - * @return void - */ - - @PUT("/pet") - void updatePet( - @Body Pet body, Callback cb - ); + +public interface PetApi { /** * Add a new pet to the store * Sync method * - * @param body Pet object that needs to be added to the store + * @param body Pet object that needs to be added to the store (optional) * @return Void */ @@ -59,7 +37,7 @@ public interface PetApi { /** * Add a new pet to the store * Async method - * @param body Pet object that needs to be added to the store + * @param body Pet object that needs to be added to the store (optional) * @param cb callback method * @return void */ @@ -69,11 +47,65 @@ public interface PetApi { @Body Pet body, Callback cb ); + /** + * Fake endpoint to test byte array in body parameter for adding a new pet to the store + * Sync method + * + * @param body Pet object in the form of byte array (optional) + * @return Void + */ + + @POST("/pet?testing_byte_array=true") + Void addPetUsingByteArray( + @Body byte[] body + ); + + /** + * Fake endpoint to test byte array in body parameter for adding a new pet to the store + * Async method + * @param body Pet object in the form of byte array (optional) + * @param cb callback method + * @return void + */ + + @POST("/pet?testing_byte_array=true") + void addPetUsingByteArray( + @Body byte[] body, Callback cb + ); + + /** + * Deletes a pet + * Sync method + * + * @param petId Pet id to delete (required) + * @param apiKey (optional) + * @return Void + */ + + @DELETE("/pet/{petId}") + Void deletePet( + @Path("petId") Long petId, @Header("api_key") String apiKey + ); + + /** + * Deletes a pet + * Async method + * @param petId Pet id to delete (required) + * @param apiKey (optional) + * @param cb callback method + * @return void + */ + + @DELETE("/pet/{petId}") + void deletePet( + @Path("petId") Long petId, @Header("api_key") String apiKey, Callback cb + ); + /** * Finds Pets by status * Sync method * Multiple status values can be provided with comma separated strings - * @param status Status values that need to be considered for query + * @param status Status values that need to be considered for query (optional, default to available) * @return List */ @@ -85,7 +117,7 @@ public interface PetApi { /** * Finds Pets by status * Async method - * @param status Status values that need to be considered for query + * @param status Status values that need to be considered for query (optional, default to available) * @param cb callback method * @return void */ @@ -99,7 +131,7 @@ public interface PetApi { * Finds Pets by tags * Sync method * Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. - * @param tags Tags to filter by + * @param tags Tags to filter by (optional) * @return List */ @@ -111,7 +143,7 @@ public interface PetApi { /** * Finds Pets by tags * Async method - * @param tags Tags to filter by + * @param tags Tags to filter by (optional) * @param cb callback method * @return void */ @@ -125,7 +157,7 @@ public interface PetApi { * Find pet by ID * Sync method * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions - * @param petId ID of pet that needs to be fetched + * @param petId ID of pet that needs to be fetched (required) * @return Pet */ @@ -137,7 +169,7 @@ public interface PetApi { /** * Find pet by ID * Async method - * @param petId ID of pet that needs to be fetched + * @param petId ID of pet that needs to be fetched (required) * @param cb callback method * @return void */ @@ -147,103 +179,11 @@ public interface PetApi { @Path("petId") Long petId, Callback cb ); - /** - * Updates a pet in the store with form data - * Sync method - * - * @param petId ID of pet that needs to be updated - * @param name Updated name of the pet - * @param status Updated status of the pet - * @return Void - */ - - @FormUrlEncoded - @POST("/pet/{petId}") - Void updatePetWithForm( - @Path("petId") String petId, @Field("name") String name, @Field("status") String status - ); - - /** - * Updates a pet in the store with form data - * Async method - * @param petId ID of pet that needs to be updated - * @param name Updated name of the pet - * @param status Updated status of the pet - * @param cb callback method - * @return void - */ - - @FormUrlEncoded - @POST("/pet/{petId}") - void updatePetWithForm( - @Path("petId") String petId, @Field("name") String name, @Field("status") String status, Callback cb - ); - - /** - * Deletes a pet - * Sync method - * - * @param petId Pet id to delete - * @param apiKey - * @return Void - */ - - @DELETE("/pet/{petId}") - Void deletePet( - @Path("petId") Long petId, @Header("api_key") String apiKey - ); - - /** - * Deletes a pet - * Async method - * @param petId Pet id to delete - * @param apiKey - * @param cb callback method - * @return void - */ - - @DELETE("/pet/{petId}") - void deletePet( - @Path("petId") Long petId, @Header("api_key") String apiKey, Callback cb - ); - - /** - * uploads an image - * Sync method - * - * @param petId ID of pet to update - * @param additionalMetadata Additional data to pass to server - * @param file file to upload - * @return Void - */ - - @Multipart - @POST("/pet/{petId}/uploadImage") - Void uploadFile( - @Path("petId") Long petId, @Part("additionalMetadata") String additionalMetadata, @Part("file") TypedFile file - ); - - /** - * uploads an image - * Async method - * @param petId ID of pet to update - * @param additionalMetadata Additional data to pass to server - * @param file file to upload - * @param cb callback method - * @return void - */ - - @Multipart - @POST("/pet/{petId}/uploadImage") - void uploadFile( - @Path("petId") Long petId, @Part("additionalMetadata") String additionalMetadata, @Part("file") TypedFile file, Callback cb - ); - /** * Fake endpoint to test inline arbitrary object return by 'Find pet by ID' * Sync method * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions - * @param petId ID of pet that needs to be fetched + * @param petId ID of pet that needs to be fetched (required) * @return InlineResponse200 */ @@ -255,7 +195,7 @@ public interface PetApi { /** * Fake endpoint to test inline arbitrary object return by 'Find pet by ID' * Async method - * @param petId ID of pet that needs to be fetched + * @param petId ID of pet that needs to be fetched (required) * @param cb callback method * @return void */ @@ -269,7 +209,7 @@ public interface PetApi { * Fake endpoint to test byte array return by 'Find pet by ID' * Sync method * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions - * @param petId ID of pet that needs to be fetched + * @param petId ID of pet that needs to be fetched (required) * @return byte[] */ @@ -281,7 +221,7 @@ public interface PetApi { /** * Fake endpoint to test byte array return by 'Find pet by ID' * Async method - * @param petId ID of pet that needs to be fetched + * @param petId ID of pet that needs to be fetched (required) * @param cb callback method * @return void */ @@ -292,29 +232,94 @@ public interface PetApi { ); /** - * Fake endpoint to test byte array in body parameter for adding a new pet to the store + * Update an existing pet * Sync method * - * @param body Pet object in the form of byte array + * @param body Pet object that needs to be added to the store (optional) * @return Void */ - @POST("/pet?testing_byte_array=true") - Void addPetUsingByteArray( - @Body byte[] body + @PUT("/pet") + Void updatePet( + @Body Pet body ); /** - * Fake endpoint to test byte array in body parameter for adding a new pet to the store + * Update an existing pet * Async method - * @param body Pet object in the form of byte array + * @param body Pet object that needs to be added to the store (optional) * @param cb callback method * @return void */ - @POST("/pet?testing_byte_array=true") - void addPetUsingByteArray( - @Body byte[] body, Callback cb + @PUT("/pet") + void updatePet( + @Body Pet body, Callback cb + ); + + /** + * Updates a pet in the store with form data + * Sync method + * + * @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 Void + */ + + @FormUrlEncoded + @POST("/pet/{petId}") + Void updatePetWithForm( + @Path("petId") String petId, @Field("name") String name, @Field("status") String status + ); + + /** + * Updates a pet in the store with form data + * Async method + * @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 cb callback method + * @return void + */ + + @FormUrlEncoded + @POST("/pet/{petId}") + void updatePetWithForm( + @Path("petId") String petId, @Field("name") String name, @Field("status") String status, Callback cb + ); + + /** + * uploads an image + * Sync method + * + * @param petId ID of pet to update (required) + * @param additionalMetadata Additional data to pass to server (optional) + * @param file file to upload (optional) + * @return Void + */ + + @Multipart + @POST("/pet/{petId}/uploadImage") + Void uploadFile( + @Path("petId") Long petId, @Part("additionalMetadata") String additionalMetadata, @Part("file") TypedFile file + ); + + /** + * uploads an image + * Async method + * @param petId ID of pet to update (required) + * @param additionalMetadata Additional data to pass to server (optional) + * @param file file to upload (optional) + * @param cb callback method + * @return void + */ + + @Multipart + @POST("/pet/{petId}/uploadImage") + void uploadFile( + @Path("petId") Long petId, @Part("additionalMetadata") String additionalMetadata, @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 d68906ca95d..815d067c967 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 @@ -8,18 +8,48 @@ import retrofit.mime.*; import io.swagger.client.model.Order; + + import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; + + public interface StoreApi { + /** + * Delete purchase order by ID + * Sync method + * 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 Void + */ + + @DELETE("/store/order/{orderId}") + Void deleteOrder( + @Path("orderId") String orderId + ); + + /** + * Delete purchase order by ID + * Async method + * @param orderId ID of the order that needs to be deleted (required) + * @param cb callback method + * @return void + */ + + @DELETE("/store/order/{orderId}") + void deleteOrder( + @Path("orderId") String orderId, Callback cb + ); + /** * Finds orders by status * Sync method * A single status value can be provided as a string - * @param status Status value that needs to be considered for query + * @param status Status value that needs to be considered for query (optional, default to placed) * @return List */ @@ -31,7 +61,7 @@ public interface StoreApi { /** * Finds orders by status * Async method - * @param status Status value that needs to be considered for query + * @param status Status value that needs to be considered for query (optional, default to placed) * @param cb callback method * @return void */ @@ -87,37 +117,11 @@ public interface StoreApi { Callback cb ); - /** - * Place an order for a pet - * Sync method - * - * @param body order placed for purchasing the pet - * @return Order - */ - - @POST("/store/order") - Order placeOrder( - @Body Order body - ); - - /** - * Place an order for a pet - * Async method - * @param body order placed for purchasing the pet - * @param cb callback method - * @return void - */ - - @POST("/store/order") - void placeOrder( - @Body Order body, Callback cb - ); - /** * Find purchase order by ID * Sync method * 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 + * @param orderId ID of pet that needs to be fetched (required) * @return Order */ @@ -129,7 +133,7 @@ public interface StoreApi { /** * Find purchase order by ID * Async method - * @param orderId ID of pet that needs to be fetched + * @param orderId ID of pet that needs to be fetched (required) * @param cb callback method * @return void */ @@ -140,29 +144,30 @@ public interface StoreApi { ); /** - * Delete purchase order by ID + * Place an order for a pet * Sync method - * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors - * @param orderId ID of the order that needs to be deleted - * @return Void + * + * @param body order placed for purchasing the pet (optional) + * @return Order */ - @DELETE("/store/order/{orderId}") - Void deleteOrder( - @Path("orderId") String orderId + @POST("/store/order") + Order placeOrder( + @Body Order body ); /** - * Delete purchase order by ID + * Place an order for a pet * Async method - * @param orderId ID of the order that needs to be deleted + * @param body order placed for purchasing the pet (optional) * @param cb callback method * @return void */ - @DELETE("/store/order/{orderId}") - void deleteOrder( - @Path("orderId") String orderId, Callback cb + @POST("/store/order") + void placeOrder( + @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 519ae4a14f4..a0d913e071f 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 @@ -8,18 +8,22 @@ import retrofit.mime.*; import io.swagger.client.model.User; + + import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; + + public interface UserApi { /** * Create user * Sync method * This can only be done by the logged in user. - * @param body Created user object + * @param body Created user object (optional) * @return Void */ @@ -31,7 +35,7 @@ public interface UserApi { /** * Create user * Async method - * @param body Created user object + * @param body Created user object (optional) * @param cb callback method * @return void */ @@ -45,7 +49,7 @@ public interface UserApi { * Creates list of users with given input array * Sync method * - * @param body List of user object + * @param body List of user object (optional) * @return Void */ @@ -57,7 +61,7 @@ public interface UserApi { /** * Creates list of users with given input array * Async method - * @param body List of user object + * @param body List of user object (optional) * @param cb callback method * @return void */ @@ -71,7 +75,7 @@ public interface UserApi { * Creates list of users with given input array * Sync method * - * @param body List of user object + * @param body List of user object (optional) * @return Void */ @@ -83,7 +87,7 @@ public interface UserApi { /** * Creates list of users with given input array * Async method - * @param body List of user object + * @param body List of user object (optional) * @param cb callback method * @return void */ @@ -93,12 +97,64 @@ public interface UserApi { @Body List body, Callback cb ); + /** + * Delete user + * Sync method + * This can only be done by the logged in user. + * @param username The name that needs to be deleted (required) + * @return Void + */ + + @DELETE("/user/{username}") + Void deleteUser( + @Path("username") String username + ); + + /** + * Delete user + * Async method + * @param username The name that needs to be deleted (required) + * @param cb callback method + * @return void + */ + + @DELETE("/user/{username}") + void deleteUser( + @Path("username") String username, Callback cb + ); + + /** + * Get user by user name + * Sync method + * + * @param username The name that needs to be fetched. Use user1 for testing. (required) + * @return User + */ + + @GET("/user/{username}") + User getUserByName( + @Path("username") String username + ); + + /** + * Get user by user name + * Async method + * @param username The name that needs to be fetched. Use user1 for testing. (required) + * @param cb callback method + * @return void + */ + + @GET("/user/{username}") + void getUserByName( + @Path("username") String username, Callback cb + ); + /** * Logs user into the system * Sync method * - * @param username The user name for login - * @param password The password for login in clear text + * @param username The user name for login (optional) + * @param password The password for login in clear text (optional) * @return String */ @@ -110,8 +166,8 @@ public interface UserApi { /** * Logs user into the system * Async method - * @param username The user name for login - * @param password The password for login in clear text + * @param username The user name for login (optional) + * @param password The password for login in clear text (optional) * @param cb callback method * @return void */ @@ -144,38 +200,12 @@ public interface UserApi { Callback cb ); - /** - * Get user by user name - * Sync method - * - * @param username The name that needs to be fetched. Use user1 for testing. - * @return User - */ - - @GET("/user/{username}") - User getUserByName( - @Path("username") String username - ); - - /** - * Get user by user name - * Async method - * @param username The name that needs to be fetched. Use user1 for testing. - * @param cb callback method - * @return void - */ - - @GET("/user/{username}") - void getUserByName( - @Path("username") String username, Callback cb - ); - /** * Updated user * Sync method * This can only be done by the logged in user. - * @param username name that need to be deleted - * @param body Updated user object + * @param username name that need to be deleted (required) + * @param body Updated user object (optional) * @return Void */ @@ -187,8 +217,8 @@ public interface UserApi { /** * Updated user * Async method - * @param username name that need to be deleted - * @param body Updated user object + * @param username name that need to be deleted (required) + * @param body Updated user object (optional) * @param cb callback method * @return void */ @@ -198,30 +228,5 @@ public interface UserApi { @Path("username") String username, @Body User body, Callback cb ); - /** - * Delete user - * Sync method - * This can only be done by the logged in user. - * @param username The name that needs to be deleted - * @return Void - */ - - @DELETE("/user/{username}") - Void deleteUser( - @Path("username") String username - ); - - /** - * Delete user - * Async method - * @param username The name that needs to be deleted - * @param cb callback method - * @return void - */ - - @DELETE("/user/{username}") - void deleteUser( - @Path("username") String username, Callback cb - ); - } + 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 d0908afd9e1..67de63eb179 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 @@ -4,12 +4,14 @@ import java.util.Objects; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; + import com.google.gson.annotations.SerializedName; -@ApiModel(description = "") + + public class Category { @SerializedName("id") @@ -83,3 +85,5 @@ public class Category { return o.toString().replace("\n", "\n "); } } + + diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/InlineResponse200.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/InlineResponse200.java index 41e49b9cd3c..165f069a05b 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/InlineResponse200.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/InlineResponse200.java @@ -3,15 +3,23 @@ package io.swagger.client.model; import java.util.Objects; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; +import io.swagger.client.model.Tag; +import java.util.ArrayList; +import java.util.List; + import com.google.gson.annotations.SerializedName; -@ApiModel(description = "") + + public class InlineResponse200 { + @SerializedName("photoUrls") + private List photoUrls = new ArrayList(); + @SerializedName("name") private String name = null; @@ -21,6 +29,46 @@ public class InlineResponse200 { @SerializedName("category") private Object category = null; + @SerializedName("tags") + private List tags = new ArrayList(); + + +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 value; + } +} + + @SerializedName("status") + private StatusEnum status = null; + + + + /** + **/ + @ApiModelProperty(value = "") + public List getPhotoUrls() { + return photoUrls; + } + public void setPhotoUrls(List photoUrls) { + this.photoUrls = photoUrls; + } /** @@ -56,6 +104,29 @@ public class InlineResponse200 { } + /** + **/ + @ApiModelProperty(value = "") + public List getTags() { + return tags; + } + public void setTags(List tags) { + this.tags = tags; + } + + + /** + * pet status in the store + **/ + @ApiModelProperty(value = "pet status in the store") + public StatusEnum getStatus() { + return status; + } + public void setStatus(StatusEnum status) { + this.status = status; + } + + @Override public boolean equals(Object o) { @@ -66,14 +137,17 @@ public class InlineResponse200 { return false; } InlineResponse200 inlineResponse200 = (InlineResponse200) o; - return Objects.equals(name, inlineResponse200.name) && + return Objects.equals(photoUrls, inlineResponse200.photoUrls) && + Objects.equals(name, inlineResponse200.name) && Objects.equals(id, inlineResponse200.id) && - Objects.equals(category, inlineResponse200.category); + Objects.equals(category, inlineResponse200.category) && + Objects.equals(tags, inlineResponse200.tags) && + Objects.equals(status, inlineResponse200.status); } @Override public int hashCode() { - return Objects.hash(name, id, category); + return Objects.hash(photoUrls, name, id, category, tags, status); } @Override @@ -81,9 +155,12 @@ public class InlineResponse200 { StringBuilder sb = new StringBuilder(); sb.append("class InlineResponse200 {\n"); + sb.append(" photoUrls: ").append(toIndentedString(photoUrls)).append("\n"); sb.append(" name: ").append(toIndentedString(name)).append("\n"); sb.append(" id: ").append(toIndentedString(id)).append("\n"); sb.append(" category: ").append(toIndentedString(category)).append("\n"); + sb.append(" tags: ").append(toIndentedString(tags)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); sb.append("}"); return sb.toString(); } @@ -99,3 +176,5 @@ public class InlineResponse200 { 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 new file mode 100644 index 00000000000..80b0aed92a8 --- /dev/null +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Model200Response.java @@ -0,0 +1,73 @@ +package io.swagger.client.model; + +import java.util.Objects; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + + +import com.google.gson.annotations.SerializedName; + + + + + + +public class Model200Response { + + @SerializedName("name") + private Integer name = null; + + + + /** + **/ + @ApiModelProperty(value = "") + public Integer getName() { + return name; + } + public void setName(Integer name) { + this.name = name; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Model200Response _200Response = (Model200Response) o; + return Objects.equals(name, _200Response.name); + } + + @Override + public int hashCode() { + return Objects.hash(name); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Model200Response {\n"); + + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + 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 new file mode 100644 index 00000000000..ce8c1238fdb --- /dev/null +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ModelReturn.java @@ -0,0 +1,73 @@ +package io.swagger.client.model; + +import java.util.Objects; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + + +import com.google.gson.annotations.SerializedName; + + + + + + +public class ModelReturn { + + @SerializedName("return") + private Integer _return = null; + + + + /** + **/ + @ApiModelProperty(value = "") + public Integer getReturn() { + return _return; + } + public void setReturn(Integer _return) { + this._return = _return; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + 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/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 new file mode 100644 index 00000000000..370214bd21c --- /dev/null +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Name.java @@ -0,0 +1,89 @@ +package io.swagger.client.model; + +import java.util.Objects; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + + +import com.google.gson.annotations.SerializedName; + + + + + + +public class Name { + + @SerializedName("name") + private Integer name = null; + + @SerializedName("snake_case") + private Integer snakeCase = null; + + + + /** + **/ + @ApiModelProperty(value = "") + public Integer getName() { + return name; + } + public void setName(Integer name) { + this.name = name; + } + + + /** + **/ + @ApiModelProperty(value = "") + public Integer getSnakeCase() { + return snakeCase; + } + public void setSnakeCase(Integer snakeCase) { + this.snakeCase = snakeCase; + } + + + + @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); + } + + @Override + public int hashCode() { + return Objects.hash(name, snakeCase); + } + + @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("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + + diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Order.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Order.java index c73230a4119..e601bd7a15a 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 @@ -5,12 +5,14 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.util.Date; + import com.google.gson.annotations.SerializedName; -@ApiModel(description = "") + + public class Order { @SerializedName("id") @@ -169,3 +171,5 @@ public enum StatusEnum { 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 0374eabfba4..5d1210dc55b 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 @@ -8,12 +8,14 @@ import io.swagger.client.model.Tag; import java.util.ArrayList; import java.util.List; + import com.google.gson.annotations.SerializedName; -@ApiModel(description = "") + + public class Pet { @SerializedName("id") @@ -175,3 +177,5 @@ public enum StatusEnum { 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 new file mode 100644 index 00000000000..b5a96d5fc39 --- /dev/null +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/SpecialModelName.java @@ -0,0 +1,73 @@ +package io.swagger.client.model; + +import java.util.Objects; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + + +import com.google.gson.annotations.SerializedName; + + + + + + +public class SpecialModelName { + + @SerializedName("$special[property.name]") + private Long specialPropertyName = null; + + + + /** + **/ + @ApiModelProperty(value = "") + public Long getSpecialPropertyName() { + return specialPropertyName; + } + public void setSpecialPropertyName(Long specialPropertyName) { + this.specialPropertyName = specialPropertyName; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + 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/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 a4ca1074ca1..6ee49ee2166 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 @@ -4,12 +4,14 @@ import java.util.Objects; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; + import com.google.gson.annotations.SerializedName; -@ApiModel(description = "") + + public class Tag { @SerializedName("id") @@ -83,3 +85,5 @@ public class Tag { 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 072f510081a..98196393ef1 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 @@ -4,12 +4,14 @@ import java.util.Objects; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; + import com.google.gson.annotations.SerializedName; -@ApiModel(description = "") + + public class User { @SerializedName("id") @@ -180,3 +182,5 @@ public class User { return o.toString().replace("\n", "\n "); } } + + diff --git a/samples/client/petstore/java/retrofit2/.gitignore b/samples/client/petstore/java/retrofit2/.gitignore new file mode 100644 index 00000000000..32858aad3c3 --- /dev/null +++ b/samples/client/petstore/java/retrofit2/.gitignore @@ -0,0 +1,12 @@ +*.class + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.ear + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* diff --git a/samples/client/petstore/java/retrofit2/README.md b/samples/client/petstore/java/retrofit2/README.md index 1a6255eb563..d5f7ec9f1ce 100644 --- a/samples/client/petstore/java/retrofit2/README.md +++ b/samples/client/petstore/java/retrofit2/README.md @@ -20,7 +20,7 @@ mvn deploy Refer to the [official documentation](https://maven.apache.org/plugins/maven-deploy-plugin/usage.html) for more information. -After the client libarary is installed/deployed, you can use it in your Maven project by adding the following to your *pom.xml*: +After the client library is installed/deployed, you can use it in your Maven project by adding the following to your *pom.xml*: ```xml diff --git a/samples/client/petstore/java/retrofit2/build.gradle b/samples/client/petstore/java/retrofit2/build.gradle index 5f5ff488f18..ab71653f739 100644 --- a/samples/client/petstore/java/retrofit2/build.gradle +++ b/samples/client/petstore/java/retrofit2/build.gradle @@ -46,6 +46,10 @@ if(hasProperty('target') && target == 'android') { } } } + + dependencies { + provided 'javax.annotation:jsr250-api:1.0' + } } afterEvaluate { @@ -100,6 +104,7 @@ ext { dependencies { compile "com.squareup.retrofit2:retrofit:$retrofit_version" + compile "com.squareup.retrofit2:converter-scalars:$retrofit_version" compile "com.squareup.retrofit2:converter-gson:$retrofit_version" diff --git a/samples/client/petstore/java/retrofit2/git_push.sh b/samples/client/petstore/java/retrofit2/git_push.sh new file mode 100644 index 00000000000..1a36388db02 --- /dev/null +++ b/samples/client/petstore/java/retrofit2/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="YOUR_GIT_USR_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="YOUR_GIT_REPO_ID" + 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/retrofit2/pom.xml b/samples/client/petstore/java/retrofit2/pom.xml index 07c24f98116..2d8f0440161 100644 --- a/samples/client/petstore/java/retrofit2/pom.xml +++ b/samples/client/petstore/java/retrofit2/pom.xml @@ -118,6 +118,11 @@ retrofit ${retrofit-version} + + com.squareup.retrofit2 + converter-scalars + ${retrofit-version} + com.squareup.retrofit2 converter-gson @@ -128,7 +133,6 @@ org.apache.oltu.oauth2.client ${oltu-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 398a1014c71..ffff8c26d4f 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 @@ -12,8 +12,9 @@ import org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuil import retrofit2.Converter; import retrofit2.Retrofit; -import retrofit2.converter.gson.GsonConverterFactory; +import retrofit2.converter.gson.GsonConverterFactory; +import retrofit2.converter.scalars.ScalarsConverterFactory; import com.google.gson.Gson; import com.google.gson.GsonBuilder; @@ -46,10 +47,18 @@ public class ApiClient { this(); for(String authName : authNames) { Interceptor auth; - if (authName == "api_key") { - auth = new ApiKeyAuth("header", "api_key"); - } else if (authName == "petstore_auth") { + if (authName == "petstore_auth") { auth = new OAuth(OAuthFlow.implicit, "http://petstore.swagger.io/api/oauth/dialog", "", "write:pets, read:pets"); + } else if (authName == "test_api_client_id") { + auth = new ApiKeyAuth("header", "x-test_api_client_id"); + } else if (authName == "test_api_client_secret") { + auth = new ApiKeyAuth("header", "x-test_api_client_secret"); + } else if (authName == "api_key") { + auth = new ApiKeyAuth("header", "api_key"); + } else if (authName == "test_api_key_query") { + auth = new ApiKeyAuth("query", "test_api_key_query"); + } else if (authName == "test_api_key_header") { + auth = new ApiKeyAuth("header", "test_api_key_header"); } else { throw new RuntimeException("auth name \"" + authName + "\" not found in available auth names"); } @@ -119,6 +128,7 @@ public class ApiClient { .baseUrl(baseUrl) .client(okClient) + .addConverterFactory(ScalarsConverterFactory.create()) .addConverterFactory(GsonCustomConverterFactory.create(gson)); } 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 22e010034b2..d7254df29fc 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/StringUtil.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/StringUtil.java @@ -1,6 +1,6 @@ package io.swagger.client; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-02-26T13:30:07.836+01:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-03-14T22:17:54.660+08:00") public class StringUtil { /** * Check if the given array contains the given value (with case-insensitive comparison). diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/PetApi.java index f7e5f15a424..2cc69238a6b 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,33 +9,24 @@ import retrofit2.http.*; import okhttp3.RequestBody; import io.swagger.client.model.Pet; -import java.io.File; import io.swagger.client.model.InlineResponse200; +import java.io.File; + + import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; -public interface PetApi { - - /** - * Update an existing pet - * - * @param body Pet object that needs to be added to the store - * @return Call - */ - - @PUT("pet") - Call updatePet( - @Body Pet body - ); + +public interface PetApi { /** * Add a new pet to the store * - * @param body Pet object that needs to be added to the store + * @param body Pet object that needs to be added to the store (optional) * @return Call */ @@ -45,10 +36,37 @@ public interface PetApi { ); + /** + * Fake endpoint to test byte array in body parameter for adding a new pet to the store + * + * @param body Pet object in the form of byte array (optional) + * @return Call + */ + + @POST("pet?testing_byte_array=true") + Call addPetUsingByteArray( + @Body byte[] body + ); + + + /** + * Deletes a pet + * + * @param petId Pet id to delete (required) + * @param apiKey (optional) + * @return Call + */ + + @DELETE("pet/{petId}") + Call deletePet( + @Path("petId") Long petId, @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 query + * @param status Status values that need to be considered for query (optional, default to available) * @return Call> */ @@ -61,7 +79,7 @@ public interface PetApi { /** * Finds Pets by tags * Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. - * @param tags Tags to filter by + * @param tags Tags to filter by (optional) * @return Call> */ @@ -74,7 +92,7 @@ public interface PetApi { /** * Find pet by ID * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions - * @param petId ID of pet that needs to be fetched + * @param petId ID of pet that needs to be fetched (required) * @return Call */ @@ -84,56 +102,10 @@ public interface PetApi { ); - /** - * Updates a pet in the store with form data - * - * @param petId ID of pet that needs to be updated - * @param name Updated name of the pet - * @param status Updated status of the pet - * @return Call - */ - - @FormUrlEncoded - @POST("pet/{petId}") - Call updatePetWithForm( - @Path("petId") String petId, @Field("name") String name, @Field("status") String status - ); - - - /** - * Deletes a pet - * - * @param petId Pet id to delete - * @param apiKey - * @return Call - */ - - @DELETE("pet/{petId}") - Call deletePet( - @Path("petId") Long petId, @Header("api_key") String apiKey - ); - - - /** - * uploads an image - * - * @param petId ID of pet to update - * @param additionalMetadata Additional data to pass to server - * @param file file to upload - * @return Call - */ - - @Multipart - @POST("pet/{petId}/uploadImage") - Call uploadFile( - @Path("petId") Long petId, @Part("additionalMetadata") String additionalMetadata, @Part("file\"; filename=\"file\"") RequestBody file - ); - - /** * Fake endpoint to test inline arbitrary object return by 'Find pet by ID' * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions - * @param petId ID of pet that needs to be fetched + * @param petId ID of pet that needs to be fetched (required) * @return Call */ @@ -146,7 +118,7 @@ public interface PetApi { /** * Fake endpoint to test byte array return by 'Find pet by ID' * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions - * @param petId ID of pet that needs to be fetched + * @param petId ID of pet that needs to be fetched (required) * @return Call */ @@ -157,16 +129,49 @@ public interface PetApi { /** - * Fake endpoint to test byte array in body parameter for adding a new pet to the store + * Update an existing pet * - * @param body Pet object in the form of byte array + * @param body Pet object that needs to be added to the store (optional) * @return Call */ - @POST("pet?testing_byte_array=true") - Call addPetUsingByteArray( - @Body byte[] body + @PUT("pet") + Call updatePet( + @Body Pet body + ); + + + /** + * 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 Call + */ + + @FormUrlEncoded + @POST("pet/{petId}") + Call updatePetWithForm( + @Path("petId") String petId, @Field("name") String name, @Field("status") String status + ); + + + /** + * 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 Call + */ + + @Multipart + @POST("pet/{petId}/uploadImage") + Call uploadFile( + @Path("petId") Long petId, @Part("additionalMetadata") String additionalMetadata, @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 f23b71a2e19..d023308c32e 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 @@ -10,17 +10,34 @@ import okhttp3.RequestBody; import io.swagger.client.model.Order; + + import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; + + 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 + */ + + @DELETE("store/order/{orderId}") + Call deleteOrder( + @Path("orderId") String orderId + ); + + /** * Finds orders by status * A single status value can be provided as a string - * @param status Status value that needs to be considered for query + * @param status Status value that needs to be considered for query (optional, default to placed) * @return Call> */ @@ -52,23 +69,10 @@ public interface StoreApi { - /** - * Place an order for a pet - * - * @param body order placed for purchasing the pet - * @return Call - */ - - @POST("store/order") - Call placeOrder( - @Body Order body - ); - - /** * Find purchase order by ID * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - * @param orderId ID of pet that needs to be fetched + * @param orderId ID of pet that needs to be fetched (required) * @return Call */ @@ -79,16 +83,17 @@ 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 - * @return Call + * Place an order for a pet + * + * @param body order placed for purchasing the pet (optional) + * @return Call */ - @DELETE("store/order/{orderId}") - Call deleteOrder( - @Path("orderId") String orderId + @POST("store/order") + Call placeOrder( + @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 61d3101843a..08aeb90a583 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 @@ -10,17 +10,21 @@ import okhttp3.RequestBody; import io.swagger.client.model.User; + + import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; + + public interface UserApi { /** * Create user * This can only be done by the logged in user. - * @param body Created user object + * @param body Created user object (optional) * @return Call */ @@ -33,7 +37,7 @@ public interface UserApi { /** * Creates list of users with given input array * - * @param body List of user object + * @param body List of user object (optional) * @return Call */ @@ -46,7 +50,7 @@ public interface UserApi { /** * Creates list of users with given input array * - * @param body List of user object + * @param body List of user object (optional) * @return Call */ @@ -56,11 +60,37 @@ public interface UserApi { ); + /** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted (required) + * @return Call + */ + + @DELETE("user/{username}") + Call deleteUser( + @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 + */ + + @GET("user/{username}") + Call getUserByName( + @Path("username") String username + ); + + /** * Logs user into the system * - * @param username The user name for login - * @param password The password for login in clear text + * @param username The user name for login (optional) + * @param password The password for login in clear text (optional) * @return Call */ @@ -81,24 +111,11 @@ public interface UserApi { - /** - * Get user by user name - * - * @param username The name that needs to be fetched. Use user1 for testing. - * @return Call - */ - - @GET("user/{username}") - Call getUserByName( - @Path("username") String username - ); - - /** * Updated user * This can only be done by the logged in user. - * @param username name that need to be deleted - * @param body Updated user object + * @param username name that need to be deleted (required) + * @param body Updated user object (optional) * @return Call */ @@ -108,17 +125,5 @@ public interface UserApi { ); - /** - * Delete user - * This can only be done by the logged in user. - * @param username The name that needs to be deleted - * @return Call - */ - - @DELETE("user/{username}") - Call deleteUser( - @Path("username") String username - ); - - } + 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 d0908afd9e1..67de63eb179 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 @@ -4,12 +4,14 @@ import java.util.Objects; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; + import com.google.gson.annotations.SerializedName; -@ApiModel(description = "") + + public class Category { @SerializedName("id") @@ -83,3 +85,5 @@ public class Category { return o.toString().replace("\n", "\n "); } } + + diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/InlineResponse200.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/InlineResponse200.java index 41e49b9cd3c..165f069a05b 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/InlineResponse200.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/InlineResponse200.java @@ -3,15 +3,23 @@ package io.swagger.client.model; import java.util.Objects; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; +import io.swagger.client.model.Tag; +import java.util.ArrayList; +import java.util.List; + import com.google.gson.annotations.SerializedName; -@ApiModel(description = "") + + public class InlineResponse200 { + @SerializedName("photoUrls") + private List photoUrls = new ArrayList(); + @SerializedName("name") private String name = null; @@ -21,6 +29,46 @@ public class InlineResponse200 { @SerializedName("category") private Object category = null; + @SerializedName("tags") + private List tags = new ArrayList(); + + +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 value; + } +} + + @SerializedName("status") + private StatusEnum status = null; + + + + /** + **/ + @ApiModelProperty(value = "") + public List getPhotoUrls() { + return photoUrls; + } + public void setPhotoUrls(List photoUrls) { + this.photoUrls = photoUrls; + } /** @@ -56,6 +104,29 @@ public class InlineResponse200 { } + /** + **/ + @ApiModelProperty(value = "") + public List getTags() { + return tags; + } + public void setTags(List tags) { + this.tags = tags; + } + + + /** + * pet status in the store + **/ + @ApiModelProperty(value = "pet status in the store") + public StatusEnum getStatus() { + return status; + } + public void setStatus(StatusEnum status) { + this.status = status; + } + + @Override public boolean equals(Object o) { @@ -66,14 +137,17 @@ public class InlineResponse200 { return false; } InlineResponse200 inlineResponse200 = (InlineResponse200) o; - return Objects.equals(name, inlineResponse200.name) && + return Objects.equals(photoUrls, inlineResponse200.photoUrls) && + Objects.equals(name, inlineResponse200.name) && Objects.equals(id, inlineResponse200.id) && - Objects.equals(category, inlineResponse200.category); + Objects.equals(category, inlineResponse200.category) && + Objects.equals(tags, inlineResponse200.tags) && + Objects.equals(status, inlineResponse200.status); } @Override public int hashCode() { - return Objects.hash(name, id, category); + return Objects.hash(photoUrls, name, id, category, tags, status); } @Override @@ -81,9 +155,12 @@ public class InlineResponse200 { StringBuilder sb = new StringBuilder(); sb.append("class InlineResponse200 {\n"); + sb.append(" photoUrls: ").append(toIndentedString(photoUrls)).append("\n"); sb.append(" name: ").append(toIndentedString(name)).append("\n"); sb.append(" id: ").append(toIndentedString(id)).append("\n"); sb.append(" category: ").append(toIndentedString(category)).append("\n"); + sb.append(" tags: ").append(toIndentedString(tags)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); sb.append("}"); return sb.toString(); } @@ -99,3 +176,5 @@ public class InlineResponse200 { 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 new file mode 100644 index 00000000000..80b0aed92a8 --- /dev/null +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Model200Response.java @@ -0,0 +1,73 @@ +package io.swagger.client.model; + +import java.util.Objects; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + + +import com.google.gson.annotations.SerializedName; + + + + + + +public class Model200Response { + + @SerializedName("name") + private Integer name = null; + + + + /** + **/ + @ApiModelProperty(value = "") + public Integer getName() { + return name; + } + public void setName(Integer name) { + this.name = name; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Model200Response _200Response = (Model200Response) o; + return Objects.equals(name, _200Response.name); + } + + @Override + public int hashCode() { + return Objects.hash(name); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Model200Response {\n"); + + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + 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 new file mode 100644 index 00000000000..ce8c1238fdb --- /dev/null +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/ModelReturn.java @@ -0,0 +1,73 @@ +package io.swagger.client.model; + +import java.util.Objects; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + + +import com.google.gson.annotations.SerializedName; + + + + + + +public class ModelReturn { + + @SerializedName("return") + private Integer _return = null; + + + + /** + **/ + @ApiModelProperty(value = "") + public Integer getReturn() { + return _return; + } + public void setReturn(Integer _return) { + this._return = _return; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + 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/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 new file mode 100644 index 00000000000..370214bd21c --- /dev/null +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Name.java @@ -0,0 +1,89 @@ +package io.swagger.client.model; + +import java.util.Objects; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + + +import com.google.gson.annotations.SerializedName; + + + + + + +public class Name { + + @SerializedName("name") + private Integer name = null; + + @SerializedName("snake_case") + private Integer snakeCase = null; + + + + /** + **/ + @ApiModelProperty(value = "") + public Integer getName() { + return name; + } + public void setName(Integer name) { + this.name = name; + } + + + /** + **/ + @ApiModelProperty(value = "") + public Integer getSnakeCase() { + return snakeCase; + } + public void setSnakeCase(Integer snakeCase) { + this.snakeCase = snakeCase; + } + + + + @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); + } + + @Override + public int hashCode() { + return Objects.hash(name, snakeCase); + } + + @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("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + + diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/ObjectReturn.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/ObjectReturn.java new file mode 100644 index 00000000000..920640ad2cb --- /dev/null +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/ObjectReturn.java @@ -0,0 +1,69 @@ +package io.swagger.client.model; + +import java.util.Objects; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +import com.google.gson.annotations.SerializedName; + + + + +@ApiModel(description = "") +public class ObjectReturn { + + @SerializedName("return") + private Integer _return = null; + + + + /** + **/ + @ApiModelProperty(value = "") + public Integer getReturn() { + return _return; + } + public void setReturn(Integer _return) { + this._return = _return; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ObjectReturn _return = (ObjectReturn) 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 ObjectReturn {\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/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 c73230a4119..e601bd7a15a 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 @@ -5,12 +5,14 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.util.Date; + import com.google.gson.annotations.SerializedName; -@ApiModel(description = "") + + public class Order { @SerializedName("id") @@ -169,3 +171,5 @@ public enum StatusEnum { 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 0374eabfba4..5d1210dc55b 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 @@ -8,12 +8,14 @@ import io.swagger.client.model.Tag; import java.util.ArrayList; import java.util.List; + import com.google.gson.annotations.SerializedName; -@ApiModel(description = "") + + public class Pet { @SerializedName("id") @@ -175,3 +177,5 @@ public enum StatusEnum { 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 new file mode 100644 index 00000000000..b5a96d5fc39 --- /dev/null +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/SpecialModelName.java @@ -0,0 +1,73 @@ +package io.swagger.client.model; + +import java.util.Objects; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + + +import com.google.gson.annotations.SerializedName; + + + + + + +public class SpecialModelName { + + @SerializedName("$special[property.name]") + private Long specialPropertyName = null; + + + + /** + **/ + @ApiModelProperty(value = "") + public Long getSpecialPropertyName() { + return specialPropertyName; + } + public void setSpecialPropertyName(Long specialPropertyName) { + this.specialPropertyName = specialPropertyName; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + 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/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 a4ca1074ca1..6ee49ee2166 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 @@ -4,12 +4,14 @@ import java.util.Objects; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; + import com.google.gson.annotations.SerializedName; -@ApiModel(description = "") + + public class Tag { @SerializedName("id") @@ -83,3 +85,5 @@ public class Tag { 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 072f510081a..98196393ef1 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 @@ -4,12 +4,14 @@ import java.util.Objects; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; + import com.google.gson.annotations.SerializedName; -@ApiModel(description = "") + + public class User { @SerializedName("id") @@ -180,3 +182,5 @@ public class User { return o.toString().replace("\n", "\n "); } } + + diff --git a/samples/client/petstore/java/retrofit2rx/.gitignore b/samples/client/petstore/java/retrofit2rx/.gitignore new file mode 100644 index 00000000000..32858aad3c3 --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/.gitignore @@ -0,0 +1,12 @@ +*.class + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.ear + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* diff --git a/samples/client/petstore/java/retrofit2rx/README.md b/samples/client/petstore/java/retrofit2rx/README.md index 7673712f5a5..a1f0b3468be 100644 --- a/samples/client/petstore/java/retrofit2rx/README.md +++ b/samples/client/petstore/java/retrofit2rx/README.md @@ -20,7 +20,7 @@ mvn deploy Refer to the [official documentation](https://maven.apache.org/plugins/maven-deploy-plugin/usage.html) for more information. -After the client libarary is installed/deployed, you can use it in your Maven project by adding the following to your *pom.xml*: +After the client library is installed/deployed, you can use it in your Maven project by adding the following to your *pom.xml*: ```xml diff --git a/samples/client/petstore/java/retrofit2rx/build.gradle b/samples/client/petstore/java/retrofit2rx/build.gradle index 1ab839078a4..c7139267298 100644 --- a/samples/client/petstore/java/retrofit2rx/build.gradle +++ b/samples/client/petstore/java/retrofit2rx/build.gradle @@ -101,6 +101,7 @@ ext { dependencies { compile "com.squareup.retrofit2:retrofit:$retrofit_version" + compile "com.squareup.retrofit2:converter-scalars:$retrofit_version" compile "com.squareup.retrofit2:converter-gson:$retrofit_version" compile "com.squareup.retrofit2:adapter-rxjava:$retrofit_version" compile "io.reactivex:rxjava:$rx_java_version" diff --git a/samples/client/petstore/java/retrofit2rx/git_push.sh b/samples/client/petstore/java/retrofit2rx/git_push.sh new file mode 100644 index 00000000000..1a36388db02 --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/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="YOUR_GIT_USR_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="YOUR_GIT_REPO_ID" + 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/retrofit2rx/hello.txt b/samples/client/petstore/java/retrofit2rx/hello.txt deleted file mode 100644 index 6769dd60bdf..00000000000 --- a/samples/client/petstore/java/retrofit2rx/hello.txt +++ /dev/null @@ -1 +0,0 @@ -Hello world! \ No newline at end of file diff --git a/samples/client/petstore/java/retrofit2rx/pom.xml b/samples/client/petstore/java/retrofit2rx/pom.xml index e5c4e687511..b2cf9949578 100644 --- a/samples/client/petstore/java/retrofit2rx/pom.xml +++ b/samples/client/petstore/java/retrofit2rx/pom.xml @@ -118,6 +118,11 @@ retrofit ${retrofit-version} + + com.squareup.retrofit2 + converter-scalars + ${retrofit-version} + com.squareup.retrofit2 converter-gson @@ -128,18 +133,16 @@ org.apache.oltu.oauth2.client ${oltu-version} - - - io.reactivex - rxjava - ${rxjava-version} - - - com.squareup.retrofit2 - adapter-rxjava - ${retrofit-version} - - + + io.reactivex + rxjava + ${rxjava-version} + + + com.squareup.retrofit2 + adapter-rxjava + ${retrofit-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 800e4db8bd8..5582509be76 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 @@ -12,8 +12,9 @@ import org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuil import retrofit2.Converter; import retrofit2.Retrofit; -import retrofit2.converter.gson.GsonConverterFactory; import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory; +import retrofit2.converter.gson.GsonConverterFactory; +import retrofit2.converter.scalars.ScalarsConverterFactory; import com.google.gson.Gson; import com.google.gson.GsonBuilder; @@ -46,10 +47,18 @@ public class ApiClient { this(); for(String authName : authNames) { Interceptor auth; - if (authName == "api_key") { - auth = new ApiKeyAuth("header", "api_key"); - } else if (authName == "petstore_auth") { + if (authName == "petstore_auth") { auth = new OAuth(OAuthFlow.implicit, "http://petstore.swagger.io/api/oauth/dialog", "", "write:pets, read:pets"); + } else if (authName == "test_api_client_id") { + auth = new ApiKeyAuth("header", "x-test_api_client_id"); + } else if (authName == "test_api_client_secret") { + auth = new ApiKeyAuth("header", "x-test_api_client_secret"); + } else if (authName == "api_key") { + auth = new ApiKeyAuth("header", "api_key"); + } else if (authName == "test_api_key_query") { + auth = new ApiKeyAuth("query", "test_api_key_query"); + } else if (authName == "test_api_key_header") { + auth = new ApiKeyAuth("header", "test_api_key_header"); } else { throw new RuntimeException("auth name \"" + authName + "\" not found in available auth names"); } @@ -119,6 +128,7 @@ public class ApiClient { .baseUrl(baseUrl) .client(okClient) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) + .addConverterFactory(ScalarsConverterFactory.create()) .addConverterFactory(GsonCustomConverterFactory.create(gson)); } 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 1e7e09a6aa9..e8c0dc4d062 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/StringUtil.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/StringUtil.java @@ -1,6 +1,6 @@ package io.swagger.client; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-02-26T13:30:13.630+01:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-03-07T09:11:59.834Z") public class StringUtil { /** * Check if the given array contains the given value (with case-insensitive comparison). diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/PetApi.java index 3068b6be265..33d4760a605 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,32 +9,24 @@ import retrofit2.http.*; import okhttp3.RequestBody; import io.swagger.client.model.Pet; +import io.swagger.client.model.InlineResponse200; import java.io.File; + + import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; -public interface PetApi { - - /** - * Update an existing pet - * - * @param body Pet object that needs to be added to the store - * @return Call - */ - - @PUT("pet") - Observable updatePet( - @Body Pet body - ); + +public interface PetApi { /** * Add a new pet to the store * - * @param body Pet object that needs to be added to the store + * @param body Pet object that needs to be added to the store (optional) * @return Call */ @@ -44,10 +36,37 @@ public interface PetApi { ); + /** + * Fake endpoint to test byte array in body parameter for adding a new pet to the store + * + * @param body Pet object in the form of byte array (optional) + * @return Call + */ + + @POST("pet?testing_byte_array=true") + Observable addPetUsingByteArray( + @Body byte[] body + ); + + + /** + * Deletes a pet + * + * @param petId Pet id to delete (required) + * @param apiKey (optional) + * @return Call + */ + + @DELETE("pet/{petId}") + Observable deletePet( + @Path("petId") Long petId, @Header("api_key") String apiKey + ); + + /** * Finds Pets by status - * Multiple status values can be provided with comma seperated strings - * @param status Status values that need to be considered for filter + * Multiple status values can be provided with comma separated strings + * @param status Status values that need to be considered for query (optional, default to available) * @return Call> */ @@ -60,7 +79,7 @@ public interface PetApi { /** * Finds Pets by tags * Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. - * @param tags Tags to filter by + * @param tags Tags to filter by (optional) * @return Call> */ @@ -73,7 +92,7 @@ public interface PetApi { /** * Find pet by ID * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions - * @param petId ID of pet that needs to be fetched + * @param petId ID of pet that needs to be fetched (required) * @return Call */ @@ -83,12 +102,51 @@ public interface PetApi { ); + /** + * Fake endpoint to test inline arbitrary object return by 'Find pet by ID' + * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + * @param petId ID of pet that needs to be fetched (required) + * @return Call + */ + + @GET("pet/{petId}?response=inline_arbitrary_object") + Observable getPetByIdInObject( + @Path("petId") Long petId + ); + + + /** + * Fake endpoint to test byte array return by 'Find pet by ID' + * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + * @param petId ID of pet that needs to be fetched (required) + * @return Call + */ + + @GET("pet/{petId}?testing_byte_array=true") + Observable petPetIdtestingByteArraytrueGet( + @Path("petId") Long petId + ); + + + /** + * Update an existing pet + * + * @param body Pet object that needs to be added to the store (optional) + * @return Call + */ + + @PUT("pet") + Observable updatePet( + @Body Pet body + ); + + /** * Updates a pet in the store with form data * - * @param petId ID of pet that needs to be updated - * @param name Updated name of the pet - * @param status Updated status of the pet + * @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 */ @@ -99,26 +157,12 @@ public interface PetApi { ); - /** - * Deletes a pet - * - * @param petId Pet id to delete - * @param apiKey - * @return Call - */ - - @DELETE("pet/{petId}") - Observable deletePet( - @Path("petId") Long petId, @Header("api_key") String apiKey - ); - - /** * uploads an image * - * @param petId ID of pet to update - * @param additionalMetadata Additional data to pass to server - * @param file file to upload + * @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 */ @@ -129,30 +173,5 @@ public interface PetApi { ); - /** - * Fake endpoint to test byte array return by 'Find pet by ID' - * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions - * @param petId ID of pet that needs to be fetched - * @return Call - */ - - @GET("pet/{petId}?testing_byte_array=true") - Observable getPetByIdWithByteArray( - @Path("petId") Long petId - ); - - - /** - * Fake endpoint to test byte array in body parameter for adding a new pet to the store - * - * @param body Pet object in the form of byte array - * @return Call - */ - - @POST("pet?testing_byte_array=true") - Observable addPetUsingByteArray( - @Body byte[] body - ); - - } + 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 e1761527bf5..b4effc010df 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 @@ -10,13 +10,43 @@ import okhttp3.RequestBody; import io.swagger.client.model.Order; + + import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; + + 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 + */ + + @DELETE("store/order/{orderId}") + Observable deleteOrder( + @Path("orderId") String orderId + ); + + + /** + * Finds orders by status + * A single status value can be provided as a string + * @param status Status value that needs to be considered for query (optional, default to placed) + * @return Call> + */ + + @GET("store/findByStatus") + Observable> findOrdersByStatus( + @Query("status") String status + ); + + /** * Returns pet inventories by status * Returns a map of status codes to quantities @@ -29,22 +59,20 @@ public interface StoreApi { /** - * Place an order for a pet - * - * @param body order placed for purchasing the pet - * @return Call + * Fake endpoint to test arbitrary object return by 'Get inventory' + * Returns an arbitrary object which is actually a map of status codes to quantities + * @return Call */ - @POST("store/order") - Observable placeOrder( - @Body Order body - ); + @GET("store/inventory?response=arbitrary_object") + Observable getInventoryInObject(); + /** * 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 + * @param orderId ID of pet that needs to be fetched (required) * @return Call */ @@ -55,16 +83,17 @@ 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 - * @return Call + * Place an order for a pet + * + * @param body order placed for purchasing the pet (optional) + * @return Call */ - @DELETE("store/order/{orderId}") - Observable deleteOrder( - @Path("orderId") String orderId + @POST("store/order") + Observable placeOrder( + @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 935d9ff4383..6019e10711d 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 @@ -10,17 +10,21 @@ import okhttp3.RequestBody; import io.swagger.client.model.User; + + import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; + + public interface UserApi { /** * Create user * This can only be done by the logged in user. - * @param body Created user object + * @param body Created user object (optional) * @return Call */ @@ -33,7 +37,7 @@ public interface UserApi { /** * Creates list of users with given input array * - * @param body List of user object + * @param body List of user object (optional) * @return Call */ @@ -46,7 +50,7 @@ public interface UserApi { /** * Creates list of users with given input array * - * @param body List of user object + * @param body List of user object (optional) * @return Call */ @@ -56,11 +60,37 @@ public interface UserApi { ); + /** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted (required) + * @return Call + */ + + @DELETE("user/{username}") + Observable deleteUser( + @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 + */ + + @GET("user/{username}") + Observable getUserByName( + @Path("username") String username + ); + + /** * Logs user into the system * - * @param username The user name for login - * @param password The password for login in clear text + * @param username The user name for login (optional) + * @param password The password for login in clear text (optional) * @return Call */ @@ -81,24 +111,11 @@ public interface UserApi { - /** - * Get user by user name - * - * @param username The name that needs to be fetched. Use user1 for testing. - * @return Call - */ - - @GET("user/{username}") - Observable getUserByName( - @Path("username") String username - ); - - /** * Updated user * This can only be done by the logged in user. - * @param username name that need to be deleted - * @param body Updated user object + * @param username name that need to be deleted (required) + * @param body Updated user object (optional) * @return Call */ @@ -108,17 +125,5 @@ public interface UserApi { ); - /** - * Delete user - * This can only be done by the logged in user. - * @param username The name that needs to be deleted - * @return Call - */ - - @DELETE("user/{username}") - Observable deleteUser( - @Path("username") String username - ); - - } + 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 d0908afd9e1..67de63eb179 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 @@ -4,12 +4,14 @@ import java.util.Objects; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; + import com.google.gson.annotations.SerializedName; -@ApiModel(description = "") + + public class Category { @SerializedName("id") @@ -83,3 +85,5 @@ public class Category { return o.toString().replace("\n", "\n "); } } + + diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/InlineResponse200.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/InlineResponse200.java new file mode 100644 index 00000000000..165f069a05b --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/InlineResponse200.java @@ -0,0 +1,180 @@ +package io.swagger.client.model; + +import java.util.Objects; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.client.model.Tag; +import java.util.ArrayList; +import java.util.List; + + +import com.google.gson.annotations.SerializedName; + + + + + + +public class InlineResponse200 { + + @SerializedName("photoUrls") + private List photoUrls = new ArrayList(); + + @SerializedName("name") + private String name = null; + + @SerializedName("id") + private Long id = null; + + @SerializedName("category") + private Object category = null; + + @SerializedName("tags") + private List tags = new ArrayList(); + + +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 value; + } +} + + @SerializedName("status") + private StatusEnum status = null; + + + + /** + **/ + @ApiModelProperty(value = "") + public List getPhotoUrls() { + return photoUrls; + } + public void setPhotoUrls(List photoUrls) { + this.photoUrls = photoUrls; + } + + + /** + **/ + @ApiModelProperty(value = "") + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + + + /** + **/ + @ApiModelProperty(required = true, value = "") + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + + /** + **/ + @ApiModelProperty(value = "") + public Object getCategory() { + return category; + } + public void setCategory(Object category) { + this.category = category; + } + + + /** + **/ + @ApiModelProperty(value = "") + public List getTags() { + return tags; + } + public void setTags(List tags) { + this.tags = tags; + } + + + /** + * pet status in the store + **/ + @ApiModelProperty(value = "pet status in the store") + public StatusEnum getStatus() { + return status; + } + public void setStatus(StatusEnum status) { + this.status = status; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + InlineResponse200 inlineResponse200 = (InlineResponse200) o; + return Objects.equals(photoUrls, inlineResponse200.photoUrls) && + Objects.equals(name, inlineResponse200.name) && + Objects.equals(id, inlineResponse200.id) && + Objects.equals(category, inlineResponse200.category) && + Objects.equals(tags, inlineResponse200.tags) && + Objects.equals(status, inlineResponse200.status); + } + + @Override + public int hashCode() { + return Objects.hash(photoUrls, name, id, category, tags, status); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class InlineResponse200 {\n"); + + sb.append(" photoUrls: ").append(toIndentedString(photoUrls)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" category: ").append(toIndentedString(category)).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/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 new file mode 100644 index 00000000000..80b0aed92a8 --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Model200Response.java @@ -0,0 +1,73 @@ +package io.swagger.client.model; + +import java.util.Objects; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + + +import com.google.gson.annotations.SerializedName; + + + + + + +public class Model200Response { + + @SerializedName("name") + private Integer name = null; + + + + /** + **/ + @ApiModelProperty(value = "") + public Integer getName() { + return name; + } + public void setName(Integer name) { + this.name = name; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Model200Response _200Response = (Model200Response) o; + return Objects.equals(name, _200Response.name); + } + + @Override + public int hashCode() { + return Objects.hash(name); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Model200Response {\n"); + + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + 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 new file mode 100644 index 00000000000..ce8c1238fdb --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/ModelReturn.java @@ -0,0 +1,73 @@ +package io.swagger.client.model; + +import java.util.Objects; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + + +import com.google.gson.annotations.SerializedName; + + + + + + +public class ModelReturn { + + @SerializedName("return") + private Integer _return = null; + + + + /** + **/ + @ApiModelProperty(value = "") + public Integer getReturn() { + return _return; + } + public void setReturn(Integer _return) { + this._return = _return; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + 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/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 new file mode 100644 index 00000000000..370214bd21c --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Name.java @@ -0,0 +1,89 @@ +package io.swagger.client.model; + +import java.util.Objects; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + + +import com.google.gson.annotations.SerializedName; + + + + + + +public class Name { + + @SerializedName("name") + private Integer name = null; + + @SerializedName("snake_case") + private Integer snakeCase = null; + + + + /** + **/ + @ApiModelProperty(value = "") + public Integer getName() { + return name; + } + public void setName(Integer name) { + this.name = name; + } + + + /** + **/ + @ApiModelProperty(value = "") + public Integer getSnakeCase() { + return snakeCase; + } + public void setSnakeCase(Integer snakeCase) { + this.snakeCase = snakeCase; + } + + + + @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); + } + + @Override + public int hashCode() { + return Objects.hash(name, snakeCase); + } + + @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("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + + diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/ObjectReturn.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/ObjectReturn.java new file mode 100644 index 00000000000..920640ad2cb --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/ObjectReturn.java @@ -0,0 +1,69 @@ +package io.swagger.client.model; + +import java.util.Objects; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +import com.google.gson.annotations.SerializedName; + + + + +@ApiModel(description = "") +public class ObjectReturn { + + @SerializedName("return") + private Integer _return = null; + + + + /** + **/ + @ApiModelProperty(value = "") + public Integer getReturn() { + return _return; + } + public void setReturn(Integer _return) { + this._return = _return; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ObjectReturn _return = (ObjectReturn) 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 ObjectReturn {\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/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 c73230a4119..e601bd7a15a 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 @@ -5,12 +5,14 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.util.Date; + import com.google.gson.annotations.SerializedName; -@ApiModel(description = "") + + public class Order { @SerializedName("id") @@ -169,3 +171,5 @@ public enum StatusEnum { 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 0374eabfba4..5d1210dc55b 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 @@ -8,12 +8,14 @@ import io.swagger.client.model.Tag; import java.util.ArrayList; import java.util.List; + import com.google.gson.annotations.SerializedName; -@ApiModel(description = "") + + public class Pet { @SerializedName("id") @@ -175,3 +177,5 @@ public enum StatusEnum { 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 new file mode 100644 index 00000000000..b5a96d5fc39 --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/SpecialModelName.java @@ -0,0 +1,73 @@ +package io.swagger.client.model; + +import java.util.Objects; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + + +import com.google.gson.annotations.SerializedName; + + + + + + +public class SpecialModelName { + + @SerializedName("$special[property.name]") + private Long specialPropertyName = null; + + + + /** + **/ + @ApiModelProperty(value = "") + public Long getSpecialPropertyName() { + return specialPropertyName; + } + public void setSpecialPropertyName(Long specialPropertyName) { + this.specialPropertyName = specialPropertyName; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + 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/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 a4ca1074ca1..6ee49ee2166 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 @@ -4,12 +4,14 @@ import java.util.Objects; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; + import com.google.gson.annotations.SerializedName; -@ApiModel(description = "") + + public class Tag { @SerializedName("id") @@ -83,3 +85,5 @@ public class Tag { 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 072f510081a..98196393ef1 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 @@ -4,12 +4,14 @@ import java.util.Objects; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; + import com.google.gson.annotations.SerializedName; -@ApiModel(description = "") + + public class User { @SerializedName("id") @@ -180,3 +182,5 @@ public class User { return o.toString().replace("\n", "\n "); } } + + diff --git a/samples/client/petstore/javascript-promise/README.md b/samples/client/petstore/javascript-promise/README.md new file mode 100644 index 00000000000..3fc0c158a2a --- /dev/null +++ b/samples/client/petstore/javascript-promise/README.md @@ -0,0 +1,171 @@ +# swagger-petstore + +SwaggerPetstore - JavaScript client for 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 +This SDK is automatically generated by the [Swagger Codegen](https://github.com/swagger-api/swagger-codegen) project: + +- API version: 1.0.0 +- Package version: 1.0.0 +- Build date: 2016-03-30T20:58:13.565+08:00 +- Build package: class io.swagger.codegen.languages.JavascriptClientCodegen + +## Installation + +### For [Node.js](https://nodejs.org/) + +#### npm + +To publish the library as a [npm](https://www.npmjs.com/), +please follow the procedure in ["Publishing npm packages"](https://docs.npmjs.com/getting-started/publishing-npm-packages). + +Then install it via: + +```shell +npm install swagger-petstore --save +``` + +#### git +# +If the library is hosted at a git repository, e.g. +https://github.com/YOUR_USERNAME/YOUR_GIT_REPO_ID +then install it via: + +```shell +npm install YOUR_USERNAME/YOUR_GIT_REPO_ID --save +``` + +### For browser + +The library also works in the browser environment via npm and [browserify](http://browserify.org/). After following +the above steps with Node.js and installing browserify with `npm install -g browserify`, +perform the following (assuming *main.js* is your entry file): + +```shell +browserify main.js > bundle.js +``` + +Then include *bundle.js* in the HTML pages. + +## Getting Started + +Please follow the [installation](#installation) instruction and execute the following JS code: + +```javascript +var SwaggerPetstore = require('swagger-petstore'); + +var defaultClient = SwaggerPetstore.ApiClient.default; + +// Configure OAuth2 access token for authorization: petstore_auth +var petstore_auth = defaultClient.authentications['petstore_auth']; +petstore_auth.accessToken = "YOUR ACCESS TOKEN" + +var api = new SwaggerPetstore.PetApi() + +var opts = { + 'body': new SwaggerPetstore.Pet() // {Pet} Pet object that needs to be added to the store +}; +api.addPet(opts).then(function() { + console.log('API called successfully.'); +}, function(error) { + console.error(error); +}); + + +``` + +## Documentation for API Endpoints + +All URIs are relative to *http://petstore.swagger.io/v2* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +*SwaggerPetstore.PetApi* | [**addPet**](docs/PetApi.md#addPet) | **POST** /pet | Add a new pet to the store +*SwaggerPetstore.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 +*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 +*SwaggerPetstore.PetApi* | [**findPetsByTags**](docs/PetApi.md#findPetsByTags) | **GET** /pet/findByTags | Finds Pets by tags +*SwaggerPetstore.PetApi* | [**getPetById**](docs/PetApi.md#getPetById) | **GET** /pet/{petId} | Find pet by ID +*SwaggerPetstore.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' +*SwaggerPetstore.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' +*SwaggerPetstore.PetApi* | [**updatePet**](docs/PetApi.md#updatePet) | **PUT** /pet | Update an existing pet +*SwaggerPetstore.PetApi* | [**updatePetWithForm**](docs/PetApi.md#updatePetWithForm) | **POST** /pet/{petId} | Updates a pet in the store with form data +*SwaggerPetstore.PetApi* | [**uploadFile**](docs/PetApi.md#uploadFile) | **POST** /pet/{petId}/uploadImage | uploads an image +*SwaggerPetstore.StoreApi* | [**deleteOrder**](docs/StoreApi.md#deleteOrder) | **DELETE** /store/order/{orderId} | Delete purchase order by ID +*SwaggerPetstore.StoreApi* | [**findOrdersByStatus**](docs/StoreApi.md#findOrdersByStatus) | **GET** /store/findByStatus | Finds orders by status +*SwaggerPetstore.StoreApi* | [**getInventory**](docs/StoreApi.md#getInventory) | **GET** /store/inventory | Returns pet inventories by status +*SwaggerPetstore.StoreApi* | [**getInventoryInObject**](docs/StoreApi.md#getInventoryInObject) | **GET** /store/inventory?response=arbitrary_object | Fake endpoint to test arbitrary object return by 'Get inventory' +*SwaggerPetstore.StoreApi* | [**getOrderById**](docs/StoreApi.md#getOrderById) | **GET** /store/order/{orderId} | Find purchase order by ID +*SwaggerPetstore.StoreApi* | [**placeOrder**](docs/StoreApi.md#placeOrder) | **POST** /store/order | Place an order for a pet +*SwaggerPetstore.UserApi* | [**createUser**](docs/UserApi.md#createUser) | **POST** /user | Create user +*SwaggerPetstore.UserApi* | [**createUsersWithArrayInput**](docs/UserApi.md#createUsersWithArrayInput) | **POST** /user/createWithArray | Creates list of users with given input array +*SwaggerPetstore.UserApi* | [**createUsersWithListInput**](docs/UserApi.md#createUsersWithListInput) | **POST** /user/createWithList | Creates list of users with given input array +*SwaggerPetstore.UserApi* | [**deleteUser**](docs/UserApi.md#deleteUser) | **DELETE** /user/{username} | Delete user +*SwaggerPetstore.UserApi* | [**getUserByName**](docs/UserApi.md#getUserByName) | **GET** /user/{username} | Get user by user name +*SwaggerPetstore.UserApi* | [**loginUser**](docs/UserApi.md#loginUser) | **GET** /user/login | Logs user into the system +*SwaggerPetstore.UserApi* | [**logoutUser**](docs/UserApi.md#logoutUser) | **GET** /user/logout | Logs out current logged in user session +*SwaggerPetstore.UserApi* | [**updateUser**](docs/UserApi.md#updateUser) | **PUT** /user/{username} | Updated user + + +## Documentation for Models + + - [SwaggerPetstore.Animal](docs/Animal.md) + - [SwaggerPetstore.Cat](docs/Cat.md) + - [SwaggerPetstore.Category](docs/Category.md) + - [SwaggerPetstore.Dog](docs/Dog.md) + - [SwaggerPetstore.InlineResponse200](docs/InlineResponse200.md) + - [SwaggerPetstore.Model200Response](docs/Model200Response.md) + - [SwaggerPetstore.ModelReturn](docs/ModelReturn.md) + - [SwaggerPetstore.Name](docs/Name.md) + - [SwaggerPetstore.Order](docs/Order.md) + - [SwaggerPetstore.Pet](docs/Pet.md) + - [SwaggerPetstore.SpecialModelName](docs/SpecialModelName.md) + - [SwaggerPetstore.Tag](docs/Tag.md) + - [SwaggerPetstore.User](docs/User.md) + + +## Documentation for Authorization + + +### test_api_key_header + +- **Type**: API key +- **API key parameter name**: test_api_key_header +- **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_client_secret + +- **Type**: API key +- **API key parameter name**: x-test_api_client_secret +- **Location**: HTTP header + +### test_api_client_id + +- **Type**: API key +- **API key parameter name**: x-test_api_client_id +- **Location**: HTTP header + +### test_api_key_query + +- **Type**: API key +- **API key parameter name**: test_api_key_query +- **Location**: URL query string + +### 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 + diff --git a/samples/client/petstore/javascript-promise/docs/Animal.md b/samples/client/petstore/javascript-promise/docs/Animal.md new file mode 100644 index 00000000000..c37d95695a0 --- /dev/null +++ b/samples/client/petstore/javascript-promise/docs/Animal.md @@ -0,0 +1,8 @@ +# SwaggerPetstore.Animal + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**className** | **String** | | + + diff --git a/samples/client/petstore/javascript-promise/docs/Cat.md b/samples/client/petstore/javascript-promise/docs/Cat.md new file mode 100644 index 00000000000..8cd391bc911 --- /dev/null +++ b/samples/client/petstore/javascript-promise/docs/Cat.md @@ -0,0 +1,8 @@ +# SwaggerPetstore.Cat + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**declawed** | **Boolean** | | [optional] + + diff --git a/samples/client/petstore/javascript-promise/docs/Category.md b/samples/client/petstore/javascript-promise/docs/Category.md new file mode 100644 index 00000000000..47930eb882c --- /dev/null +++ b/samples/client/petstore/javascript-promise/docs/Category.md @@ -0,0 +1,9 @@ +# SwaggerPetstore.Category + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Integer** | | [optional] +**name** | **String** | | [optional] + + diff --git a/samples/client/petstore/javascript-promise/docs/Dog.md b/samples/client/petstore/javascript-promise/docs/Dog.md new file mode 100644 index 00000000000..9253eace011 --- /dev/null +++ b/samples/client/petstore/javascript-promise/docs/Dog.md @@ -0,0 +1,8 @@ +# SwaggerPetstore.Dog + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**breed** | **String** | | [optional] + + diff --git a/samples/client/petstore/javascript-promise/docs/InlineResponse200.md b/samples/client/petstore/javascript-promise/docs/InlineResponse200.md new file mode 100644 index 00000000000..bbb11067e9a --- /dev/null +++ b/samples/client/petstore/javascript-promise/docs/InlineResponse200.md @@ -0,0 +1,13 @@ +# SwaggerPetstore.InlineResponse200 + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**tags** | [**[Tag]**](Tag.md) | | [optional] +**id** | **Integer** | | +**category** | **Object** | | [optional] +**status** | **String** | pet status in the store | [optional] +**name** | **String** | | [optional] +**photoUrls** | **[String]** | | [optional] + + diff --git a/samples/client/petstore/javascript-promise/docs/Model200Response.md b/samples/client/petstore/javascript-promise/docs/Model200Response.md new file mode 100644 index 00000000000..cc06fcd2d18 --- /dev/null +++ b/samples/client/petstore/javascript-promise/docs/Model200Response.md @@ -0,0 +1,8 @@ +# SwaggerPetstore.Model200Response + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **Integer** | | [optional] + + diff --git a/samples/client/petstore/javascript-promise/docs/ModelReturn.md b/samples/client/petstore/javascript-promise/docs/ModelReturn.md new file mode 100644 index 00000000000..88412c87197 --- /dev/null +++ b/samples/client/petstore/javascript-promise/docs/ModelReturn.md @@ -0,0 +1,8 @@ +# SwaggerPetstore.ModelReturn + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**_return** | **Integer** | | [optional] + + diff --git a/samples/client/petstore/javascript-promise/docs/Name.md b/samples/client/petstore/javascript-promise/docs/Name.md new file mode 100644 index 00000000000..5086f6c5a3e --- /dev/null +++ b/samples/client/petstore/javascript-promise/docs/Name.md @@ -0,0 +1,9 @@ +# SwaggerPetstore.Name + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **Integer** | | [optional] +**snakeCase** | **Integer** | | [optional] + + diff --git a/samples/client/petstore/javascript-promise/docs/Order.md b/samples/client/petstore/javascript-promise/docs/Order.md new file mode 100644 index 00000000000..b34b67d3a56 --- /dev/null +++ b/samples/client/petstore/javascript-promise/docs/Order.md @@ -0,0 +1,13 @@ +# SwaggerPetstore.Order + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Integer** | | [optional] +**petId** | **Integer** | | [optional] +**quantity** | **Integer** | | [optional] +**shipDate** | **Date** | | [optional] +**status** | **String** | Order Status | [optional] +**complete** | **Boolean** | | [optional] + + diff --git a/samples/client/petstore/javascript-promise/docs/Pet.md b/samples/client/petstore/javascript-promise/docs/Pet.md new file mode 100644 index 00000000000..f1b049dcadd --- /dev/null +++ b/samples/client/petstore/javascript-promise/docs/Pet.md @@ -0,0 +1,13 @@ +# SwaggerPetstore.Pet + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Integer** | | [optional] +**category** | [**Category**](Category.md) | | [optional] +**name** | **String** | | +**photoUrls** | **[String]** | | +**tags** | [**[Tag]**](Tag.md) | | [optional] +**status** | **String** | pet status in the store | [optional] + + diff --git a/samples/client/petstore/javascript-promise/docs/PetApi.md b/samples/client/petstore/javascript-promise/docs/PetApi.md new file mode 100644 index 00000000000..77d9630f888 --- /dev/null +++ b/samples/client/petstore/javascript-promise/docs/PetApi.md @@ -0,0 +1,586 @@ +# SwaggerPetstore.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 +[**addPetUsingByteArray**](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 +[**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 +[**getPetByIdInObject**](PetApi.md#getPetByIdInObject) | **GET** /pet/{petId}?response=inline_arbitrary_object | Fake endpoint to test inline arbitrary object return by 'Find pet by ID' +[**petPetIdtestingByteArraytrueGet**](PetApi.md#petPetIdtestingByteArraytrueGet) | **GET** /pet/{petId}?testing_byte_array=true | Fake endpoint to test byte array return by '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(opts) + +Add a new pet to the store + + + +### Example +```javascript +var SwaggerPetstore = require('swagger-petstore'); +var defaultClient = SwaggerPetstore.ApiClient.default; + +// Configure OAuth2 access token for authorization: petstore_auth +var petstore_auth = defaultClient.authentications['petstore_auth']; +petstore_auth.accessToken = "YOUR ACCESS TOKEN" + +var apiInstance = new SwaggerPetstore.PetApi() + +var opts = { + 'body': new SwaggerPetstore.Pet() // {Pet} Pet object that needs to be added to the store +}; +apiInstance.addPet(opts).then(function() { + console.log('API called successfully.'); +}, function(error) { + console.error(error); +}); + +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | [optional] + +### Return type + +null (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP reuqest headers + + - **Content-Type**: application/json, application/xml + - **Accept**: application/json, application/xml + + +# **addPetUsingByteArray** +> addPetUsingByteArray(opts) + +Fake endpoint to test byte array in body parameter for adding a new pet to the store + + + +### Example +```javascript +var SwaggerPetstore = require('swagger-petstore'); +var defaultClient = SwaggerPetstore.ApiClient.default; + +// Configure OAuth2 access token for authorization: petstore_auth +var petstore_auth = defaultClient.authentications['petstore_auth']; +petstore_auth.accessToken = "YOUR ACCESS TOKEN" + +var apiInstance = new SwaggerPetstore.PetApi() + +var opts = { + 'body': "B" // {String} Pet object in the form of byte array +}; +apiInstance.addPetUsingByteArray(opts).then(function() { + console.log('API called successfully.'); +}, function(error) { + console.error(error); +}); + +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | **String**| Pet object in the form of byte array | [optional] + +### Return type + +null (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP reuqest headers + + - **Content-Type**: application/json, application/xml + - **Accept**: application/json, application/xml + + +# **deletePet** +> deletePet(petId, opts) + +Deletes a pet + + + +### Example +```javascript +var SwaggerPetstore = require('swagger-petstore'); +var defaultClient = SwaggerPetstore.ApiClient.default; + +// Configure OAuth2 access token for authorization: petstore_auth +var petstore_auth = defaultClient.authentications['petstore_auth']; +petstore_auth.accessToken = "YOUR ACCESS TOKEN" + +var apiInstance = new SwaggerPetstore.PetApi() + +var petId = 789; // {Integer} Pet id to delete + +var opts = { + 'apiKey': "apiKey_example" // {String} +}; +apiInstance.deletePet(petId, opts).then(function() { + console.log('API called successfully.'); +}, function(error) { + console.error(error); +}); + +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **Integer**| Pet id to delete | + **apiKey** | **String**| | [optional] + +### Return type + +null (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + + +# **findPetsByStatus** +> [Pet] findPetsByStatus(opts) + +Finds Pets by status + +Multiple status values can be provided with comma separated strings + +### Example +```javascript +var SwaggerPetstore = require('swagger-petstore'); +var defaultClient = SwaggerPetstore.ApiClient.default; + +// Configure OAuth2 access token for authorization: petstore_auth +var petstore_auth = defaultClient.authentications['petstore_auth']; +petstore_auth.accessToken = "YOUR ACCESS TOKEN" + +var apiInstance = new SwaggerPetstore.PetApi() + +var opts = { + 'status': ["available"] // {[String]} Status values that need to be considered for query +}; +apiInstance.findPetsByStatus(opts).then(function(data) { + console.log('API called successfully. Returned data: ' + data); +}, function(error) { + console.error(error); +}); + +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **status** | [**[String]**](String.md)| Status values that need to be considered for query | [optional] [default to available] + +### Return type + +[**[Pet]**](Pet.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + + +# **findPetsByTags** +> [Pet] findPetsByTags(opts) + +Finds Pets by tags + +Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + +### Example +```javascript +var SwaggerPetstore = require('swagger-petstore'); +var defaultClient = SwaggerPetstore.ApiClient.default; + +// Configure OAuth2 access token for authorization: petstore_auth +var petstore_auth = defaultClient.authentications['petstore_auth']; +petstore_auth.accessToken = "YOUR ACCESS TOKEN" + +var apiInstance = new SwaggerPetstore.PetApi() + +var opts = { + 'tags': ["tags_example"] // {[String]} Tags to filter by +}; +apiInstance.findPetsByTags(opts).then(function(data) { + console.log('API called successfully. Returned data: ' + data); +}, function(error) { + console.error(error); +}); + +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **tags** | [**[String]**](String.md)| Tags to filter by | [optional] + +### Return type + +[**[Pet]**](Pet.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + + +# **getPetById** +> Pet getPetById(petId) + +Find pet by ID + +Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + +### Example +```javascript +var SwaggerPetstore = require('swagger-petstore'); +var defaultClient = SwaggerPetstore.ApiClient.default; + +// 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" + +// Configure OAuth2 access token for authorization: petstore_auth +var petstore_auth = defaultClient.authentications['petstore_auth']; +petstore_auth.accessToken = "YOUR ACCESS TOKEN" + +var apiInstance = new SwaggerPetstore.PetApi() + +var petId = 789; // {Integer} ID of pet that needs to be fetched + +apiInstance.getPetById(petId).then(function(data) { + console.log('API called successfully. Returned data: ' + data); +}, function(error) { + console.error(error); +}); + +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **Integer**| ID of pet that needs to be fetched | + +### Return type + +[**Pet**](Pet.md) + +### Authorization + +[api_key](../README.md#api_key), [petstore_auth](../README.md#petstore_auth) + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + + +# **getPetByIdInObject** +> InlineResponse200 getPetByIdInObject(petId) + +Fake endpoint to test inline arbitrary object return by 'Find pet by ID' + +Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + +### Example +```javascript +var SwaggerPetstore = require('swagger-petstore'); +var defaultClient = SwaggerPetstore.ApiClient.default; + +// 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" + +// Configure OAuth2 access token for authorization: petstore_auth +var petstore_auth = defaultClient.authentications['petstore_auth']; +petstore_auth.accessToken = "YOUR ACCESS TOKEN" + +var apiInstance = new SwaggerPetstore.PetApi() + +var petId = 789; // {Integer} ID of pet that needs to be fetched + +apiInstance.getPetByIdInObject(petId).then(function(data) { + console.log('API called successfully. Returned data: ' + data); +}, function(error) { + console.error(error); +}); + +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **Integer**| ID of pet that needs to be fetched | + +### Return type + +[**InlineResponse200**](InlineResponse200.md) + +### Authorization + +[api_key](../README.md#api_key), [petstore_auth](../README.md#petstore_auth) + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + + +# **petPetIdtestingByteArraytrueGet** +> 'String' petPetIdtestingByteArraytrueGet(petId) + +Fake endpoint to test byte array return by 'Find pet by ID' + +Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + +### Example +```javascript +var SwaggerPetstore = require('swagger-petstore'); +var defaultClient = SwaggerPetstore.ApiClient.default; + +// 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" + +// Configure OAuth2 access token for authorization: petstore_auth +var petstore_auth = defaultClient.authentications['petstore_auth']; +petstore_auth.accessToken = "YOUR ACCESS TOKEN" + +var apiInstance = new SwaggerPetstore.PetApi() + +var petId = 789; // {Integer} ID of pet that needs to be fetched + +apiInstance.petPetIdtestingByteArraytrueGet(petId).then(function(data) { + console.log('API called successfully. Returned data: ' + data); +}, function(error) { + console.error(error); +}); + +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **Integer**| ID of pet that needs to be fetched | + +### Return type + +**'String'** + +### Authorization + +[api_key](../README.md#api_key), [petstore_auth](../README.md#petstore_auth) + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + + +# **updatePet** +> updatePet(opts) + +Update an existing pet + + + +### Example +```javascript +var SwaggerPetstore = require('swagger-petstore'); +var defaultClient = SwaggerPetstore.ApiClient.default; + +// Configure OAuth2 access token for authorization: petstore_auth +var petstore_auth = defaultClient.authentications['petstore_auth']; +petstore_auth.accessToken = "YOUR ACCESS TOKEN" + +var apiInstance = new SwaggerPetstore.PetApi() + +var opts = { + 'body': new SwaggerPetstore.Pet() // {Pet} Pet object that needs to be added to the store +}; +apiInstance.updatePet(opts).then(function() { + console.log('API called successfully.'); +}, function(error) { + console.error(error); +}); + +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | [optional] + +### Return type + +null (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP reuqest headers + + - **Content-Type**: application/json, application/xml + - **Accept**: application/json, application/xml + + +# **updatePetWithForm** +> updatePetWithForm(petId, opts) + +Updates a pet in the store with form data + + + +### Example +```javascript +var SwaggerPetstore = require('swagger-petstore'); +var defaultClient = SwaggerPetstore.ApiClient.default; + +// Configure OAuth2 access token for authorization: petstore_auth +var petstore_auth = defaultClient.authentications['petstore_auth']; +petstore_auth.accessToken = "YOUR ACCESS TOKEN" + +var apiInstance = new SwaggerPetstore.PetApi() + +var petId = "petId_example"; // {String} 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 +}; +apiInstance.updatePetWithForm(petId, opts).then(function() { + console.log('API called successfully.'); +}, function(error) { + console.error(error); +}); + +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **String**| 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 reuqest headers + + - **Content-Type**: application/x-www-form-urlencoded + - **Accept**: application/json, application/xml + + +# **uploadFile** +> uploadFile(petId, opts) + +uploads an image + + + +### Example +```javascript +var SwaggerPetstore = require('swagger-petstore'); +var defaultClient = SwaggerPetstore.ApiClient.default; + +// Configure OAuth2 access token for authorization: petstore_auth +var petstore_auth = defaultClient.authentications['petstore_auth']; +petstore_auth.accessToken = "YOUR ACCESS TOKEN" + +var apiInstance = new SwaggerPetstore.PetApi() + +var petId = 789; // {Integer} 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 +}; +apiInstance.uploadFile(petId, opts).then(function() { + console.log('API called successfully.'); +}, function(error) { + console.error(error); +}); + +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **Integer**| ID of pet to update | + **additionalMetadata** | **String**| Additional data to pass to server | [optional] + **file** | **File**| file to upload | [optional] + +### Return type + +null (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP reuqest headers + + - **Content-Type**: multipart/form-data + - **Accept**: application/json, application/xml + diff --git a/samples/client/petstore/javascript-promise/docs/SpecialModelName.md b/samples/client/petstore/javascript-promise/docs/SpecialModelName.md new file mode 100644 index 00000000000..03dffa54c3f --- /dev/null +++ b/samples/client/petstore/javascript-promise/docs/SpecialModelName.md @@ -0,0 +1,8 @@ +# SwaggerPetstore.SpecialModelName + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**specialPropertyName** | **Integer** | | [optional] + + diff --git a/samples/client/petstore/javascript-promise/docs/StoreApi.md b/samples/client/petstore/javascript-promise/docs/StoreApi.md new file mode 100644 index 00000000000..930586a96f5 --- /dev/null +++ b/samples/client/petstore/javascript-promise/docs/StoreApi.md @@ -0,0 +1,315 @@ +# SwaggerPetstore.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 +[**findOrdersByStatus**](StoreApi.md#findOrdersByStatus) | **GET** /store/findByStatus | Finds orders by status +[**getInventory**](StoreApi.md#getInventory) | **GET** /store/inventory | Returns pet inventories by status +[**getInventoryInObject**](StoreApi.md#getInventoryInObject) | **GET** /store/inventory?response=arbitrary_object | Fake endpoint to test arbitrary object return by 'Get inventory' +[**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 +```javascript +var SwaggerPetstore = require('swagger-petstore'); + +var apiInstance = new SwaggerPetstore.StoreApi() + +var orderId = "orderId_example"; // {String} ID of the order that needs to be deleted + +apiInstance.deleteOrder(orderId).then(function() { + console.log('API called successfully.'); +}, function(error) { + console.error(error); +}); + +``` + +### 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 reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + + +# **findOrdersByStatus** +> [Order] findOrdersByStatus(opts) + +Finds orders by status + +A single status value can be provided as a string + +### Example +```javascript +var SwaggerPetstore = require('swagger-petstore'); +var defaultClient = SwaggerPetstore.ApiClient.default; + +// Configure API key authorization: test_api_client_id +var test_api_client_id = defaultClient.authentications['test_api_client_id']; +test_api_client_id.apiKey = "YOUR API KEY" +// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null) +//test_api_client_id.apiKeyPrefix['x-test_api_client_id'] = "Token" + +// Configure API key authorization: test_api_client_secret +var test_api_client_secret = defaultClient.authentications['test_api_client_secret']; +test_api_client_secret.apiKey = "YOUR API KEY" +// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null) +//test_api_client_secret.apiKeyPrefix['x-test_api_client_secret'] = "Token" + +var apiInstance = new SwaggerPetstore.StoreApi() + +var opts = { + 'status': "placed" // {String} Status value that needs to be considered for query +}; +apiInstance.findOrdersByStatus(opts).then(function(data) { + console.log('API called successfully. Returned data: ' + data); +}, function(error) { + console.error(error); +}); + +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **status** | **String**| Status value that needs to be considered for query | [optional] [default to placed] + +### Return type + +[**[Order]**](Order.md) + +### Authorization + +[test_api_client_id](../README.md#test_api_client_id), [test_api_client_secret](../README.md#test_api_client_secret) + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + + +# **getInventory** +> {'String': 'Integer'} getInventory + +Returns pet inventories by status + +Returns a map of status codes to quantities + +### Example +```javascript +var SwaggerPetstore = require('swagger-petstore'); +var defaultClient = SwaggerPetstore.ApiClient.default; + +// 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 apiInstance = new SwaggerPetstore.StoreApi() +apiInstance.getInventory().then(function(data) { + console.log('API called successfully. Returned data: ' + data); +}, function(error) { + console.error(error); +}); + +``` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +**{'String': 'Integer'}** + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + + +# **getInventoryInObject** +> Object getInventoryInObject + +Fake endpoint to test arbitrary object return by 'Get inventory' + +Returns an arbitrary object which is actually a map of status codes to quantities + +### Example +```javascript +var SwaggerPetstore = require('swagger-petstore'); +var defaultClient = SwaggerPetstore.ApiClient.default; + +// 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 apiInstance = new SwaggerPetstore.StoreApi() +apiInstance.getInventoryInObject().then(function(data) { + console.log('API called successfully. Returned data: ' + data); +}, function(error) { + console.error(error); +}); + +``` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +**Object** + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + + +# **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 +```javascript +var SwaggerPetstore = require('swagger-petstore'); +var defaultClient = SwaggerPetstore.ApiClient.default; + +// Configure API key authorization: test_api_key_header +var test_api_key_header = defaultClient.authentications['test_api_key_header']; +test_api_key_header.apiKey = "YOUR API KEY" +// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null) +//test_api_key_header.apiKeyPrefix['test_api_key_header'] = "Token" + +// Configure API key authorization: test_api_key_query +var test_api_key_query = defaultClient.authentications['test_api_key_query']; +test_api_key_query.apiKey = "YOUR API KEY" +// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null) +//test_api_key_query.apiKeyPrefix['test_api_key_query'] = "Token" + +var apiInstance = new SwaggerPetstore.StoreApi() + +var orderId = "orderId_example"; // {String} ID of pet that needs to be fetched + +apiInstance.getOrderById(orderId).then(function(data) { + console.log('API called successfully. Returned data: ' + data); +}, function(error) { + console.error(error); +}); + +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **orderId** | **String**| ID of pet that needs to be fetched | + +### Return type + +[**Order**](Order.md) + +### Authorization + +[test_api_key_header](../README.md#test_api_key_header), [test_api_key_query](../README.md#test_api_key_query) + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + + +# **placeOrder** +> Order placeOrder(opts) + +Place an order for a pet + + + +### Example +```javascript +var SwaggerPetstore = require('swagger-petstore'); +var defaultClient = SwaggerPetstore.ApiClient.default; + +// Configure API key authorization: test_api_client_id +var test_api_client_id = defaultClient.authentications['test_api_client_id']; +test_api_client_id.apiKey = "YOUR API KEY" +// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null) +//test_api_client_id.apiKeyPrefix['x-test_api_client_id'] = "Token" + +// Configure API key authorization: test_api_client_secret +var test_api_client_secret = defaultClient.authentications['test_api_client_secret']; +test_api_client_secret.apiKey = "YOUR API KEY" +// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null) +//test_api_client_secret.apiKeyPrefix['x-test_api_client_secret'] = "Token" + +var apiInstance = new SwaggerPetstore.StoreApi() + +var opts = { + 'body': new SwaggerPetstore.Order() // {Order} order placed for purchasing the pet +}; +apiInstance.placeOrder(opts).then(function(data) { + console.log('API called successfully. Returned data: ' + data); +}, function(error) { + console.error(error); +}); + +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Order**](Order.md)| order placed for purchasing the pet | [optional] + +### Return type + +[**Order**](Order.md) + +### Authorization + +[test_api_client_id](../README.md#test_api_client_id), [test_api_client_secret](../README.md#test_api_client_secret) + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + diff --git a/samples/client/petstore/javascript-promise/docs/Tag.md b/samples/client/petstore/javascript-promise/docs/Tag.md new file mode 100644 index 00000000000..6c109046fb3 --- /dev/null +++ b/samples/client/petstore/javascript-promise/docs/Tag.md @@ -0,0 +1,9 @@ +# SwaggerPetstore.Tag + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Integer** | | [optional] +**name** | **String** | | [optional] + + diff --git a/samples/client/petstore/javascript-promise/docs/User.md b/samples/client/petstore/javascript-promise/docs/User.md new file mode 100644 index 00000000000..071fbb46e47 --- /dev/null +++ b/samples/client/petstore/javascript-promise/docs/User.md @@ -0,0 +1,15 @@ +# SwaggerPetstore.User + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Integer** | | [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/javascript-promise/docs/UserApi.md b/samples/client/petstore/javascript-promise/docs/UserApi.md new file mode 100644 index 00000000000..1c14b708231 --- /dev/null +++ b/samples/client/petstore/javascript-promise/docs/UserApi.md @@ -0,0 +1,370 @@ +# SwaggerPetstore.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(opts) + +Create user + +This can only be done by the logged in user. + +### Example +```javascript +var SwaggerPetstore = require('swagger-petstore'); + +var apiInstance = new SwaggerPetstore.UserApi() + +var opts = { + 'body': new SwaggerPetstore.User() // {User} Created user object +}; +apiInstance.createUser(opts).then(function() { + console.log('API called successfully.'); +}, function(error) { + console.error(error); +}); + +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**User**](User.md)| Created user object | [optional] + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + + +# **createUsersWithArrayInput** +> createUsersWithArrayInput(opts) + +Creates list of users with given input array + + + +### Example +```javascript +var SwaggerPetstore = require('swagger-petstore'); + +var apiInstance = new SwaggerPetstore.UserApi() + +var opts = { + 'body': [new SwaggerPetstore.User()] // {[User]} List of user object +}; +apiInstance.createUsersWithArrayInput(opts).then(function() { + console.log('API called successfully.'); +}, function(error) { + console.error(error); +}); + +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**[User]**](User.md)| List of user object | [optional] + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + + +# **createUsersWithListInput** +> createUsersWithListInput(opts) + +Creates list of users with given input array + + + +### Example +```javascript +var SwaggerPetstore = require('swagger-petstore'); + +var apiInstance = new SwaggerPetstore.UserApi() + +var opts = { + 'body': [new SwaggerPetstore.User()] // {[User]} List of user object +}; +apiInstance.createUsersWithListInput(opts).then(function() { + console.log('API called successfully.'); +}, function(error) { + console.error(error); +}); + +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**[User]**](User.md)| List of user object | [optional] + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + + +# **deleteUser** +> deleteUser(username) + +Delete user + +This can only be done by the logged in user. + +### Example +```javascript +var SwaggerPetstore = require('swagger-petstore'); +var defaultClient = SwaggerPetstore.ApiClient.default; + +// Configure HTTP basic authorization: test_http_basic +var test_http_basic = defaultClient.authentications['test_http_basic']; +test_http_basic.username = 'YOUR USERNAME' +test_http_basic.password = 'YOUR PASSWORD' + +var apiInstance = new SwaggerPetstore.UserApi() + +var username = "username_example"; // {String} The name that needs to be deleted + +apiInstance.deleteUser(username).then(function() { + console.log('API called successfully.'); +}, function(error) { + console.error(error); +}); + +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **String**| The name that needs to be deleted | + +### Return type + +null (empty response body) + +### Authorization + +[test_http_basic](../README.md#test_http_basic) + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + + +# **getUserByName** +> User getUserByName(username) + +Get user by user name + + + +### Example +```javascript +var SwaggerPetstore = require('swagger-petstore'); + +var apiInstance = new SwaggerPetstore.UserApi() + +var username = "username_example"; // {String} The name that needs to be fetched. Use user1 for testing. + +apiInstance.getUserByName(username).then(function(data) { + console.log('API called successfully. Returned data: ' + data); +}, function(error) { + console.error(error); +}); + +``` + +### 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 reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + + +# **loginUser** +> 'String' loginUser(opts) + +Logs user into the system + + + +### Example +```javascript +var SwaggerPetstore = require('swagger-petstore'); + +var apiInstance = new SwaggerPetstore.UserApi() + +var opts = { + 'username': "username_example", // {String} The user name for login + 'password': "password_example" // {String} The password for login in clear text +}; +apiInstance.loginUser(opts).then(function(data) { + console.log('API called successfully. Returned data: ' + data); +}, function(error) { + console.error(error); +}); + +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **String**| The user name for login | [optional] + **password** | **String**| The password for login in clear text | [optional] + +### Return type + +**'String'** + +### Authorization + +No authorization required + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + + +# **logoutUser** +> logoutUser + +Logs out current logged in user session + + + +### Example +```javascript +var SwaggerPetstore = require('swagger-petstore'); + +var apiInstance = new SwaggerPetstore.UserApi() +apiInstance.logoutUser().then(function() { + console.log('API called successfully.'); +}, function(error) { + console.error(error); +}); + +``` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + + +# **updateUser** +> updateUser(username, opts) + +Updated user + +This can only be done by the logged in user. + +### Example +```javascript +var SwaggerPetstore = require('swagger-petstore'); + +var apiInstance = new SwaggerPetstore.UserApi() + +var username = "username_example"; // {String} name that need to be deleted + +var opts = { + 'body': new SwaggerPetstore.User() // {User} Updated user object +}; +apiInstance.updateUser(username, opts).then(function() { + console.log('API called successfully.'); +}, function(error) { + console.error(error); +}); + +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **String**| name that need to be deleted | + **body** | [**User**](User.md)| Updated user object | [optional] + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + diff --git a/samples/client/petstore/javascript-promise/git_push.sh b/samples/client/petstore/javascript-promise/git_push.sh new file mode 100644 index 00000000000..1a36388db02 --- /dev/null +++ b/samples/client/petstore/javascript-promise/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="YOUR_GIT_USR_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="YOUR_GIT_REPO_ID" + 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/javascript-promise/src/ApiClient.js b/samples/client/petstore/javascript-promise/src/ApiClient.js index e2ab48cf09c..8943bd4792b 100644 --- a/samples/client/petstore/javascript-promise/src/ApiClient.js +++ b/samples/client/petstore/javascript-promise/src/ApiClient.js @@ -15,49 +15,78 @@ }(this, function(superagent) { 'use strict'; - var ApiClient = function ApiClient() { + /** + * @module ApiClient + * @version 1.0.0 + */ + + /** + * Manages low level client-server communications, parameter marshalling, etc. There should not be any need for an + * application to use this class directly - the *Api and model classes provide the public API for the service. The + * contents of this file should be regarded as internal but are documented for completeness. + * @alias module:ApiClient + * @class + */ + var exports = function() { /** - * The base path to put in front of every API call's (relative) path. + * The base URL against which to resolve every API call's (relative) path. + * @type {String} + * @default http://petstore.swagger.io/v2 */ this.basePath = 'http://petstore.swagger.io/v2'.replace(/\/+$/, ''); + /** + * The authentication methods to be included for all API calls. + * @type {Array.} + */ this.authentications = { - 'petstore_auth': {type: 'oauth2'}, - 'test_api_client_id': {type: 'apiKey', in: 'header', name: 'x-test_api_client_id'}, - 'test_api_client_secret': {type: 'apiKey', in: 'header', name: 'x-test_api_client_secret'}, - 'api_key': {type: 'apiKey', in: 'header', name: 'api_key'}, - 'test_api_key_query': {type: 'apiKey', in: 'query', name: 'test_api_key_query'}, - 'test_api_key_header': {type: 'apiKey', in: 'header', name: 'test_api_key_header'} + 'test_api_key_header': {type: 'apiKey', 'in': 'header', name: 'test_api_key_header'}, + 'api_key': {type: 'apiKey', 'in': 'header', name: 'api_key'}, + 'test_http_basic': {type: 'basic'}, + 'test_api_client_secret': {type: 'apiKey', 'in': 'header', name: 'x-test_api_client_secret'}, + 'test_api_client_id': {type: 'apiKey', 'in': 'header', name: 'x-test_api_client_id'}, + 'test_api_key_query': {type: 'apiKey', 'in': 'query', name: 'test_api_key_query'}, + 'petstore_auth': {type: 'oauth2'} }; /** * The default HTTP headers to be included for all API calls. + * @type {Array.} + * @default {} */ this.defaultHeaders = {}; /** * The default HTTP timeout for all API calls. + * @type {Number} + * @default 60000 */ this.timeout = 60000; }; - ApiClient.prototype.paramToString = function paramToString(param) { - if (param == null) { - // return empty string for null and undefined + /** + * Returns a string representation for an actual parameter. + * @param param The actual parameter. + * @returns {String} The string representation of param. + */ + exports.prototype.paramToString = function(param) { + if (param == undefined || param == null) { return ''; - } else if (param instanceof Date) { - return param.toJSON(); - } else { - return param.toString(); } + if (param instanceof Date) { + return param.toJSON(); + } + return param.toString(); }; /** - * Build full URL by appending the given path to base path and replacing - * path parameter placeholders with parameter values. + * Builds full URL by appending the given path to the base URL and replacing path parameter place-holders with parameter values. * NOTE: query parameters are not handled here. + * @param {String} path The path to append to the base URL. + * @param {Object} pathParams The parameter values to append. + * @returns {String} The encoded path with parameter values substituted. */ - ApiClient.prototype.buildUrl = function buildUrl(path, pathParams) { + exports.prototype.buildUrl = function(path, pathParams) { if (!path.match(/^\//)) { path = '/' + path; } @@ -76,34 +105,40 @@ }; /** - * Check if the given MIME is a JSON MIME. - * JSON MIME examples: - * application/json - * application/json; charset=UTF8 - * APPLICATION/JSON + * Checks whether the given content type represents JSON.
+ * JSON content type examples:
+ *
    + *
  • application/json
  • + *
  • application/json; charset=UTF8
  • + *
  • APPLICATION/JSON
  • + *
+ * @param {String} contentType The MIME content type to check. + * @returns {Boolean} true if contentType represents JSON, otherwise false. */ - ApiClient.prototype.isJsonMime = function isJsonMime(mime) { - return Boolean(mime != null && mime.match(/^application\/json(;.*)?$/i)); + exports.prototype.isJsonMime = function(contentType) { + return Boolean(contentType != null && contentType.match(/^application\/json(;.*)?$/i)); }; /** - * Choose a MIME from the given MIMEs with JSON preferred, - * i.e. return JSON if included, otherwise return the first one. + * Chooses a content type from the given array, with JSON preferred; i.e. return JSON if included, otherwise return the first. + * @param {Array.} contentTypes + * @returns {String} The chosen content type, preferring JSON. */ - ApiClient.prototype.jsonPreferredMime = function jsonPreferredMime(mimes) { - var len = mimes.length; - for (var i = 0; i < len; i++) { - if (this.isJsonMime(mimes[i])) { - return mimes[i]; + exports.prototype.jsonPreferredMime = function(contentTypes) { + for (var i = 0; i < contentTypes.length; i++) { + if (this.isJsonMime(contentTypes[i])) { + return contentTypes[i]; } } - return mimes[0]; + return contentTypes[0]; }; /** - * Check if the given parameter value is like file content. + * Checks whether the given parameter value represents file-like content. + * @param param The parameter to check. + * @returns {Boolean} true if param represents a file. */ - ApiClient.prototype.isFileParam = function isFileParam(param) { + exports.prototype.isFileParam = function(param) { // fs.ReadStream in Node.js (but not in runtime like browserify) if (typeof window === 'undefined' && typeof require === 'function' && @@ -127,15 +162,19 @@ }; /** - * Normalize parameters values: - * remove nils, - * keep files and arrays, - * format to string with `paramToString` for other cases. + * Normalizes parameter values: + *
    + *
  • remove nils
  • + *
  • keep files and arrays
  • + *
  • format to string with `paramToString` for other cases
  • + *
+ * @param {Object.} params The parameters as object properties. + * @returns {Object.} normalized parameters. */ - ApiClient.prototype.normalizeParams = function normalizeParams(params) { + exports.prototype.normalizeParams = function(params) { var newParams = {}; for (var key in params) { - if (params.hasOwnProperty(key) && params[key] != null) { + if (params.hasOwnProperty(key) && params[key] != undefined && params[key] != null) { var value = params[key]; if (this.isFileParam(value) || Array.isArray(value)) { newParams[key] = value; @@ -148,10 +187,46 @@ }; /** - * Build parameter value according to the given collection format. - * @param {String} collectionFormat one of 'csv', 'ssv', 'tsv', 'pipes' and 'multi' + * Enumeration of collection format separator strategies. + * @enum {String} + * @readonly */ - ApiClient.prototype.buildCollectionParam = function buildCollectionParam(param, collectionFormat) { + exports.CollectionFormatEnum = { + /** + * Comma-separated values. Value: csv + * @const + */ + CSV: ',', + /** + * Space-separated values. Value: ssv + * @const + */ + SSV: ' ', + /** + * Tab-separated values. Value: tsv + * @const + */ + TSV: '\t', + /** + * Pipe(|)-separated values. Value: pipes + * @const + */ + PIPES: '|', + /** + * Native array. Value: multi + * @const + */ + MULTI: 'multi' + }; + + /** + * Builds a string representation of an array-type actual parameter, according to the given collection format. + * @param {Array} param An array parameter. + * @param {module:ApiClient.CollectionFormatEnum} collectionFormat The array element separator strategy. + * @returns {String|Array} A string representation of the supplied collection, using the specified delimiter. Returns + * param as is if collectionFormat is multi. + */ + exports.prototype.buildCollectionParam = function buildCollectionParam(param, collectionFormat) { if (param == null) { return null; } @@ -165,14 +240,19 @@ case 'pipes': return param.map(this.paramToString).join('|'); case 'multi': - // return the array directly as Superagent will handle it as expected + // return the array directly as SuperAgent will handle it as expected return param.map(this.paramToString); default: throw new Error('Unknown collection format: ' + collectionFormat); } }; - ApiClient.prototype.applyAuthToRequest = function applyAuthToRequest(request, authNames) { + /** + * Applies authentication headers to the request. + * @param {Object} request The request object created by a superagent() call. + * @param {Array.} authNames An array of authentication method names. + */ + exports.prototype.applyAuthToRequest = function(request, authNames) { var _this = this; authNames.forEach(function(authName) { var auth = _this.authentications[authName]; @@ -190,7 +270,7 @@ } else { data[auth.name] = auth.apiKey; } - if (auth.in === 'header') { + if (auth['in'] === 'header') { request.set(data); } else { request.query(data); @@ -208,24 +288,48 @@ }); }; - ApiClient.prototype.deserialize = function deserialize(response, returnType) { + /** + * Deserializes an HTTP response body into a value of the specified type. + * @param {Object} response A SuperAgent response object. + * @param {(String|Array.|Object.|Function)} returnType The type to return. Pass a string for simple types + * or the constructor function for a complex type. Pass an array containing the type name to return an array of that type. To + * return an object, pass an object with one property whose name is the key type and whose value is the corresponding value type: + * all properties on data will be converted to this type. + * @returns A value of the specified type. + */ + exports.prototype.deserialize = function deserialize(response, returnType) { if (response == null || returnType == null) { return null; } - // Rely on Superagent for parsing response body. + // Rely on SuperAgent for parsing response body. // See http://visionmedia.github.io/superagent/#parsing-response-bodies var data = response.body; if (data == null) { - // Superagent does not always produce a body; use the unparsed response - // as a fallback + // SuperAgent does not always produce a body; use the unparsed response as a fallback data = response.text; } - return ApiClient.convertToType(data, returnType); + return exports.convertToType(data, returnType); }; - ApiClient.prototype.callApi = function callApi(path, httpMethod, pathParams, - queryParams, headerParams, formParams, bodyParam, authNames, contentTypes, - accepts, returnType) { + /** + * Invokes the REST service using the supplied settings and parameters. + * @param {String} path The base URL to invoke. + * @param {String} httpMethod The HTTP method to use. + * @param {Object.} pathParams A map of path parameters and their values. + * @param {Object.} queryParams A map of query parameters and their values. + * @param {Object.} headerParams A map of header parameters and their values. + * @param {Object.} formParams A map of form parameters and their values. + * @param {Object} bodyParam The value to pass as the request body. + * @param {Array.} authNames An array of authentication type names. + * @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. + */ + exports.prototype.callApi = function callApi(path, httpMethod, pathParams, + queryParams, headerParams, formParams, bodyParam, authNames, contentTypes, accepts, + returnType) { + var _this = this; var url = this.buildUrl(path, pathParams); var request = superagent(httpMethod, url); @@ -239,7 +343,7 @@ // set header parameters request.set(this.defaultHeaders).set(this.normalizeParams(headerParams)); - //set request timeout + // set request timeout request.timeout(this.timeout); var contentType = this.jsonPreferredMime(contentTypes); @@ -272,28 +376,37 @@ request.accept(accept); } - - return new Promise( function(resolve,reject) { + return new Promise(function(resolve, reject) { request.end(function(error, response) { if (error) { reject(error); - } - else { + } else { var data = _this.deserialize(response, returnType); resolve(data); } }); }); - - }; - ApiClient.parseDate = function parseDate(str) { - str = str.replace(/T/i, ' '); - return new Date(str); + /** + * Parses an ISO-8601 string representation of a date value. + * @param {String} str The date value as a string. + * @returns {Date} The parsed date object. + */ + exports.parseDate = function(str) { + return new Date(str.replace(/T/i, ' ')); }; - ApiClient.convertToType = function convertToType(data, type) { + /** + * Converts a value to the specified type. + * @param {(String|Object)} data The data to convert, as a string or object. + * @param {(String|Array.|Object.|Function)} type The type to return. Pass a string for simple types + * or the constructor function for a complex type. Pass an array containing the type name to return an array of that type. To + * return an object, pass an object with one property whose name is the key type and whose value is the corresponding value type: + * all properties on data will be converted to this type. + * @returns An instance of the specified type. + */ + exports.convertToType = function(data, type) { switch (type) { case 'Boolean': return Boolean(data); @@ -306,15 +419,17 @@ case 'Date': return this.parseDate(String(data)); default: - if (typeof type === 'function') { + if (type === Object) { + // generic object, return directly + return data; + } else if (typeof type === 'function') { // for model type like: User - var model = type.constructFromObject(data); - return model; + return type.constructFromObject(data); } else if (Array.isArray(type)) { // for array type like: ['String'] var itemType = type[0]; return data.map(function(item) { - return ApiClient.convertToType(item, itemType); + return exports.convertToType(item, itemType); }); } else if (typeof type === 'object') { // for plain object type like: {'String': 'Integer'} @@ -329,8 +444,8 @@ var result = {}; for (var k in data) { if (data.hasOwnProperty(k)) { - var key = ApiClient.convertToType(k, keyType); - var value = ApiClient.convertToType(data[k], valueType); + var key = exports.convertToType(k, keyType); + var value = exports.convertToType(data[k], valueType); result[key] = value; } } @@ -342,7 +457,11 @@ } }; - ApiClient.default = new ApiClient(); + /** + * The default API client implementation. + * @type {module:ApiClient} + */ + exports.instance = new exports(); - return ApiClient; + return exports; })); diff --git a/samples/client/petstore/javascript-promise/src/api/PetApi.js b/samples/client/petstore/javascript-promise/src/api/PetApi.js index 044413ab544..520791b3f0a 100644 --- a/samples/client/petstore/javascript-promise/src/api/PetApi.js +++ b/samples/client/petstore/javascript-promise/src/api/PetApi.js @@ -1,67 +1,48 @@ (function(root, factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. - define(['../ApiClient', '../model/Pet'], factory); + define(['../ApiClient', '../model/Pet', '../model/InlineResponse200'], factory); } else if (typeof module === 'object' && module.exports) { // CommonJS-like environments that support module.exports, like Node. - module.exports = factory(require('../ApiClient'), require('../model/Pet')); + module.exports = factory(require('../ApiClient'), require('../model/Pet'), require('../model/InlineResponse200')); } else { // Browser globals (root is window) if (!root.SwaggerPetstore) { root.SwaggerPetstore = {}; } - root.SwaggerPetstore.PetApi = factory(root.SwaggerPetstore.ApiClient, root.SwaggerPetstore.Pet); + root.SwaggerPetstore.PetApi = factory(root.SwaggerPetstore.ApiClient, root.SwaggerPetstore.Pet, root.SwaggerPetstore.InlineResponse200); } -}(this, function(ApiClient, Pet) { +}(this, function(ApiClient, Pet, InlineResponse200) { 'use strict'; - var PetApi = function PetApi(apiClient) { - this.apiClient = apiClient || ApiClient.default; + /** + * Pet service. + * @module api/PetApi + * @version 1.0.0 + */ - var self = this; - - - /** - * Update an existing pet - * - * @param {Pet} opts['body'] Pet object that needs to be added to the store - */ - self.updatePet = function(opts) { - opts = opts || {}; - var postBody = opts['body']; - + /** + * Constructs a new PetApi. + * @alias module:api/PetApi + * @class + * @param {module:ApiClient} apiClient Optional API client implementation to use, default to {@link module:ApiClient#instance} + * if unspecified. + */ + var exports = function(apiClient) { + this.apiClient = apiClient || ApiClient.instance; - var pathParams = { - }; - var queryParams = { - }; - var headerParams = { - }; - var formParams = { - }; - var authNames = ['petstore_auth']; - var contentTypes = ['application/json', 'application/xml']; - var accepts = ['application/json', 'application/xml']; - var returnType = null; - return this.apiClient.callApi( - '/pet', 'PUT', - pathParams, queryParams, headerParams, formParams, postBody, - authNames, contentTypes, accepts, returnType - ); - - } - /** * Add a new pet to the store * - * @param {Pet} opts['body'] Pet object that needs to be added to the store + * @param {Object} opts Optional parameters + * @param {module:model/Pet} opts.body Pet object that needs to be added to the store */ - self.addPet = function(opts) { + this.addPet = function(opts) { opts = opts || {}; var postBody = opts['body']; - + var pathParams = { }; @@ -82,19 +63,94 @@ pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType ); - } - + + + /** + * Fake endpoint to test byte array in body parameter for adding a new pet to the store + * + * @param {Object} opts Optional parameters + * @param {String} opts.body Pet object in the form of byte array + */ + this.addPetUsingByteArray = function(opts) { + opts = opts || {}; + var postBody = opts['body']; + + + var pathParams = { + }; + var queryParams = { + }; + var headerParams = { + }; + var formParams = { + }; + + var authNames = ['petstore_auth']; + var contentTypes = ['application/json', 'application/xml']; + var accepts = ['application/json', 'application/xml']; + var returnType = null; + + return this.apiClient.callApi( + '/pet?testing_byte_array=true', 'POST', + pathParams, queryParams, headerParams, formParams, postBody, + authNames, contentTypes, accepts, returnType + ); + } + + + /** + * Deletes a pet + * + * @param {Integer} petId Pet id to delete + * @param {Object} opts Optional parameters + * @param {String} opts.apiKey + */ + this.deletePet = function(petId, opts) { + opts = opts || {}; + var postBody = null; + + // verify the required parameter 'petId' is set + if (petId == undefined || petId == null) { + throw "Missing the required parameter 'petId' when calling deletePet"; + } + + + var pathParams = { + 'petId': petId + }; + var queryParams = { + }; + var headerParams = { + 'api_key': opts['apiKey'] + }; + var formParams = { + }; + + var authNames = ['petstore_auth']; + var contentTypes = []; + var accepts = ['application/json', 'application/xml']; + var returnType = null; + + return this.apiClient.callApi( + '/pet/{petId}', 'DELETE', + pathParams, queryParams, headerParams, formParams, postBody, + authNames, contentTypes, accepts, returnType + ); + } + + /** * Finds Pets by status * Multiple status values can be provided with comma separated strings - * @param {[String]} opts['status'] Status values that need to be considered for query - * data is of type: [Pet] + * @param {Object} opts Optional parameters + * @param {Array.} opts.status Status values that need to be considered for query (default to available) + * data is of type: {Array.} */ - self.findPetsByStatus = function(opts) { + this.findPetsByStatus = function(opts) { opts = opts || {}; var postBody = null; - + var pathParams = { }; @@ -116,19 +172,20 @@ pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType ); - } - + + /** * Finds Pets by tags * Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. - * @param {[String]} opts['tags'] Tags to filter by - * data is of type: [Pet] + * @param {Object} opts Optional parameters + * @param {Array.} opts.tags Tags to filter by + * data is of type: {Array.} */ - self.findPetsByTags = function(opts) { + this.findPetsByTags = function(opts) { opts = opts || {}; var postBody = null; - + var pathParams = { }; @@ -150,23 +207,23 @@ pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType ); - } - + + /** * Find pet by ID * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions * @param {Integer} petId ID of pet that needs to be fetched - * data is of type: Pet + * data is of type: {module:model/Pet} */ - self.getPetById = function(petId) { + this.getPetById = function(petId) { var postBody = null; - + // verify the required parameter 'petId' is set - if (petId == null) { + if (petId == undefined || petId == null) { throw "Missing the required parameter 'petId' when calling getPetById"; } - + var pathParams = { 'petId': petId @@ -178,7 +235,7 @@ var formParams = { }; - var authNames = ['petstore_auth', 'api_key']; + var authNames = ['api_key', 'petstore_auth']; var contentTypes = []; var accepts = ['application/json', 'application/xml']; var returnType = Pet; @@ -188,25 +245,135 @@ pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType ); - } - + + + /** + * Fake endpoint to test inline arbitrary object return by 'Find pet by ID' + * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + * @param {Integer} petId ID of pet that needs to be fetched + * data is of type: {module:model/InlineResponse200} + */ + this.getPetByIdInObject = function(petId) { + var postBody = null; + + // verify the required parameter 'petId' is set + if (petId == undefined || petId == null) { + throw "Missing the required parameter 'petId' when calling getPetByIdInObject"; + } + + + var pathParams = { + 'petId': petId + }; + var queryParams = { + }; + var headerParams = { + }; + var formParams = { + }; + + var authNames = ['api_key', 'petstore_auth']; + var contentTypes = []; + var accepts = ['application/json', 'application/xml']; + var returnType = InlineResponse200; + + return this.apiClient.callApi( + '/pet/{petId}?response=inline_arbitrary_object', 'GET', + pathParams, queryParams, headerParams, formParams, postBody, + authNames, contentTypes, accepts, returnType + ); + } + + + /** + * Fake endpoint to test byte array return by 'Find pet by ID' + * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + * @param {Integer} petId ID of pet that needs to be fetched + * data is of type: {'String'} + */ + this.petPetIdtestingByteArraytrueGet = function(petId) { + var postBody = null; + + // verify the required parameter 'petId' is set + if (petId == undefined || petId == null) { + throw "Missing the required parameter 'petId' when calling petPetIdtestingByteArraytrueGet"; + } + + + var pathParams = { + 'petId': petId + }; + var queryParams = { + }; + var headerParams = { + }; + var formParams = { + }; + + var authNames = ['api_key', 'petstore_auth']; + var contentTypes = []; + var accepts = ['application/json', 'application/xml']; + var returnType = 'String'; + + return this.apiClient.callApi( + '/pet/{petId}?testing_byte_array=true', 'GET', + pathParams, queryParams, headerParams, formParams, postBody, + authNames, contentTypes, accepts, returnType + ); + } + + + /** + * Update an existing pet + * + * @param {Object} opts Optional parameters + * @param {module:model/Pet} opts.body Pet object that needs to be added to the store + */ + this.updatePet = function(opts) { + opts = opts || {}; + var postBody = opts['body']; + + + var pathParams = { + }; + var queryParams = { + }; + var headerParams = { + }; + var formParams = { + }; + + var authNames = ['petstore_auth']; + var contentTypes = ['application/json', 'application/xml']; + var accepts = ['application/json', 'application/xml']; + var returnType = null; + + return this.apiClient.callApi( + '/pet', 'PUT', + pathParams, queryParams, headerParams, formParams, postBody, + authNames, contentTypes, accepts, returnType + ); + } + + /** * Updates a pet in the store with form data * * @param {String} petId ID of pet that needs to be updated - * @param {String} opts['name'] Updated name of the pet - * @param {String} opts['status'] Updated status of the pet + * @param {Object} opts Optional parameters + * @param {String} opts.name Updated name of the pet + * @param {String} opts.status Updated status of the pet */ - self.updatePetWithForm = function(petId, opts) { + this.updatePetWithForm = function(petId, opts) { opts = opts || {}; var postBody = null; - + // verify the required parameter 'petId' is set - if (petId == null) { + if (petId == undefined || petId == null) { throw "Missing the required parameter 'petId' when calling updatePetWithForm"; } - + var pathParams = { 'petId': petId @@ -230,65 +397,26 @@ pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType ); - } - - /** - * Deletes a pet - * - * @param {Integer} petId Pet id to delete - * @param {String} opts['apiKey'] - */ - self.deletePet = function(petId, opts) { - opts = opts || {}; - var postBody = null; - - // verify the required parameter 'petId' is set - if (petId == null) { - throw "Missing the required parameter 'petId' when calling deletePet"; - } - - var pathParams = { - 'petId': petId - }; - var queryParams = { - }; - var headerParams = { - 'api_key': opts['apiKey'] - }; - var formParams = { - }; - var authNames = ['petstore_auth']; - var contentTypes = []; - var accepts = ['application/json', 'application/xml']; - var returnType = null; - - return this.apiClient.callApi( - '/pet/{petId}', 'DELETE', - pathParams, queryParams, headerParams, formParams, postBody, - authNames, contentTypes, accepts, returnType - ); - - } - /** * uploads an image * * @param {Integer} petId ID of pet to update - * @param {String} opts['additionalMetadata'] Additional data to pass to server - * @param {File} opts['file'] file to upload + * @param {Object} opts Optional parameters + * @param {String} opts.additionalMetadata Additional data to pass to server + * @param {File} opts.file file to upload */ - self.uploadFile = function(petId, opts) { + this.uploadFile = function(petId, opts) { opts = opts || {}; var postBody = null; - + // verify the required parameter 'petId' is set - if (petId == null) { + if (petId == undefined || petId == null) { throw "Missing the required parameter 'petId' when calling uploadFile"; } - + var pathParams = { 'petId': petId @@ -312,81 +440,8 @@ pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType ); - } - - /** - * Fake endpoint to test byte array return by 'Find pet by ID' - * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions - * @param {Integer} petId ID of pet that needs to be fetched - * data is of type: 'String' - */ - self.petPetIdtestingByteArraytrueGet = function(petId) { - var postBody = null; - - // verify the required parameter 'petId' is set - if (petId == null) { - throw "Missing the required parameter 'petId' when calling petPetIdtestingByteArraytrueGet"; - } - - - var pathParams = { - 'petId': petId - }; - var queryParams = { - }; - var headerParams = { - }; - var formParams = { - }; - - var authNames = ['petstore_auth', 'api_key']; - var contentTypes = []; - var accepts = ['application/json', 'application/xml']; - var returnType = 'String'; - - return this.apiClient.callApi( - '/pet/{petId}?testing_byte_array=true', 'GET', - pathParams, queryParams, headerParams, formParams, postBody, - authNames, contentTypes, accepts, returnType - ); - - } - - /** - * Fake endpoint to test byte array in body parameter for adding a new pet to the store - * - * @param {String} opts['body'] Pet object in the form of byte array - */ - self.addPetUsingByteArray = function(opts) { - opts = opts || {}; - var postBody = opts['body']; - - - var pathParams = { - }; - var queryParams = { - }; - var headerParams = { - }; - var formParams = { - }; - - var authNames = ['petstore_auth']; - var contentTypes = ['application/json', 'application/xml']; - var accepts = ['application/json', 'application/xml']; - var returnType = null; - - return this.apiClient.callApi( - '/pet?testing_byte_array=true', 'POST', - pathParams, queryParams, headerParams, formParams, postBody, - authNames, contentTypes, accepts, returnType - ); - - } - - }; - return PetApi; + return exports; })); diff --git a/samples/client/petstore/javascript-promise/src/api/StoreApi.js b/samples/client/petstore/javascript-promise/src/api/StoreApi.js index 1919aacef5f..32a6dce47e9 100644 --- a/samples/client/petstore/javascript-promise/src/api/StoreApi.js +++ b/samples/client/petstore/javascript-promise/src/api/StoreApi.js @@ -15,161 +15,37 @@ }(this, function(ApiClient, Order) { 'use strict'; - var StoreApi = function StoreApi(apiClient) { - this.apiClient = apiClient || ApiClient.default; + /** + * Store service. + * @module api/StoreApi + * @version 1.0.0 + */ - var self = this; - - - /** - * Finds orders by status - * A single status value can be provided as a string - * @param {String} opts['status'] Status value that needs to be considered for query - * data is of type: [Order] - */ - self.findOrdersByStatus = function(opts) { - opts = opts || {}; - var postBody = null; - + /** + * Constructs a new StoreApi. + * @alias module:api/StoreApi + * @class + * @param {module:ApiClient} apiClient Optional API client implementation to use, default to {@link module:ApiClient#instance} + * if unspecified. + */ + var exports = function(apiClient) { + this.apiClient = apiClient || ApiClient.instance; - var pathParams = { - }; - var queryParams = { - 'status': opts['status'] - }; - var headerParams = { - }; - var formParams = { - }; - var authNames = ['test_api_client_id', 'test_api_client_secret']; - var contentTypes = []; - var accepts = ['application/json', 'application/xml']; - var returnType = [Order]; - return this.apiClient.callApi( - '/store/findByStatus', 'GET', - pathParams, queryParams, headerParams, formParams, postBody, - authNames, contentTypes, accepts, returnType - ); - - } - - /** - * Returns pet inventories by status - * Returns a map of status codes to quantities - * data is of type: {'String': 'Integer'} - */ - self.getInventory = function() { - var postBody = null; - - - var pathParams = { - }; - var queryParams = { - }; - var headerParams = { - }; - var formParams = { - }; - - var authNames = ['api_key']; - var contentTypes = []; - var accepts = ['application/json', 'application/xml']; - var returnType = {'String': 'Integer'}; - - return this.apiClient.callApi( - '/store/inventory', 'GET', - pathParams, queryParams, headerParams, formParams, postBody, - authNames, contentTypes, accepts, returnType - ); - - } - - /** - * Place an order for a pet - * - * @param {Order} opts['body'] order placed for purchasing the pet - * data is of type: Order - */ - self.placeOrder = function(opts) { - opts = opts || {}; - var postBody = opts['body']; - - - var pathParams = { - }; - var queryParams = { - }; - var headerParams = { - }; - var formParams = { - }; - - var authNames = ['test_api_client_id', 'test_api_client_secret']; - var contentTypes = []; - var accepts = ['application/json', 'application/xml']; - var returnType = Order; - - return this.apiClient.callApi( - '/store/order', 'POST', - pathParams, queryParams, headerParams, formParams, postBody, - authNames, contentTypes, accepts, returnType - ); - - } - - /** - * Find purchase order by ID - * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - * @param {String} orderId ID of pet that needs to be fetched - * data is of type: Order - */ - self.getOrderById = function(orderId) { - var postBody = null; - - // verify the required parameter 'orderId' is set - if (orderId == null) { - throw "Missing the required parameter 'orderId' when calling getOrderById"; - } - - - var pathParams = { - 'orderId': orderId - }; - var queryParams = { - }; - var headerParams = { - }; - var formParams = { - }; - - var authNames = ['test_api_key_query', 'test_api_key_header']; - var contentTypes = []; - var accepts = ['application/json', 'application/xml']; - var returnType = Order; - - return this.apiClient.callApi( - '/store/order/{orderId}', 'GET', - pathParams, queryParams, headerParams, formParams, postBody, - authNames, contentTypes, accepts, returnType - ); - - } - /** * 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 */ - self.deleteOrder = function(orderId) { + this.deleteOrder = function(orderId) { var postBody = null; - + // verify the required parameter 'orderId' is set - if (orderId == null) { + if (orderId == undefined || orderId == null) { throw "Missing the required parameter 'orderId' when calling deleteOrder"; } - + var pathParams = { 'orderId': orderId @@ -191,11 +67,177 @@ pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType ); - } - - + + + /** + * Finds orders by status + * A single status value can be provided as a string + * @param {Object} opts Optional parameters + * @param {module:model/String} opts.status Status value that needs to be considered for query (default to placed) + * data is of type: {Array.} + */ + this.findOrdersByStatus = function(opts) { + opts = opts || {}; + var postBody = null; + + + var pathParams = { + }; + var queryParams = { + 'status': opts['status'] + }; + var headerParams = { + }; + var formParams = { + }; + + var authNames = ['test_api_client_id', 'test_api_client_secret']; + var contentTypes = []; + var accepts = ['application/json', 'application/xml']; + var returnType = [Order]; + + return this.apiClient.callApi( + '/store/findByStatus', 'GET', + pathParams, queryParams, headerParams, formParams, postBody, + authNames, contentTypes, accepts, returnType + ); + } + + + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + * data is of type: {Object.} + */ + this.getInventory = function() { + var postBody = null; + + + var pathParams = { + }; + var queryParams = { + }; + var headerParams = { + }; + var formParams = { + }; + + var authNames = ['api_key']; + var contentTypes = []; + var accepts = ['application/json', 'application/xml']; + var returnType = {'String': 'Integer'}; + + return this.apiClient.callApi( + '/store/inventory', 'GET', + pathParams, queryParams, headerParams, formParams, postBody, + authNames, contentTypes, accepts, returnType + ); + } + + + /** + * Fake endpoint to test arbitrary object return by 'Get inventory' + * Returns an arbitrary object which is actually a map of status codes to quantities + * data is of type: {Object} + */ + this.getInventoryInObject = function() { + var postBody = null; + + + var pathParams = { + }; + var queryParams = { + }; + var headerParams = { + }; + var formParams = { + }; + + var authNames = ['api_key']; + var contentTypes = []; + var accepts = ['application/json', 'application/xml']; + var returnType = Object; + + return this.apiClient.callApi( + '/store/inventory?response=arbitrary_object', 'GET', + pathParams, queryParams, headerParams, formParams, postBody, + authNames, contentTypes, accepts, returnType + ); + } + + + /** + * Find purchase order by ID + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * @param {String} orderId ID of pet that needs to be fetched + * data is of type: {module:model/Order} + */ + this.getOrderById = function(orderId) { + var postBody = null; + + // verify the required parameter 'orderId' is set + if (orderId == undefined || orderId == null) { + throw "Missing the required parameter 'orderId' when calling getOrderById"; + } + + + var pathParams = { + 'orderId': orderId + }; + var queryParams = { + }; + var headerParams = { + }; + var formParams = { + }; + + var authNames = ['test_api_key_header', 'test_api_key_query']; + var contentTypes = []; + var accepts = ['application/json', 'application/xml']; + var returnType = Order; + + return this.apiClient.callApi( + '/store/order/{orderId}', 'GET', + pathParams, queryParams, headerParams, formParams, postBody, + authNames, contentTypes, accepts, returnType + ); + } + + + /** + * Place an order for a pet + * + * @param {Object} opts Optional parameters + * @param {module:model/Order} opts.body order placed for purchasing the pet + * data is of type: {module:model/Order} + */ + this.placeOrder = function(opts) { + opts = opts || {}; + var postBody = opts['body']; + + + var pathParams = { + }; + var queryParams = { + }; + var headerParams = { + }; + var formParams = { + }; + + var authNames = ['test_api_client_id', 'test_api_client_secret']; + var contentTypes = []; + var accepts = ['application/json', 'application/xml']; + var returnType = Order; + + return this.apiClient.callApi( + '/store/order', 'POST', + pathParams, queryParams, headerParams, formParams, postBody, + authNames, contentTypes, accepts, returnType + ); + } }; - return StoreApi; + return exports; })); diff --git a/samples/client/petstore/javascript-promise/src/api/UserApi.js b/samples/client/petstore/javascript-promise/src/api/UserApi.js index 893ab3e68f1..8914d9c883d 100644 --- a/samples/client/petstore/javascript-promise/src/api/UserApi.js +++ b/samples/client/petstore/javascript-promise/src/api/UserApi.js @@ -15,21 +15,34 @@ }(this, function(ApiClient, User) { 'use strict'; - var UserApi = function UserApi(apiClient) { - this.apiClient = apiClient || ApiClient.default; + /** + * User service. + * @module api/UserApi + * @version 1.0.0 + */ + + /** + * Constructs a new UserApi. + * @alias module:api/UserApi + * @class + * @param {module:ApiClient} apiClient Optional API client implementation to use, default to {@link module:ApiClient#instance} + * if unspecified. + */ + var exports = function(apiClient) { + this.apiClient = apiClient || ApiClient.instance; + + - var self = this; - - /** * Create user * This can only be done by the logged in user. - * @param {User} opts['body'] Created user object + * @param {Object} opts Optional parameters + * @param {module:model/User} opts.body Created user object */ - self.createUser = function(opts) { + this.createUser = function(opts) { opts = opts || {}; var postBody = opts['body']; - + var pathParams = { }; @@ -50,18 +63,19 @@ pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType ); - } - + + /** * Creates list of users with given input array * - * @param {[User]} opts['body'] List of user object + * @param {Object} opts Optional parameters + * @param {Array.} opts.body List of user object */ - self.createUsersWithArrayInput = function(opts) { + this.createUsersWithArrayInput = function(opts) { opts = opts || {}; var postBody = opts['body']; - + var pathParams = { }; @@ -82,18 +96,19 @@ pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType ); - } - + + /** * Creates list of users with given input array * - * @param {[User]} opts['body'] List of user object + * @param {Object} opts Optional parameters + * @param {Array.} opts.body List of user object */ - self.createUsersWithListInput = function(opts) { + this.createUsersWithListInput = function(opts) { opts = opts || {}; var postBody = opts['body']; - + var pathParams = { }; @@ -114,20 +129,96 @@ pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType ); - } - + + + /** + * Delete user + * This can only be done by the logged in user. + * @param {String} username The name that needs to be deleted + */ + this.deleteUser = function(username) { + var postBody = null; + + // verify the required parameter 'username' is set + if (username == undefined || username == null) { + throw "Missing the required parameter 'username' when calling deleteUser"; + } + + + var pathParams = { + 'username': username + }; + var queryParams = { + }; + var headerParams = { + }; + var formParams = { + }; + + var authNames = ['test_http_basic']; + var contentTypes = []; + var accepts = ['application/json', 'application/xml']; + var returnType = null; + + return this.apiClient.callApi( + '/user/{username}', 'DELETE', + pathParams, queryParams, headerParams, formParams, postBody, + authNames, contentTypes, accepts, returnType + ); + } + + + /** + * 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} + */ + this.getUserByName = function(username) { + var postBody = null; + + // verify the required parameter 'username' is set + if (username == undefined || username == null) { + throw "Missing the required parameter 'username' when calling getUserByName"; + } + + + var pathParams = { + 'username': username + }; + var queryParams = { + }; + var headerParams = { + }; + var formParams = { + }; + + var authNames = []; + var contentTypes = []; + var accepts = ['application/json', 'application/xml']; + var returnType = User; + + return this.apiClient.callApi( + '/user/{username}', 'GET', + pathParams, queryParams, headerParams, formParams, postBody, + authNames, contentTypes, accepts, returnType + ); + } + + /** * Logs user into the system * - * @param {String} opts['username'] The user name for login - * @param {String} opts['password'] The password for login in clear text - * data is of type: 'String' + * @param {Object} opts Optional parameters + * @param {String} opts.username The user name for login + * @param {String} opts.password The password for login in clear text + * data is of type: {'String'} */ - self.loginUser = function(opts) { + this.loginUser = function(opts) { opts = opts || {}; var postBody = null; - + var pathParams = { }; @@ -150,16 +241,16 @@ pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType ); - } - + + /** * Logs out current logged in user session * */ - self.logoutUser = function() { + this.logoutUser = function() { var postBody = null; - + var pathParams = { }; @@ -180,62 +271,25 @@ pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType ); - } - - /** - * Get user by user name - * - * @param {String} username The name that needs to be fetched. Use user1 for testing. - * data is of type: User - */ - self.getUserByName = function(username) { - var postBody = null; - - // verify the required parameter 'username' is set - if (username == null) { - throw "Missing the required parameter 'username' when calling getUserByName"; - } - - var pathParams = { - 'username': username - }; - var queryParams = { - }; - var headerParams = { - }; - var formParams = { - }; - var authNames = []; - var contentTypes = []; - var accepts = ['application/json', 'application/xml']; - var returnType = User; - - return this.apiClient.callApi( - '/user/{username}', 'GET', - pathParams, queryParams, headerParams, formParams, postBody, - authNames, contentTypes, accepts, returnType - ); - - } - /** * Updated user * This can only be done by the logged in user. * @param {String} username name that need to be deleted - * @param {User} opts['body'] Updated user object + * @param {Object} opts Optional parameters + * @param {module:model/User} opts.body Updated user object */ - self.updateUser = function(username, opts) { + this.updateUser = function(username, opts) { opts = opts || {}; var postBody = opts['body']; - + // verify the required parameter 'username' is set - if (username == null) { + if (username == undefined || username == null) { throw "Missing the required parameter 'username' when calling updateUser"; } - + var pathParams = { 'username': username @@ -257,48 +311,8 @@ pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType ); - } - - /** - * Delete user - * This can only be done by the logged in user. - * @param {String} username The name that needs to be deleted - */ - self.deleteUser = function(username) { - var postBody = null; - - // verify the required parameter 'username' is set - if (username == null) { - throw "Missing the required parameter 'username' when calling deleteUser"; - } - - - var pathParams = { - 'username': username - }; - var queryParams = { - }; - var headerParams = { - }; - var formParams = { - }; - - var authNames = []; - var contentTypes = []; - var accepts = ['application/json', 'application/xml']; - var returnType = null; - - return this.apiClient.callApi( - '/user/{username}', 'DELETE', - pathParams, queryParams, headerParams, formParams, postBody, - authNames, contentTypes, accepts, returnType - ); - - } - - }; - return UserApi; + return exports; })); diff --git a/samples/client/petstore/javascript-promise/src/index.js b/samples/client/petstore/javascript-promise/src/index.js index dcf02fc1547..da193f80e4d 100644 --- a/samples/client/petstore/javascript-promise/src/index.js +++ b/samples/client/petstore/javascript-promise/src/index.js @@ -1,23 +1,132 @@ (function(factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. - define(['./ApiClient', './model/Order', './model/User', './model/Category', './model/Tag', './model/Pet', './api/UserApi', './api/StoreApi', './api/PetApi'], factory); + define(['./ApiClient', './model/Animal', './model/Cat', './model/Category', './model/Dog', './model/InlineResponse200', './model/Model200Response', './model/ModelReturn', './model/Name', './model/Order', './model/Pet', './model/SpecialModelName', './model/Tag', './model/User', './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/Order'), require('./model/User'), require('./model/Category'), require('./model/Tag'), require('./model/Pet'), require('./api/UserApi'), require('./api/StoreApi'), require('./api/PetApi')); + module.exports = factory(require('./ApiClient'), require('./model/Animal'), require('./model/Cat'), require('./model/Category'), require('./model/Dog'), require('./model/InlineResponse200'), require('./model/Model200Response'), require('./model/ModelReturn'), require('./model/Name'), require('./model/Order'), require('./model/Pet'), require('./model/SpecialModelName'), require('./model/Tag'), require('./model/User'), require('./api/PetApi'), require('./api/StoreApi'), require('./api/UserApi')); } -}(function(ApiClient, Order, User, Category, Tag, Pet, UserApi, StoreApi, PetApi) { +}(function(ApiClient, Animal, Cat, Category, Dog, InlineResponse200, Model200Response, ModelReturn, Name, Order, Pet, SpecialModelName, Tag, User, PetApi, StoreApi, UserApi) { 'use strict'; - return { + /** + * This is a sample server Petstore server. You can find out more about Swagger at <a href=\"http://swagger.io\">http://swagger.io</a> or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters.
+ * The index module provides access to constructors for all the classes which comprise the public API. + *

+ * An AMD (recommended!) or CommonJS application will generally do something equivalent to the following: + *

+   * var SwaggerPetstore = require('./index'); // See note below*.
+   * var xxxSvc = new SwaggerPetstore.XxxApi(); // Allocate the API class we're going to use.
+   * var yyyModel = new SwaggerPetstore.Yyy(); // Construct a model instance.
+   * yyyModel.someProperty = 'someValue';
+   * ...
+   * var zzz = xxxSvc.doSomething(yyyModel); // Invoke the service.
+   * ...
+   * 
+ * *NOTE: For a top-level AMD script, use require(['./index'], function(){...}) and put the application logic within the + * callback function. + *

+ *

+ * A non-AMD browser application (discouraged) might do something like this: + *

+   * var xxxSvc = new SwaggerPetstore.XxxApi(); // Allocate the API class we're going to use.
+   * var yyy = new SwaggerPetstore.Yyy(); // Construct a model instance.
+   * yyyModel.someProperty = 'someValue';
+   * ...
+   * var zzz = xxxSvc.doSomething(yyyModel); // Invoke the service.
+   * ...
+   * 
+ *

+ * @module index + * @version 1.0.0 + */ + var exports = { + /** + * The ApiClient constructor. + * @property {module:ApiClient} + */ ApiClient: ApiClient, - Order: Order, - User: User, + /** + * The Animal model constructor. + * @property {module:model/Animal} + */ + Animal: Animal, + /** + * The Cat model constructor. + * @property {module:model/Cat} + */ + Cat: Cat, + /** + * The Category model constructor. + * @property {module:model/Category} + */ Category: Category, - Tag: Tag, + /** + * The Dog model constructor. + * @property {module:model/Dog} + */ + Dog: Dog, + /** + * The InlineResponse200 model constructor. + * @property {module:model/InlineResponse200} + */ + InlineResponse200: InlineResponse200, + /** + * The Model200Response model constructor. + * @property {module:model/Model200Response} + */ + Model200Response: Model200Response, + /** + * The ModelReturn model constructor. + * @property {module:model/ModelReturn} + */ + ModelReturn: ModelReturn, + /** + * The Name model constructor. + * @property {module:model/Name} + */ + Name: Name, + /** + * The Order model constructor. + * @property {module:model/Order} + */ + Order: Order, + /** + * The Pet model constructor. + * @property {module:model/Pet} + */ Pet: Pet, - UserApi: UserApi, + /** + * The SpecialModelName model constructor. + * @property {module:model/SpecialModelName} + */ + SpecialModelName: SpecialModelName, + /** + * The Tag model constructor. + * @property {module:model/Tag} + */ + Tag: Tag, + /** + * The User model constructor. + * @property {module:model/User} + */ + User: User, + /** + * The PetApi service constructor. + * @property {module:api/PetApi} + */ + PetApi: PetApi, + /** + * The StoreApi service constructor. + * @property {module:api/StoreApi} + */ StoreApi: StoreApi, - PetApi: PetApi + /** + * The UserApi service constructor. + * @property {module:api/UserApi} + */ + UserApi: UserApi }; + + return exports; })); diff --git a/samples/client/petstore/javascript-promise/src/model/Animal.js b/samples/client/petstore/javascript-promise/src/model/Animal.js new file mode 100644 index 00000000000..674471a30ee --- /dev/null +++ b/samples/client/petstore/javascript-promise/src/model/Animal.js @@ -0,0 +1,63 @@ +(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.Animal = factory(root.SwaggerPetstore.ApiClient); + } +}(this, function(ApiClient) { + 'use strict'; + + /** + * The Animal model module. + * @module model/Animal + * @version 1.0.0 + */ + + /** + * Constructs a new Animal. + * @alias module:model/Animal + * @class + * @param className + */ + var exports = function(className) { + + this['className'] = className; + }; + + /** + * Constructs a Animal 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/Animal} obj Optional instance to populate. + * @return {module:model/Animal} The populated Animal instance. + */ + exports.constructFromObject = function(data, obj) { + if (data) { + obj = obj || new exports(); + + if (data.hasOwnProperty('className')) { + obj['className'] = ApiClient.convertToType(data['className'], 'String'); + } + } + return obj; + } + + + /** + * @member {String} className + */ + exports.prototype['className'] = undefined; + + + + + return exports; +})); diff --git a/samples/client/petstore/javascript-promise/src/model/Cat.js b/samples/client/petstore/javascript-promise/src/model/Cat.js new file mode 100644 index 00000000000..c878af6edec --- /dev/null +++ b/samples/client/petstore/javascript-promise/src/model/Cat.js @@ -0,0 +1,67 @@ +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(['../ApiClient', './Animal'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + module.exports = factory(require('../ApiClient'), require('./Animal')); + } else { + // Browser globals (root is window) + if (!root.SwaggerPetstore) { + root.SwaggerPetstore = {}; + } + root.SwaggerPetstore.Cat = factory(root.SwaggerPetstore.ApiClient, root.SwaggerPetstore.Animal); + } +}(this, function(ApiClient, Animal) { + 'use strict'; + + /** + * The Cat model module. + * @module model/Cat + * @version 1.0.0 + */ + + /** + * Constructs a new Cat. + * @alias module:model/Cat + * @class + * @extends module:model/Animal + * @param className + */ + var exports = function(className) { + Animal.call(this, className); + + }; + + /** + * Constructs a Cat 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/Cat} obj Optional instance to populate. + * @return {module:model/Cat} The populated Cat instance. + */ + exports.constructFromObject = function(data, obj) { + if (data) { + obj = obj || new exports(); + Animal.constructFromObject(data, obj); + if (data.hasOwnProperty('declawed')) { + obj['declawed'] = ApiClient.convertToType(data['declawed'], 'Boolean'); + } + } + return obj; + } + + exports.prototype = Object.create(Animal.prototype); + exports.prototype.constructor = exports; + + + /** + * @member {Boolean} declawed + */ + exports.prototype['declawed'] = undefined; + + + + + return exports; +})); diff --git a/samples/client/petstore/javascript-promise/src/model/Category.js b/samples/client/petstore/javascript-promise/src/model/Category.js index 729a22b9e04..473f4b783d5 100644 --- a/samples/client/petstore/javascript-promise/src/model/Category.js +++ b/samples/client/petstore/javascript-promise/src/model/Category.js @@ -1,81 +1,71 @@ (function(root, factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. - define([undefined, '../ApiClient'], factory); + define(['../ApiClient'], factory); } else if (typeof module === 'object' && module.exports) { // CommonJS-like environments that support module.exports, like Node. - module.exports = factory(undefined, require('../ApiClient')); + module.exports = factory(require('../ApiClient')); } else { // Browser globals (root is window) if (!root.SwaggerPetstore) { root.SwaggerPetstore = {}; } - factory(root.SwaggerPetstore, root.SwaggerPetstore.ApiClient); + root.SwaggerPetstore.Category = factory(root.SwaggerPetstore.ApiClient); } -}(this, function(module, ApiClient) { +}(this, function(ApiClient) { 'use strict'; - - - var Category = function Category() { - + + /** + * The Category model module. + * @module model/Category + * @version 1.0.0 + */ + + /** + * Constructs a new Category. + * @alias module:model/Category + * @class + */ + var exports = function() { + + + }; - Category.constructFromObject = function(data) { - if (!data) { - return null; + /** + * Constructs a Category 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/Category} obj Optional instance to populate. + * @return {module:model/Category} The populated Category instance. + */ + exports.constructFromObject = function(data, obj) { + if (data) { + obj = obj || new exports(); + + if (data.hasOwnProperty('id')) { + obj['id'] = ApiClient.convertToType(data['id'], 'Integer'); + } + if (data.hasOwnProperty('name')) { + obj['name'] = ApiClient.convertToType(data['name'], 'String'); + } } - var _this = new Category(); - - if (data['id']) { - _this['id'] = ApiClient.convertToType(data['id'], 'Integer'); - } - - if (data['name']) { - _this['name'] = ApiClient.convertToType(data['name'], 'String'); - } - - return _this; + return obj; } - - - /** - * @return {Integer} - **/ - Category.prototype.getId = function() { - return this['id']; - } /** - * @param {Integer} id - **/ - Category.prototype.setId = function(id) { - this['id'] = id; - } - - /** - * @return {String} - **/ - Category.prototype.getName = function() { - return this['name']; - } + * @member {Integer} id + */ + exports.prototype['id'] = undefined; /** - * @param {String} name - **/ - Category.prototype.setName = function(name) { - this['name'] = name; - } - - + * @member {String} name + */ + exports.prototype['name'] = undefined; - - if (module) { - module.Category = Category; - } - return Category; - - + + return exports; })); diff --git a/samples/client/petstore/javascript-promise/src/model/Dog.js b/samples/client/petstore/javascript-promise/src/model/Dog.js new file mode 100644 index 00000000000..e5e55581a70 --- /dev/null +++ b/samples/client/petstore/javascript-promise/src/model/Dog.js @@ -0,0 +1,67 @@ +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(['../ApiClient', './Animal'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + module.exports = factory(require('../ApiClient'), require('./Animal')); + } else { + // Browser globals (root is window) + if (!root.SwaggerPetstore) { + root.SwaggerPetstore = {}; + } + root.SwaggerPetstore.Dog = factory(root.SwaggerPetstore.ApiClient, root.SwaggerPetstore.Animal); + } +}(this, function(ApiClient, Animal) { + 'use strict'; + + /** + * The Dog model module. + * @module model/Dog + * @version 1.0.0 + */ + + /** + * Constructs a new Dog. + * @alias module:model/Dog + * @class + * @extends module:model/Animal + * @param className + */ + var exports = function(className) { + Animal.call(this, className); + + }; + + /** + * Constructs a Dog 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/Dog} obj Optional instance to populate. + * @return {module:model/Dog} The populated Dog instance. + */ + exports.constructFromObject = function(data, obj) { + if (data) { + obj = obj || new exports(); + Animal.constructFromObject(data, obj); + if (data.hasOwnProperty('breed')) { + obj['breed'] = ApiClient.convertToType(data['breed'], 'String'); + } + } + return obj; + } + + exports.prototype = Object.create(Animal.prototype); + exports.prototype.constructor = exports; + + + /** + * @member {String} breed + */ + exports.prototype['breed'] = undefined; + + + + + return exports; +})); diff --git a/samples/client/petstore/javascript-promise/src/model/InlineResponse200.js b/samples/client/petstore/javascript-promise/src/model/InlineResponse200.js new file mode 100644 index 00000000000..f9ecda79491 --- /dev/null +++ b/samples/client/petstore/javascript-promise/src/model/InlineResponse200.js @@ -0,0 +1,132 @@ +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(['../ApiClient', './Tag'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + module.exports = factory(require('../ApiClient'), require('./Tag')); + } else { + // Browser globals (root is window) + if (!root.SwaggerPetstore) { + root.SwaggerPetstore = {}; + } + root.SwaggerPetstore.InlineResponse200 = factory(root.SwaggerPetstore.ApiClient, root.SwaggerPetstore.Tag); + } +}(this, function(ApiClient, Tag) { + 'use strict'; + + /** + * The InlineResponse200 model module. + * @module model/InlineResponse200 + * @version 1.0.0 + */ + + /** + * Constructs a new InlineResponse200. + * @alias module:model/InlineResponse200 + * @class + * @param id + */ + var exports = function(id) { + + + this['id'] = id; + + + + + }; + + /** + * Constructs a InlineResponse200 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/InlineResponse200} obj Optional instance to populate. + * @return {module:model/InlineResponse200} The populated InlineResponse200 instance. + */ + exports.constructFromObject = function(data, obj) { + if (data) { + obj = obj || new exports(); + + if (data.hasOwnProperty('tags')) { + obj['tags'] = ApiClient.convertToType(data['tags'], [Tag]); + } + if (data.hasOwnProperty('id')) { + obj['id'] = ApiClient.convertToType(data['id'], 'Integer'); + } + if (data.hasOwnProperty('category')) { + obj['category'] = ApiClient.convertToType(data['category'], Object); + } + if (data.hasOwnProperty('status')) { + obj['status'] = ApiClient.convertToType(data['status'], 'String'); + } + if (data.hasOwnProperty('name')) { + obj['name'] = ApiClient.convertToType(data['name'], 'String'); + } + if (data.hasOwnProperty('photoUrls')) { + obj['photoUrls'] = ApiClient.convertToType(data['photoUrls'], ['String']); + } + } + return obj; + } + + + /** + * @member {Array.} tags + */ + exports.prototype['tags'] = undefined; + + /** + * @member {Integer} id + */ + exports.prototype['id'] = undefined; + + /** + * @member {Object} category + */ + exports.prototype['category'] = undefined; + + /** + * pet status in the store + * @member {module:model/InlineResponse200.StatusEnum} status + */ + exports.prototype['status'] = undefined; + + /** + * @member {String} name + */ + exports.prototype['name'] = undefined; + + /** + * @member {Array.} photoUrls + */ + exports.prototype['photoUrls'] = undefined; + + + /** + * Allowed values for the status property. + * @enum {String} + * @readonly + */ + exports.StatusEnum = { + /** + * value: available + * @const + */ + AVAILABLE: "available", + + /** + * value: pending + * @const + */ + PENDING: "pending", + + /** + * value: sold + * @const + */ + SOLD: "sold" + }; + + return exports; +})); diff --git a/samples/client/petstore/javascript-promise/src/model/Model200Response.js b/samples/client/petstore/javascript-promise/src/model/Model200Response.js new file mode 100644 index 00000000000..fb559f5ebaa --- /dev/null +++ b/samples/client/petstore/javascript-promise/src/model/Model200Response.js @@ -0,0 +1,62 @@ +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(['../ApiClient'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + module.exports = factory(require('../ApiClient')); + } else { + // Browser globals (root is window) + if (!root.SwaggerPetstore) { + root.SwaggerPetstore = {}; + } + root.SwaggerPetstore.Model200Response = factory(root.SwaggerPetstore.ApiClient); + } +}(this, function(ApiClient) { + 'use strict'; + + /** + * The Model200Response model module. + * @module model/Model200Response + * @version 1.0.0 + */ + + /** + * Constructs a new Model200Response. + * @alias module:model/Model200Response + * @class + */ + var exports = function() { + + + }; + + /** + * Constructs a Model200Response 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/Model200Response} obj Optional instance to populate. + * @return {module:model/Model200Response} The populated Model200Response instance. + */ + exports.constructFromObject = function(data, obj) { + if (data) { + obj = obj || new exports(); + + if (data.hasOwnProperty('name')) { + obj['name'] = ApiClient.convertToType(data['name'], 'Integer'); + } + } + return obj; + } + + + /** + * @member {Integer} name + */ + exports.prototype['name'] = undefined; + + + + + return exports; +})); diff --git a/samples/client/petstore/javascript-promise/src/model/ModelReturn.js b/samples/client/petstore/javascript-promise/src/model/ModelReturn.js new file mode 100644 index 00000000000..d5036e230ea --- /dev/null +++ b/samples/client/petstore/javascript-promise/src/model/ModelReturn.js @@ -0,0 +1,62 @@ +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(['../ApiClient'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + module.exports = factory(require('../ApiClient')); + } else { + // Browser globals (root is window) + if (!root.SwaggerPetstore) { + root.SwaggerPetstore = {}; + } + root.SwaggerPetstore.ModelReturn = factory(root.SwaggerPetstore.ApiClient); + } +}(this, function(ApiClient) { + 'use strict'; + + /** + * The ModelReturn model module. + * @module model/ModelReturn + * @version 1.0.0 + */ + + /** + * Constructs a new ModelReturn. + * @alias module:model/ModelReturn + * @class + */ + var exports = function() { + + + }; + + /** + * Constructs a ModelReturn 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/ModelReturn} obj Optional instance to populate. + * @return {module:model/ModelReturn} The populated ModelReturn instance. + */ + exports.constructFromObject = function(data, obj) { + if (data) { + obj = obj || new exports(); + + if (data.hasOwnProperty('return')) { + obj['return'] = ApiClient.convertToType(data['return'], 'Integer'); + } + } + return obj; + } + + + /** + * @member {Integer} return + */ + exports.prototype['return'] = undefined; + + + + + return exports; +})); diff --git a/samples/client/petstore/javascript-promise/src/model/Name.js b/samples/client/petstore/javascript-promise/src/model/Name.js new file mode 100644 index 00000000000..a5a070025f7 --- /dev/null +++ b/samples/client/petstore/javascript-promise/src/model/Name.js @@ -0,0 +1,71 @@ +(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.Name = factory(root.SwaggerPetstore.ApiClient); + } +}(this, function(ApiClient) { + 'use strict'; + + /** + * The Name model module. + * @module model/Name + * @version 1.0.0 + */ + + /** + * Constructs a new Name. + * @alias module:model/Name + * @class + */ + var exports = function() { + + + + }; + + /** + * Constructs a Name 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/Name} obj Optional instance to populate. + * @return {module:model/Name} The populated Name instance. + */ + exports.constructFromObject = function(data, obj) { + if (data) { + obj = obj || new exports(); + + if (data.hasOwnProperty('name')) { + obj['name'] = ApiClient.convertToType(data['name'], 'Integer'); + } + if (data.hasOwnProperty('snake_case')) { + obj['snake_case'] = ApiClient.convertToType(data['snake_case'], 'Integer'); + } + } + return obj; + } + + + /** + * @member {Integer} name + */ + exports.prototype['name'] = undefined; + + /** + * @member {Integer} snake_case + */ + exports.prototype['snake_case'] = undefined; + + + + + return exports; +})); diff --git a/samples/client/petstore/javascript-promise/src/model/Order.js b/samples/client/petstore/javascript-promise/src/model/Order.js index 4d2e4625d90..81f1feb7800 100644 --- a/samples/client/petstore/javascript-promise/src/model/Order.js +++ b/samples/client/petstore/javascript-promise/src/model/Order.js @@ -1,174 +1,131 @@ (function(root, factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. - define([undefined, '../ApiClient'], factory); + define(['../ApiClient'], factory); } else if (typeof module === 'object' && module.exports) { // CommonJS-like environments that support module.exports, like Node. - module.exports = factory(undefined, require('../ApiClient')); + module.exports = factory(require('../ApiClient')); } else { // Browser globals (root is window) if (!root.SwaggerPetstore) { root.SwaggerPetstore = {}; } - factory(root.SwaggerPetstore, root.SwaggerPetstore.ApiClient); + root.SwaggerPetstore.Order = factory(root.SwaggerPetstore.ApiClient); } -}(this, function(module, ApiClient) { +}(this, function(ApiClient) { 'use strict'; - - - var Order = function Order() { - + + /** + * The Order model module. + * @module model/Order + * @version 1.0.0 + */ + + /** + * Constructs a new Order. + * @alias module:model/Order + * @class + */ + var exports = function() { + + + + + + + }; - Order.constructFromObject = function(data) { - if (!data) { - return null; + /** + * Constructs a Order 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/Order} obj Optional instance to populate. + * @return {module:model/Order} The populated Order instance. + */ + exports.constructFromObject = function(data, obj) { + if (data) { + obj = obj || new exports(); + + if (data.hasOwnProperty('id')) { + obj['id'] = ApiClient.convertToType(data['id'], 'Integer'); + } + if (data.hasOwnProperty('petId')) { + obj['petId'] = ApiClient.convertToType(data['petId'], 'Integer'); + } + if (data.hasOwnProperty('quantity')) { + obj['quantity'] = ApiClient.convertToType(data['quantity'], 'Integer'); + } + if (data.hasOwnProperty('shipDate')) { + obj['shipDate'] = ApiClient.convertToType(data['shipDate'], 'Date'); + } + if (data.hasOwnProperty('status')) { + obj['status'] = ApiClient.convertToType(data['status'], 'String'); + } + if (data.hasOwnProperty('complete')) { + obj['complete'] = ApiClient.convertToType(data['complete'], 'Boolean'); + } } - var _this = new Order(); + return obj; + } + + + /** + * @member {Integer} id + */ + exports.prototype['id'] = undefined; + + /** + * @member {Integer} petId + */ + exports.prototype['petId'] = undefined; + + /** + * @member {Integer} quantity + */ + exports.prototype['quantity'] = undefined; + + /** + * @member {Date} shipDate + */ + exports.prototype['shipDate'] = undefined; + + /** + * Order Status + * @member {module:model/Order.StatusEnum} status + */ + exports.prototype['status'] = undefined; + + /** + * @member {Boolean} complete + */ + exports.prototype['complete'] = undefined; + + + /** + * Allowed values for the status property. + * @enum {String} + * @readonly + */ + exports.StatusEnum = { + /** + * value: placed + * @const + */ + PLACED: "placed", - if (data['id']) { - _this['id'] = ApiClient.convertToType(data['id'], 'Integer'); - } + /** + * value: approved + * @const + */ + APPROVED: "approved", - if (data['petId']) { - _this['petId'] = ApiClient.convertToType(data['petId'], 'Integer'); - } - - if (data['quantity']) { - _this['quantity'] = ApiClient.convertToType(data['quantity'], 'Integer'); - } - - if (data['shipDate']) { - _this['shipDate'] = ApiClient.convertToType(data['shipDate'], 'Date'); - } - - if (data['status']) { - _this['status'] = ApiClient.convertToType(data['status'], 'String'); - } - - if (data['complete']) { - _this['complete'] = ApiClient.convertToType(data['complete'], 'Boolean'); - } - - return _this; - } - - - - /** - * @return {Integer} - **/ - Order.prototype.getId = function() { - return this['id']; - } - - /** - * @param {Integer} id - **/ - Order.prototype.setId = function(id) { - this['id'] = id; - } - - /** - * @return {Integer} - **/ - Order.prototype.getPetId = function() { - return this['petId']; - } - - /** - * @param {Integer} petId - **/ - Order.prototype.setPetId = function(petId) { - this['petId'] = petId; - } - - /** - * @return {Integer} - **/ - Order.prototype.getQuantity = function() { - return this['quantity']; - } - - /** - * @param {Integer} quantity - **/ - Order.prototype.setQuantity = function(quantity) { - this['quantity'] = quantity; - } - - /** - * @return {Date} - **/ - Order.prototype.getShipDate = function() { - return this['shipDate']; - } - - /** - * @param {Date} shipDate - **/ - Order.prototype.setShipDate = function(shipDate) { - this['shipDate'] = shipDate; - } - - /** - * get Order Status - * @return {StatusEnum} - **/ - Order.prototype.getStatus = function() { - return this['status']; - } - - /** - * set Order Status - * @param {StatusEnum} status - **/ - Order.prototype.setStatus = function(status) { - this['status'] = status; - } - - /** - * @return {Boolean} - **/ - Order.prototype.getComplete = function() { - return this['complete']; - } - - /** - * @param {Boolean} complete - **/ - Order.prototype.setComplete = function(complete) { - this['complete'] = complete; - } - - - - var StatusEnum = { - - /** - * @const - */ - PLACED: "placed", - - /** - * @const - */ - APPROVED: "approved", - - /** - * @const - */ - DELIVERED: "delivered" + /** + * value: delivered + * @const + */ + DELIVERED: "delivered" }; - Order.StatusEnum = StatusEnum; - - - if (module) { - module.Order = Order; - } - - return Order; - - + return exports; })); diff --git a/samples/client/petstore/javascript-promise/src/model/Pet.js b/samples/client/petstore/javascript-promise/src/model/Pet.js index d751182c303..39a09b47170 100644 --- a/samples/client/petstore/javascript-promise/src/model/Pet.js +++ b/samples/client/petstore/javascript-promise/src/model/Pet.js @@ -1,184 +1,133 @@ (function(root, factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. - define([undefined, '../ApiClient', './Category', './Tag'], factory); + define(['../ApiClient', './Category', './Tag'], factory); } else if (typeof module === 'object' && module.exports) { // CommonJS-like environments that support module.exports, like Node. - module.exports = factory(undefined, require('../ApiClient'), require('./Category'), require('./Tag')); + module.exports = factory(require('../ApiClient'), require('./Category'), require('./Tag')); } else { // Browser globals (root is window) if (!root.SwaggerPetstore) { root.SwaggerPetstore = {}; } - factory(root.SwaggerPetstore, root.SwaggerPetstore.ApiClient, root.SwaggerPetstore.Category, root.SwaggerPetstore.Tag); + root.SwaggerPetstore.Pet = factory(root.SwaggerPetstore.ApiClient, root.SwaggerPetstore.Category, root.SwaggerPetstore.Tag); } -}(this, function(module, ApiClient, Category, Tag) { +}(this, function(ApiClient, Category, Tag) { 'use strict'; - - - var Pet = function Pet(name, photoUrls) { - - /** - * datatype: String - * required - **/ + + /** + * The Pet model module. + * @module model/Pet + * @version 1.0.0 + */ + + /** + * Constructs a new Pet. + * @alias module:model/Pet + * @class + * @param name + * @param photoUrls + */ + var exports = function(name, photoUrls) { + + + this['name'] = name; - /** - * datatype: [String] - * required - **/ this['photoUrls'] = photoUrls; + + }; - Pet.constructFromObject = function(data) { - if (!data) { - return null; + /** + * Constructs a Pet 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/Pet} obj Optional instance to populate. + * @return {module:model/Pet} The populated Pet instance. + */ + exports.constructFromObject = function(data, obj) { + if (data) { + obj = obj || new exports(); + + if (data.hasOwnProperty('id')) { + obj['id'] = ApiClient.convertToType(data['id'], 'Integer'); + } + if (data.hasOwnProperty('category')) { + obj['category'] = Category.constructFromObject(data['category']); + } + if (data.hasOwnProperty('name')) { + obj['name'] = ApiClient.convertToType(data['name'], 'String'); + } + if (data.hasOwnProperty('photoUrls')) { + obj['photoUrls'] = ApiClient.convertToType(data['photoUrls'], ['String']); + } + if (data.hasOwnProperty('tags')) { + obj['tags'] = ApiClient.convertToType(data['tags'], [Tag]); + } + if (data.hasOwnProperty('status')) { + obj['status'] = ApiClient.convertToType(data['status'], 'String'); + } } - var _this = new Pet(); + return obj; + } + + + /** + * @member {Integer} id + */ + exports.prototype['id'] = undefined; + + /** + * @member {module:model/Category} category + */ + exports.prototype['category'] = undefined; + + /** + * @member {String} name + */ + exports.prototype['name'] = undefined; + + /** + * @member {Array.} photoUrls + */ + exports.prototype['photoUrls'] = undefined; + + /** + * @member {Array.} tags + */ + exports.prototype['tags'] = undefined; + + /** + * pet status in the store + * @member {module:model/Pet.StatusEnum} status + */ + exports.prototype['status'] = undefined; + + + /** + * Allowed values for the status property. + * @enum {String} + * @readonly + */ + exports.StatusEnum = { + /** + * value: available + * @const + */ + AVAILABLE: "available", - if (data['id']) { - _this['id'] = ApiClient.convertToType(data['id'], 'Integer'); - } + /** + * value: pending + * @const + */ + PENDING: "pending", - if (data['category']) { - _this['category'] = Category.constructFromObject(data['category']); - } - - if (data['name']) { - _this['name'] = ApiClient.convertToType(data['name'], 'String'); - } - - if (data['photoUrls']) { - _this['photoUrls'] = ApiClient.convertToType(data['photoUrls'], ['String']); - } - - if (data['tags']) { - _this['tags'] = ApiClient.convertToType(data['tags'], [Tag]); - } - - if (data['status']) { - _this['status'] = ApiClient.convertToType(data['status'], 'String'); - } - - return _this; - } - - - - /** - * @return {Integer} - **/ - Pet.prototype.getId = function() { - return this['id']; - } - - /** - * @param {Integer} id - **/ - Pet.prototype.setId = function(id) { - this['id'] = id; - } - - /** - * @return {Category} - **/ - Pet.prototype.getCategory = function() { - return this['category']; - } - - /** - * @param {Category} category - **/ - Pet.prototype.setCategory = function(category) { - this['category'] = category; - } - - /** - * @return {String} - **/ - Pet.prototype.getName = function() { - return this['name']; - } - - /** - * @param {String} name - **/ - Pet.prototype.setName = function(name) { - this['name'] = name; - } - - /** - * @return {[String]} - **/ - Pet.prototype.getPhotoUrls = function() { - return this['photoUrls']; - } - - /** - * @param {[String]} photoUrls - **/ - Pet.prototype.setPhotoUrls = function(photoUrls) { - this['photoUrls'] = photoUrls; - } - - /** - * @return {[Tag]} - **/ - Pet.prototype.getTags = function() { - return this['tags']; - } - - /** - * @param {[Tag]} tags - **/ - Pet.prototype.setTags = function(tags) { - this['tags'] = tags; - } - - /** - * get pet status in the store - * @return {StatusEnum} - **/ - Pet.prototype.getStatus = function() { - return this['status']; - } - - /** - * set pet status in the store - * @param {StatusEnum} status - **/ - Pet.prototype.setStatus = function(status) { - this['status'] = status; - } - - - - var StatusEnum = { - - /** - * @const - */ - AVAILABLE: "available", - - /** - * @const - */ - PENDING: "pending", - - /** - * @const - */ - SOLD: "sold" + /** + * value: sold + * @const + */ + SOLD: "sold" }; - Pet.StatusEnum = StatusEnum; - - - if (module) { - module.Pet = Pet; - } - - return Pet; - - + return exports; })); diff --git a/samples/client/petstore/javascript-promise/src/model/SpecialModelName.js b/samples/client/petstore/javascript-promise/src/model/SpecialModelName.js new file mode 100644 index 00000000000..fb6b4765d3f --- /dev/null +++ b/samples/client/petstore/javascript-promise/src/model/SpecialModelName.js @@ -0,0 +1,62 @@ +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(['../ApiClient'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + module.exports = factory(require('../ApiClient')); + } else { + // Browser globals (root is window) + if (!root.SwaggerPetstore) { + root.SwaggerPetstore = {}; + } + root.SwaggerPetstore.SpecialModelName = factory(root.SwaggerPetstore.ApiClient); + } +}(this, function(ApiClient) { + 'use strict'; + + /** + * The SpecialModelName model module. + * @module model/SpecialModelName + * @version 1.0.0 + */ + + /** + * Constructs a new SpecialModelName. + * @alias module:model/SpecialModelName + * @class + */ + var exports = function() { + + + }; + + /** + * Constructs a SpecialModelName 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/SpecialModelName} obj Optional instance to populate. + * @return {module:model/SpecialModelName} The populated SpecialModelName instance. + */ + exports.constructFromObject = function(data, obj) { + if (data) { + obj = obj || new exports(); + + if (data.hasOwnProperty('$special[property.name]')) { + obj['$special[property.name]'] = ApiClient.convertToType(data['$special[property.name]'], 'Integer'); + } + } + return obj; + } + + + /** + * @member {Integer} $special[property.name] + */ + exports.prototype['$special[property.name]'] = undefined; + + + + + return exports; +})); diff --git a/samples/client/petstore/javascript-promise/src/model/Tag.js b/samples/client/petstore/javascript-promise/src/model/Tag.js index fbd43adb7e0..8a0739b2ef5 100644 --- a/samples/client/petstore/javascript-promise/src/model/Tag.js +++ b/samples/client/petstore/javascript-promise/src/model/Tag.js @@ -1,81 +1,71 @@ (function(root, factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. - define([undefined, '../ApiClient'], factory); + define(['../ApiClient'], factory); } else if (typeof module === 'object' && module.exports) { // CommonJS-like environments that support module.exports, like Node. - module.exports = factory(undefined, require('../ApiClient')); + module.exports = factory(require('../ApiClient')); } else { // Browser globals (root is window) if (!root.SwaggerPetstore) { root.SwaggerPetstore = {}; } - factory(root.SwaggerPetstore, root.SwaggerPetstore.ApiClient); + root.SwaggerPetstore.Tag = factory(root.SwaggerPetstore.ApiClient); } -}(this, function(module, ApiClient) { +}(this, function(ApiClient) { 'use strict'; - - - var Tag = function Tag() { - + + /** + * The Tag model module. + * @module model/Tag + * @version 1.0.0 + */ + + /** + * Constructs a new Tag. + * @alias module:model/Tag + * @class + */ + var exports = function() { + + + }; - Tag.constructFromObject = function(data) { - if (!data) { - return null; + /** + * Constructs a Tag 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/Tag} obj Optional instance to populate. + * @return {module:model/Tag} The populated Tag instance. + */ + exports.constructFromObject = function(data, obj) { + if (data) { + obj = obj || new exports(); + + if (data.hasOwnProperty('id')) { + obj['id'] = ApiClient.convertToType(data['id'], 'Integer'); + } + if (data.hasOwnProperty('name')) { + obj['name'] = ApiClient.convertToType(data['name'], 'String'); + } } - var _this = new Tag(); - - if (data['id']) { - _this['id'] = ApiClient.convertToType(data['id'], 'Integer'); - } - - if (data['name']) { - _this['name'] = ApiClient.convertToType(data['name'], 'String'); - } - - return _this; + return obj; } - - - /** - * @return {Integer} - **/ - Tag.prototype.getId = function() { - return this['id']; - } /** - * @param {Integer} id - **/ - Tag.prototype.setId = function(id) { - this['id'] = id; - } - - /** - * @return {String} - **/ - Tag.prototype.getName = function() { - return this['name']; - } + * @member {Integer} id + */ + exports.prototype['id'] = undefined; /** - * @param {String} name - **/ - Tag.prototype.setName = function(name) { - this['name'] = name; - } - - + * @member {String} name + */ + exports.prototype['name'] = undefined; - - if (module) { - module.Tag = Tag; - } - return Tag; - - + + return exports; })); diff --git a/samples/client/petstore/javascript-promise/src/model/User.js b/samples/client/petstore/javascript-promise/src/model/User.js index 2f6c9863ef8..1d960a89914 100644 --- a/samples/client/petstore/javascript-promise/src/model/User.js +++ b/samples/client/petstore/javascript-promise/src/model/User.js @@ -1,191 +1,126 @@ (function(root, factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. - define([undefined, '../ApiClient'], factory); + define(['../ApiClient'], factory); } else if (typeof module === 'object' && module.exports) { // CommonJS-like environments that support module.exports, like Node. - module.exports = factory(undefined, require('../ApiClient')); + module.exports = factory(require('../ApiClient')); } else { // Browser globals (root is window) if (!root.SwaggerPetstore) { root.SwaggerPetstore = {}; } - factory(root.SwaggerPetstore, root.SwaggerPetstore.ApiClient); + root.SwaggerPetstore.User = factory(root.SwaggerPetstore.ApiClient); } -}(this, function(module, ApiClient) { +}(this, function(ApiClient) { 'use strict'; - - - var User = function User() { - + + /** + * The User model module. + * @module model/User + * @version 1.0.0 + */ + + /** + * Constructs a new User. + * @alias module:model/User + * @class + */ + var exports = function() { + + + + + + + + + }; - User.constructFromObject = function(data) { - if (!data) { - return null; + /** + * Constructs a User 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/User} obj Optional instance to populate. + * @return {module:model/User} The populated User instance. + */ + exports.constructFromObject = function(data, obj) { + if (data) { + obj = obj || new exports(); + + if (data.hasOwnProperty('id')) { + obj['id'] = ApiClient.convertToType(data['id'], 'Integer'); + } + if (data.hasOwnProperty('username')) { + obj['username'] = ApiClient.convertToType(data['username'], 'String'); + } + if (data.hasOwnProperty('firstName')) { + obj['firstName'] = ApiClient.convertToType(data['firstName'], 'String'); + } + if (data.hasOwnProperty('lastName')) { + obj['lastName'] = ApiClient.convertToType(data['lastName'], 'String'); + } + if (data.hasOwnProperty('email')) { + obj['email'] = ApiClient.convertToType(data['email'], 'String'); + } + if (data.hasOwnProperty('password')) { + obj['password'] = ApiClient.convertToType(data['password'], 'String'); + } + if (data.hasOwnProperty('phone')) { + obj['phone'] = ApiClient.convertToType(data['phone'], 'String'); + } + if (data.hasOwnProperty('userStatus')) { + obj['userStatus'] = ApiClient.convertToType(data['userStatus'], 'Integer'); + } } - var _this = new User(); - - if (data['id']) { - _this['id'] = ApiClient.convertToType(data['id'], 'Integer'); - } - - if (data['username']) { - _this['username'] = ApiClient.convertToType(data['username'], 'String'); - } - - if (data['firstName']) { - _this['firstName'] = ApiClient.convertToType(data['firstName'], 'String'); - } - - if (data['lastName']) { - _this['lastName'] = ApiClient.convertToType(data['lastName'], 'String'); - } - - if (data['email']) { - _this['email'] = ApiClient.convertToType(data['email'], 'String'); - } - - if (data['password']) { - _this['password'] = ApiClient.convertToType(data['password'], 'String'); - } - - if (data['phone']) { - _this['phone'] = ApiClient.convertToType(data['phone'], 'String'); - } - - if (data['userStatus']) { - _this['userStatus'] = ApiClient.convertToType(data['userStatus'], 'Integer'); - } - - return _this; + return obj; } - - - /** - * @return {Integer} - **/ - User.prototype.getId = function() { - return this['id']; - } /** - * @param {Integer} id - **/ - User.prototype.setId = function(id) { - this['id'] = id; - } - - /** - * @return {String} - **/ - User.prototype.getUsername = function() { - return this['username']; - } + * @member {Integer} id + */ + exports.prototype['id'] = undefined; /** - * @param {String} username - **/ - User.prototype.setUsername = function(username) { - this['username'] = username; - } - - /** - * @return {String} - **/ - User.prototype.getFirstName = function() { - return this['firstName']; - } + * @member {String} username + */ + exports.prototype['username'] = undefined; /** - * @param {String} firstName - **/ - User.prototype.setFirstName = function(firstName) { - this['firstName'] = firstName; - } - - /** - * @return {String} - **/ - User.prototype.getLastName = function() { - return this['lastName']; - } + * @member {String} firstName + */ + exports.prototype['firstName'] = undefined; /** - * @param {String} lastName - **/ - User.prototype.setLastName = function(lastName) { - this['lastName'] = lastName; - } - - /** - * @return {String} - **/ - User.prototype.getEmail = function() { - return this['email']; - } + * @member {String} lastName + */ + exports.prototype['lastName'] = undefined; /** - * @param {String} email - **/ - User.prototype.setEmail = function(email) { - this['email'] = email; - } - - /** - * @return {String} - **/ - User.prototype.getPassword = function() { - return this['password']; - } + * @member {String} email + */ + exports.prototype['email'] = undefined; /** - * @param {String} password - **/ - User.prototype.setPassword = function(password) { - this['password'] = password; - } - - /** - * @return {String} - **/ - User.prototype.getPhone = function() { - return this['phone']; - } + * @member {String} password + */ + exports.prototype['password'] = undefined; /** - * @param {String} phone - **/ - User.prototype.setPhone = function(phone) { - this['phone'] = phone; - } - - /** - * get User Status - * @return {Integer} - **/ - User.prototype.getUserStatus = function() { - return this['userStatus']; - } + * @member {String} phone + */ + exports.prototype['phone'] = undefined; /** - * set User Status - * @param {Integer} userStatus - **/ - User.prototype.setUserStatus = function(userStatus) { - this['userStatus'] = userStatus; - } - - + * User Status + * @member {Integer} userStatus + */ + exports.prototype['userStatus'] = undefined; - - if (module) { - module.User = User; - } - return User; - - + + return exports; })); diff --git a/samples/client/petstore/javascript-promise/test/ApiClientTest.js b/samples/client/petstore/javascript-promise/test/ApiClientTest.js index fd3f63bb7af..c91fbb03783 100644 --- a/samples/client/petstore/javascript-promise/test/ApiClientTest.js +++ b/samples/client/petstore/javascript-promise/test/ApiClientTest.js @@ -4,33 +4,35 @@ if (typeof module === 'object' && module.exports) { var sinon = require('sinon'); } -var apiClient = SwaggerPetstore.ApiClient.default; +var apiClient = SwaggerPetstore.ApiClient.instance; describe('ApiClient', function() { describe('defaults', function() { it('should have correct default values with the default API client', function() { expect(apiClient).to.be.ok(); + expect(apiClient.basePath).to.be('http://petstore.swagger.io/v2'); expect(apiClient.authentications).to.eql({ petstore_auth: {type: 'oauth2'}, - api_key: {type: 'apiKey', in: 'header', name: 'api_key'}, + api_key: {type: 'apiKey', 'in': 'header', name: 'api_key'}, + test_http_basic: {type: 'basic'}, test_api_client_id: { type: 'apiKey', - in: 'header', + 'in': 'header', name: 'x-test_api_client_id' }, test_api_client_secret: { type: 'apiKey', - in: 'header', + 'in': 'header', name: 'x-test_api_client_secret' }, test_api_key_query: { type: 'apiKey', - in: 'query', + 'in': 'query', name: 'test_api_key_query' }, test_api_key_header: { type: 'apiKey', - in: 'header', + 'in': 'header', name: 'test_api_key_header' } }); @@ -273,7 +275,7 @@ describe('ApiClient', function() { var apiKeyAuth, oauth2; beforeEach(function() { - newClient.authentications[apiKeyAuthName] = {type: 'apiKey', name: 'api_key', in: 'query'}; + newClient.authentications[apiKeyAuthName] = {type: 'apiKey', name: 'api_key', 'in': 'query'}; newClient.authentications[oauth2Name] = {type: 'oauth2'}; apiKeyAuth = newClient.authentications[apiKeyAuthName]; oauth2 = newClient.authentications[oauth2Name]; @@ -376,10 +378,10 @@ function makeDumbRequest(apiClient, opts) { var headerParams = opts.headerParams || {}; var formParams = opts.formParams || {}; var bodyParam = opts.bodyParam; + var authNames = []; var contentTypes = opts.contentTypes || []; var accepts = opts.accepts || []; var callback = opts.callback; return apiClient.callApi(path, httpMethod, pathParams, queryParams, - headerParams, formParams, bodyParam, contentTypes, accepts, callback - ); + headerParams, formParams, bodyParam, authNames, contentTypes, accepts); } diff --git a/samples/client/petstore/javascript-promise/test/api/PetApiTest.js b/samples/client/petstore/javascript-promise/test/api/PetApiTest.js index d444529a927..1119546014d 100644 --- a/samples/client/petstore/javascript-promise/test/api/PetApiTest.js +++ b/samples/client/petstore/javascript-promise/test/api/PetApiTest.js @@ -3,25 +3,45 @@ if (typeof module === 'object' && module.exports) { var SwaggerPetstore = require('../../src/index'); } +// When testing in the Node.js environment, ApiClient will need access to a Promise constructor. +if (typeof Promise == 'undefined') + Promise = require('promise'); + var api; beforeEach(function() { api = new SwaggerPetstore.PetApi(); }); +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; +} + var createRandomPet = function() { var id = new Date().getTime(); var pet = new SwaggerPetstore.Pet(); - pet.setId(id); - pet.setName("gorilla" + id); + setProperty(pet, "setId", "id", id); + setProperty(pet, "setName", "name", "gorilla" + id); var category = new SwaggerPetstore.Category(); - category.setName("really-happy"); - pet.setCategory(category); + setProperty(category, "setName", "name", "really-happy"); + setProperty(pet, "setCategory", "category", category); - pet.setStatus('available'); + setProperty(pet, "setStatus", "status", "available"); var photos = ["http://foo.bar.com/1", "http://foo.bar.com/2"]; - pet.setPhotoUrls(photos); + setProperty(pet, "setPhotoUrls", "photoUrls", photos); return pet; }; @@ -34,14 +54,13 @@ describe('PetApi', function() { return api.getPetById(pet.id) }) .then(function(fetched) { - //expect(response.status).to.be(200); - //expect(response.ok).to.be(true); - //expect(response.get('Content-Type')).to.be('application/json'); expect(fetched).to.be.ok(); expect(fetched.id).to.be(pet.id); - expect(fetched.getPhotoUrls()).to.eql(pet.getPhotoUrls()); - expect(fetched.getCategory()).to.be.ok(); - expect(fetched.getCategory().getName()).to.be(pet.getCategory().getName()); + expect(getProperty(fetched, "getPhotoUrls", "photoUrls")) + .to.eql(getProperty(pet, "getPhotoUrls", "photoUrls")); + expect(getProperty(fetched, "getCategory", "category")).to.be.ok(); + expect(getProperty(getProperty(fetched, "getCategory", "category"), "getName", "name")) + .to.be(getProperty(getProperty(pet, "getCategory", "category"), "getName", "name")); api.deletePet(pet.id); done(); diff --git a/samples/client/petstore/javascript/README.md b/samples/client/petstore/javascript/README.md new file mode 100644 index 00000000000..0867d3ec1d5 --- /dev/null +++ b/samples/client/petstore/javascript/README.md @@ -0,0 +1,174 @@ +# swagger-petstore + +SwaggerPetstore - JavaScript client for 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 +This SDK is automatically generated by the [Swagger Codegen](https://github.com/swagger-api/swagger-codegen) project: + +- API version: 1.0.0 +- Package version: 1.0.0 +- Build date: 2016-03-30T20:58:07.996+08:00 +- Build package: class io.swagger.codegen.languages.JavascriptClientCodegen + +## Installation + +### For [Node.js](https://nodejs.org/) + +#### npm + +To publish the library as a [npm](https://www.npmjs.com/), +please follow the procedure in ["Publishing npm packages"](https://docs.npmjs.com/getting-started/publishing-npm-packages). + +Then install it via: + +```shell +npm install swagger-petstore --save +``` + +#### git +# +If the library is hosted at a git repository, e.g. +https://github.com/YOUR_USERNAME/YOUR_GIT_REPO_ID +then install it via: + +```shell +npm install YOUR_USERNAME/YOUR_GIT_REPO_ID --save +``` + +### For browser + +The library also works in the browser environment via npm and [browserify](http://browserify.org/). After following +the above steps with Node.js and installing browserify with `npm install -g browserify`, +perform the following (assuming *main.js* is your entry file): + +```shell +browserify main.js > bundle.js +``` + +Then include *bundle.js* in the HTML pages. + +## Getting Started + +Please follow the [installation](#installation) instruction and execute the following JS code: + +```javascript +var SwaggerPetstore = require('swagger-petstore'); + +var defaultClient = SwaggerPetstore.ApiClient.default; + +// Configure OAuth2 access token for authorization: petstore_auth +var petstore_auth = defaultClient.authentications['petstore_auth']; +petstore_auth.accessToken = "YOUR ACCESS TOKEN" + +var api = new SwaggerPetstore.PetApi() + +var opts = { + 'body': new SwaggerPetstore.Pet() // {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(opts, callback); + +``` + +## Documentation for API Endpoints + +All URIs are relative to *http://petstore.swagger.io/v2* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +*SwaggerPetstore.PetApi* | [**addPet**](docs/PetApi.md#addPet) | **POST** /pet | Add a new pet to the store +*SwaggerPetstore.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 +*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 +*SwaggerPetstore.PetApi* | [**findPetsByTags**](docs/PetApi.md#findPetsByTags) | **GET** /pet/findByTags | Finds Pets by tags +*SwaggerPetstore.PetApi* | [**getPetById**](docs/PetApi.md#getPetById) | **GET** /pet/{petId} | Find pet by ID +*SwaggerPetstore.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' +*SwaggerPetstore.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' +*SwaggerPetstore.PetApi* | [**updatePet**](docs/PetApi.md#updatePet) | **PUT** /pet | Update an existing pet +*SwaggerPetstore.PetApi* | [**updatePetWithForm**](docs/PetApi.md#updatePetWithForm) | **POST** /pet/{petId} | Updates a pet in the store with form data +*SwaggerPetstore.PetApi* | [**uploadFile**](docs/PetApi.md#uploadFile) | **POST** /pet/{petId}/uploadImage | uploads an image +*SwaggerPetstore.StoreApi* | [**deleteOrder**](docs/StoreApi.md#deleteOrder) | **DELETE** /store/order/{orderId} | Delete purchase order by ID +*SwaggerPetstore.StoreApi* | [**findOrdersByStatus**](docs/StoreApi.md#findOrdersByStatus) | **GET** /store/findByStatus | Finds orders by status +*SwaggerPetstore.StoreApi* | [**getInventory**](docs/StoreApi.md#getInventory) | **GET** /store/inventory | Returns pet inventories by status +*SwaggerPetstore.StoreApi* | [**getInventoryInObject**](docs/StoreApi.md#getInventoryInObject) | **GET** /store/inventory?response=arbitrary_object | Fake endpoint to test arbitrary object return by 'Get inventory' +*SwaggerPetstore.StoreApi* | [**getOrderById**](docs/StoreApi.md#getOrderById) | **GET** /store/order/{orderId} | Find purchase order by ID +*SwaggerPetstore.StoreApi* | [**placeOrder**](docs/StoreApi.md#placeOrder) | **POST** /store/order | Place an order for a pet +*SwaggerPetstore.UserApi* | [**createUser**](docs/UserApi.md#createUser) | **POST** /user | Create user +*SwaggerPetstore.UserApi* | [**createUsersWithArrayInput**](docs/UserApi.md#createUsersWithArrayInput) | **POST** /user/createWithArray | Creates list of users with given input array +*SwaggerPetstore.UserApi* | [**createUsersWithListInput**](docs/UserApi.md#createUsersWithListInput) | **POST** /user/createWithList | Creates list of users with given input array +*SwaggerPetstore.UserApi* | [**deleteUser**](docs/UserApi.md#deleteUser) | **DELETE** /user/{username} | Delete user +*SwaggerPetstore.UserApi* | [**getUserByName**](docs/UserApi.md#getUserByName) | **GET** /user/{username} | Get user by user name +*SwaggerPetstore.UserApi* | [**loginUser**](docs/UserApi.md#loginUser) | **GET** /user/login | Logs user into the system +*SwaggerPetstore.UserApi* | [**logoutUser**](docs/UserApi.md#logoutUser) | **GET** /user/logout | Logs out current logged in user session +*SwaggerPetstore.UserApi* | [**updateUser**](docs/UserApi.md#updateUser) | **PUT** /user/{username} | Updated user + + +## Documentation for Models + + - [SwaggerPetstore.Animal](docs/Animal.md) + - [SwaggerPetstore.Cat](docs/Cat.md) + - [SwaggerPetstore.Category](docs/Category.md) + - [SwaggerPetstore.Dog](docs/Dog.md) + - [SwaggerPetstore.InlineResponse200](docs/InlineResponse200.md) + - [SwaggerPetstore.Model200Response](docs/Model200Response.md) + - [SwaggerPetstore.ModelReturn](docs/ModelReturn.md) + - [SwaggerPetstore.Name](docs/Name.md) + - [SwaggerPetstore.Order](docs/Order.md) + - [SwaggerPetstore.Pet](docs/Pet.md) + - [SwaggerPetstore.SpecialModelName](docs/SpecialModelName.md) + - [SwaggerPetstore.Tag](docs/Tag.md) + - [SwaggerPetstore.User](docs/User.md) + + +## Documentation for Authorization + + +### test_api_key_header + +- **Type**: API key +- **API key parameter name**: test_api_key_header +- **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_client_secret + +- **Type**: API key +- **API key parameter name**: x-test_api_client_secret +- **Location**: HTTP header + +### test_api_client_id + +- **Type**: API key +- **API key parameter name**: x-test_api_client_id +- **Location**: HTTP header + +### test_api_key_query + +- **Type**: API key +- **API key parameter name**: test_api_key_query +- **Location**: URL query string + +### 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 + diff --git a/samples/client/petstore/javascript/docs/Animal.md b/samples/client/petstore/javascript/docs/Animal.md new file mode 100644 index 00000000000..c37d95695a0 --- /dev/null +++ b/samples/client/petstore/javascript/docs/Animal.md @@ -0,0 +1,8 @@ +# SwaggerPetstore.Animal + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**className** | **String** | | + + diff --git a/samples/client/petstore/javascript/docs/Cat.md b/samples/client/petstore/javascript/docs/Cat.md new file mode 100644 index 00000000000..8cd391bc911 --- /dev/null +++ b/samples/client/petstore/javascript/docs/Cat.md @@ -0,0 +1,8 @@ +# SwaggerPetstore.Cat + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**declawed** | **Boolean** | | [optional] + + diff --git a/samples/client/petstore/javascript/docs/Category.md b/samples/client/petstore/javascript/docs/Category.md new file mode 100644 index 00000000000..47930eb882c --- /dev/null +++ b/samples/client/petstore/javascript/docs/Category.md @@ -0,0 +1,9 @@ +# SwaggerPetstore.Category + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Integer** | | [optional] +**name** | **String** | | [optional] + + diff --git a/samples/client/petstore/javascript/docs/Dog.md b/samples/client/petstore/javascript/docs/Dog.md new file mode 100644 index 00000000000..9253eace011 --- /dev/null +++ b/samples/client/petstore/javascript/docs/Dog.md @@ -0,0 +1,8 @@ +# SwaggerPetstore.Dog + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**breed** | **String** | | [optional] + + diff --git a/samples/client/petstore/javascript/docs/InlineResponse200.md b/samples/client/petstore/javascript/docs/InlineResponse200.md new file mode 100644 index 00000000000..bbb11067e9a --- /dev/null +++ b/samples/client/petstore/javascript/docs/InlineResponse200.md @@ -0,0 +1,13 @@ +# SwaggerPetstore.InlineResponse200 + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**tags** | [**[Tag]**](Tag.md) | | [optional] +**id** | **Integer** | | +**category** | **Object** | | [optional] +**status** | **String** | pet status in the store | [optional] +**name** | **String** | | [optional] +**photoUrls** | **[String]** | | [optional] + + diff --git a/samples/client/petstore/javascript/docs/Model200Response.md b/samples/client/petstore/javascript/docs/Model200Response.md new file mode 100644 index 00000000000..cc06fcd2d18 --- /dev/null +++ b/samples/client/petstore/javascript/docs/Model200Response.md @@ -0,0 +1,8 @@ +# SwaggerPetstore.Model200Response + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **Integer** | | [optional] + + diff --git a/samples/client/petstore/javascript/docs/ModelReturn.md b/samples/client/petstore/javascript/docs/ModelReturn.md new file mode 100644 index 00000000000..88412c87197 --- /dev/null +++ b/samples/client/petstore/javascript/docs/ModelReturn.md @@ -0,0 +1,8 @@ +# SwaggerPetstore.ModelReturn + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**_return** | **Integer** | | [optional] + + diff --git a/samples/client/petstore/javascript/docs/Name.md b/samples/client/petstore/javascript/docs/Name.md new file mode 100644 index 00000000000..5086f6c5a3e --- /dev/null +++ b/samples/client/petstore/javascript/docs/Name.md @@ -0,0 +1,9 @@ +# SwaggerPetstore.Name + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **Integer** | | [optional] +**snakeCase** | **Integer** | | [optional] + + diff --git a/samples/client/petstore/javascript/docs/Order.md b/samples/client/petstore/javascript/docs/Order.md new file mode 100644 index 00000000000..b34b67d3a56 --- /dev/null +++ b/samples/client/petstore/javascript/docs/Order.md @@ -0,0 +1,13 @@ +# SwaggerPetstore.Order + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Integer** | | [optional] +**petId** | **Integer** | | [optional] +**quantity** | **Integer** | | [optional] +**shipDate** | **Date** | | [optional] +**status** | **String** | Order Status | [optional] +**complete** | **Boolean** | | [optional] + + diff --git a/samples/client/petstore/javascript/docs/Pet.md b/samples/client/petstore/javascript/docs/Pet.md new file mode 100644 index 00000000000..f1b049dcadd --- /dev/null +++ b/samples/client/petstore/javascript/docs/Pet.md @@ -0,0 +1,13 @@ +# SwaggerPetstore.Pet + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Integer** | | [optional] +**category** | [**Category**](Category.md) | | [optional] +**name** | **String** | | +**photoUrls** | **[String]** | | +**tags** | [**[Tag]**](Tag.md) | | [optional] +**status** | **String** | pet status in the store | [optional] + + diff --git a/samples/client/petstore/javascript/docs/PetApi.md b/samples/client/petstore/javascript/docs/PetApi.md new file mode 100644 index 00000000000..e33bf7c3b12 --- /dev/null +++ b/samples/client/petstore/javascript/docs/PetApi.md @@ -0,0 +1,619 @@ +# SwaggerPetstore.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 +[**addPetUsingByteArray**](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 +[**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 +[**getPetByIdInObject**](PetApi.md#getPetByIdInObject) | **GET** /pet/{petId}?response=inline_arbitrary_object | Fake endpoint to test inline arbitrary object return by 'Find pet by ID' +[**petPetIdtestingByteArraytrueGet**](PetApi.md#petPetIdtestingByteArraytrueGet) | **GET** /pet/{petId}?testing_byte_array=true | Fake endpoint to test byte array return by '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(opts) + +Add a new pet to the store + + + +### Example +```javascript +var SwaggerPetstore = require('swagger-petstore'); +var defaultClient = SwaggerPetstore.ApiClient.default; + +// Configure OAuth2 access token for authorization: petstore_auth +var petstore_auth = defaultClient.authentications['petstore_auth']; +petstore_auth.accessToken = "YOUR ACCESS TOKEN" + +var apiInstance = new SwaggerPetstore.PetApi() + +var opts = { + 'body': new SwaggerPetstore.Pet() // {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(opts, callback); +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | [optional] + +### Return type + +null (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP reuqest headers + + - **Content-Type**: application/json, application/xml + - **Accept**: application/json, application/xml + + +# **addPetUsingByteArray** +> addPetUsingByteArray(opts) + +Fake endpoint to test byte array in body parameter for adding a new pet to the store + + + +### Example +```javascript +var SwaggerPetstore = require('swagger-petstore'); +var defaultClient = SwaggerPetstore.ApiClient.default; + +// Configure OAuth2 access token for authorization: petstore_auth +var petstore_auth = defaultClient.authentications['petstore_auth']; +petstore_auth.accessToken = "YOUR ACCESS TOKEN" + +var apiInstance = new SwaggerPetstore.PetApi() + +var opts = { + 'body': "B" // {String} Pet object in the form of byte array +}; + +var callback = function(error, data, response) { + if (error) { + console.error(error); + } else { + console.log('API called successfully.'); + } +}; +api.addPetUsingByteArray(opts, callback); +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | **String**| Pet object in the form of byte array | [optional] + +### Return type + +null (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP reuqest headers + + - **Content-Type**: application/json, application/xml + - **Accept**: application/json, application/xml + + +# **deletePet** +> deletePet(petId, opts) + +Deletes a pet + + + +### Example +```javascript +var SwaggerPetstore = require('swagger-petstore'); +var defaultClient = SwaggerPetstore.ApiClient.default; + +// Configure OAuth2 access token for authorization: petstore_auth +var petstore_auth = defaultClient.authentications['petstore_auth']; +petstore_auth.accessToken = "YOUR ACCESS TOKEN" + +var apiInstance = new SwaggerPetstore.PetApi() + +var petId = 789; // {Integer} 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); +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **Integer**| Pet id to delete | + **apiKey** | **String**| | [optional] + +### Return type + +null (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + + +# **findPetsByStatus** +> [Pet] findPetsByStatus(opts) + +Finds Pets by status + +Multiple status values can be provided with comma separated strings + +### Example +```javascript +var SwaggerPetstore = require('swagger-petstore'); +var defaultClient = SwaggerPetstore.ApiClient.default; + +// Configure OAuth2 access token for authorization: petstore_auth +var petstore_auth = defaultClient.authentications['petstore_auth']; +petstore_auth.accessToken = "YOUR ACCESS TOKEN" + +var apiInstance = new SwaggerPetstore.PetApi() + +var opts = { + 'status': ["available"] // {[String]} Status values that need to be considered for query +}; + +var callback = function(error, data, response) { + if (error) { + console.error(error); + } else { + console.log('API called successfully. Returned data: ' + data); + } +}; +api.findPetsByStatus(opts, callback); +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **status** | [**[String]**](String.md)| Status values that need to be considered for query | [optional] [default to available] + +### Return type + +[**[Pet]**](Pet.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + + +# **findPetsByTags** +> [Pet] findPetsByTags(opts) + +Finds Pets by tags + +Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + +### Example +```javascript +var SwaggerPetstore = require('swagger-petstore'); +var defaultClient = SwaggerPetstore.ApiClient.default; + +// Configure OAuth2 access token for authorization: petstore_auth +var petstore_auth = defaultClient.authentications['petstore_auth']; +petstore_auth.accessToken = "YOUR ACCESS TOKEN" + +var apiInstance = new SwaggerPetstore.PetApi() + +var opts = { + 'tags': ["tags_example"] // {[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(opts, callback); +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **tags** | [**[String]**](String.md)| Tags to filter by | [optional] + +### Return type + +[**[Pet]**](Pet.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + + +# **getPetById** +> Pet getPetById(petId) + +Find pet by ID + +Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + +### Example +```javascript +var SwaggerPetstore = require('swagger-petstore'); +var defaultClient = SwaggerPetstore.ApiClient.default; + +// 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" + +// Configure OAuth2 access token for authorization: petstore_auth +var petstore_auth = defaultClient.authentications['petstore_auth']; +petstore_auth.accessToken = "YOUR ACCESS TOKEN" + +var apiInstance = new SwaggerPetstore.PetApi() + +var petId = 789; // {Integer} 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.getPetById(petId, callback); +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **Integer**| ID of pet that needs to be fetched | + +### Return type + +[**Pet**](Pet.md) + +### Authorization + +[api_key](../README.md#api_key), [petstore_auth](../README.md#petstore_auth) + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + + +# **getPetByIdInObject** +> InlineResponse200 getPetByIdInObject(petId) + +Fake endpoint to test inline arbitrary object return by 'Find pet by ID' + +Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + +### Example +```javascript +var SwaggerPetstore = require('swagger-petstore'); +var defaultClient = SwaggerPetstore.ApiClient.default; + +// 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" + +// Configure OAuth2 access token for authorization: petstore_auth +var petstore_auth = defaultClient.authentications['petstore_auth']; +petstore_auth.accessToken = "YOUR ACCESS TOKEN" + +var apiInstance = new SwaggerPetstore.PetApi() + +var petId = 789; // {Integer} 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.getPetByIdInObject(petId, callback); +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **Integer**| ID of pet that needs to be fetched | + +### Return type + +[**InlineResponse200**](InlineResponse200.md) + +### Authorization + +[api_key](../README.md#api_key), [petstore_auth](../README.md#petstore_auth) + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + + +# **petPetIdtestingByteArraytrueGet** +> 'String' petPetIdtestingByteArraytrueGet(petId) + +Fake endpoint to test byte array return by 'Find pet by ID' + +Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + +### Example +```javascript +var SwaggerPetstore = require('swagger-petstore'); +var defaultClient = SwaggerPetstore.ApiClient.default; + +// 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" + +// Configure OAuth2 access token for authorization: petstore_auth +var petstore_auth = defaultClient.authentications['petstore_auth']; +petstore_auth.accessToken = "YOUR ACCESS TOKEN" + +var apiInstance = new SwaggerPetstore.PetApi() + +var petId = 789; // {Integer} 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.petPetIdtestingByteArraytrueGet(petId, callback); +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **Integer**| ID of pet that needs to be fetched | + +### Return type + +**'String'** + +### Authorization + +[api_key](../README.md#api_key), [petstore_auth](../README.md#petstore_auth) + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + + +# **updatePet** +> updatePet(opts) + +Update an existing pet + + + +### Example +```javascript +var SwaggerPetstore = require('swagger-petstore'); +var defaultClient = SwaggerPetstore.ApiClient.default; + +// Configure OAuth2 access token for authorization: petstore_auth +var petstore_auth = defaultClient.authentications['petstore_auth']; +petstore_auth.accessToken = "YOUR ACCESS TOKEN" + +var apiInstance = new SwaggerPetstore.PetApi() + +var opts = { + 'body': new SwaggerPetstore.Pet() // {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(opts, callback); +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | [optional] + +### Return type + +null (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP reuqest headers + + - **Content-Type**: application/json, application/xml + - **Accept**: application/json, application/xml + + +# **updatePetWithForm** +> updatePetWithForm(petId, opts) + +Updates a pet in the store with form data + + + +### Example +```javascript +var SwaggerPetstore = require('swagger-petstore'); +var defaultClient = SwaggerPetstore.ApiClient.default; + +// Configure OAuth2 access token for authorization: petstore_auth +var petstore_auth = defaultClient.authentications['petstore_auth']; +petstore_auth.accessToken = "YOUR ACCESS TOKEN" + +var apiInstance = new SwaggerPetstore.PetApi() + +var petId = "petId_example"; // {String} 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); +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **String**| 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 reuqest headers + + - **Content-Type**: application/x-www-form-urlencoded + - **Accept**: application/json, application/xml + + +# **uploadFile** +> uploadFile(petId, opts) + +uploads an image + + + +### Example +```javascript +var SwaggerPetstore = require('swagger-petstore'); +var defaultClient = SwaggerPetstore.ApiClient.default; + +// Configure OAuth2 access token for authorization: petstore_auth +var petstore_auth = defaultClient.authentications['petstore_auth']; +petstore_auth.accessToken = "YOUR ACCESS TOKEN" + +var apiInstance = new SwaggerPetstore.PetApi() + +var petId = 789; // {Integer} 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.'); + } +}; +api.uploadFile(petId, opts, callback); +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **Integer**| ID of pet to update | + **additionalMetadata** | **String**| Additional data to pass to server | [optional] + **file** | **File**| file to upload | [optional] + +### Return type + +null (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP reuqest headers + + - **Content-Type**: multipart/form-data + - **Accept**: application/json, application/xml + diff --git a/samples/client/petstore/javascript/docs/SpecialModelName.md b/samples/client/petstore/javascript/docs/SpecialModelName.md new file mode 100644 index 00000000000..03dffa54c3f --- /dev/null +++ b/samples/client/petstore/javascript/docs/SpecialModelName.md @@ -0,0 +1,8 @@ +# SwaggerPetstore.SpecialModelName + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**specialPropertyName** | **Integer** | | [optional] + + diff --git a/samples/client/petstore/javascript/docs/StoreApi.md b/samples/client/petstore/javascript/docs/StoreApi.md new file mode 100644 index 00000000000..b2ea41e35ee --- /dev/null +++ b/samples/client/petstore/javascript/docs/StoreApi.md @@ -0,0 +1,333 @@ +# SwaggerPetstore.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 +[**findOrdersByStatus**](StoreApi.md#findOrdersByStatus) | **GET** /store/findByStatus | Finds orders by status +[**getInventory**](StoreApi.md#getInventory) | **GET** /store/inventory | Returns pet inventories by status +[**getInventoryInObject**](StoreApi.md#getInventoryInObject) | **GET** /store/inventory?response=arbitrary_object | Fake endpoint to test arbitrary object return by 'Get inventory' +[**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 +```javascript +var SwaggerPetstore = require('swagger-petstore'); + +var apiInstance = new SwaggerPetstore.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); +``` + +### 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 reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + + +# **findOrdersByStatus** +> [Order] findOrdersByStatus(opts) + +Finds orders by status + +A single status value can be provided as a string + +### Example +```javascript +var SwaggerPetstore = require('swagger-petstore'); +var defaultClient = SwaggerPetstore.ApiClient.default; + +// Configure API key authorization: test_api_client_id +var test_api_client_id = defaultClient.authentications['test_api_client_id']; +test_api_client_id.apiKey = "YOUR API KEY" +// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null) +//test_api_client_id.apiKeyPrefix['x-test_api_client_id'] = "Token" + +// Configure API key authorization: test_api_client_secret +var test_api_client_secret = defaultClient.authentications['test_api_client_secret']; +test_api_client_secret.apiKey = "YOUR API KEY" +// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null) +//test_api_client_secret.apiKeyPrefix['x-test_api_client_secret'] = "Token" + +var apiInstance = new SwaggerPetstore.StoreApi() + +var opts = { + 'status': "placed" // {String} Status value that needs to be considered for query +}; + +var callback = function(error, data, response) { + if (error) { + console.error(error); + } else { + console.log('API called successfully. Returned data: ' + data); + } +}; +api.findOrdersByStatus(opts, callback); +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **status** | **String**| Status value that needs to be considered for query | [optional] [default to placed] + +### Return type + +[**[Order]**](Order.md) + +### Authorization + +[test_api_client_id](../README.md#test_api_client_id), [test_api_client_secret](../README.md#test_api_client_secret) + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + + +# **getInventory** +> {'String': 'Integer'} getInventory + +Returns pet inventories by status + +Returns a map of status codes to quantities + +### Example +```javascript +var SwaggerPetstore = require('swagger-petstore'); +var defaultClient = SwaggerPetstore.ApiClient.default; + +// 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 apiInstance = new SwaggerPetstore.StoreApi() + +var callback = function(error, data, response) { + if (error) { + console.error(error); + } else { + console.log('API called successfully. Returned data: ' + data); + } +}; +api.getInventory(callback); +``` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +**{'String': 'Integer'}** + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + + +# **getInventoryInObject** +> Object getInventoryInObject + +Fake endpoint to test arbitrary object return by 'Get inventory' + +Returns an arbitrary object which is actually a map of status codes to quantities + +### Example +```javascript +var SwaggerPetstore = require('swagger-petstore'); +var defaultClient = SwaggerPetstore.ApiClient.default; + +// 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 apiInstance = new SwaggerPetstore.StoreApi() + +var callback = function(error, data, response) { + if (error) { + console.error(error); + } else { + console.log('API called successfully. Returned data: ' + data); + } +}; +api.getInventoryInObject(callback); +``` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +**Object** + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + + +# **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 +```javascript +var SwaggerPetstore = require('swagger-petstore'); +var defaultClient = SwaggerPetstore.ApiClient.default; + +// Configure API key authorization: test_api_key_header +var test_api_key_header = defaultClient.authentications['test_api_key_header']; +test_api_key_header.apiKey = "YOUR API KEY" +// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null) +//test_api_key_header.apiKeyPrefix['test_api_key_header'] = "Token" + +// Configure API key authorization: test_api_key_query +var test_api_key_query = defaultClient.authentications['test_api_key_query']; +test_api_key_query.apiKey = "YOUR API KEY" +// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null) +//test_api_key_query.apiKeyPrefix['test_api_key_query'] = "Token" + +var apiInstance = new SwaggerPetstore.StoreApi() + +var orderId = "orderId_example"; // {String} 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); +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **orderId** | **String**| ID of pet that needs to be fetched | + +### Return type + +[**Order**](Order.md) + +### Authorization + +[test_api_key_header](../README.md#test_api_key_header), [test_api_key_query](../README.md#test_api_key_query) + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + + +# **placeOrder** +> Order placeOrder(opts) + +Place an order for a pet + + + +### Example +```javascript +var SwaggerPetstore = require('swagger-petstore'); +var defaultClient = SwaggerPetstore.ApiClient.default; + +// Configure API key authorization: test_api_client_id +var test_api_client_id = defaultClient.authentications['test_api_client_id']; +test_api_client_id.apiKey = "YOUR API KEY" +// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null) +//test_api_client_id.apiKeyPrefix['x-test_api_client_id'] = "Token" + +// Configure API key authorization: test_api_client_secret +var test_api_client_secret = defaultClient.authentications['test_api_client_secret']; +test_api_client_secret.apiKey = "YOUR API KEY" +// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null) +//test_api_client_secret.apiKeyPrefix['x-test_api_client_secret'] = "Token" + +var apiInstance = new SwaggerPetstore.StoreApi() + +var opts = { + 'body': new SwaggerPetstore.Order() // {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(opts, callback); +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Order**](Order.md)| order placed for purchasing the pet | [optional] + +### Return type + +[**Order**](Order.md) + +### Authorization + +[test_api_client_id](../README.md#test_api_client_id), [test_api_client_secret](../README.md#test_api_client_secret) + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + diff --git a/samples/client/petstore/javascript/docs/Tag.md b/samples/client/petstore/javascript/docs/Tag.md new file mode 100644 index 00000000000..6c109046fb3 --- /dev/null +++ b/samples/client/petstore/javascript/docs/Tag.md @@ -0,0 +1,9 @@ +# SwaggerPetstore.Tag + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Integer** | | [optional] +**name** | **String** | | [optional] + + diff --git a/samples/client/petstore/javascript/docs/User.md b/samples/client/petstore/javascript/docs/User.md new file mode 100644 index 00000000000..071fbb46e47 --- /dev/null +++ b/samples/client/petstore/javascript/docs/User.md @@ -0,0 +1,15 @@ +# SwaggerPetstore.User + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Integer** | | [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/javascript/docs/UserApi.md b/samples/client/petstore/javascript/docs/UserApi.md new file mode 100644 index 00000000000..f2fcf2c4b52 --- /dev/null +++ b/samples/client/petstore/javascript/docs/UserApi.md @@ -0,0 +1,394 @@ +# SwaggerPetstore.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(opts) + +Create user + +This can only be done by the logged in user. + +### Example +```javascript +var SwaggerPetstore = require('swagger-petstore'); + +var apiInstance = new SwaggerPetstore.UserApi() + +var opts = { + 'body': new SwaggerPetstore.User() // {User} Created user object +}; + +var callback = function(error, data, response) { + if (error) { + console.error(error); + } else { + console.log('API called successfully.'); + } +}; +api.createUser(opts, callback); +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**User**](User.md)| Created user object | [optional] + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + + +# **createUsersWithArrayInput** +> createUsersWithArrayInput(opts) + +Creates list of users with given input array + + + +### Example +```javascript +var SwaggerPetstore = require('swagger-petstore'); + +var apiInstance = new SwaggerPetstore.UserApi() + +var opts = { + 'body': [new SwaggerPetstore.User()] // {[User]} List of user object +}; + +var callback = function(error, data, response) { + if (error) { + console.error(error); + } else { + console.log('API called successfully.'); + } +}; +api.createUsersWithArrayInput(opts, callback); +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**[User]**](User.md)| List of user object | [optional] + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + + +# **createUsersWithListInput** +> createUsersWithListInput(opts) + +Creates list of users with given input array + + + +### Example +```javascript +var SwaggerPetstore = require('swagger-petstore'); + +var apiInstance = new SwaggerPetstore.UserApi() + +var opts = { + 'body': [new SwaggerPetstore.User()] // {[User]} List of user object +}; + +var callback = function(error, data, response) { + if (error) { + console.error(error); + } else { + console.log('API called successfully.'); + } +}; +api.createUsersWithListInput(opts, callback); +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**[User]**](User.md)| List of user object | [optional] + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + + +# **deleteUser** +> deleteUser(username) + +Delete user + +This can only be done by the logged in user. + +### Example +```javascript +var SwaggerPetstore = require('swagger-petstore'); +var defaultClient = SwaggerPetstore.ApiClient.default; + +// Configure HTTP basic authorization: test_http_basic +var test_http_basic = defaultClient.authentications['test_http_basic']; +test_http_basic.username = 'YOUR USERNAME' +test_http_basic.password = 'YOUR PASSWORD' + +var apiInstance = new SwaggerPetstore.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); +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **String**| The name that needs to be deleted | + +### Return type + +null (empty response body) + +### Authorization + +[test_http_basic](../README.md#test_http_basic) + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + + +# **getUserByName** +> User getUserByName(username) + +Get user by user name + + + +### Example +```javascript +var SwaggerPetstore = require('swagger-petstore'); + +var apiInstance = new SwaggerPetstore.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); +``` + +### 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 reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + + +# **loginUser** +> 'String' loginUser(opts) + +Logs user into the system + + + +### Example +```javascript +var SwaggerPetstore = require('swagger-petstore'); + +var apiInstance = new SwaggerPetstore.UserApi() + +var opts = { + 'username': "username_example", // {String} The user name for login + '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(opts, callback); +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **String**| The user name for login | [optional] + **password** | **String**| The password for login in clear text | [optional] + +### Return type + +**'String'** + +### Authorization + +No authorization required + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + + +# **logoutUser** +> logoutUser + +Logs out current logged in user session + + + +### Example +```javascript +var SwaggerPetstore = require('swagger-petstore'); + +var apiInstance = new SwaggerPetstore.UserApi() + +var callback = function(error, data, response) { + if (error) { + console.error(error); + } else { + console.log('API called successfully.'); + } +}; +api.logoutUser(callback); +``` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + + +# **updateUser** +> updateUser(username, opts) + +Updated user + +This can only be done by the logged in user. + +### Example +```javascript +var SwaggerPetstore = require('swagger-petstore'); + +var apiInstance = new SwaggerPetstore.UserApi() + +var username = "username_example"; // {String} name that need to be deleted + +var opts = { + 'body': new SwaggerPetstore.User() // {User} Updated user object +}; + +var callback = function(error, data, response) { + if (error) { + console.error(error); + } else { + console.log('API called successfully.'); + } +}; +api.updateUser(username, opts, callback); +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **String**| name that need to be deleted | + **body** | [**User**](User.md)| Updated user object | [optional] + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + diff --git a/samples/client/petstore/javascript/git_push.sh b/samples/client/petstore/javascript/git_push.sh new file mode 100644 index 00000000000..1a36388db02 --- /dev/null +++ b/samples/client/petstore/javascript/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="YOUR_GIT_USR_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="YOUR_GIT_REPO_ID" + 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/javascript/src/ApiClient.js b/samples/client/petstore/javascript/src/ApiClient.js index ec15c154cac..71dd888d7d9 100644 --- a/samples/client/petstore/javascript/src/ApiClient.js +++ b/samples/client/petstore/javascript/src/ApiClient.js @@ -15,49 +15,78 @@ }(this, function(superagent) { 'use strict'; - var ApiClient = function ApiClient() { + /** + * @module ApiClient + * @version 1.0.0 + */ + + /** + * Manages low level client-server communications, parameter marshalling, etc. There should not be any need for an + * application to use this class directly - the *Api and model classes provide the public API for the service. The + * contents of this file should be regarded as internal but are documented for completeness. + * @alias module:ApiClient + * @class + */ + var exports = function() { /** - * The base path to put in front of every API call's (relative) path. + * The base URL against which to resolve every API call's (relative) path. + * @type {String} + * @default http://petstore.swagger.io/v2 */ this.basePath = 'http://petstore.swagger.io/v2'.replace(/\/+$/, ''); + /** + * The authentication methods to be included for all API calls. + * @type {Array.} + */ this.authentications = { - 'petstore_auth': {type: 'oauth2'}, - 'test_api_client_id': {type: 'apiKey', in: 'header', name: 'x-test_api_client_id'}, - 'test_api_client_secret': {type: 'apiKey', in: 'header', name: 'x-test_api_client_secret'}, - 'api_key': {type: 'apiKey', in: 'header', name: 'api_key'}, - 'test_api_key_query': {type: 'apiKey', in: 'query', name: 'test_api_key_query'}, - 'test_api_key_header': {type: 'apiKey', in: 'header', name: 'test_api_key_header'} + 'test_api_key_header': {type: 'apiKey', 'in': 'header', name: 'test_api_key_header'}, + 'api_key': {type: 'apiKey', 'in': 'header', name: 'api_key'}, + 'test_http_basic': {type: 'basic'}, + 'test_api_client_secret': {type: 'apiKey', 'in': 'header', name: 'x-test_api_client_secret'}, + 'test_api_client_id': {type: 'apiKey', 'in': 'header', name: 'x-test_api_client_id'}, + 'test_api_key_query': {type: 'apiKey', 'in': 'query', name: 'test_api_key_query'}, + 'petstore_auth': {type: 'oauth2'} }; /** * The default HTTP headers to be included for all API calls. + * @type {Array.} + * @default {} */ this.defaultHeaders = {}; /** * The default HTTP timeout for all API calls. + * @type {Number} + * @default 60000 */ this.timeout = 60000; }; - ApiClient.prototype.paramToString = function paramToString(param) { - if (param == null) { - // return empty string for null and undefined + /** + * Returns a string representation for an actual parameter. + * @param param The actual parameter. + * @returns {String} The string representation of param. + */ + exports.prototype.paramToString = function(param) { + if (param == undefined || param == null) { return ''; - } else if (param instanceof Date) { - return param.toJSON(); - } else { - return param.toString(); } + if (param instanceof Date) { + return param.toJSON(); + } + return param.toString(); }; /** - * Build full URL by appending the given path to base path and replacing - * path parameter placeholders with parameter values. + * Builds full URL by appending the given path to the base URL and replacing path parameter place-holders with parameter values. * NOTE: query parameters are not handled here. + * @param {String} path The path to append to the base URL. + * @param {Object} pathParams The parameter values to append. + * @returns {String} The encoded path with parameter values substituted. */ - ApiClient.prototype.buildUrl = function buildUrl(path, pathParams) { + exports.prototype.buildUrl = function(path, pathParams) { if (!path.match(/^\//)) { path = '/' + path; } @@ -76,34 +105,40 @@ }; /** - * Check if the given MIME is a JSON MIME. - * JSON MIME examples: - * application/json - * application/json; charset=UTF8 - * APPLICATION/JSON + * Checks whether the given content type represents JSON.
+ * JSON content type examples:
+ *
    + *
  • application/json
  • + *
  • application/json; charset=UTF8
  • + *
  • APPLICATION/JSON
  • + *
+ * @param {String} contentType The MIME content type to check. + * @returns {Boolean} true if contentType represents JSON, otherwise false. */ - ApiClient.prototype.isJsonMime = function isJsonMime(mime) { - return Boolean(mime != null && mime.match(/^application\/json(;.*)?$/i)); + exports.prototype.isJsonMime = function(contentType) { + return Boolean(contentType != null && contentType.match(/^application\/json(;.*)?$/i)); }; /** - * Choose a MIME from the given MIMEs with JSON preferred, - * i.e. return JSON if included, otherwise return the first one. + * Chooses a content type from the given array, with JSON preferred; i.e. return JSON if included, otherwise return the first. + * @param {Array.} contentTypes + * @returns {String} The chosen content type, preferring JSON. */ - ApiClient.prototype.jsonPreferredMime = function jsonPreferredMime(mimes) { - var len = mimes.length; - for (var i = 0; i < len; i++) { - if (this.isJsonMime(mimes[i])) { - return mimes[i]; + exports.prototype.jsonPreferredMime = function(contentTypes) { + for (var i = 0; i < contentTypes.length; i++) { + if (this.isJsonMime(contentTypes[i])) { + return contentTypes[i]; } } - return mimes[0]; + return contentTypes[0]; }; /** - * Check if the given parameter value is like file content. + * Checks whether the given parameter value represents file-like content. + * @param param The parameter to check. + * @returns {Boolean} true if param represents a file. */ - ApiClient.prototype.isFileParam = function isFileParam(param) { + exports.prototype.isFileParam = function(param) { // fs.ReadStream in Node.js (but not in runtime like browserify) if (typeof window === 'undefined' && typeof require === 'function' && @@ -127,15 +162,19 @@ }; /** - * Normalize parameters values: - * remove nils, - * keep files and arrays, - * format to string with `paramToString` for other cases. + * Normalizes parameter values: + *
    + *
  • remove nils
  • + *
  • keep files and arrays
  • + *
  • format to string with `paramToString` for other cases
  • + *
+ * @param {Object.} params The parameters as object properties. + * @returns {Object.} normalized parameters. */ - ApiClient.prototype.normalizeParams = function normalizeParams(params) { + exports.prototype.normalizeParams = function(params) { var newParams = {}; for (var key in params) { - if (params.hasOwnProperty(key) && params[key] != null) { + if (params.hasOwnProperty(key) && params[key] != undefined && params[key] != null) { var value = params[key]; if (this.isFileParam(value) || Array.isArray(value)) { newParams[key] = value; @@ -148,10 +187,46 @@ }; /** - * Build parameter value according to the given collection format. - * @param {String} collectionFormat one of 'csv', 'ssv', 'tsv', 'pipes' and 'multi' + * Enumeration of collection format separator strategies. + * @enum {String} + * @readonly */ - ApiClient.prototype.buildCollectionParam = function buildCollectionParam(param, collectionFormat) { + exports.CollectionFormatEnum = { + /** + * Comma-separated values. Value: csv + * @const + */ + CSV: ',', + /** + * Space-separated values. Value: ssv + * @const + */ + SSV: ' ', + /** + * Tab-separated values. Value: tsv + * @const + */ + TSV: '\t', + /** + * Pipe(|)-separated values. Value: pipes + * @const + */ + PIPES: '|', + /** + * Native array. Value: multi + * @const + */ + MULTI: 'multi' + }; + + /** + * Builds a string representation of an array-type actual parameter, according to the given collection format. + * @param {Array} param An array parameter. + * @param {module:ApiClient.CollectionFormatEnum} collectionFormat The array element separator strategy. + * @returns {String|Array} A string representation of the supplied collection, using the specified delimiter. Returns + * param as is if collectionFormat is multi. + */ + exports.prototype.buildCollectionParam = function buildCollectionParam(param, collectionFormat) { if (param == null) { return null; } @@ -165,14 +240,19 @@ case 'pipes': return param.map(this.paramToString).join('|'); case 'multi': - // return the array directly as Superagent will handle it as expected + // return the array directly as SuperAgent will handle it as expected return param.map(this.paramToString); default: throw new Error('Unknown collection format: ' + collectionFormat); } }; - ApiClient.prototype.applyAuthToRequest = function applyAuthToRequest(request, authNames) { + /** + * Applies authentication headers to the request. + * @param {Object} request The request object created by a superagent() call. + * @param {Array.} authNames An array of authentication method names. + */ + exports.prototype.applyAuthToRequest = function(request, authNames) { var _this = this; authNames.forEach(function(authName) { var auth = _this.authentications[authName]; @@ -190,7 +270,7 @@ } else { data[auth.name] = auth.apiKey; } - if (auth.in === 'header') { + if (auth['in'] === 'header') { request.set(data); } else { request.query(data); @@ -208,24 +288,58 @@ }); }; - ApiClient.prototype.deserialize = function deserialize(response, returnType) { + /** + * Deserializes an HTTP response body into a value of the specified type. + * @param {Object} response A SuperAgent response object. + * @param {(String|Array.|Object.|Function)} returnType The type to return. Pass a string for simple types + * or the constructor function for a complex type. Pass an array containing the type name to return an array of that type. To + * return an object, pass an object with one property whose name is the key type and whose value is the corresponding value type: + * all properties on data will be converted to this type. + * @returns A value of the specified type. + */ + exports.prototype.deserialize = function deserialize(response, returnType) { if (response == null || returnType == null) { return null; } - // Rely on Superagent for parsing response body. + // Rely on SuperAgent for parsing response body. // See http://visionmedia.github.io/superagent/#parsing-response-bodies var data = response.body; if (data == null) { - // Superagent does not always produce a body; use the unparsed response - // as a fallback + // SuperAgent does not always produce a body; use the unparsed response as a fallback data = response.text; } - return ApiClient.convertToType(data, returnType); + return exports.convertToType(data, returnType); }; - ApiClient.prototype.callApi = function callApi(path, httpMethod, pathParams, - queryParams, headerParams, formParams, bodyParam, authNames, contentTypes, - accepts, returnType, callback) { + /** + * Callback function to receive the result of the operation. + * @callback module:ApiClient~callApiCallback + * @param {String} error Error message, if any. + * @param data The data returned by the service call. + * @param {String} response The complete HTTP response. + */ + + /** + * Invokes the REST service using the supplied settings and parameters. + * @param {String} path The base URL to invoke. + * @param {String} httpMethod The HTTP method to use. + * @param {Object.} pathParams A map of path parameters and their values. + * @param {Object.} queryParams A map of query parameters and their values. + * @param {Object.} headerParams A map of header parameters and their values. + * @param {Object.} formParams A map of form parameters and their values. + * @param {Object} bodyParam The value to pass as the request body. + * @param {Array.} authNames An array of authentication type names. + * @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. + * @param {module:ApiClient~callApiCallback} callback The callback function. + * @returns {Object} The SuperAgent request object. + */ + exports.prototype.callApi = function callApi(path, httpMethod, pathParams, + queryParams, headerParams, formParams, bodyParam, authNames, contentTypes, accepts, + returnType, callback) { + var _this = this; var url = this.buildUrl(path, pathParams); var request = superagent(httpMethod, url); @@ -239,7 +353,7 @@ // set header parameters request.set(this.defaultHeaders).set(this.normalizeParams(headerParams)); - //set request timeout + // set request timeout request.timeout(this.timeout); var contentType = this.jsonPreferredMime(contentTypes); @@ -272,8 +386,7 @@ request.accept(accept); } - - + request.end(function(error, response) { if (callback) { var data = null; @@ -285,15 +398,27 @@ }); return request; - }; - ApiClient.parseDate = function parseDate(str) { - str = str.replace(/T/i, ' '); - return new Date(str); + /** + * Parses an ISO-8601 string representation of a date value. + * @param {String} str The date value as a string. + * @returns {Date} The parsed date object. + */ + exports.parseDate = function(str) { + return new Date(str.replace(/T/i, ' ')); }; - ApiClient.convertToType = function convertToType(data, type) { + /** + * Converts a value to the specified type. + * @param {(String|Object)} data The data to convert, as a string or object. + * @param {(String|Array.|Object.|Function)} type The type to return. Pass a string for simple types + * or the constructor function for a complex type. Pass an array containing the type name to return an array of that type. To + * return an object, pass an object with one property whose name is the key type and whose value is the corresponding value type: + * all properties on data will be converted to this type. + * @returns An instance of the specified type. + */ + exports.convertToType = function(data, type) { switch (type) { case 'Boolean': return Boolean(data); @@ -311,13 +436,12 @@ return data; } else if (typeof type === 'function') { // for model type like: User - var model = type.constructFromObject(data); - return model; + return type.constructFromObject(data); } else if (Array.isArray(type)) { // for array type like: ['String'] var itemType = type[0]; return data.map(function(item) { - return ApiClient.convertToType(item, itemType); + return exports.convertToType(item, itemType); }); } else if (typeof type === 'object') { // for plain object type like: {'String': 'Integer'} @@ -332,8 +456,8 @@ var result = {}; for (var k in data) { if (data.hasOwnProperty(k)) { - var key = ApiClient.convertToType(k, keyType); - var value = ApiClient.convertToType(data[k], valueType); + var key = exports.convertToType(k, keyType); + var value = exports.convertToType(data[k], valueType); result[key] = value; } } @@ -345,7 +469,11 @@ } }; - ApiClient.default = new ApiClient(); + /** + * The default API client implementation. + * @type {module:ApiClient} + */ + exports.instance = new exports(); - return ApiClient; + return exports; })); diff --git a/samples/client/petstore/javascript/src/api/PetApi.js b/samples/client/petstore/javascript/src/api/PetApi.js index 5602b383da8..3bfc6ffd4f0 100644 --- a/samples/client/petstore/javascript/src/api/PetApi.js +++ b/samples/client/petstore/javascript/src/api/PetApi.js @@ -15,55 +15,42 @@ }(this, function(ApiClient, Pet, InlineResponse200) { 'use strict'; - var PetApi = function PetApi(apiClient) { - this.apiClient = apiClient || ApiClient.default; + /** + * Pet service. + * @module api/PetApi + * @version 1.0.0 + */ + + /** + * Constructs a new PetApi. + * @alias module:api/PetApi + * @class + * @param {module:ApiClient} apiClient Optional API client implementation to use, default to {@link module:ApiClient#instance} + * if unspecified. + */ + var exports = function(apiClient) { + this.apiClient = apiClient || ApiClient.instance; + - var self = this; - - /** - * Update an existing pet - * - * @param {Pet} opts['body'] Pet object that needs to be added to the store - * @param {function} callback the callback function, accepting three arguments: error, data, response + * Callback function to receive the result of the addPet operation. + * @callback module:api/PetApi~addPetCallback + * @param {String} error Error message, if any. + * @param data This operation does not return a value. + * @param {String} response The complete HTTP response. */ - self.updatePet = function(opts, callback) { - opts = opts || {}; - var postBody = opts['body']; - - var pathParams = { - }; - var queryParams = { - }; - var headerParams = { - }; - var formParams = { - }; - - var authNames = ['petstore_auth']; - var contentTypes = ['application/json', 'application/xml']; - var accepts = ['application/json', 'application/xml']; - var returnType = null; - - return this.apiClient.callApi( - '/pet', 'PUT', - pathParams, queryParams, headerParams, formParams, postBody, - authNames, contentTypes, accepts, returnType, callback - ); - - } - /** * Add a new pet to the store * - * @param {Pet} opts['body'] Pet object that needs to be added to the store - * @param {function} callback the callback function, accepting three arguments: error, data, response + * @param {Object} opts Optional parameters + * @param {module:model/Pet} opts.body Pet object that needs to be added to the store + * @param {module:api/PetApi~addPetCallback} callback The callback function, accepting three arguments: error, data, response */ - self.addPet = function(opts, callback) { + this.addPet = function(opts, callback) { opts = opts || {}; var postBody = opts['body']; - + var pathParams = { }; @@ -84,20 +71,118 @@ pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType, callback ); - } - + + /** + * Callback function to receive the result of the addPetUsingByteArray operation. + * @callback module:api/PetApi~addPetUsingByteArrayCallback + * @param {String} error Error message, if any. + * @param data This operation does not return a value. + * @param {String} response The complete HTTP response. + */ + + /** + * Fake endpoint to test byte array in body parameter for adding a new pet to the store + * + * @param {Object} opts Optional parameters + * @param {String} opts.body Pet object in the form of byte array + * @param {module:api/PetApi~addPetUsingByteArrayCallback} callback The callback function, accepting three arguments: error, data, response + */ + this.addPetUsingByteArray = function(opts, callback) { + opts = opts || {}; + var postBody = opts['body']; + + + var pathParams = { + }; + var queryParams = { + }; + var headerParams = { + }; + var formParams = { + }; + + var authNames = ['petstore_auth']; + var contentTypes = ['application/json', 'application/xml']; + var accepts = ['application/json', 'application/xml']; + var returnType = null; + + return this.apiClient.callApi( + '/pet?testing_byte_array=true', 'POST', + pathParams, queryParams, headerParams, formParams, postBody, + authNames, contentTypes, accepts, returnType, callback + ); + } + + /** + * Callback function to receive the result of the deletePet operation. + * @callback module:api/PetApi~deletePetCallback + * @param {String} error Error message, if any. + * @param data This operation does not return a value. + * @param {String} response The complete HTTP response. + */ + + /** + * Deletes a pet + * + * @param {Integer} 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 + */ + this.deletePet = function(petId, opts, callback) { + opts = opts || {}; + var postBody = null; + + // verify the required parameter 'petId' is set + if (petId == undefined || petId == null) { + throw "Missing the required parameter 'petId' when calling deletePet"; + } + + + var pathParams = { + 'petId': petId + }; + var queryParams = { + }; + var headerParams = { + 'api_key': opts['apiKey'] + }; + var formParams = { + }; + + var authNames = ['petstore_auth']; + var contentTypes = []; + var accepts = ['application/json', 'application/xml']; + var returnType = null; + + return this.apiClient.callApi( + '/pet/{petId}', 'DELETE', + pathParams, queryParams, headerParams, formParams, postBody, + authNames, contentTypes, accepts, returnType, callback + ); + } + + /** + * Callback function to receive the result of the findPetsByStatus operation. + * @callback module:api/PetApi~findPetsByStatusCallback + * @param {String} error Error message, if any. + * @param {Array.} data The data returned by the service call. + * @param {String} response The complete HTTP response. + */ + /** * Finds Pets by status * Multiple status values can be provided with comma separated strings - * @param {[String]} opts['status'] Status values that need to be considered for query - * @param {function} callback the callback function, accepting three arguments: error, data, response - * data is of type: [Pet] + * @param {Object} opts Optional parameters + * @param {Array.} opts.status Status values that need to be considered for query (default to available) + * @param {module:api/PetApi~findPetsByStatusCallback} callback The callback function, accepting three arguments: error, data, response + * data is of type: {Array.} */ - self.findPetsByStatus = function(opts, callback) { + this.findPetsByStatus = function(opts, callback) { opts = opts || {}; var postBody = null; - + var pathParams = { }; @@ -119,20 +204,28 @@ pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType, callback ); - } - + + /** + * Callback function to receive the result of the findPetsByTags operation. + * @callback module:api/PetApi~findPetsByTagsCallback + * @param {String} error Error message, if any. + * @param {Array.} data The data returned by the service call. + * @param {String} response The complete HTTP response. + */ + /** * Finds Pets by tags * Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. - * @param {[String]} opts['tags'] Tags to filter by - * @param {function} callback the callback function, accepting three arguments: error, data, response - * data is of type: [Pet] + * @param {Object} opts Optional parameters + * @param {Array.} opts.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.} */ - self.findPetsByTags = function(opts, callback) { + this.findPetsByTags = function(opts, callback) { opts = opts || {}; var postBody = null; - + var pathParams = { }; @@ -154,24 +247,31 @@ pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType, callback ); - } - + + /** + * Callback function to receive the result of the getPetById operation. + * @callback module:api/PetApi~getPetByIdCallback + * @param {String} error Error message, if any. + * @param {module:model/Pet} data The data returned by the service call. + * @param {String} response The complete HTTP response. + */ + /** * Find pet by ID * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions * @param {Integer} petId ID of pet that needs to be fetched - * @param {function} callback the callback function, accepting three arguments: error, data, response - * data is of type: Pet + * @param {module:api/PetApi~getPetByIdCallback} callback The callback function, accepting three arguments: error, data, response + * data is of type: {module:model/Pet} */ - self.getPetById = function(petId, callback) { + this.getPetById = function(petId, callback) { var postBody = null; - + // verify the required parameter 'petId' is set - if (petId == null) { + if (petId == undefined || petId == null) { throw "Missing the required parameter 'petId' when calling getPetById"; } - + var pathParams = { 'petId': petId @@ -183,7 +283,7 @@ var formParams = { }; - var authNames = ['petstore_auth', 'api_key']; + var authNames = ['api_key', 'petstore_auth']; var contentTypes = []; var accepts = ['application/json', 'application/xml']; var returnType = Pet; @@ -193,26 +293,167 @@ pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType, callback ); - } - + + /** + * Callback function to receive the result of the getPetByIdInObject operation. + * @callback module:api/PetApi~getPetByIdInObjectCallback + * @param {String} error Error message, if any. + * @param {module:model/InlineResponse200} data The data returned by the service call. + * @param {String} response The complete HTTP response. + */ + + /** + * Fake endpoint to test inline arbitrary object return by 'Find pet by ID' + * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + * @param {Integer} petId ID of pet that needs to be fetched + * @param {module:api/PetApi~getPetByIdInObjectCallback} callback The callback function, accepting three arguments: error, data, response + * data is of type: {module:model/InlineResponse200} + */ + this.getPetByIdInObject = function(petId, callback) { + var postBody = null; + + // verify the required parameter 'petId' is set + if (petId == undefined || petId == null) { + throw "Missing the required parameter 'petId' when calling getPetByIdInObject"; + } + + + var pathParams = { + 'petId': petId + }; + var queryParams = { + }; + var headerParams = { + }; + var formParams = { + }; + + var authNames = ['api_key', 'petstore_auth']; + var contentTypes = []; + var accepts = ['application/json', 'application/xml']; + var returnType = InlineResponse200; + + return this.apiClient.callApi( + '/pet/{petId}?response=inline_arbitrary_object', 'GET', + pathParams, queryParams, headerParams, formParams, postBody, + authNames, contentTypes, accepts, returnType, callback + ); + } + + /** + * Callback function to receive the result of the petPetIdtestingByteArraytrueGet operation. + * @callback module:api/PetApi~petPetIdtestingByteArraytrueGetCallback + * @param {String} error Error message, if any. + * @param {'String'} data The data returned by the service call. + * @param {String} response The complete HTTP response. + */ + + /** + * Fake endpoint to test byte array return by 'Find pet by ID' + * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + * @param {Integer} petId ID of pet that needs to be fetched + * @param {module:api/PetApi~petPetIdtestingByteArraytrueGetCallback} callback The callback function, accepting three arguments: error, data, response + * data is of type: {'String'} + */ + this.petPetIdtestingByteArraytrueGet = function(petId, callback) { + var postBody = null; + + // verify the required parameter 'petId' is set + if (petId == undefined || petId == null) { + throw "Missing the required parameter 'petId' when calling petPetIdtestingByteArraytrueGet"; + } + + + var pathParams = { + 'petId': petId + }; + var queryParams = { + }; + var headerParams = { + }; + var formParams = { + }; + + var authNames = ['api_key', 'petstore_auth']; + var contentTypes = []; + var accepts = ['application/json', 'application/xml']; + var returnType = 'String'; + + return this.apiClient.callApi( + '/pet/{petId}?testing_byte_array=true', 'GET', + pathParams, queryParams, headerParams, formParams, postBody, + authNames, contentTypes, accepts, returnType, callback + ); + } + + /** + * Callback function to receive the result of the updatePet operation. + * @callback module:api/PetApi~updatePetCallback + * @param {String} error Error message, if any. + * @param data This operation does not return a value. + * @param {String} response The complete HTTP response. + */ + + /** + * Update an existing pet + * + * @param {Object} opts Optional parameters + * @param {module:model/Pet} opts.body Pet object that needs to be added to the store + * @param {module:api/PetApi~updatePetCallback} callback The callback function, accepting three arguments: error, data, response + */ + this.updatePet = function(opts, callback) { + opts = opts || {}; + var postBody = opts['body']; + + + var pathParams = { + }; + var queryParams = { + }; + var headerParams = { + }; + var formParams = { + }; + + var authNames = ['petstore_auth']; + var contentTypes = ['application/json', 'application/xml']; + var accepts = ['application/json', 'application/xml']; + var returnType = null; + + return this.apiClient.callApi( + '/pet', 'PUT', + pathParams, queryParams, headerParams, formParams, postBody, + authNames, contentTypes, accepts, returnType, callback + ); + } + + /** + * Callback function to receive the result of the updatePetWithForm operation. + * @callback module:api/PetApi~updatePetWithFormCallback + * @param {String} error Error message, if any. + * @param data This operation does not return a value. + * @param {String} response The complete HTTP response. + */ + /** * Updates a pet in the store with form data * * @param {String} petId ID of pet that needs to be updated - * @param {String} opts['name'] Updated name of the pet - * @param {String} opts['status'] Updated status of the pet - * @param {function} callback the callback function, accepting three arguments: error, data, response + * @param {Object} opts Optional parameters + * @param {String} opts.name Updated name of the pet + * @param {String} opts.status Updated status of the pet + * @param {module:api/PetApi~updatePetWithFormCallback} callback The callback function, accepting three arguments: error, data, response */ - self.updatePetWithForm = function(petId, opts, callback) { + this.updatePetWithForm = function(petId, opts, callback) { opts = opts || {}; var postBody = null; - + // verify the required parameter 'petId' is set - if (petId == null) { + if (petId == undefined || petId == null) { throw "Missing the required parameter 'petId' when calling updatePetWithForm"; } - + var pathParams = { 'petId': petId @@ -236,67 +477,34 @@ pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType, callback ); - } - + /** - * Deletes a pet - * - * @param {Integer} petId Pet id to delete - * @param {String} opts['apiKey'] - * @param {function} callback the callback function, accepting three arguments: error, data, response + * Callback function to receive the result of the uploadFile operation. + * @callback module:api/PetApi~uploadFileCallback + * @param {String} error Error message, if any. + * @param data This operation does not return a value. + * @param {String} response The complete HTTP response. */ - self.deletePet = function(petId, opts, callback) { - opts = opts || {}; - var postBody = null; - - // verify the required parameter 'petId' is set - if (petId == null) { - throw "Missing the required parameter 'petId' when calling deletePet"; - } - - var pathParams = { - 'petId': petId - }; - var queryParams = { - }; - var headerParams = { - 'api_key': opts['apiKey'] - }; - var formParams = { - }; - - var authNames = ['petstore_auth']; - var contentTypes = []; - var accepts = ['application/json', 'application/xml']; - var returnType = null; - - return this.apiClient.callApi( - '/pet/{petId}', 'DELETE', - pathParams, queryParams, headerParams, formParams, postBody, - authNames, contentTypes, accepts, returnType, callback - ); - - } - /** * uploads an image * * @param {Integer} petId ID of pet to update - * @param {String} opts['additionalMetadata'] Additional data to pass to server - * @param {File} opts['file'] file to upload - * @param {function} callback the callback function, accepting three arguments: error, data, response + * @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 */ - self.uploadFile = function(petId, opts, callback) { + this.uploadFile = function(petId, opts, callback) { opts = opts || {}; var postBody = null; - + // verify the required parameter 'petId' is set - if (petId == null) { + if (petId == undefined || petId == null) { throw "Missing the required parameter 'petId' when calling uploadFile"; } - + var pathParams = { 'petId': petId @@ -320,122 +528,8 @@ pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType, callback ); - } - - /** - * Fake endpoint to test inline arbitrary object return by 'Find pet by ID' - * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions - * @param {Integer} petId ID of pet that needs to be fetched - * @param {function} callback the callback function, accepting three arguments: error, data, response - * data is of type: InlineResponse200 - */ - self.getPetByIdInObject = function(petId, callback) { - var postBody = null; - - // verify the required parameter 'petId' is set - if (petId == null) { - throw "Missing the required parameter 'petId' when calling getPetByIdInObject"; - } - - - var pathParams = { - 'petId': petId - }; - var queryParams = { - }; - var headerParams = { - }; - var formParams = { - }; - - var authNames = ['petstore_auth', 'api_key']; - var contentTypes = []; - var accepts = ['application/json', 'application/xml']; - var returnType = InlineResponse200; - - return this.apiClient.callApi( - '/pet/{petId}?response=inline_arbitrary_object', 'GET', - pathParams, queryParams, headerParams, formParams, postBody, - authNames, contentTypes, accepts, returnType, callback - ); - - } - - /** - * Fake endpoint to test byte array return by 'Find pet by ID' - * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions - * @param {Integer} petId ID of pet that needs to be fetched - * @param {function} callback the callback function, accepting three arguments: error, data, response - * data is of type: 'String' - */ - self.petPetIdtestingByteArraytrueGet = function(petId, callback) { - var postBody = null; - - // verify the required parameter 'petId' is set - if (petId == null) { - throw "Missing the required parameter 'petId' when calling petPetIdtestingByteArraytrueGet"; - } - - - var pathParams = { - 'petId': petId - }; - var queryParams = { - }; - var headerParams = { - }; - var formParams = { - }; - - var authNames = ['petstore_auth', 'api_key']; - var contentTypes = []; - var accepts = ['application/json', 'application/xml']; - var returnType = 'String'; - - return this.apiClient.callApi( - '/pet/{petId}?testing_byte_array=true', 'GET', - pathParams, queryParams, headerParams, formParams, postBody, - authNames, contentTypes, accepts, returnType, callback - ); - - } - - /** - * Fake endpoint to test byte array in body parameter for adding a new pet to the store - * - * @param {String} opts['body'] Pet object in the form of byte array - * @param {function} callback the callback function, accepting three arguments: error, data, response - */ - self.addPetUsingByteArray = function(opts, callback) { - opts = opts || {}; - var postBody = opts['body']; - - - var pathParams = { - }; - var queryParams = { - }; - var headerParams = { - }; - var formParams = { - }; - - var authNames = ['petstore_auth']; - var contentTypes = ['application/json', 'application/xml']; - var accepts = ['application/json', 'application/xml']; - var returnType = null; - - return this.apiClient.callApi( - '/pet?testing_byte_array=true', 'POST', - pathParams, queryParams, headerParams, formParams, postBody, - authNames, contentTypes, accepts, returnType, callback - ); - - } - - }; - return PetApi; + return exports; })); diff --git a/samples/client/petstore/javascript/src/api/StoreApi.js b/samples/client/petstore/javascript/src/api/StoreApi.js index a1e99293f8d..bcef8b433c1 100644 --- a/samples/client/petstore/javascript/src/api/StoreApi.js +++ b/samples/client/petstore/javascript/src/api/StoreApi.js @@ -15,198 +15,45 @@ }(this, function(ApiClient, Order) { 'use strict'; - var StoreApi = function StoreApi(apiClient) { - this.apiClient = apiClient || ApiClient.default; + /** + * Store service. + * @module api/StoreApi + * @version 1.0.0 + */ + + /** + * Constructs a new StoreApi. + * @alias module:api/StoreApi + * @class + * @param {module:ApiClient} apiClient Optional API client implementation to use, default to {@link module:ApiClient#instance} + * if unspecified. + */ + var exports = function(apiClient) { + this.apiClient = apiClient || ApiClient.instance; + - var self = this; - - /** - * Finds orders by status - * A single status value can be provided as a string - * @param {String} opts['status'] Status value that needs to be considered for query - * @param {function} callback the callback function, accepting three arguments: error, data, response - * data is of type: [Order] + * Callback function to receive the result of the deleteOrder operation. + * @callback module:api/StoreApi~deleteOrderCallback + * @param {String} error Error message, if any. + * @param data This operation does not return a value. + * @param {String} response The complete HTTP response. */ - self.findOrdersByStatus = function(opts, callback) { - opts = opts || {}; - var postBody = null; - - var pathParams = { - }; - var queryParams = { - 'status': opts['status'] - }; - var headerParams = { - }; - var formParams = { - }; - - var authNames = ['test_api_client_id', 'test_api_client_secret']; - var contentTypes = []; - var accepts = ['application/json', 'application/xml']; - var returnType = [Order]; - - return this.apiClient.callApi( - '/store/findByStatus', 'GET', - pathParams, queryParams, headerParams, formParams, postBody, - authNames, contentTypes, accepts, returnType, callback - ); - - } - - /** - * Returns pet inventories by status - * Returns a map of status codes to quantities - * @param {function} callback the callback function, accepting three arguments: error, data, response - * data is of type: {'String': 'Integer'} - */ - self.getInventory = function(callback) { - var postBody = null; - - - var pathParams = { - }; - var queryParams = { - }; - var headerParams = { - }; - var formParams = { - }; - - var authNames = ['api_key']; - var contentTypes = []; - var accepts = ['application/json', 'application/xml']; - var returnType = {'String': 'Integer'}; - - return this.apiClient.callApi( - '/store/inventory', 'GET', - pathParams, queryParams, headerParams, formParams, postBody, - authNames, contentTypes, accepts, returnType, callback - ); - - } - - /** - * Fake endpoint to test arbitrary object return by 'Get inventory' - * Returns an arbitrary object which is actually a map of status codes to quantities - * @param {function} callback the callback function, accepting three arguments: error, data, response - * data is of type: Object - */ - self.getInventoryInObject = function(callback) { - var postBody = null; - - - var pathParams = { - }; - var queryParams = { - }; - var headerParams = { - }; - var formParams = { - }; - - var authNames = ['api_key']; - var contentTypes = []; - var accepts = ['application/json', 'application/xml']; - var returnType = Object; - - return this.apiClient.callApi( - '/store/inventory?response=arbitrary_object', 'GET', - pathParams, queryParams, headerParams, formParams, postBody, - authNames, contentTypes, accepts, returnType, callback - ); - - } - - /** - * Place an order for a pet - * - * @param {Order} opts['body'] order placed for purchasing the pet - * @param {function} callback the callback function, accepting three arguments: error, data, response - * data is of type: Order - */ - self.placeOrder = function(opts, callback) { - opts = opts || {}; - var postBody = opts['body']; - - - var pathParams = { - }; - var queryParams = { - }; - var headerParams = { - }; - var formParams = { - }; - - var authNames = ['test_api_client_id', 'test_api_client_secret']; - var contentTypes = []; - var accepts = ['application/json', 'application/xml']; - var returnType = Order; - - return this.apiClient.callApi( - '/store/order', 'POST', - pathParams, queryParams, headerParams, formParams, postBody, - authNames, contentTypes, accepts, returnType, callback - ); - - } - - /** - * Find purchase order by ID - * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - * @param {String} orderId ID of pet that needs to be fetched - * @param {function} callback the callback function, accepting three arguments: error, data, response - * data is of type: Order - */ - self.getOrderById = function(orderId, callback) { - var postBody = null; - - // verify the required parameter 'orderId' is set - if (orderId == null) { - throw "Missing the required parameter 'orderId' when calling getOrderById"; - } - - - var pathParams = { - 'orderId': orderId - }; - var queryParams = { - }; - var headerParams = { - }; - var formParams = { - }; - - var authNames = ['test_api_key_query', 'test_api_key_header']; - var contentTypes = []; - var accepts = ['application/json', 'application/xml']; - var returnType = Order; - - return this.apiClient.callApi( - '/store/order/{orderId}', 'GET', - pathParams, queryParams, headerParams, formParams, postBody, - authNames, contentTypes, accepts, returnType, callback - ); - - } - /** * 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 {function} callback the callback function, accepting three arguments: error, data, response + * @param {module:api/StoreApi~deleteOrderCallback} callback The callback function, accepting three arguments: error, data, response */ - self.deleteOrder = function(orderId, callback) { + this.deleteOrder = function(orderId, callback) { var postBody = null; - + // verify the required parameter 'orderId' is set - if (orderId == null) { + if (orderId == undefined || orderId == null) { throw "Missing the required parameter 'orderId' when calling deleteOrder"; } - + var pathParams = { 'orderId': orderId @@ -228,11 +75,217 @@ pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType, callback ); - } - - + + /** + * Callback function to receive the result of the findOrdersByStatus operation. + * @callback module:api/StoreApi~findOrdersByStatusCallback + * @param {String} error Error message, if any. + * @param {Array.} data The data returned by the service call. + * @param {String} response The complete HTTP response. + */ + + /** + * Finds orders by status + * A single status value can be provided as a string + * @param {Object} opts Optional parameters + * @param {module:model/String} opts.status Status value that needs to be considered for query (default to placed) + * @param {module:api/StoreApi~findOrdersByStatusCallback} callback The callback function, accepting three arguments: error, data, response + * data is of type: {Array.} + */ + this.findOrdersByStatus = function(opts, callback) { + opts = opts || {}; + var postBody = null; + + + var pathParams = { + }; + var queryParams = { + 'status': opts['status'] + }; + var headerParams = { + }; + var formParams = { + }; + + var authNames = ['test_api_client_id', 'test_api_client_secret']; + var contentTypes = []; + var accepts = ['application/json', 'application/xml']; + var returnType = [Order]; + + return this.apiClient.callApi( + '/store/findByStatus', 'GET', + pathParams, queryParams, headerParams, formParams, postBody, + authNames, contentTypes, accepts, returnType, callback + ); + } + + /** + * 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 {String} response The complete HTTP response. + */ + + /** + * 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.} + */ + this.getInventory = function(callback) { + var postBody = null; + + + var pathParams = { + }; + var queryParams = { + }; + var headerParams = { + }; + var formParams = { + }; + + var authNames = ['api_key']; + var contentTypes = []; + var accepts = ['application/json', 'application/xml']; + var returnType = {'String': 'Integer'}; + + return this.apiClient.callApi( + '/store/inventory', 'GET', + pathParams, queryParams, headerParams, formParams, postBody, + authNames, contentTypes, accepts, returnType, callback + ); + } + + /** + * Callback function to receive the result of the getInventoryInObject operation. + * @callback module:api/StoreApi~getInventoryInObjectCallback + * @param {String} error Error message, if any. + * @param {Object} data The data returned by the service call. + * @param {String} response The complete HTTP response. + */ + + /** + * Fake endpoint to test arbitrary object return by 'Get inventory' + * Returns an arbitrary object which is actually a map of status codes to quantities + * @param {module:api/StoreApi~getInventoryInObjectCallback} callback The callback function, accepting three arguments: error, data, response + * data is of type: {Object} + */ + this.getInventoryInObject = function(callback) { + var postBody = null; + + + var pathParams = { + }; + var queryParams = { + }; + var headerParams = { + }; + var formParams = { + }; + + var authNames = ['api_key']; + var contentTypes = []; + var accepts = ['application/json', 'application/xml']; + var returnType = Object; + + return this.apiClient.callApi( + '/store/inventory?response=arbitrary_object', 'GET', + pathParams, queryParams, headerParams, formParams, postBody, + authNames, contentTypes, accepts, returnType, callback + ); + } + + /** + * Callback function to receive the result of the getOrderById operation. + * @callback module:api/StoreApi~getOrderByIdCallback + * @param {String} error Error message, if any. + * @param {module:model/Order} data The data returned by the service call. + * @param {String} response The complete HTTP response. + */ + + /** + * Find purchase order by ID + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * @param {String} 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} + */ + this.getOrderById = function(orderId, callback) { + var postBody = null; + + // verify the required parameter 'orderId' is set + if (orderId == undefined || orderId == null) { + throw "Missing the required parameter 'orderId' when calling getOrderById"; + } + + + var pathParams = { + 'orderId': orderId + }; + var queryParams = { + }; + var headerParams = { + }; + var formParams = { + }; + + var authNames = ['test_api_key_header', 'test_api_key_query']; + var contentTypes = []; + var accepts = ['application/json', 'application/xml']; + var returnType = Order; + + return this.apiClient.callApi( + '/store/order/{orderId}', 'GET', + pathParams, queryParams, headerParams, formParams, postBody, + authNames, contentTypes, accepts, returnType, callback + ); + } + + /** + * Callback function to receive the result of the placeOrder operation. + * @callback module:api/StoreApi~placeOrderCallback + * @param {String} error Error message, if any. + * @param {module:model/Order} data The data returned by the service call. + * @param {String} response The complete HTTP response. + */ + + /** + * Place an order for a pet + * + * @param {Object} opts Optional parameters + * @param {module:model/Order} opts.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} + */ + this.placeOrder = function(opts, callback) { + opts = opts || {}; + var postBody = opts['body']; + + + var pathParams = { + }; + var queryParams = { + }; + var headerParams = { + }; + var formParams = { + }; + + var authNames = ['test_api_client_id', 'test_api_client_secret']; + var contentTypes = []; + var accepts = ['application/json', 'application/xml']; + var returnType = Order; + + return this.apiClient.callApi( + '/store/order', 'POST', + pathParams, queryParams, headerParams, formParams, postBody, + authNames, contentTypes, accepts, returnType, callback + ); + } }; - return StoreApi; + return exports; })); diff --git a/samples/client/petstore/javascript/src/api/UserApi.js b/samples/client/petstore/javascript/src/api/UserApi.js index 4886330d3d6..3060a13e70c 100644 --- a/samples/client/petstore/javascript/src/api/UserApi.js +++ b/samples/client/petstore/javascript/src/api/UserApi.js @@ -15,22 +15,42 @@ }(this, function(ApiClient, User) { 'use strict'; - var UserApi = function UserApi(apiClient) { - this.apiClient = apiClient || ApiClient.default; + /** + * User service. + * @module api/UserApi + * @version 1.0.0 + */ + + /** + * Constructs a new UserApi. + * @alias module:api/UserApi + * @class + * @param {module:ApiClient} apiClient Optional API client implementation to use, default to {@link module:ApiClient#instance} + * if unspecified. + */ + var exports = function(apiClient) { + this.apiClient = apiClient || ApiClient.instance; + + + /** + * Callback function to receive the result of the createUser operation. + * @callback module:api/UserApi~createUserCallback + * @param {String} error Error message, if any. + * @param data This operation does not return a value. + * @param {String} response The complete HTTP response. + */ - var self = this; - - /** * Create user * This can only be done by the logged in user. - * @param {User} opts['body'] Created user object - * @param {function} callback the callback function, accepting three arguments: error, data, response + * @param {Object} opts Optional parameters + * @param {module:model/User} opts.body Created user object + * @param {module:api/UserApi~createUserCallback} callback The callback function, accepting three arguments: error, data, response */ - self.createUser = function(opts, callback) { + this.createUser = function(opts, callback) { opts = opts || {}; var postBody = opts['body']; - + var pathParams = { }; @@ -51,19 +71,27 @@ pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType, callback ); - } - + + /** + * Callback function to receive the result of the createUsersWithArrayInput operation. + * @callback module:api/UserApi~createUsersWithArrayInputCallback + * @param {String} error Error message, if any. + * @param data This operation does not return a value. + * @param {String} response The complete HTTP response. + */ + /** * Creates list of users with given input array * - * @param {[User]} opts['body'] List of user object - * @param {function} callback the callback function, accepting three arguments: error, data, response + * @param {Object} opts Optional parameters + * @param {Array.} opts.body List of user object + * @param {module:api/UserApi~createUsersWithArrayInputCallback} callback The callback function, accepting three arguments: error, data, response */ - self.createUsersWithArrayInput = function(opts, callback) { + this.createUsersWithArrayInput = function(opts, callback) { opts = opts || {}; var postBody = opts['body']; - + var pathParams = { }; @@ -84,19 +112,27 @@ pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType, callback ); - } - + + /** + * Callback function to receive the result of the createUsersWithListInput operation. + * @callback module:api/UserApi~createUsersWithListInputCallback + * @param {String} error Error message, if any. + * @param data This operation does not return a value. + * @param {String} response The complete HTTP response. + */ + /** * Creates list of users with given input array * - * @param {[User]} opts['body'] List of user object - * @param {function} callback the callback function, accepting three arguments: error, data, response + * @param {Object} opts Optional parameters + * @param {Array.} opts.body List of user object + * @param {module:api/UserApi~createUsersWithListInputCallback} callback The callback function, accepting three arguments: error, data, response */ - self.createUsersWithListInput = function(opts, callback) { + this.createUsersWithListInput = function(opts, callback) { opts = opts || {}; var postBody = opts['body']; - + var pathParams = { }; @@ -117,21 +153,120 @@ pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType, callback ); - } - + + /** + * Callback function to receive the result of the deleteUser operation. + * @callback module:api/UserApi~deleteUserCallback + * @param {String} error Error message, if any. + * @param data This operation does not return a value. + * @param {String} response The complete HTTP response. + */ + + /** + * Delete user + * This can only be done by the logged in user. + * @param {String} username The name that needs to be deleted + * @param {module:api/UserApi~deleteUserCallback} callback The callback function, accepting three arguments: error, data, response + */ + this.deleteUser = function(username, callback) { + var postBody = null; + + // verify the required parameter 'username' is set + if (username == undefined || username == null) { + throw "Missing the required parameter 'username' when calling deleteUser"; + } + + + var pathParams = { + 'username': username + }; + var queryParams = { + }; + var headerParams = { + }; + var formParams = { + }; + + var authNames = ['test_http_basic']; + var contentTypes = []; + var accepts = ['application/json', 'application/xml']; + var returnType = null; + + return this.apiClient.callApi( + '/user/{username}', 'DELETE', + pathParams, queryParams, headerParams, formParams, postBody, + authNames, contentTypes, accepts, returnType, callback + ); + } + + /** + * Callback function to receive the result of the getUserByName operation. + * @callback module:api/UserApi~getUserByNameCallback + * @param {String} error Error message, if any. + * @param {module:model/User} data The data returned by the service call. + * @param {String} response The complete HTTP response. + */ + + /** + * Get user by user name + * + * @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} + */ + this.getUserByName = function(username, callback) { + var postBody = null; + + // verify the required parameter 'username' is set + if (username == undefined || username == null) { + throw "Missing the required parameter 'username' when calling getUserByName"; + } + + + var pathParams = { + 'username': username + }; + var queryParams = { + }; + var headerParams = { + }; + var formParams = { + }; + + var authNames = []; + var contentTypes = []; + var accepts = ['application/json', 'application/xml']; + var returnType = User; + + return this.apiClient.callApi( + '/user/{username}', 'GET', + pathParams, queryParams, headerParams, formParams, postBody, + authNames, contentTypes, accepts, returnType, callback + ); + } + + /** + * Callback function to receive the result of the loginUser operation. + * @callback module:api/UserApi~loginUserCallback + * @param {String} error Error message, if any. + * @param {'String'} data The data returned by the service call. + * @param {String} response The complete HTTP response. + */ + /** * Logs user into the system * - * @param {String} opts['username'] The user name for login - * @param {String} opts['password'] The password for login in clear text - * @param {function} callback the callback function, accepting three arguments: error, data, response - * data is of type: 'String' + * @param {Object} opts Optional parameters + * @param {String} opts.username The user name for login + * @param {String} opts.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'} */ - self.loginUser = function(opts, callback) { + this.loginUser = function(opts, callback) { opts = opts || {}; var postBody = null; - + var pathParams = { }; @@ -154,17 +289,24 @@ pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType, callback ); - } - + + /** + * Callback function to receive the result of the logoutUser operation. + * @callback module:api/UserApi~logoutUserCallback + * @param {String} error Error message, if any. + * @param data This operation does not return a value. + * @param {String} response The complete HTTP response. + */ + /** * Logs out current logged in user session * - * @param {function} callback the callback function, accepting three arguments: error, data, response + * @param {module:api/UserApi~logoutUserCallback} callback The callback function, accepting three arguments: error, data, response */ - self.logoutUser = function(callback) { + this.logoutUser = function(callback) { var postBody = null; - + var pathParams = { }; @@ -185,64 +327,33 @@ pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType, callback ); - } - + /** - * Get user by user name - * - * @param {String} username The name that needs to be fetched. Use user1 for testing. - * @param {function} callback the callback function, accepting three arguments: error, data, response - * data is of type: User + * Callback function to receive the result of the updateUser operation. + * @callback module:api/UserApi~updateUserCallback + * @param {String} error Error message, if any. + * @param data This operation does not return a value. + * @param {String} response The complete HTTP response. */ - self.getUserByName = function(username, callback) { - var postBody = null; - - // verify the required parameter 'username' is set - if (username == null) { - throw "Missing the required parameter 'username' when calling getUserByName"; - } - - var pathParams = { - 'username': username - }; - var queryParams = { - }; - var headerParams = { - }; - var formParams = { - }; - - var authNames = []; - var contentTypes = []; - var accepts = ['application/json', 'application/xml']; - var returnType = User; - - return this.apiClient.callApi( - '/user/{username}', 'GET', - pathParams, queryParams, headerParams, formParams, postBody, - authNames, contentTypes, accepts, returnType, callback - ); - - } - /** * Updated user * This can only be done by the logged in user. * @param {String} username name that need to be deleted - * @param {User} opts['body'] Updated user object - * @param {function} callback the callback function, accepting three arguments: error, data, response + * @param {Object} opts Optional parameters + * @param {module:model/User} opts.body Updated user object + * @param {module:api/UserApi~updateUserCallback} callback The callback function, accepting three arguments: error, data, response */ - self.updateUser = function(username, opts, callback) { + this.updateUser = function(username, opts, callback) { opts = opts || {}; var postBody = opts['body']; - + // verify the required parameter 'username' is set - if (username == null) { + if (username == undefined || username == null) { throw "Missing the required parameter 'username' when calling updateUser"; } - + var pathParams = { 'username': username @@ -264,49 +375,8 @@ pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType, callback ); - } - - /** - * Delete user - * This can only be done by the logged in user. - * @param {String} username The name that needs to be deleted - * @param {function} callback the callback function, accepting three arguments: error, data, response - */ - self.deleteUser = function(username, callback) { - var postBody = null; - - // verify the required parameter 'username' is set - if (username == null) { - throw "Missing the required parameter 'username' when calling deleteUser"; - } - - - var pathParams = { - 'username': username - }; - var queryParams = { - }; - var headerParams = { - }; - var formParams = { - }; - - var authNames = []; - var contentTypes = []; - var accepts = ['application/json', 'application/xml']; - var returnType = null; - - return this.apiClient.callApi( - '/user/{username}', 'DELETE', - pathParams, queryParams, headerParams, formParams, postBody, - authNames, contentTypes, accepts, returnType, callback - ); - - } - - }; - return UserApi; + return exports; })); diff --git a/samples/client/petstore/javascript/src/index.js b/samples/client/petstore/javascript/src/index.js index 6c57bd53ded..da193f80e4d 100644 --- a/samples/client/petstore/javascript/src/index.js +++ b/samples/client/petstore/javascript/src/index.js @@ -1,26 +1,132 @@ (function(factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. - define(['./ApiClient', './model/Order', './model/SpecialModelName', './model/User', './model/Category', './model/ObjectReturn', './model/InlineResponse200', './model/Tag', './model/Pet', './api/UserApi', './api/StoreApi', './api/PetApi'], factory); + define(['./ApiClient', './model/Animal', './model/Cat', './model/Category', './model/Dog', './model/InlineResponse200', './model/Model200Response', './model/ModelReturn', './model/Name', './model/Order', './model/Pet', './model/SpecialModelName', './model/Tag', './model/User', './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/Order'), require('./model/SpecialModelName'), require('./model/User'), require('./model/Category'), require('./model/ObjectReturn'), require('./model/InlineResponse200'), require('./model/Tag'), require('./model/Pet'), require('./api/UserApi'), require('./api/StoreApi'), require('./api/PetApi')); + module.exports = factory(require('./ApiClient'), require('./model/Animal'), require('./model/Cat'), require('./model/Category'), require('./model/Dog'), require('./model/InlineResponse200'), require('./model/Model200Response'), require('./model/ModelReturn'), require('./model/Name'), require('./model/Order'), require('./model/Pet'), require('./model/SpecialModelName'), require('./model/Tag'), require('./model/User'), require('./api/PetApi'), require('./api/StoreApi'), require('./api/UserApi')); } -}(function(ApiClient, Order, SpecialModelName, User, Category, ObjectReturn, InlineResponse200, Tag, Pet, UserApi, StoreApi, PetApi) { +}(function(ApiClient, Animal, Cat, Category, Dog, InlineResponse200, Model200Response, ModelReturn, Name, Order, Pet, SpecialModelName, Tag, User, PetApi, StoreApi, UserApi) { 'use strict'; - return { + /** + * This is a sample server Petstore server. You can find out more about Swagger at <a href=\"http://swagger.io\">http://swagger.io</a> or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters.
+ * The index module provides access to constructors for all the classes which comprise the public API. + *

+ * An AMD (recommended!) or CommonJS application will generally do something equivalent to the following: + *

+   * var SwaggerPetstore = require('./index'); // See note below*.
+   * var xxxSvc = new SwaggerPetstore.XxxApi(); // Allocate the API class we're going to use.
+   * var yyyModel = new SwaggerPetstore.Yyy(); // Construct a model instance.
+   * yyyModel.someProperty = 'someValue';
+   * ...
+   * var zzz = xxxSvc.doSomething(yyyModel); // Invoke the service.
+   * ...
+   * 
+ * *NOTE: For a top-level AMD script, use require(['./index'], function(){...}) and put the application logic within the + * callback function. + *

+ *

+ * A non-AMD browser application (discouraged) might do something like this: + *

+   * var xxxSvc = new SwaggerPetstore.XxxApi(); // Allocate the API class we're going to use.
+   * var yyy = new SwaggerPetstore.Yyy(); // Construct a model instance.
+   * yyyModel.someProperty = 'someValue';
+   * ...
+   * var zzz = xxxSvc.doSomething(yyyModel); // Invoke the service.
+   * ...
+   * 
+ *

+ * @module index + * @version 1.0.0 + */ + var exports = { + /** + * The ApiClient constructor. + * @property {module:ApiClient} + */ ApiClient: ApiClient, - Order: Order, - SpecialModelName: SpecialModelName, - User: User, + /** + * The Animal model constructor. + * @property {module:model/Animal} + */ + Animal: Animal, + /** + * The Cat model constructor. + * @property {module:model/Cat} + */ + Cat: Cat, + /** + * The Category model constructor. + * @property {module:model/Category} + */ Category: Category, - ObjectReturn: ObjectReturn, + /** + * The Dog model constructor. + * @property {module:model/Dog} + */ + Dog: Dog, + /** + * The InlineResponse200 model constructor. + * @property {module:model/InlineResponse200} + */ InlineResponse200: InlineResponse200, - Tag: Tag, + /** + * The Model200Response model constructor. + * @property {module:model/Model200Response} + */ + Model200Response: Model200Response, + /** + * The ModelReturn model constructor. + * @property {module:model/ModelReturn} + */ + ModelReturn: ModelReturn, + /** + * The Name model constructor. + * @property {module:model/Name} + */ + Name: Name, + /** + * The Order model constructor. + * @property {module:model/Order} + */ + Order: Order, + /** + * The Pet model constructor. + * @property {module:model/Pet} + */ Pet: Pet, - UserApi: UserApi, + /** + * The SpecialModelName model constructor. + * @property {module:model/SpecialModelName} + */ + SpecialModelName: SpecialModelName, + /** + * The Tag model constructor. + * @property {module:model/Tag} + */ + Tag: Tag, + /** + * The User model constructor. + * @property {module:model/User} + */ + User: User, + /** + * The PetApi service constructor. + * @property {module:api/PetApi} + */ + PetApi: PetApi, + /** + * The StoreApi service constructor. + * @property {module:api/StoreApi} + */ StoreApi: StoreApi, - PetApi: PetApi + /** + * The UserApi service constructor. + * @property {module:api/UserApi} + */ + UserApi: UserApi }; + + return exports; })); diff --git a/samples/client/petstore/javascript/src/model/Animal.js b/samples/client/petstore/javascript/src/model/Animal.js new file mode 100644 index 00000000000..674471a30ee --- /dev/null +++ b/samples/client/petstore/javascript/src/model/Animal.js @@ -0,0 +1,63 @@ +(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.Animal = factory(root.SwaggerPetstore.ApiClient); + } +}(this, function(ApiClient) { + 'use strict'; + + /** + * The Animal model module. + * @module model/Animal + * @version 1.0.0 + */ + + /** + * Constructs a new Animal. + * @alias module:model/Animal + * @class + * @param className + */ + var exports = function(className) { + + this['className'] = className; + }; + + /** + * Constructs a Animal 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/Animal} obj Optional instance to populate. + * @return {module:model/Animal} The populated Animal instance. + */ + exports.constructFromObject = function(data, obj) { + if (data) { + obj = obj || new exports(); + + if (data.hasOwnProperty('className')) { + obj['className'] = ApiClient.convertToType(data['className'], 'String'); + } + } + return obj; + } + + + /** + * @member {String} className + */ + exports.prototype['className'] = undefined; + + + + + return exports; +})); diff --git a/samples/client/petstore/javascript/src/model/Cat.js b/samples/client/petstore/javascript/src/model/Cat.js new file mode 100644 index 00000000000..c878af6edec --- /dev/null +++ b/samples/client/petstore/javascript/src/model/Cat.js @@ -0,0 +1,67 @@ +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(['../ApiClient', './Animal'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + module.exports = factory(require('../ApiClient'), require('./Animal')); + } else { + // Browser globals (root is window) + if (!root.SwaggerPetstore) { + root.SwaggerPetstore = {}; + } + root.SwaggerPetstore.Cat = factory(root.SwaggerPetstore.ApiClient, root.SwaggerPetstore.Animal); + } +}(this, function(ApiClient, Animal) { + 'use strict'; + + /** + * The Cat model module. + * @module model/Cat + * @version 1.0.0 + */ + + /** + * Constructs a new Cat. + * @alias module:model/Cat + * @class + * @extends module:model/Animal + * @param className + */ + var exports = function(className) { + Animal.call(this, className); + + }; + + /** + * Constructs a Cat 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/Cat} obj Optional instance to populate. + * @return {module:model/Cat} The populated Cat instance. + */ + exports.constructFromObject = function(data, obj) { + if (data) { + obj = obj || new exports(); + Animal.constructFromObject(data, obj); + if (data.hasOwnProperty('declawed')) { + obj['declawed'] = ApiClient.convertToType(data['declawed'], 'Boolean'); + } + } + return obj; + } + + exports.prototype = Object.create(Animal.prototype); + exports.prototype.constructor = exports; + + + /** + * @member {Boolean} declawed + */ + exports.prototype['declawed'] = undefined; + + + + + return exports; +})); diff --git a/samples/client/petstore/javascript/src/model/Category.js b/samples/client/petstore/javascript/src/model/Category.js index 729a22b9e04..473f4b783d5 100644 --- a/samples/client/petstore/javascript/src/model/Category.js +++ b/samples/client/petstore/javascript/src/model/Category.js @@ -1,81 +1,71 @@ (function(root, factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. - define([undefined, '../ApiClient'], factory); + define(['../ApiClient'], factory); } else if (typeof module === 'object' && module.exports) { // CommonJS-like environments that support module.exports, like Node. - module.exports = factory(undefined, require('../ApiClient')); + module.exports = factory(require('../ApiClient')); } else { // Browser globals (root is window) if (!root.SwaggerPetstore) { root.SwaggerPetstore = {}; } - factory(root.SwaggerPetstore, root.SwaggerPetstore.ApiClient); + root.SwaggerPetstore.Category = factory(root.SwaggerPetstore.ApiClient); } -}(this, function(module, ApiClient) { +}(this, function(ApiClient) { 'use strict'; - - - var Category = function Category() { - + + /** + * The Category model module. + * @module model/Category + * @version 1.0.0 + */ + + /** + * Constructs a new Category. + * @alias module:model/Category + * @class + */ + var exports = function() { + + + }; - Category.constructFromObject = function(data) { - if (!data) { - return null; + /** + * Constructs a Category 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/Category} obj Optional instance to populate. + * @return {module:model/Category} The populated Category instance. + */ + exports.constructFromObject = function(data, obj) { + if (data) { + obj = obj || new exports(); + + if (data.hasOwnProperty('id')) { + obj['id'] = ApiClient.convertToType(data['id'], 'Integer'); + } + if (data.hasOwnProperty('name')) { + obj['name'] = ApiClient.convertToType(data['name'], 'String'); + } } - var _this = new Category(); - - if (data['id']) { - _this['id'] = ApiClient.convertToType(data['id'], 'Integer'); - } - - if (data['name']) { - _this['name'] = ApiClient.convertToType(data['name'], 'String'); - } - - return _this; + return obj; } - - - /** - * @return {Integer} - **/ - Category.prototype.getId = function() { - return this['id']; - } /** - * @param {Integer} id - **/ - Category.prototype.setId = function(id) { - this['id'] = id; - } - - /** - * @return {String} - **/ - Category.prototype.getName = function() { - return this['name']; - } + * @member {Integer} id + */ + exports.prototype['id'] = undefined; /** - * @param {String} name - **/ - Category.prototype.setName = function(name) { - this['name'] = name; - } - - + * @member {String} name + */ + exports.prototype['name'] = undefined; - - if (module) { - module.Category = Category; - } - return Category; - - + + return exports; })); diff --git a/samples/client/petstore/javascript/src/model/Dog.js b/samples/client/petstore/javascript/src/model/Dog.js new file mode 100644 index 00000000000..e5e55581a70 --- /dev/null +++ b/samples/client/petstore/javascript/src/model/Dog.js @@ -0,0 +1,67 @@ +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(['../ApiClient', './Animal'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + module.exports = factory(require('../ApiClient'), require('./Animal')); + } else { + // Browser globals (root is window) + if (!root.SwaggerPetstore) { + root.SwaggerPetstore = {}; + } + root.SwaggerPetstore.Dog = factory(root.SwaggerPetstore.ApiClient, root.SwaggerPetstore.Animal); + } +}(this, function(ApiClient, Animal) { + 'use strict'; + + /** + * The Dog model module. + * @module model/Dog + * @version 1.0.0 + */ + + /** + * Constructs a new Dog. + * @alias module:model/Dog + * @class + * @extends module:model/Animal + * @param className + */ + var exports = function(className) { + Animal.call(this, className); + + }; + + /** + * Constructs a Dog 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/Dog} obj Optional instance to populate. + * @return {module:model/Dog} The populated Dog instance. + */ + exports.constructFromObject = function(data, obj) { + if (data) { + obj = obj || new exports(); + Animal.constructFromObject(data, obj); + if (data.hasOwnProperty('breed')) { + obj['breed'] = ApiClient.convertToType(data['breed'], 'String'); + } + } + return obj; + } + + exports.prototype = Object.create(Animal.prototype); + exports.prototype.constructor = exports; + + + /** + * @member {String} breed + */ + exports.prototype['breed'] = undefined; + + + + + return exports; +})); diff --git a/samples/client/petstore/javascript/src/model/InlineResponse200.js b/samples/client/petstore/javascript/src/model/InlineResponse200.js index d864bea66e2..f9ecda79491 100644 --- a/samples/client/petstore/javascript/src/model/InlineResponse200.js +++ b/samples/client/petstore/javascript/src/model/InlineResponse200.js @@ -1,104 +1,132 @@ (function(root, factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. - define([undefined, '../ApiClient'], factory); + define(['../ApiClient', './Tag'], factory); } else if (typeof module === 'object' && module.exports) { // CommonJS-like environments that support module.exports, like Node. - module.exports = factory(undefined, require('../ApiClient')); + module.exports = factory(require('../ApiClient'), require('./Tag')); } else { // Browser globals (root is window) if (!root.SwaggerPetstore) { root.SwaggerPetstore = {}; } - factory(root.SwaggerPetstore, root.SwaggerPetstore.ApiClient); + root.SwaggerPetstore.InlineResponse200 = factory(root.SwaggerPetstore.ApiClient, root.SwaggerPetstore.Tag); } -}(this, function(module, ApiClient) { +}(this, function(ApiClient, Tag) { 'use strict'; - - - var InlineResponse200 = function InlineResponse200(id) { - - /** - * datatype: Integer - * required - **/ + + /** + * The InlineResponse200 model module. + * @module model/InlineResponse200 + * @version 1.0.0 + */ + + /** + * Constructs a new InlineResponse200. + * @alias module:model/InlineResponse200 + * @class + * @param id + */ + var exports = function(id) { + + this['id'] = id; + + + + }; - InlineResponse200.constructFromObject = function(data) { - if (!data) { - return null; + /** + * Constructs a InlineResponse200 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/InlineResponse200} obj Optional instance to populate. + * @return {module:model/InlineResponse200} The populated InlineResponse200 instance. + */ + exports.constructFromObject = function(data, obj) { + if (data) { + obj = obj || new exports(); + + if (data.hasOwnProperty('tags')) { + obj['tags'] = ApiClient.convertToType(data['tags'], [Tag]); + } + if (data.hasOwnProperty('id')) { + obj['id'] = ApiClient.convertToType(data['id'], 'Integer'); + } + if (data.hasOwnProperty('category')) { + obj['category'] = ApiClient.convertToType(data['category'], Object); + } + if (data.hasOwnProperty('status')) { + obj['status'] = ApiClient.convertToType(data['status'], 'String'); + } + if (data.hasOwnProperty('name')) { + obj['name'] = ApiClient.convertToType(data['name'], 'String'); + } + if (data.hasOwnProperty('photoUrls')) { + obj['photoUrls'] = ApiClient.convertToType(data['photoUrls'], ['String']); + } } - var _this = new InlineResponse200(); + return obj; + } + + + /** + * @member {Array.} tags + */ + exports.prototype['tags'] = undefined; + + /** + * @member {Integer} id + */ + exports.prototype['id'] = undefined; + + /** + * @member {Object} category + */ + exports.prototype['category'] = undefined; + + /** + * pet status in the store + * @member {module:model/InlineResponse200.StatusEnum} status + */ + exports.prototype['status'] = undefined; + + /** + * @member {String} name + */ + exports.prototype['name'] = undefined; + + /** + * @member {Array.} photoUrls + */ + exports.prototype['photoUrls'] = undefined; + + + /** + * Allowed values for the status property. + * @enum {String} + * @readonly + */ + exports.StatusEnum = { + /** + * value: available + * @const + */ + AVAILABLE: "available", - if (data['name']) { - _this['name'] = ApiClient.convertToType(data['name'], 'String'); - } + /** + * value: pending + * @const + */ + PENDING: "pending", - if (data['id']) { - _this['id'] = ApiClient.convertToType(data['id'], 'Integer'); - } - - if (data['category']) { - _this['category'] = ApiClient.convertToType(data['category'], Object); - } - - return _this; - } + /** + * value: sold + * @const + */ + SOLD: "sold" + }; - - - /** - * @return {String} - **/ - InlineResponse200.prototype.getName = function() { - return this['name']; - } - - /** - * @param {String} name - **/ - InlineResponse200.prototype.setName = function(name) { - this['name'] = name; - } - - /** - * @return {Integer} - **/ - InlineResponse200.prototype.getId = function() { - return this['id']; - } - - /** - * @param {Integer} id - **/ - InlineResponse200.prototype.setId = function(id) { - this['id'] = id; - } - - /** - * @return {Object} - **/ - InlineResponse200.prototype.getCategory = function() { - return this['category']; - } - - /** - * @param {Object} category - **/ - InlineResponse200.prototype.setCategory = function(category) { - this['category'] = category; - } - - - - - - if (module) { - module.InlineResponse200 = InlineResponse200; - } - - return InlineResponse200; - - + return exports; })); diff --git a/samples/client/petstore/javascript/src/model/Model200Response.js b/samples/client/petstore/javascript/src/model/Model200Response.js new file mode 100644 index 00000000000..fb559f5ebaa --- /dev/null +++ b/samples/client/petstore/javascript/src/model/Model200Response.js @@ -0,0 +1,62 @@ +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(['../ApiClient'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + module.exports = factory(require('../ApiClient')); + } else { + // Browser globals (root is window) + if (!root.SwaggerPetstore) { + root.SwaggerPetstore = {}; + } + root.SwaggerPetstore.Model200Response = factory(root.SwaggerPetstore.ApiClient); + } +}(this, function(ApiClient) { + 'use strict'; + + /** + * The Model200Response model module. + * @module model/Model200Response + * @version 1.0.0 + */ + + /** + * Constructs a new Model200Response. + * @alias module:model/Model200Response + * @class + */ + var exports = function() { + + + }; + + /** + * Constructs a Model200Response 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/Model200Response} obj Optional instance to populate. + * @return {module:model/Model200Response} The populated Model200Response instance. + */ + exports.constructFromObject = function(data, obj) { + if (data) { + obj = obj || new exports(); + + if (data.hasOwnProperty('name')) { + obj['name'] = ApiClient.convertToType(data['name'], 'Integer'); + } + } + return obj; + } + + + /** + * @member {Integer} name + */ + exports.prototype['name'] = undefined; + + + + + return exports; +})); diff --git a/samples/client/petstore/javascript/src/model/ModelReturn.js b/samples/client/petstore/javascript/src/model/ModelReturn.js new file mode 100644 index 00000000000..d5036e230ea --- /dev/null +++ b/samples/client/petstore/javascript/src/model/ModelReturn.js @@ -0,0 +1,62 @@ +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(['../ApiClient'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + module.exports = factory(require('../ApiClient')); + } else { + // Browser globals (root is window) + if (!root.SwaggerPetstore) { + root.SwaggerPetstore = {}; + } + root.SwaggerPetstore.ModelReturn = factory(root.SwaggerPetstore.ApiClient); + } +}(this, function(ApiClient) { + 'use strict'; + + /** + * The ModelReturn model module. + * @module model/ModelReturn + * @version 1.0.0 + */ + + /** + * Constructs a new ModelReturn. + * @alias module:model/ModelReturn + * @class + */ + var exports = function() { + + + }; + + /** + * Constructs a ModelReturn 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/ModelReturn} obj Optional instance to populate. + * @return {module:model/ModelReturn} The populated ModelReturn instance. + */ + exports.constructFromObject = function(data, obj) { + if (data) { + obj = obj || new exports(); + + if (data.hasOwnProperty('return')) { + obj['return'] = ApiClient.convertToType(data['return'], 'Integer'); + } + } + return obj; + } + + + /** + * @member {Integer} return + */ + exports.prototype['return'] = undefined; + + + + + return exports; +})); diff --git a/samples/client/petstore/javascript/src/model/Name.js b/samples/client/petstore/javascript/src/model/Name.js new file mode 100644 index 00000000000..a5a070025f7 --- /dev/null +++ b/samples/client/petstore/javascript/src/model/Name.js @@ -0,0 +1,71 @@ +(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.Name = factory(root.SwaggerPetstore.ApiClient); + } +}(this, function(ApiClient) { + 'use strict'; + + /** + * The Name model module. + * @module model/Name + * @version 1.0.0 + */ + + /** + * Constructs a new Name. + * @alias module:model/Name + * @class + */ + var exports = function() { + + + + }; + + /** + * Constructs a Name 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/Name} obj Optional instance to populate. + * @return {module:model/Name} The populated Name instance. + */ + exports.constructFromObject = function(data, obj) { + if (data) { + obj = obj || new exports(); + + if (data.hasOwnProperty('name')) { + obj['name'] = ApiClient.convertToType(data['name'], 'Integer'); + } + if (data.hasOwnProperty('snake_case')) { + obj['snake_case'] = ApiClient.convertToType(data['snake_case'], 'Integer'); + } + } + return obj; + } + + + /** + * @member {Integer} name + */ + exports.prototype['name'] = undefined; + + /** + * @member {Integer} snake_case + */ + exports.prototype['snake_case'] = undefined; + + + + + return exports; +})); diff --git a/samples/client/petstore/javascript/src/model/ObjectReturn.js b/samples/client/petstore/javascript/src/model/ObjectReturn.js deleted file mode 100644 index fec38c178d2..00000000000 --- a/samples/client/petstore/javascript/src/model/ObjectReturn.js +++ /dev/null @@ -1,63 +0,0 @@ -(function(root, factory) { - if (typeof define === 'function' && define.amd) { - // AMD. Register as an anonymous module. - define([undefined, '../ApiClient'], factory); - } else if (typeof module === 'object' && module.exports) { - // CommonJS-like environments that support module.exports, like Node. - module.exports = factory(undefined, require('../ApiClient')); - } else { - // Browser globals (root is window) - if (!root.SwaggerPetstore) { - root.SwaggerPetstore = {}; - } - factory(root.SwaggerPetstore, root.SwaggerPetstore.ApiClient); - } -}(this, function(module, ApiClient) { - 'use strict'; - - - var ObjectReturn = function ObjectReturn() { - - }; - - ObjectReturn.constructFromObject = function(data) { - if (!data) { - return null; - } - var _this = new ObjectReturn(); - - if (data['return']) { - _this['return'] = ApiClient.convertToType(data['return'], 'Integer'); - } - - return _this; - } - - - - /** - * @return {Integer} - **/ - ObjectReturn.prototype.getReturn = function() { - return this['return']; - } - - /** - * @param {Integer} _return - **/ - ObjectReturn.prototype.setReturn = function(_return) { - this['return'] = _return; - } - - - - - - if (module) { - module.ObjectReturn = ObjectReturn; - } - - return ObjectReturn; - - -})); diff --git a/samples/client/petstore/javascript/src/model/Order.js b/samples/client/petstore/javascript/src/model/Order.js index 4d2e4625d90..81f1feb7800 100644 --- a/samples/client/petstore/javascript/src/model/Order.js +++ b/samples/client/petstore/javascript/src/model/Order.js @@ -1,174 +1,131 @@ (function(root, factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. - define([undefined, '../ApiClient'], factory); + define(['../ApiClient'], factory); } else if (typeof module === 'object' && module.exports) { // CommonJS-like environments that support module.exports, like Node. - module.exports = factory(undefined, require('../ApiClient')); + module.exports = factory(require('../ApiClient')); } else { // Browser globals (root is window) if (!root.SwaggerPetstore) { root.SwaggerPetstore = {}; } - factory(root.SwaggerPetstore, root.SwaggerPetstore.ApiClient); + root.SwaggerPetstore.Order = factory(root.SwaggerPetstore.ApiClient); } -}(this, function(module, ApiClient) { +}(this, function(ApiClient) { 'use strict'; - - - var Order = function Order() { - + + /** + * The Order model module. + * @module model/Order + * @version 1.0.0 + */ + + /** + * Constructs a new Order. + * @alias module:model/Order + * @class + */ + var exports = function() { + + + + + + + }; - Order.constructFromObject = function(data) { - if (!data) { - return null; + /** + * Constructs a Order 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/Order} obj Optional instance to populate. + * @return {module:model/Order} The populated Order instance. + */ + exports.constructFromObject = function(data, obj) { + if (data) { + obj = obj || new exports(); + + if (data.hasOwnProperty('id')) { + obj['id'] = ApiClient.convertToType(data['id'], 'Integer'); + } + if (data.hasOwnProperty('petId')) { + obj['petId'] = ApiClient.convertToType(data['petId'], 'Integer'); + } + if (data.hasOwnProperty('quantity')) { + obj['quantity'] = ApiClient.convertToType(data['quantity'], 'Integer'); + } + if (data.hasOwnProperty('shipDate')) { + obj['shipDate'] = ApiClient.convertToType(data['shipDate'], 'Date'); + } + if (data.hasOwnProperty('status')) { + obj['status'] = ApiClient.convertToType(data['status'], 'String'); + } + if (data.hasOwnProperty('complete')) { + obj['complete'] = ApiClient.convertToType(data['complete'], 'Boolean'); + } } - var _this = new Order(); + return obj; + } + + + /** + * @member {Integer} id + */ + exports.prototype['id'] = undefined; + + /** + * @member {Integer} petId + */ + exports.prototype['petId'] = undefined; + + /** + * @member {Integer} quantity + */ + exports.prototype['quantity'] = undefined; + + /** + * @member {Date} shipDate + */ + exports.prototype['shipDate'] = undefined; + + /** + * Order Status + * @member {module:model/Order.StatusEnum} status + */ + exports.prototype['status'] = undefined; + + /** + * @member {Boolean} complete + */ + exports.prototype['complete'] = undefined; + + + /** + * Allowed values for the status property. + * @enum {String} + * @readonly + */ + exports.StatusEnum = { + /** + * value: placed + * @const + */ + PLACED: "placed", - if (data['id']) { - _this['id'] = ApiClient.convertToType(data['id'], 'Integer'); - } + /** + * value: approved + * @const + */ + APPROVED: "approved", - if (data['petId']) { - _this['petId'] = ApiClient.convertToType(data['petId'], 'Integer'); - } - - if (data['quantity']) { - _this['quantity'] = ApiClient.convertToType(data['quantity'], 'Integer'); - } - - if (data['shipDate']) { - _this['shipDate'] = ApiClient.convertToType(data['shipDate'], 'Date'); - } - - if (data['status']) { - _this['status'] = ApiClient.convertToType(data['status'], 'String'); - } - - if (data['complete']) { - _this['complete'] = ApiClient.convertToType(data['complete'], 'Boolean'); - } - - return _this; - } - - - - /** - * @return {Integer} - **/ - Order.prototype.getId = function() { - return this['id']; - } - - /** - * @param {Integer} id - **/ - Order.prototype.setId = function(id) { - this['id'] = id; - } - - /** - * @return {Integer} - **/ - Order.prototype.getPetId = function() { - return this['petId']; - } - - /** - * @param {Integer} petId - **/ - Order.prototype.setPetId = function(petId) { - this['petId'] = petId; - } - - /** - * @return {Integer} - **/ - Order.prototype.getQuantity = function() { - return this['quantity']; - } - - /** - * @param {Integer} quantity - **/ - Order.prototype.setQuantity = function(quantity) { - this['quantity'] = quantity; - } - - /** - * @return {Date} - **/ - Order.prototype.getShipDate = function() { - return this['shipDate']; - } - - /** - * @param {Date} shipDate - **/ - Order.prototype.setShipDate = function(shipDate) { - this['shipDate'] = shipDate; - } - - /** - * get Order Status - * @return {StatusEnum} - **/ - Order.prototype.getStatus = function() { - return this['status']; - } - - /** - * set Order Status - * @param {StatusEnum} status - **/ - Order.prototype.setStatus = function(status) { - this['status'] = status; - } - - /** - * @return {Boolean} - **/ - Order.prototype.getComplete = function() { - return this['complete']; - } - - /** - * @param {Boolean} complete - **/ - Order.prototype.setComplete = function(complete) { - this['complete'] = complete; - } - - - - var StatusEnum = { - - /** - * @const - */ - PLACED: "placed", - - /** - * @const - */ - APPROVED: "approved", - - /** - * @const - */ - DELIVERED: "delivered" + /** + * value: delivered + * @const + */ + DELIVERED: "delivered" }; - Order.StatusEnum = StatusEnum; - - - if (module) { - module.Order = Order; - } - - return Order; - - + return exports; })); diff --git a/samples/client/petstore/javascript/src/model/Pet.js b/samples/client/petstore/javascript/src/model/Pet.js index d751182c303..39a09b47170 100644 --- a/samples/client/petstore/javascript/src/model/Pet.js +++ b/samples/client/petstore/javascript/src/model/Pet.js @@ -1,184 +1,133 @@ (function(root, factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. - define([undefined, '../ApiClient', './Category', './Tag'], factory); + define(['../ApiClient', './Category', './Tag'], factory); } else if (typeof module === 'object' && module.exports) { // CommonJS-like environments that support module.exports, like Node. - module.exports = factory(undefined, require('../ApiClient'), require('./Category'), require('./Tag')); + module.exports = factory(require('../ApiClient'), require('./Category'), require('./Tag')); } else { // Browser globals (root is window) if (!root.SwaggerPetstore) { root.SwaggerPetstore = {}; } - factory(root.SwaggerPetstore, root.SwaggerPetstore.ApiClient, root.SwaggerPetstore.Category, root.SwaggerPetstore.Tag); + root.SwaggerPetstore.Pet = factory(root.SwaggerPetstore.ApiClient, root.SwaggerPetstore.Category, root.SwaggerPetstore.Tag); } -}(this, function(module, ApiClient, Category, Tag) { +}(this, function(ApiClient, Category, Tag) { 'use strict'; - - - var Pet = function Pet(name, photoUrls) { - - /** - * datatype: String - * required - **/ + + /** + * The Pet model module. + * @module model/Pet + * @version 1.0.0 + */ + + /** + * Constructs a new Pet. + * @alias module:model/Pet + * @class + * @param name + * @param photoUrls + */ + var exports = function(name, photoUrls) { + + + this['name'] = name; - /** - * datatype: [String] - * required - **/ this['photoUrls'] = photoUrls; + + }; - Pet.constructFromObject = function(data) { - if (!data) { - return null; + /** + * Constructs a Pet 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/Pet} obj Optional instance to populate. + * @return {module:model/Pet} The populated Pet instance. + */ + exports.constructFromObject = function(data, obj) { + if (data) { + obj = obj || new exports(); + + if (data.hasOwnProperty('id')) { + obj['id'] = ApiClient.convertToType(data['id'], 'Integer'); + } + if (data.hasOwnProperty('category')) { + obj['category'] = Category.constructFromObject(data['category']); + } + if (data.hasOwnProperty('name')) { + obj['name'] = ApiClient.convertToType(data['name'], 'String'); + } + if (data.hasOwnProperty('photoUrls')) { + obj['photoUrls'] = ApiClient.convertToType(data['photoUrls'], ['String']); + } + if (data.hasOwnProperty('tags')) { + obj['tags'] = ApiClient.convertToType(data['tags'], [Tag]); + } + if (data.hasOwnProperty('status')) { + obj['status'] = ApiClient.convertToType(data['status'], 'String'); + } } - var _this = new Pet(); + return obj; + } + + + /** + * @member {Integer} id + */ + exports.prototype['id'] = undefined; + + /** + * @member {module:model/Category} category + */ + exports.prototype['category'] = undefined; + + /** + * @member {String} name + */ + exports.prototype['name'] = undefined; + + /** + * @member {Array.} photoUrls + */ + exports.prototype['photoUrls'] = undefined; + + /** + * @member {Array.} tags + */ + exports.prototype['tags'] = undefined; + + /** + * pet status in the store + * @member {module:model/Pet.StatusEnum} status + */ + exports.prototype['status'] = undefined; + + + /** + * Allowed values for the status property. + * @enum {String} + * @readonly + */ + exports.StatusEnum = { + /** + * value: available + * @const + */ + AVAILABLE: "available", - if (data['id']) { - _this['id'] = ApiClient.convertToType(data['id'], 'Integer'); - } + /** + * value: pending + * @const + */ + PENDING: "pending", - if (data['category']) { - _this['category'] = Category.constructFromObject(data['category']); - } - - if (data['name']) { - _this['name'] = ApiClient.convertToType(data['name'], 'String'); - } - - if (data['photoUrls']) { - _this['photoUrls'] = ApiClient.convertToType(data['photoUrls'], ['String']); - } - - if (data['tags']) { - _this['tags'] = ApiClient.convertToType(data['tags'], [Tag]); - } - - if (data['status']) { - _this['status'] = ApiClient.convertToType(data['status'], 'String'); - } - - return _this; - } - - - - /** - * @return {Integer} - **/ - Pet.prototype.getId = function() { - return this['id']; - } - - /** - * @param {Integer} id - **/ - Pet.prototype.setId = function(id) { - this['id'] = id; - } - - /** - * @return {Category} - **/ - Pet.prototype.getCategory = function() { - return this['category']; - } - - /** - * @param {Category} category - **/ - Pet.prototype.setCategory = function(category) { - this['category'] = category; - } - - /** - * @return {String} - **/ - Pet.prototype.getName = function() { - return this['name']; - } - - /** - * @param {String} name - **/ - Pet.prototype.setName = function(name) { - this['name'] = name; - } - - /** - * @return {[String]} - **/ - Pet.prototype.getPhotoUrls = function() { - return this['photoUrls']; - } - - /** - * @param {[String]} photoUrls - **/ - Pet.prototype.setPhotoUrls = function(photoUrls) { - this['photoUrls'] = photoUrls; - } - - /** - * @return {[Tag]} - **/ - Pet.prototype.getTags = function() { - return this['tags']; - } - - /** - * @param {[Tag]} tags - **/ - Pet.prototype.setTags = function(tags) { - this['tags'] = tags; - } - - /** - * get pet status in the store - * @return {StatusEnum} - **/ - Pet.prototype.getStatus = function() { - return this['status']; - } - - /** - * set pet status in the store - * @param {StatusEnum} status - **/ - Pet.prototype.setStatus = function(status) { - this['status'] = status; - } - - - - var StatusEnum = { - - /** - * @const - */ - AVAILABLE: "available", - - /** - * @const - */ - PENDING: "pending", - - /** - * @const - */ - SOLD: "sold" + /** + * value: sold + * @const + */ + SOLD: "sold" }; - Pet.StatusEnum = StatusEnum; - - - if (module) { - module.Pet = Pet; - } - - return Pet; - - + return exports; })); diff --git a/samples/client/petstore/javascript/src/model/SpecialModelName.js b/samples/client/petstore/javascript/src/model/SpecialModelName.js index fa1df55d6d5..fb6b4765d3f 100644 --- a/samples/client/petstore/javascript/src/model/SpecialModelName.js +++ b/samples/client/petstore/javascript/src/model/SpecialModelName.js @@ -1,63 +1,62 @@ (function(root, factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. - define([undefined, '../ApiClient'], factory); + define(['../ApiClient'], factory); } else if (typeof module === 'object' && module.exports) { // CommonJS-like environments that support module.exports, like Node. - module.exports = factory(undefined, require('../ApiClient')); + module.exports = factory(require('../ApiClient')); } else { // Browser globals (root is window) if (!root.SwaggerPetstore) { root.SwaggerPetstore = {}; } - factory(root.SwaggerPetstore, root.SwaggerPetstore.ApiClient); + root.SwaggerPetstore.SpecialModelName = factory(root.SwaggerPetstore.ApiClient); } -}(this, function(module, ApiClient) { +}(this, function(ApiClient) { 'use strict'; - - - var SpecialModelName = function SpecialModelName() { - + + /** + * The SpecialModelName model module. + * @module model/SpecialModelName + * @version 1.0.0 + */ + + /** + * Constructs a new SpecialModelName. + * @alias module:model/SpecialModelName + * @class + */ + var exports = function() { + + }; - SpecialModelName.constructFromObject = function(data) { - if (!data) { - return null; + /** + * Constructs a SpecialModelName 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/SpecialModelName} obj Optional instance to populate. + * @return {module:model/SpecialModelName} The populated SpecialModelName instance. + */ + exports.constructFromObject = function(data, obj) { + if (data) { + obj = obj || new exports(); + + if (data.hasOwnProperty('$special[property.name]')) { + obj['$special[property.name]'] = ApiClient.convertToType(data['$special[property.name]'], 'Integer'); + } } - var _this = new SpecialModelName(); - - if (data['$special[property.name]']) { - _this['$special[property.name]'] = ApiClient.convertToType(data['$special[property.name]'], 'Integer'); - } - - return _this; + return obj; } - - - /** - * @return {Integer} - **/ - SpecialModelName.prototype.getSpecialPropertyName = function() { - return this['$special[property.name]']; - } /** - * @param {Integer} specialPropertyName - **/ - SpecialModelName.prototype.setSpecialPropertyName = function(specialPropertyName) { - this['$special[property.name]'] = specialPropertyName; - } - - + * @member {Integer} $special[property.name] + */ + exports.prototype['$special[property.name]'] = undefined; - - if (module) { - module.SpecialModelName = SpecialModelName; - } - return SpecialModelName; - - + + return exports; })); diff --git a/samples/client/petstore/javascript/src/model/Tag.js b/samples/client/petstore/javascript/src/model/Tag.js index fbd43adb7e0..8a0739b2ef5 100644 --- a/samples/client/petstore/javascript/src/model/Tag.js +++ b/samples/client/petstore/javascript/src/model/Tag.js @@ -1,81 +1,71 @@ (function(root, factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. - define([undefined, '../ApiClient'], factory); + define(['../ApiClient'], factory); } else if (typeof module === 'object' && module.exports) { // CommonJS-like environments that support module.exports, like Node. - module.exports = factory(undefined, require('../ApiClient')); + module.exports = factory(require('../ApiClient')); } else { // Browser globals (root is window) if (!root.SwaggerPetstore) { root.SwaggerPetstore = {}; } - factory(root.SwaggerPetstore, root.SwaggerPetstore.ApiClient); + root.SwaggerPetstore.Tag = factory(root.SwaggerPetstore.ApiClient); } -}(this, function(module, ApiClient) { +}(this, function(ApiClient) { 'use strict'; - - - var Tag = function Tag() { - + + /** + * The Tag model module. + * @module model/Tag + * @version 1.0.0 + */ + + /** + * Constructs a new Tag. + * @alias module:model/Tag + * @class + */ + var exports = function() { + + + }; - Tag.constructFromObject = function(data) { - if (!data) { - return null; + /** + * Constructs a Tag 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/Tag} obj Optional instance to populate. + * @return {module:model/Tag} The populated Tag instance. + */ + exports.constructFromObject = function(data, obj) { + if (data) { + obj = obj || new exports(); + + if (data.hasOwnProperty('id')) { + obj['id'] = ApiClient.convertToType(data['id'], 'Integer'); + } + if (data.hasOwnProperty('name')) { + obj['name'] = ApiClient.convertToType(data['name'], 'String'); + } } - var _this = new Tag(); - - if (data['id']) { - _this['id'] = ApiClient.convertToType(data['id'], 'Integer'); - } - - if (data['name']) { - _this['name'] = ApiClient.convertToType(data['name'], 'String'); - } - - return _this; + return obj; } - - - /** - * @return {Integer} - **/ - Tag.prototype.getId = function() { - return this['id']; - } /** - * @param {Integer} id - **/ - Tag.prototype.setId = function(id) { - this['id'] = id; - } - - /** - * @return {String} - **/ - Tag.prototype.getName = function() { - return this['name']; - } + * @member {Integer} id + */ + exports.prototype['id'] = undefined; /** - * @param {String} name - **/ - Tag.prototype.setName = function(name) { - this['name'] = name; - } - - + * @member {String} name + */ + exports.prototype['name'] = undefined; - - if (module) { - module.Tag = Tag; - } - return Tag; - - + + return exports; })); diff --git a/samples/client/petstore/javascript/src/model/User.js b/samples/client/petstore/javascript/src/model/User.js index 2f6c9863ef8..1d960a89914 100644 --- a/samples/client/petstore/javascript/src/model/User.js +++ b/samples/client/petstore/javascript/src/model/User.js @@ -1,191 +1,126 @@ (function(root, factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. - define([undefined, '../ApiClient'], factory); + define(['../ApiClient'], factory); } else if (typeof module === 'object' && module.exports) { // CommonJS-like environments that support module.exports, like Node. - module.exports = factory(undefined, require('../ApiClient')); + module.exports = factory(require('../ApiClient')); } else { // Browser globals (root is window) if (!root.SwaggerPetstore) { root.SwaggerPetstore = {}; } - factory(root.SwaggerPetstore, root.SwaggerPetstore.ApiClient); + root.SwaggerPetstore.User = factory(root.SwaggerPetstore.ApiClient); } -}(this, function(module, ApiClient) { +}(this, function(ApiClient) { 'use strict'; - - - var User = function User() { - + + /** + * The User model module. + * @module model/User + * @version 1.0.0 + */ + + /** + * Constructs a new User. + * @alias module:model/User + * @class + */ + var exports = function() { + + + + + + + + + }; - User.constructFromObject = function(data) { - if (!data) { - return null; + /** + * Constructs a User 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/User} obj Optional instance to populate. + * @return {module:model/User} The populated User instance. + */ + exports.constructFromObject = function(data, obj) { + if (data) { + obj = obj || new exports(); + + if (data.hasOwnProperty('id')) { + obj['id'] = ApiClient.convertToType(data['id'], 'Integer'); + } + if (data.hasOwnProperty('username')) { + obj['username'] = ApiClient.convertToType(data['username'], 'String'); + } + if (data.hasOwnProperty('firstName')) { + obj['firstName'] = ApiClient.convertToType(data['firstName'], 'String'); + } + if (data.hasOwnProperty('lastName')) { + obj['lastName'] = ApiClient.convertToType(data['lastName'], 'String'); + } + if (data.hasOwnProperty('email')) { + obj['email'] = ApiClient.convertToType(data['email'], 'String'); + } + if (data.hasOwnProperty('password')) { + obj['password'] = ApiClient.convertToType(data['password'], 'String'); + } + if (data.hasOwnProperty('phone')) { + obj['phone'] = ApiClient.convertToType(data['phone'], 'String'); + } + if (data.hasOwnProperty('userStatus')) { + obj['userStatus'] = ApiClient.convertToType(data['userStatus'], 'Integer'); + } } - var _this = new User(); - - if (data['id']) { - _this['id'] = ApiClient.convertToType(data['id'], 'Integer'); - } - - if (data['username']) { - _this['username'] = ApiClient.convertToType(data['username'], 'String'); - } - - if (data['firstName']) { - _this['firstName'] = ApiClient.convertToType(data['firstName'], 'String'); - } - - if (data['lastName']) { - _this['lastName'] = ApiClient.convertToType(data['lastName'], 'String'); - } - - if (data['email']) { - _this['email'] = ApiClient.convertToType(data['email'], 'String'); - } - - if (data['password']) { - _this['password'] = ApiClient.convertToType(data['password'], 'String'); - } - - if (data['phone']) { - _this['phone'] = ApiClient.convertToType(data['phone'], 'String'); - } - - if (data['userStatus']) { - _this['userStatus'] = ApiClient.convertToType(data['userStatus'], 'Integer'); - } - - return _this; + return obj; } - - - /** - * @return {Integer} - **/ - User.prototype.getId = function() { - return this['id']; - } /** - * @param {Integer} id - **/ - User.prototype.setId = function(id) { - this['id'] = id; - } - - /** - * @return {String} - **/ - User.prototype.getUsername = function() { - return this['username']; - } + * @member {Integer} id + */ + exports.prototype['id'] = undefined; /** - * @param {String} username - **/ - User.prototype.setUsername = function(username) { - this['username'] = username; - } - - /** - * @return {String} - **/ - User.prototype.getFirstName = function() { - return this['firstName']; - } + * @member {String} username + */ + exports.prototype['username'] = undefined; /** - * @param {String} firstName - **/ - User.prototype.setFirstName = function(firstName) { - this['firstName'] = firstName; - } - - /** - * @return {String} - **/ - User.prototype.getLastName = function() { - return this['lastName']; - } + * @member {String} firstName + */ + exports.prototype['firstName'] = undefined; /** - * @param {String} lastName - **/ - User.prototype.setLastName = function(lastName) { - this['lastName'] = lastName; - } - - /** - * @return {String} - **/ - User.prototype.getEmail = function() { - return this['email']; - } + * @member {String} lastName + */ + exports.prototype['lastName'] = undefined; /** - * @param {String} email - **/ - User.prototype.setEmail = function(email) { - this['email'] = email; - } - - /** - * @return {String} - **/ - User.prototype.getPassword = function() { - return this['password']; - } + * @member {String} email + */ + exports.prototype['email'] = undefined; /** - * @param {String} password - **/ - User.prototype.setPassword = function(password) { - this['password'] = password; - } - - /** - * @return {String} - **/ - User.prototype.getPhone = function() { - return this['phone']; - } + * @member {String} password + */ + exports.prototype['password'] = undefined; /** - * @param {String} phone - **/ - User.prototype.setPhone = function(phone) { - this['phone'] = phone; - } - - /** - * get User Status - * @return {Integer} - **/ - User.prototype.getUserStatus = function() { - return this['userStatus']; - } + * @member {String} phone + */ + exports.prototype['phone'] = undefined; /** - * set User Status - * @param {Integer} userStatus - **/ - User.prototype.setUserStatus = function(userStatus) { - this['userStatus'] = userStatus; - } - - + * User Status + * @member {Integer} userStatus + */ + exports.prototype['userStatus'] = undefined; - - if (module) { - module.User = User; - } - return User; - - + + return exports; })); diff --git a/samples/client/petstore/javascript/test/ApiClientTest.js b/samples/client/petstore/javascript/test/ApiClientTest.js index b149175d682..d259ad54c14 100644 --- a/samples/client/petstore/javascript/test/ApiClientTest.js +++ b/samples/client/petstore/javascript/test/ApiClientTest.js @@ -4,7 +4,7 @@ if (typeof module === 'object' && module.exports) { var sinon = require('sinon'); } -var apiClient = SwaggerPetstore.ApiClient.default; +var apiClient = SwaggerPetstore.ApiClient.instance; describe('ApiClient', function() { describe('defaults', function() { @@ -13,25 +13,26 @@ describe('ApiClient', function() { expect(apiClient.basePath).to.be('http://petstore.swagger.io/v2'); expect(apiClient.authentications).to.eql({ petstore_auth: {type: 'oauth2'}, - api_key: {type: 'apiKey', in: 'header', name: 'api_key'}, + api_key: {type: 'apiKey', 'in': 'header', name: 'api_key'}, + test_http_basic: {type: 'basic'}, test_api_client_id: { type: 'apiKey', - in: 'header', + 'in': 'header', name: 'x-test_api_client_id' }, test_api_client_secret: { type: 'apiKey', - in: 'header', + 'in': 'header', name: 'x-test_api_client_secret' }, test_api_key_query: { type: 'apiKey', - in: 'query', + 'in': 'query', name: 'test_api_key_query' }, test_api_key_header: { type: 'apiKey', - in: 'header', + 'in': 'header', name: 'test_api_key_header' } }); @@ -274,7 +275,7 @@ describe('ApiClient', function() { var apiKeyAuth, oauth2; beforeEach(function() { - newClient.authentications[apiKeyAuthName] = {type: 'apiKey', name: 'api_key', in: 'query'}; + newClient.authentications[apiKeyAuthName] = {type: 'apiKey', name: 'api_key', 'in': 'query'}; newClient.authentications[oauth2Name] = {type: 'oauth2'}; apiKeyAuth = newClient.authentications[apiKeyAuthName]; oauth2 = newClient.authentications[oauth2Name]; diff --git a/samples/client/petstore/javascript/test/api/PetApiTest.js b/samples/client/petstore/javascript/test/api/PetApiTest.js index 3cde6ef4761..d5f7ba3424c 100644 --- a/samples/client/petstore/javascript/test/api/PetApiTest.js +++ b/samples/client/petstore/javascript/test/api/PetApiTest.js @@ -18,20 +18,36 @@ api = new SwaggerPetstore.PetApi(); }); + 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; + } + var createRandomPet = function() { var id = new Date().getTime(); var pet = new SwaggerPetstore.Pet(); - pet.setId(id); - pet.setName("pet" + id); + setProperty(pet, "setId", "id", id); + setProperty(pet, "setName", "name", "pet" + id); var category = new SwaggerPetstore.Category(); - category.setId(id); - category.setName("category" + id); - pet.setCategory(category); + setProperty(category, "setId", "id", id); + setProperty(category, "setName", "name", "category" + id); + setProperty(pet, "setCategory", "category", category); - pet.setStatus('available'); + setProperty(pet, "setStatus", "status", "available"); var photos = ["http://foo.bar.com/1", "http://foo.bar.com/2"]; - pet.setPhotoUrls(photos); + setProperty(pet, "setPhotoUrls", "photoUrls", photos); return pet; }; @@ -50,9 +66,12 @@ expect(fetched).to.be.a(SwaggerPetstore.Pet); expect(fetched.id).to.be(pet.id); - expect(fetched.getPhotoUrls()).to.eql(pet.getPhotoUrls()); - expect(fetched.getCategory()).to.be.a(SwaggerPetstore.Category); - expect(fetched.getCategory().getName()).to.be(pet.getCategory().getName()); + expect(getProperty(fetched, "getPhotoUrls", "photoUrls")) + .to.eql(getProperty(pet, "getPhotoUrls", "photoUrls")); + expect(getProperty(fetched, "getCategory", "category")) + .to.be.a(SwaggerPetstore.Category); + expect(getProperty(getProperty(fetched, "getCategory", "category"), "getName", "name")) + .to.be(getProperty(getProperty(pet, "getCategory", "category"), "getName", "name")); api.deletePet(pet.id); done(); @@ -75,8 +94,10 @@ var categoryObj = fetched.category; expect(categoryObj).to.be.a(Object); expect(categoryObj).not.to.be.a(SwaggerPetstore.Category); - expect(categoryObj.id).to.be(pet.getCategory().getId()); - expect(categoryObj.name).to.be(pet.getCategory().getName()); + expect(categoryObj.id) + .to.be(getProperty(getProperty(pet, "getCategory", "category"), "getId", "id")); + expect(categoryObj.name) + .to.be(getProperty(getProperty(pet, "getCategory", "category"), "getName", "name")); api.deletePet(pet.id); done(); diff --git a/samples/client/petstore/objc/.gitignore b/samples/client/petstore/objc/.gitignore new file mode 100644 index 00000000000..79d9331b6d4 --- /dev/null +++ b/samples/client/petstore/objc/.gitignore @@ -0,0 +1,53 @@ +# 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 + +# 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/objc/README.md b/samples/client/petstore/objc/README.md index 10e44984683..8da8058bc76 100644 --- a/samples/client/petstore/objc/README.md +++ b/samples/client/petstore/objc/README.md @@ -1,20 +1,202 @@ # SwaggerClient +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 + +This ObjC package is automatically generated by the [Swagger Codegen](https://github.com/swagger-api/swagger-codegen) project: + +- API version: 1.0.0 +- Package version: +- Build date: 2016-04-10T18:34:45.604+08:00 +- Build package: class io.swagger.codegen.languages.ObjcClientCodegen + ## Requirements -The API client library requires ARC (Automatic Reference Counting) to be enabled in your Xcode project. +The SDK requires [**ARC (Automatic Reference Counting)**](http://stackoverflow.com/questions/7778356/how-to-enable-disable-automatic-reference-counting) to be enabled in the Xcode project. -## Installation +## Installation & Usage +### Install from Github using [CocoaPods](https://cocoapods.org/) -To install it, put the API client library in your project and then simply add the following line to your Podfile: +Add the following to the Podfile: ```ruby -pod "SwaggerClient", :path => "/path/to/lib" +pod 'SwaggerClient', :git => 'https://github.com/YOUR_GIT_USR_ID/YOUR_GIT_REPO_ID.git' +``` + +To specify a particular branch, append `, :branch => 'branch-name-here'` + +To specify a particular commit, append `, :commit => '11aa22'` + +### Install from local path using [CocoaPods](https://cocoapods.org/) + +Put the SDK under your project folder (e.g. /path/to/objc_project/Vendor/SwaggerClient) and then add the following to the Podfile: + +```ruby +pod 'SwaggerClient', :path => 'Vendor/SwaggerClient' +``` + +### Usage + +Import the following: +```objc +#import +#import +// load models +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +// load API classes for accessing endpoints +#import +#import +#import + ``` ## 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 multi-threaded environment to avoid any potential issue. + +## Getting Started + +Please follow the [installation procedure](#installation--usage) and then run the following: + +```objc + +SWGConfiguration *apiConfig = [SWGConfiguration sharedConfig]; + +// Configure OAuth2 access token for authorization: (authentication scheme: petstore_auth) +[apiConfig setAccessToken:@"YOUR_ACCESS_TOKEN"]; + + +SWGPet* *body = [[SWGPet alloc] init]; // Pet object that needs to be added to the store (optional) + +@try +{ + SWGPetApi *apiInstance = [[SWGPetApi alloc] init]; + + // Add a new pet to the store + [apiInstance addPetWithBody:body + completionHandler: ^(NSError* error)) { + if (error) { + NSLog(@"Error: %@", error); + } + }]; +} +@catch (NSException *exception) +{ + NSLog(@"Exception when calling SWGPetApi->addPet: %@ ", exception.name); + NSLog(@"Reason: %@ ", exception.reason); +} + +``` + +## Documentation for API Endpoints + +All URIs are relative to *http://petstore.swagger.io/v2* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +*SWGPetApi* | [**addPet**](docs/SWGPetApi.md#addpet) | **POST** /pet | Add a new pet to the store +*SWGPetApi* | [**addPetUsingByteArray**](docs/SWGPetApi.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 +*SWGPetApi* | [**deletePet**](docs/SWGPetApi.md#deletepet) | **DELETE** /pet/{petId} | Deletes a pet +*SWGPetApi* | [**findPetsByStatus**](docs/SWGPetApi.md#findpetsbystatus) | **GET** /pet/findByStatus | Finds Pets by status +*SWGPetApi* | [**findPetsByTags**](docs/SWGPetApi.md#findpetsbytags) | **GET** /pet/findByTags | Finds Pets by tags +*SWGPetApi* | [**getPetById**](docs/SWGPetApi.md#getpetbyid) | **GET** /pet/{petId} | Find pet by ID +*SWGPetApi* | [**getPetByIdInObject**](docs/SWGPetApi.md#getpetbyidinobject) | **GET** /pet/{petId}?response=inline_arbitrary_object | Fake endpoint to test inline arbitrary object return by 'Find pet by ID' +*SWGPetApi* | [**petPetIdtestingByteArraytrueGet**](docs/SWGPetApi.md#petpetidtestingbytearraytrueget) | **GET** /pet/{petId}?testing_byte_array=true | Fake endpoint to test byte array return by 'Find pet by ID' +*SWGPetApi* | [**updatePet**](docs/SWGPetApi.md#updatepet) | **PUT** /pet | Update an existing pet +*SWGPetApi* | [**updatePetWithForm**](docs/SWGPetApi.md#updatepetwithform) | **POST** /pet/{petId} | Updates a pet in the store with form data +*SWGPetApi* | [**uploadFile**](docs/SWGPetApi.md#uploadfile) | **POST** /pet/{petId}/uploadImage | uploads an image +*SWGStoreApi* | [**deleteOrder**](docs/SWGStoreApi.md#deleteorder) | **DELETE** /store/order/{orderId} | Delete purchase order by ID +*SWGStoreApi* | [**findOrdersByStatus**](docs/SWGStoreApi.md#findordersbystatus) | **GET** /store/findByStatus | Finds orders by status +*SWGStoreApi* | [**getInventory**](docs/SWGStoreApi.md#getinventory) | **GET** /store/inventory | Returns pet inventories by status +*SWGStoreApi* | [**getInventoryInObject**](docs/SWGStoreApi.md#getinventoryinobject) | **GET** /store/inventory?response=arbitrary_object | Fake endpoint to test arbitrary object return by 'Get inventory' +*SWGStoreApi* | [**getOrderById**](docs/SWGStoreApi.md#getorderbyid) | **GET** /store/order/{orderId} | Find purchase order by ID +*SWGStoreApi* | [**placeOrder**](docs/SWGStoreApi.md#placeorder) | **POST** /store/order | Place an order for a pet +*SWGUserApi* | [**createUser**](docs/SWGUserApi.md#createuser) | **POST** /user | Create user +*SWGUserApi* | [**createUsersWithArrayInput**](docs/SWGUserApi.md#createuserswitharrayinput) | **POST** /user/createWithArray | Creates list of users with given input array +*SWGUserApi* | [**createUsersWithListInput**](docs/SWGUserApi.md#createuserswithlistinput) | **POST** /user/createWithList | Creates list of users with given input array +*SWGUserApi* | [**deleteUser**](docs/SWGUserApi.md#deleteuser) | **DELETE** /user/{username} | Delete user +*SWGUserApi* | [**getUserByName**](docs/SWGUserApi.md#getuserbyname) | **GET** /user/{username} | Get user by user name +*SWGUserApi* | [**loginUser**](docs/SWGUserApi.md#loginuser) | **GET** /user/login | Logs user into the system +*SWGUserApi* | [**logoutUser**](docs/SWGUserApi.md#logoutuser) | **GET** /user/logout | Logs out current logged in user session +*SWGUserApi* | [**updateUser**](docs/SWGUserApi.md#updateuser) | **PUT** /user/{username} | Updated user + + +## Documentation For Models + + - [SWG200Response](docs/SWG200Response.md) + - [SWGAnimal](docs/SWGAnimal.md) + - [SWGCat](docs/SWGCat.md) + - [SWGCategory](docs/SWGCategory.md) + - [SWGDog](docs/SWGDog.md) + - [SWGFormatTest](docs/SWGFormatTest.md) + - [SWGInlineResponse200](docs/SWGInlineResponse200.md) + - [SWGName](docs/SWGName.md) + - [SWGOrder](docs/SWGOrder.md) + - [SWGPet](docs/SWGPet.md) + - [SWGReturn](docs/SWGReturn.md) + - [SWGSpecialModelName_](docs/SWGSpecialModelName_.md) + - [SWGTag](docs/SWGTag.md) + - [SWGUser](docs/SWGUser.md) + + +## Documentation For Authorization + + +## test_api_key_header + +- **Type**: API key +- **API key parameter name**: test_api_key_header +- **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_client_secret + +- **Type**: API key +- **API key parameter name**: x-test_api_client_secret +- **Location**: HTTP header + +## test_api_client_id + +- **Type**: API key +- **API key parameter name**: x-test_api_client_id +- **Location**: HTTP header + +## test_api_key_query + +- **Type**: API key +- **API key parameter name**: test_api_key_query +- **Location**: URL query string + +## 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 + ## Author diff --git a/samples/client/petstore/objc/SwaggerClient.podspec b/samples/client/petstore/objc/SwaggerClient.podspec index 0afb511073c..740680eb9e2 100644 --- a/samples/client/petstore/objc/SwaggerClient.podspec +++ b/samples/client/petstore/objc/SwaggerClient.podspec @@ -13,7 +13,7 @@ Pod::Spec.new do |s| s.summary = "Swagger Petstore" s.description = <<-DESC - This is a sample server Petstore server. You can find out more about Swagger at <a href=\"http://swagger.io\">http://swagger.io</a> or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters + This is a sample server Petstore server. You can find out more about Swagger at <a href=\"http://swagger.io\">http://swagger.io</a> or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters DESC s.platform = :ios, '7.0' diff --git a/samples/client/petstore/objc/SwaggerClient/SWG200Response.h b/samples/client/petstore/objc/SwaggerClient/SWG200Response.h new file mode 100644 index 00000000000..c576bc204ad --- /dev/null +++ b/samples/client/petstore/objc/SwaggerClient/SWG200Response.h @@ -0,0 +1,20 @@ +#import +#import "SWGObject.h" + +/** + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen + * Do not edit the class manually. + */ + + + +@protocol SWG200Response +@end + +@interface SWG200Response : SWGObject + + +@property(nonatomic) NSNumber* name; + +@end diff --git a/samples/client/petstore/objc/SwaggerClient/SWG200Response.m b/samples/client/petstore/objc/SwaggerClient/SWG200Response.m new file mode 100644 index 00000000000..9cafc782f1a --- /dev/null +++ b/samples/client/petstore/objc/SwaggerClient/SWG200Response.m @@ -0,0 +1,51 @@ +#import "SWG200Response.h" + +@implementation SWG200Response + +- (instancetype)init { + self = [super init]; + + if (self) { + // initalise property's default value, if any + + } + + return self; +} + + +/** + * Maps json key to property name. + * This method is used by `JSONModel`. + */ ++ (JSONKeyMapper *)keyMapper +{ + return [[JSONKeyMapper alloc] initWithDictionary:@{ @"name": @"name" }]; +} + +/** + * Indicates whether the property with the given name is optional. + * If `propertyName` is optional, then return `YES`, otherwise return `NO`. + * This method is used by `JSONModel`. + */ ++ (BOOL)propertyIsOptional:(NSString *)propertyName +{ + NSArray *optionalProperties = @[@"name"]; + + if ([optionalProperties containsObject:propertyName]) { + return YES; + } + else { + return NO; + } +} + +/** + * Gets the string presentation of the object. + * This method will be called when logging model object using `NSLog`. + */ +- (NSString *)description { + return [[self toDictionary] description]; +} + +@end diff --git a/samples/client/petstore/objc/SwaggerClient/SWGApiClient.h b/samples/client/petstore/objc/SwaggerClient/SWGApiClient.h index f4009bbc408..af299ff0008 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGApiClient.h +++ b/samples/client/petstore/objc/SwaggerClient/SWGApiClient.h @@ -12,14 +12,21 @@ * Do not edit the class manually. */ -#import "SWGUser.h" +#import "SWG200Response.h" +#import "SWGAnimal.h" +#import "SWGCat.h" #import "SWGCategory.h" -#import "SWGPet.h" -#import "SWGTag.h" -#import "SWGReturn.h" -#import "SWGOrder.h" -#import "SWGSpecialModelName_.h" +#import "SWGDog.h" +#import "SWGFormatTest.h" #import "SWGInlineResponse200.h" +#import "SWGName.h" +#import "SWGOrder.h" +#import "SWGPet.h" +#import "SWGReturn.h" +#import "SWGSpecialModelName_.h" +#import "SWGTag.h" +#import "SWGUser.h" + @class SWGConfiguration; @@ -71,6 +78,20 @@ extern NSString *const SWGResponseObjectErrorKey; */ +(void) setOfflineState:(BOOL) state; +/** + * Gets if the client is unreachable + * + * @return The client offline state + */ ++(bool) getOfflineState; + +/** + * Sets the client reachability, this may be overridden by the reachability manager if reachability changes + * + * @param The client reachability. + */ ++(void) setReachabilityStatus:(AFNetworkReachabilityStatus) status; + /** * Gets the client reachability * diff --git a/samples/client/petstore/objc/SwaggerClient/SWGApiClient.m b/samples/client/petstore/objc/SwaggerClient/SWGApiClient.m index 5792adaca2e..0c8f21d3ae7 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGApiClient.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGApiClient.m @@ -53,6 +53,10 @@ static void (^reachabilityChangeBlock)(int); cacheEnabled = enabled; } ++(void) setReachabilityStatus:(AFNetworkReachabilityStatus)status { + reachabilityStatus = status; +} + - (void)setHeaderValue:(NSString*) value forKey:(NSString*) forKey { [self.requestSerializer setValue:value forHTTPHeaderField:forKey]; @@ -238,6 +242,10 @@ static void (^reachabilityChangeBlock)(int); return reachabilityStatus; } ++(bool) getOfflineState { + return offlineState; +} + +(void) setReachabilityChangeBlock:(void(^)(int))changeBlock { reachabilityChangeBlock = changeBlock; } @@ -708,11 +716,11 @@ static void (^reachabilityChangeBlock)(int); for (NSString *auth in authSettings) { NSDictionary *authSetting = [[config authSettings] objectForKey:auth]; - if (authSetting) { - if ([authSetting[@"in"] isEqualToString:@"header"]) { + if (authSetting) { // auth setting is set only if the key is non-empty + if ([authSetting[@"in"] isEqualToString:@"header"] && [authSetting[@"key"] length] != 0) { [headersWithAuth setObject:authSetting[@"value"] forKey:authSetting[@"key"]]; } - else if ([authSetting[@"in"] isEqualToString:@"query"]) { + else if ([authSetting[@"in"] isEqualToString:@"query"] && [authSetting[@"key"] length] != 0) { [querysWithAuth setObject:authSetting[@"value"] forKey:authSetting[@"key"]]; } } diff --git a/samples/client/petstore/objc/SwaggerClient/SWGConfiguration.h b/samples/client/petstore/objc/SwaggerClient/SWGConfiguration.h index cd4e7117e89..27cfe5d6d24 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGConfiguration.h +++ b/samples/client/petstore/objc/SwaggerClient/SWGConfiguration.h @@ -46,6 +46,11 @@ */ @property (nonatomic) NSString *password; +/** + * Access token for OAuth + */ +@property (nonatomic) NSString *accessToken; + /** * Temp folder for file download */ @@ -132,6 +137,11 @@ */ - (NSString *) getBasicAuthToken; +/** + * Gets OAuth access token + */ +- (NSString *) getAccessToken; + /** * Gets Authentication Setings */ diff --git a/samples/client/petstore/objc/SwaggerClient/SWGConfiguration.m b/samples/client/petstore/objc/SwaggerClient/SWGConfiguration.m index abe60d76a38..0e5b36f4a81 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGConfiguration.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGConfiguration.m @@ -29,6 +29,7 @@ self.host = @"http://petstore.swagger.io/v2"; self.username = @""; self.password = @""; + self.accessToken= @""; self.tempFolderPath = nil; self.debug = NO; self.verifySSL = YES; @@ -42,18 +43,23 @@ #pragma mark - Instance Methods - (NSString *) getApiKeyWithPrefix:(NSString *)key { - if ([self.apiKeyPrefix objectForKey:key] && [self.apiKey objectForKey:key]) { + if ([self.apiKeyPrefix objectForKey:key] && [self.apiKey objectForKey:key] != (id)[NSNull null] && [[self.apiKey objectForKey:key] length] != 0) { // both api key prefix and api key are set return [NSString stringWithFormat:@"%@ %@", [self.apiKeyPrefix objectForKey:key], [self.apiKey objectForKey:key]]; } - else if ([self.apiKey objectForKey:key]) { + else if ([self.apiKey objectForKey:key] != (id)[NSNull null] && [[self.apiKey objectForKey:key] length] != 0) { // only api key, no api key prefix return [NSString stringWithFormat:@"%@", [self.apiKey objectForKey:key]]; } - else { + else { // return empty string if nothing is set return @""; } } - (NSString *) getBasicAuthToken { + // return empty string if username and password are empty + if (self.username.length == 0 && self.password.length == 0){ + return @""; + } + NSString *basicAuthCredentials = [NSString stringWithFormat:@"%@:%@", self.username, self.password]; NSData *data = [basicAuthCredentials dataUsingEncoding:NSUTF8StringEncoding]; basicAuthCredentials = [NSString stringWithFormat:@"Basic %@", [data base64EncodedStringWithOptions:0]]; @@ -61,6 +67,15 @@ return basicAuthCredentials; } +- (NSString *) getAccessToken { + if (self.accessToken.length == 0) { // token not set, return empty string + return @""; + } + else { + return [NSString stringWithFormat:@"BEARER %@", self.accessToken]; + } +} + #pragma mark - Setter Methods - (void) setApiKey:(NSString *)apiKey forApiKeyIdentifier:(NSString *)identifier { @@ -121,6 +136,13 @@ @"key": @"api_key", @"value": [self getApiKeyWithPrefix:@"api_key"] }, + @"test_http_basic": + @{ + @"type": @"basic", + @"in": @"header", + @"key": @"Authorization", + @"value": [self getBasicAuthToken] + }, @"test_api_client_secret": @{ @"type": @"api_key", @@ -142,6 +164,13 @@ @"key": @"test_api_key_query", @"value": [self getApiKeyWithPrefix:@"test_api_key_query"] }, + @"petstore_auth": + @{ + @"type": @"oauth", + @"in": @"header", + @"key": @"Authorization", + @"value": [self getAccessToken] + }, }; } diff --git a/samples/client/petstore/objc/SwaggerClient/SWGInlineResponse200.h b/samples/client/petstore/objc/SwaggerClient/SWGInlineResponse200.h index 74860956be9..aeb69eafa69 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGInlineResponse200.h +++ b/samples/client/petstore/objc/SwaggerClient/SWGInlineResponse200.h @@ -7,6 +7,7 @@ * Do not edit the class manually. */ +#import "SWGTag.h" @protocol SWGInlineResponse200 @@ -15,10 +16,17 @@ @interface SWGInlineResponse200 : SWGObject +@property(nonatomic) NSArray* tags; + @property(nonatomic) NSNumber* _id; @property(nonatomic) NSObject* category; +/* pet status in the store [optional] + */ +@property(nonatomic) NSString* status; @property(nonatomic) NSString* name; +@property(nonatomic) NSArray* /* NSString */ photoUrls; + @end diff --git a/samples/client/petstore/objc/SwaggerClient/SWGInlineResponse200.m b/samples/client/petstore/objc/SwaggerClient/SWGInlineResponse200.m index 9f332e31a15..5ac2e7b4057 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGInlineResponse200.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGInlineResponse200.m @@ -20,7 +20,7 @@ */ + (JSONKeyMapper *)keyMapper { - return [[JSONKeyMapper alloc] initWithDictionary:@{ @"id": @"_id", @"category": @"category", @"name": @"name" }]; + return [[JSONKeyMapper alloc] initWithDictionary:@{ @"tags": @"tags", @"id": @"_id", @"category": @"category", @"status": @"status", @"name": @"name", @"photoUrls": @"photoUrls" }]; } /** @@ -30,7 +30,7 @@ */ + (BOOL)propertyIsOptional:(NSString *)propertyName { - NSArray *optionalProperties = @[@"category", @"name"]; + NSArray *optionalProperties = @[@"tags", @"category", @"status", @"name", @"photoUrls"]; if ([optionalProperties containsObject:propertyName]) { return YES; diff --git a/samples/client/petstore/objc/SwaggerClient/SWGName.h b/samples/client/petstore/objc/SwaggerClient/SWGName.h new file mode 100644 index 00000000000..fd34af7b66a --- /dev/null +++ b/samples/client/petstore/objc/SwaggerClient/SWGName.h @@ -0,0 +1,22 @@ +#import +#import "SWGObject.h" + +/** + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen + * Do not edit the class manually. + */ + + + +@protocol SWGName +@end + +@interface SWGName : SWGObject + + +@property(nonatomic) NSNumber* name; + +@property(nonatomic) NSNumber* snakeCase; + +@end diff --git a/samples/client/petstore/objc/SwaggerClient/SWGName.m b/samples/client/petstore/objc/SwaggerClient/SWGName.m new file mode 100644 index 00000000000..16aec784549 --- /dev/null +++ b/samples/client/petstore/objc/SwaggerClient/SWGName.m @@ -0,0 +1,51 @@ +#import "SWGName.h" + +@implementation SWGName + +- (instancetype)init { + self = [super init]; + + if (self) { + // initalise property's default value, if any + + } + + return self; +} + + +/** + * Maps json key to property name. + * This method is used by `JSONModel`. + */ ++ (JSONKeyMapper *)keyMapper +{ + return [[JSONKeyMapper alloc] initWithDictionary:@{ @"name": @"name", @"snake_case": @"snakeCase" }]; +} + +/** + * Indicates whether the property with the given name is optional. + * If `propertyName` is optional, then return `YES`, otherwise return `NO`. + * This method is used by `JSONModel`. + */ ++ (BOOL)propertyIsOptional:(NSString *)propertyName +{ + NSArray *optionalProperties = @[@"snakeCase"]; + + if ([optionalProperties containsObject:propertyName]) { + return YES; + } + else { + return NO; + } +} + +/** + * Gets the string presentation of the object. + * This method will be called when logging model object using `NSLog`. + */ +- (NSString *)description { + return [[self toDictionary] description]; +} + +@end diff --git a/samples/client/petstore/objc/SwaggerClient/SWGPetApi.h b/samples/client/petstore/objc/SwaggerClient/SWGPetApi.h index 76bcd3524d9..1142ff5311f 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGPetApi.h +++ b/samples/client/petstore/objc/SwaggerClient/SWGPetApi.h @@ -20,19 +20,6 @@ -(unsigned long) requestQueueSize; +(SWGPetApi*) apiWithHeader:(NSString*)headerValue key:(NSString*)key; +(SWGPetApi*) sharedAPI; -/// -/// -/// Update an existing pet -/// -/// -/// @param body Pet object that needs to be added to the store -/// -/// -/// @return --(NSNumber*) updatePetWithBody: (SWGPet*) body - completionHandler: (void (^)(NSError* error)) handler; - - /// /// /// Add a new pet to the store @@ -46,6 +33,34 @@ completionHandler: (void (^)(NSError* error)) handler; +/// +/// +/// Fake endpoint to test byte array in body parameter for adding a new pet to the store +/// +/// +/// @param body Pet object in the form of byte array +/// +/// +/// @return +-(NSNumber*) addPetUsingByteArrayWithBody: (NSString*) body + completionHandler: (void (^)(NSError* error)) handler; + + +/// +/// +/// Deletes a pet +/// +/// +/// @param petId Pet id to delete +/// @param apiKey +/// +/// +/// @return +-(NSNumber*) deletePetWithPetId: (NSNumber*) petId + apiKey: (NSString*) apiKey + completionHandler: (void (^)(NSError* error)) handler; + + /// /// /// Finds Pets by status @@ -85,55 +100,6 @@ completionHandler: (void (^)(SWGPet* output, NSError* error)) handler; -/// -/// -/// Updates a pet in the store with form data -/// -/// -/// @param petId ID of pet that needs to be updated -/// @param name Updated name of the pet -/// @param status Updated status of the pet -/// -/// -/// @return --(NSNumber*) updatePetWithFormWithPetId: (NSString*) petId - name: (NSString*) name - status: (NSString*) status - completionHandler: (void (^)(NSError* error)) handler; - - -/// -/// -/// Deletes a pet -/// -/// -/// @param petId Pet id to delete -/// @param apiKey -/// -/// -/// @return --(NSNumber*) deletePetWithPetId: (NSNumber*) petId - apiKey: (NSString*) apiKey - completionHandler: (void (^)(NSError* error)) handler; - - -/// -/// -/// uploads an image -/// -/// -/// @param petId ID of pet to update -/// @param additionalMetadata Additional data to pass to server -/// @param file file to upload -/// -/// -/// @return --(NSNumber*) uploadFileWithPetId: (NSNumber*) petId - additionalMetadata: (NSString*) additionalMetadata - file: (NSURL*) file - completionHandler: (void (^)(NSError* error)) handler; - - /// /// /// Fake endpoint to test inline arbitrary object return by 'Find pet by ID' @@ -162,14 +128,48 @@ /// /// -/// Fake endpoint to test byte array in body parameter for adding a new pet to the store +/// Update an existing pet /// /// -/// @param body Pet object in the form of byte array +/// @param body Pet object that needs to be added to the store /// /// /// @return --(NSNumber*) addPetUsingByteArrayWithBody: (NSString*) body +-(NSNumber*) updatePetWithBody: (SWGPet*) body + completionHandler: (void (^)(NSError* error)) handler; + + +/// +/// +/// Updates a pet in the store with form data +/// +/// +/// @param petId ID of pet that needs to be updated +/// @param name Updated name of the pet +/// @param status Updated status of the pet +/// +/// +/// @return +-(NSNumber*) updatePetWithFormWithPetId: (NSString*) petId + name: (NSString*) name + status: (NSString*) status + completionHandler: (void (^)(NSError* error)) handler; + + +/// +/// +/// uploads an image +/// +/// +/// @param petId ID of pet to update +/// @param additionalMetadata Additional data to pass to server +/// @param file file to upload +/// +/// +/// @return +-(NSNumber*) uploadFileWithPetId: (NSNumber*) petId + additionalMetadata: (NSString*) additionalMetadata + file: (NSURL*) file completionHandler: (void (^)(NSError* error)) handler; diff --git a/samples/client/petstore/objc/SwaggerClient/SWGPetApi.m b/samples/client/petstore/objc/SwaggerClient/SWGPetApi.m index 717ca6b7b22..8c7959a8c3f 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGPetApi.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGPetApi.m @@ -39,7 +39,6 @@ static SWGPetApi* singletonAPI = nil; #pragma mark - +(SWGPetApi*) apiWithHeader:(NSString*)headerValue key:(NSString*)key { - if (singletonAPI == nil) { singletonAPI = [[SWGPetApi alloc] init]; [singletonAPI addHeader:headerValue forKey:key]; @@ -48,7 +47,6 @@ static SWGPetApi* singletonAPI = nil; } +(SWGPetApi*) sharedAPI { - if (singletonAPI == nil) { singletonAPI = [[SWGPetApi alloc] init]; } @@ -70,93 +68,15 @@ static SWGPetApi* singletonAPI = nil; #pragma mark - Api Methods -/// -/// Update an existing pet -/// -/// @param body Pet object that needs to be added to the store -/// -/// @returns void -/// --(NSNumber*) updatePetWithBody: (SWGPet*) body - completionHandler: (void (^)(NSError* error)) handler { - - - - NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/pet"]; - - // remove format in URL if needed - if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { - [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; - } - - NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; - - - NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; - - NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; - - - - // HTTP header `Accept` - headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; - if ([headerParams[@"Accept"] length] == 0) { - [headerParams removeObjectForKey:@"Accept"]; - } - - // response content type - NSString *responseContentType; - if ([headerParams objectForKey:@"Accept"]) { - responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0]; - } - else { - responseContentType = @""; - } - - // request content type - NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[@"application/json", @"application/xml"]]; - - // Authentication setting - NSArray *authSettings = @[@"petstore_auth"]; - - id bodyParam = nil; - NSMutableDictionary *formParams = [[NSMutableDictionary alloc] init]; - NSMutableDictionary *localVarFiles = [[NSMutableDictionary alloc] init]; - - bodyParam = body; - - - - return [self.apiClient requestWithPath: resourcePath - method: @"PUT" - pathParams: pathParams - queryParams: queryParams - formParams: formParams - files: localVarFiles - body: bodyParam - headerParams: headerParams - authSettings: authSettings - requestContentType: requestContentType - responseContentType: responseContentType - responseType: nil - completionBlock: ^(id data, NSError *error) { - handler(error); - } - ]; -} - /// /// Add a new pet to the store /// -/// @param body Pet object that needs to be added to the store +/// @param body Pet object that needs to be added to the store (optional) /// /// @returns void /// -(NSNumber*) addPetWithBody: (SWGPet*) body completionHandler: (void (^)(NSError* error)) handler { - - - NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/pet"]; // remove format in URL if needed @@ -165,14 +85,9 @@ static SWGPetApi* singletonAPI = nil; } NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; - NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; - NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; - - - // HTTP header `Accept` headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; if ([headerParams[@"Accept"] length] == 0) { @@ -197,11 +112,8 @@ static SWGPetApi* singletonAPI = nil; id bodyParam = nil; NSMutableDictionary *formParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary *localVarFiles = [[NSMutableDictionary alloc] init]; - bodyParam = body; - - return [self.apiClient requestWithPath: resourcePath method: @"POST" pathParams: pathParams @@ -221,18 +133,15 @@ static SWGPetApi* singletonAPI = nil; } /// -/// Finds Pets by status -/// Multiple status values can be provided with comma separated strings -/// @param status Status values that need to be considered for query +/// Fake endpoint to test byte array in body parameter for adding a new pet to the store +/// +/// @param body Pet object in the form of byte array (optional) /// -/// @returns NSArray* +/// @returns void /// --(NSNumber*) findPetsByStatusWithStatus: (NSArray* /* NSString */) status - completionHandler: (void (^)(NSArray* output, NSError* error)) handler { - - - - NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/pet/findByStatus"]; +-(NSNumber*) addPetUsingByteArrayWithBody: (NSString*) body + completionHandler: (void (^)(NSError* error)) handler { + NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/pet?testing_byte_array=true"]; // remove format in URL if needed if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { @@ -240,19 +149,88 @@ static SWGPetApi* singletonAPI = nil; } NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; - NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; - if (status != nil) { - - queryParams[@"status"] = [[SWGQueryParamCollection alloc] initWithValuesAndFormat: status format: @"multi"]; - - - } - NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; + // HTTP header `Accept` + headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; + if ([headerParams[@"Accept"] length] == 0) { + [headerParams removeObjectForKey:@"Accept"]; + } + // response content type + NSString *responseContentType; + if ([headerParams objectForKey:@"Accept"]) { + responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0]; + } + else { + responseContentType = @""; + } + + // request content type + NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[@"application/json", @"application/xml"]]; + + // Authentication setting + NSArray *authSettings = @[@"petstore_auth"]; + + id bodyParam = nil; + NSMutableDictionary *formParams = [[NSMutableDictionary alloc] init]; + NSMutableDictionary *localVarFiles = [[NSMutableDictionary alloc] init]; + bodyParam = body; + + return [self.apiClient requestWithPath: resourcePath + method: @"POST" + pathParams: pathParams + queryParams: queryParams + formParams: formParams + files: localVarFiles + body: bodyParam + headerParams: headerParams + authSettings: authSettings + requestContentType: requestContentType + responseContentType: responseContentType + responseType: nil + completionBlock: ^(id data, NSError *error) { + handler(error); + } + ]; +} + +/// +/// Deletes a pet +/// +/// @param petId Pet id to delete +/// +/// @param apiKey (optional) +/// +/// @returns void +/// +-(NSNumber*) deletePetWithPetId: (NSNumber*) petId + apiKey: (NSString*) apiKey + completionHandler: (void (^)(NSError* error)) handler { + // verify the required parameter 'petId' is set + if (petId == nil) { + [NSException raise:@"Invalid parameter" format:@"Missing the required parameter `petId` when calling `deletePet`"]; + } + + NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/pet/{petId}"]; + + // remove format in URL if needed + if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { + [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; + } + + NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; + if (petId != nil) { + pathParams[@"petId"] = petId; + } + + NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; + NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; + if (apiKey != nil) { + headerParams[@"api_key"] = apiKey; + } // HTTP header `Accept` headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; @@ -278,11 +256,74 @@ static SWGPetApi* singletonAPI = nil; id bodyParam = nil; NSMutableDictionary *formParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary *localVarFiles = [[NSMutableDictionary alloc] init]; - - - - + return [self.apiClient requestWithPath: resourcePath + method: @"DELETE" + pathParams: pathParams + queryParams: queryParams + formParams: formParams + files: localVarFiles + body: bodyParam + headerParams: headerParams + authSettings: authSettings + requestContentType: requestContentType + responseContentType: responseContentType + responseType: nil + completionBlock: ^(id data, NSError *error) { + handler(error); + } + ]; +} + +/// +/// Finds Pets by status +/// Multiple status values can be provided with comma separated strings +/// @param status Status values that need to be considered for query (optional, default to available) +/// +/// @returns NSArray* +/// +-(NSNumber*) findPetsByStatusWithStatus: (NSArray* /* NSString */) status + completionHandler: (void (^)(NSArray* output, NSError* error)) handler { + NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/pet/findByStatus"]; + + // remove format in URL if needed + if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { + [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; + } + + NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; + + NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; + if (status != nil) { + queryParams[@"status"] = [[SWGQueryParamCollection alloc] initWithValuesAndFormat: status format: @"multi"]; + + } + NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; + // HTTP header `Accept` + headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; + if ([headerParams[@"Accept"] length] == 0) { + [headerParams removeObjectForKey:@"Accept"]; + } + + // response content type + NSString *responseContentType; + if ([headerParams objectForKey:@"Accept"]) { + responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0]; + } + else { + responseContentType = @""; + } + + // request content type + NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; + + // Authentication setting + NSArray *authSettings = @[@"petstore_auth"]; + + id bodyParam = nil; + NSMutableDictionary *formParams = [[NSMutableDictionary alloc] init]; + NSMutableDictionary *localVarFiles = [[NSMutableDictionary alloc] init]; + return [self.apiClient requestWithPath: resourcePath method: @"GET" pathParams: pathParams @@ -304,15 +345,12 @@ static SWGPetApi* singletonAPI = nil; /// /// Finds Pets by tags /// Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. -/// @param tags Tags to filter by +/// @param tags Tags to filter by (optional) /// /// @returns NSArray* /// -(NSNumber*) findPetsByTagsWithTags: (NSArray* /* NSString */) tags completionHandler: (void (^)(NSArray* output, NSError* error)) handler { - - - NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/pet/findByTags"]; // remove format in URL if needed @@ -321,20 +359,13 @@ static SWGPetApi* singletonAPI = nil; } NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; - NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; if (tags != nil) { - queryParams[@"tags"] = [[SWGQueryParamCollection alloc] initWithValuesAndFormat: tags format: @"multi"]; - } - NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; - - - // HTTP header `Accept` headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; if ([headerParams[@"Accept"] length] == 0) { @@ -359,11 +390,7 @@ static SWGPetApi* singletonAPI = nil; id bodyParam = nil; NSMutableDictionary *formParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary *localVarFiles = [[NSMutableDictionary alloc] init]; - - - - return [self.apiClient requestWithPath: resourcePath method: @"GET" pathParams: pathParams @@ -385,19 +412,16 @@ static SWGPetApi* singletonAPI = nil; /// /// Find pet by ID /// Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions -/// @param petId ID of pet that needs to be fetched +/// @param petId ID of pet that needs to be fetched /// /// @returns SWGPet* /// -(NSNumber*) getPetByIdWithPetId: (NSNumber*) petId completionHandler: (void (^)(SWGPet* output, NSError* error)) handler { - - // verify the required parameter 'petId' is set if (petId == nil) { [NSException raise:@"Invalid parameter" format:@"Missing the required parameter `petId` when calling `getPetById`"]; } - NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/pet/{petId}"]; @@ -410,14 +434,9 @@ static SWGPetApi* singletonAPI = nil; if (petId != nil) { pathParams[@"petId"] = petId; } - NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; - NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; - - - // HTTP header `Accept` headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; if ([headerParams[@"Accept"] length] == 0) { @@ -442,11 +461,7 @@ static SWGPetApi* singletonAPI = nil; id bodyParam = nil; NSMutableDictionary *formParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary *localVarFiles = [[NSMutableDictionary alloc] init]; - - - - return [self.apiClient requestWithPath: resourcePath method: @"GET" pathParams: pathParams @@ -465,14 +480,220 @@ static SWGPetApi* singletonAPI = nil; ]; } +/// +/// Fake endpoint to test inline arbitrary object return by 'Find pet by ID' +/// Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions +/// @param petId ID of pet that needs to be fetched +/// +/// @returns SWGInlineResponse200* +/// +-(NSNumber*) getPetByIdInObjectWithPetId: (NSNumber*) petId + completionHandler: (void (^)(SWGInlineResponse200* output, NSError* error)) handler { + // verify the required parameter 'petId' is set + if (petId == nil) { + [NSException raise:@"Invalid parameter" format:@"Missing the required parameter `petId` when calling `getPetByIdInObject`"]; + } + + NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/pet/{petId}?response=inline_arbitrary_object"]; + + // remove format in URL if needed + if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { + [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; + } + + NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; + if (petId != nil) { + pathParams[@"petId"] = petId; + } + + NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; + NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; + // HTTP header `Accept` + headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; + if ([headerParams[@"Accept"] length] == 0) { + [headerParams removeObjectForKey:@"Accept"]; + } + + // response content type + NSString *responseContentType; + if ([headerParams objectForKey:@"Accept"]) { + responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0]; + } + else { + responseContentType = @""; + } + + // request content type + NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; + + // Authentication setting + NSArray *authSettings = @[@"api_key", @"petstore_auth"]; + + id bodyParam = nil; + NSMutableDictionary *formParams = [[NSMutableDictionary alloc] init]; + NSMutableDictionary *localVarFiles = [[NSMutableDictionary alloc] init]; + + return [self.apiClient requestWithPath: resourcePath + method: @"GET" + pathParams: pathParams + queryParams: queryParams + formParams: formParams + files: localVarFiles + body: bodyParam + headerParams: headerParams + authSettings: authSettings + requestContentType: requestContentType + responseContentType: responseContentType + responseType: @"SWGInlineResponse200*" + completionBlock: ^(id data, NSError *error) { + handler((SWGInlineResponse200*)data, error); + } + ]; +} + +/// +/// Fake endpoint to test byte array return by 'Find pet by ID' +/// Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions +/// @param petId ID of pet that needs to be fetched +/// +/// @returns NSString* +/// +-(NSNumber*) petPetIdtestingByteArraytrueGetWithPetId: (NSNumber*) petId + completionHandler: (void (^)(NSString* output, NSError* error)) handler { + // verify the required parameter 'petId' is set + if (petId == nil) { + [NSException raise:@"Invalid parameter" format:@"Missing the required parameter `petId` when calling `petPetIdtestingByteArraytrueGet`"]; + } + + NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/pet/{petId}?testing_byte_array=true"]; + + // remove format in URL if needed + if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { + [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; + } + + NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; + if (petId != nil) { + pathParams[@"petId"] = petId; + } + + NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; + NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; + // HTTP header `Accept` + headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; + if ([headerParams[@"Accept"] length] == 0) { + [headerParams removeObjectForKey:@"Accept"]; + } + + // response content type + NSString *responseContentType; + if ([headerParams objectForKey:@"Accept"]) { + responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0]; + } + else { + responseContentType = @""; + } + + // request content type + NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; + + // Authentication setting + NSArray *authSettings = @[@"api_key", @"petstore_auth"]; + + id bodyParam = nil; + NSMutableDictionary *formParams = [[NSMutableDictionary alloc] init]; + NSMutableDictionary *localVarFiles = [[NSMutableDictionary alloc] init]; + + return [self.apiClient requestWithPath: resourcePath + method: @"GET" + pathParams: pathParams + queryParams: queryParams + formParams: formParams + files: localVarFiles + body: bodyParam + headerParams: headerParams + authSettings: authSettings + requestContentType: requestContentType + responseContentType: responseContentType + responseType: @"NSString*" + completionBlock: ^(id data, NSError *error) { + handler((NSString*)data, error); + } + ]; +} + +/// +/// Update an existing pet +/// +/// @param body Pet object that needs to be added to the store (optional) +/// +/// @returns void +/// +-(NSNumber*) updatePetWithBody: (SWGPet*) body + completionHandler: (void (^)(NSError* error)) handler { + NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/pet"]; + + // remove format in URL if needed + if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { + [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; + } + + NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; + + NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; + NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; + // HTTP header `Accept` + headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; + if ([headerParams[@"Accept"] length] == 0) { + [headerParams removeObjectForKey:@"Accept"]; + } + + // response content type + NSString *responseContentType; + if ([headerParams objectForKey:@"Accept"]) { + responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0]; + } + else { + responseContentType = @""; + } + + // request content type + NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[@"application/json", @"application/xml"]]; + + // Authentication setting + NSArray *authSettings = @[@"petstore_auth"]; + + id bodyParam = nil; + NSMutableDictionary *formParams = [[NSMutableDictionary alloc] init]; + NSMutableDictionary *localVarFiles = [[NSMutableDictionary alloc] init]; + bodyParam = body; + + return [self.apiClient requestWithPath: resourcePath + method: @"PUT" + pathParams: pathParams + queryParams: queryParams + formParams: formParams + files: localVarFiles + body: bodyParam + headerParams: headerParams + authSettings: authSettings + requestContentType: requestContentType + responseContentType: responseContentType + responseType: nil + completionBlock: ^(id data, NSError *error) { + handler(error); + } + ]; +} + /// /// Updates a pet in the store with form data /// -/// @param petId ID of pet that needs to be updated +/// @param petId ID of pet that needs to be updated /// -/// @param name Updated name of the pet +/// @param name Updated name of the pet (optional) /// -/// @param status Updated status of the pet +/// @param status Updated status of the pet (optional) /// /// @returns void /// @@ -480,13 +701,10 @@ static SWGPetApi* singletonAPI = nil; name: (NSString*) name status: (NSString*) status completionHandler: (void (^)(NSError* error)) handler { - - // verify the required parameter 'petId' is set if (petId == nil) { [NSException raise:@"Invalid parameter" format:@"Missing the required parameter `petId` when calling `updatePetWithForm`"]; } - NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/pet/{petId}"]; @@ -499,14 +717,9 @@ static SWGPetApi* singletonAPI = nil; if (petId != nil) { pathParams[@"petId"] = petId; } - NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; - NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; - - - // HTTP header `Accept` headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; if ([headerParams[@"Accept"] length] == 0) { @@ -531,23 +744,13 @@ static SWGPetApi* singletonAPI = nil; id bodyParam = nil; NSMutableDictionary *formParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary *localVarFiles = [[NSMutableDictionary alloc] init]; - - - if (name) { formParams[@"name"] = name; } - - - if (status) { formParams[@"status"] = status; } - - - - return [self.apiClient requestWithPath: resourcePath method: @"POST" pathParams: pathParams @@ -566,103 +769,14 @@ static SWGPetApi* singletonAPI = nil; ]; } -/// -/// Deletes a pet -/// -/// @param petId Pet id to delete -/// -/// @param apiKey -/// -/// @returns void -/// --(NSNumber*) deletePetWithPetId: (NSNumber*) petId - apiKey: (NSString*) apiKey - completionHandler: (void (^)(NSError* error)) handler { - - - // verify the required parameter 'petId' is set - if (petId == nil) { - [NSException raise:@"Invalid parameter" format:@"Missing the required parameter `petId` when calling `deletePet`"]; - } - - - NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/pet/{petId}"]; - - // remove format in URL if needed - if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { - [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; - } - - NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; - if (petId != nil) { - pathParams[@"petId"] = petId; - } - - - NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; - - NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; - - if (apiKey != nil) { - headerParams[@"api_key"] = apiKey; - } - - - // HTTP header `Accept` - headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; - if ([headerParams[@"Accept"] length] == 0) { - [headerParams removeObjectForKey:@"Accept"]; - } - - // response content type - NSString *responseContentType; - if ([headerParams objectForKey:@"Accept"]) { - responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0]; - } - else { - responseContentType = @""; - } - - // request content type - NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; - - // Authentication setting - NSArray *authSettings = @[@"petstore_auth"]; - - id bodyParam = nil; - NSMutableDictionary *formParams = [[NSMutableDictionary alloc] init]; - NSMutableDictionary *localVarFiles = [[NSMutableDictionary alloc] init]; - - - - - - return [self.apiClient requestWithPath: resourcePath - method: @"DELETE" - pathParams: pathParams - queryParams: queryParams - formParams: formParams - files: localVarFiles - body: bodyParam - headerParams: headerParams - authSettings: authSettings - requestContentType: requestContentType - responseContentType: responseContentType - responseType: nil - completionBlock: ^(id data, NSError *error) { - handler(error); - } - ]; -} - /// /// uploads an image /// -/// @param petId ID of pet to update +/// @param petId ID of pet to update /// -/// @param additionalMetadata Additional data to pass to server +/// @param additionalMetadata Additional data to pass to server (optional) /// -/// @param file file to upload +/// @param file file to upload (optional) /// /// @returns void /// @@ -670,13 +784,10 @@ static SWGPetApi* singletonAPI = nil; additionalMetadata: (NSString*) additionalMetadata file: (NSURL*) file completionHandler: (void (^)(NSError* error)) handler { - - // verify the required parameter 'petId' is set if (petId == nil) { [NSException raise:@"Invalid parameter" format:@"Missing the required parameter `petId` when calling `uploadFile`"]; } - NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/pet/{petId}/uploadImage"]; @@ -689,14 +800,9 @@ static SWGPetApi* singletonAPI = nil; if (petId != nil) { pathParams[@"petId"] = petId; } - NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; - NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; - - - // HTTP header `Accept` headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; if ([headerParams[@"Accept"] length] == 0) { @@ -721,262 +827,11 @@ static SWGPetApi* singletonAPI = nil; id bodyParam = nil; NSMutableDictionary *formParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary *localVarFiles = [[NSMutableDictionary alloc] init]; - - - if (additionalMetadata) { formParams[@"additionalMetadata"] = additionalMetadata; } - - - localVarFiles[@"file"] = file; - - - - - return [self.apiClient requestWithPath: resourcePath - method: @"POST" - pathParams: pathParams - queryParams: queryParams - formParams: formParams - files: localVarFiles - body: bodyParam - headerParams: headerParams - authSettings: authSettings - requestContentType: requestContentType - responseContentType: responseContentType - responseType: nil - completionBlock: ^(id data, NSError *error) { - handler(error); - } - ]; -} - -/// -/// Fake endpoint to test inline arbitrary object return by 'Find pet by ID' -/// Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions -/// @param petId ID of pet that needs to be fetched -/// -/// @returns SWGInlineResponse200* -/// --(NSNumber*) getPetByIdInObjectWithPetId: (NSNumber*) petId - completionHandler: (void (^)(SWGInlineResponse200* output, NSError* error)) handler { - - - // verify the required parameter 'petId' is set - if (petId == nil) { - [NSException raise:@"Invalid parameter" format:@"Missing the required parameter `petId` when calling `getPetByIdInObject`"]; - } - - - NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/pet/{petId}?response=inline_arbitrary_object"]; - - // remove format in URL if needed - if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { - [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; - } - - NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; - if (petId != nil) { - pathParams[@"petId"] = petId; - } - - - NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; - - NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; - - - - // HTTP header `Accept` - headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; - if ([headerParams[@"Accept"] length] == 0) { - [headerParams removeObjectForKey:@"Accept"]; - } - - // response content type - NSString *responseContentType; - if ([headerParams objectForKey:@"Accept"]) { - responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0]; - } - else { - responseContentType = @""; - } - - // request content type - NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; - - // Authentication setting - NSArray *authSettings = @[@"api_key", @"petstore_auth"]; - - id bodyParam = nil; - NSMutableDictionary *formParams = [[NSMutableDictionary alloc] init]; - NSMutableDictionary *localVarFiles = [[NSMutableDictionary alloc] init]; - - - - - - return [self.apiClient requestWithPath: resourcePath - method: @"GET" - pathParams: pathParams - queryParams: queryParams - formParams: formParams - files: localVarFiles - body: bodyParam - headerParams: headerParams - authSettings: authSettings - requestContentType: requestContentType - responseContentType: responseContentType - responseType: @"SWGInlineResponse200*" - completionBlock: ^(id data, NSError *error) { - handler((SWGInlineResponse200*)data, error); - } - ]; -} - -/// -/// Fake endpoint to test byte array return by 'Find pet by ID' -/// Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions -/// @param petId ID of pet that needs to be fetched -/// -/// @returns NSString* -/// --(NSNumber*) petPetIdtestingByteArraytrueGetWithPetId: (NSNumber*) petId - completionHandler: (void (^)(NSString* output, NSError* error)) handler { - - - // verify the required parameter 'petId' is set - if (petId == nil) { - [NSException raise:@"Invalid parameter" format:@"Missing the required parameter `petId` when calling `petPetIdtestingByteArraytrueGet`"]; - } - - - NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/pet/{petId}?testing_byte_array=true"]; - - // remove format in URL if needed - if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { - [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; - } - - NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; - if (petId != nil) { - pathParams[@"petId"] = petId; - } - - - NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; - - NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; - - - - // HTTP header `Accept` - headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; - if ([headerParams[@"Accept"] length] == 0) { - [headerParams removeObjectForKey:@"Accept"]; - } - - // response content type - NSString *responseContentType; - if ([headerParams objectForKey:@"Accept"]) { - responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0]; - } - else { - responseContentType = @""; - } - - // request content type - NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; - - // Authentication setting - NSArray *authSettings = @[@"api_key", @"petstore_auth"]; - - id bodyParam = nil; - NSMutableDictionary *formParams = [[NSMutableDictionary alloc] init]; - NSMutableDictionary *localVarFiles = [[NSMutableDictionary alloc] init]; - - - - - - return [self.apiClient requestWithPath: resourcePath - method: @"GET" - pathParams: pathParams - queryParams: queryParams - formParams: formParams - files: localVarFiles - body: bodyParam - headerParams: headerParams - authSettings: authSettings - requestContentType: requestContentType - responseContentType: responseContentType - responseType: @"NSString*" - completionBlock: ^(id data, NSError *error) { - handler((NSString*)data, error); - } - ]; -} - -/// -/// Fake endpoint to test byte array in body parameter for adding a new pet to the store -/// -/// @param body Pet object in the form of byte array -/// -/// @returns void -/// --(NSNumber*) addPetUsingByteArrayWithBody: (NSString*) body - completionHandler: (void (^)(NSError* error)) handler { - - - - NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/pet?testing_byte_array=true"]; - - // remove format in URL if needed - if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { - [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; - } - - NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; - - - NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; - - NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; - - - - // HTTP header `Accept` - headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; - if ([headerParams[@"Accept"] length] == 0) { - [headerParams removeObjectForKey:@"Accept"]; - } - - // response content type - NSString *responseContentType; - if ([headerParams objectForKey:@"Accept"]) { - responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0]; - } - else { - responseContentType = @""; - } - - // request content type - NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[@"application/json", @"application/xml"]]; - - // Authentication setting - NSArray *authSettings = @[@"petstore_auth"]; - - id bodyParam = nil; - NSMutableDictionary *formParams = [[NSMutableDictionary alloc] init]; - NSMutableDictionary *localVarFiles = [[NSMutableDictionary alloc] init]; - - bodyParam = body; - - - return [self.apiClient requestWithPath: resourcePath method: @"POST" pathParams: pathParams diff --git a/samples/client/petstore/objc/SwaggerClient/SWGStoreApi.h b/samples/client/petstore/objc/SwaggerClient/SWGStoreApi.h index f8f058462a0..d565a01e15b 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGStoreApi.h +++ b/samples/client/petstore/objc/SwaggerClient/SWGStoreApi.h @@ -19,6 +19,19 @@ -(unsigned long) requestQueueSize; +(SWGStoreApi*) apiWithHeader:(NSString*)headerValue key:(NSString*)key; +(SWGStoreApi*) sharedAPI; +/// +/// +/// Delete purchase order by ID +/// For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors +/// +/// @param orderId ID of the order that needs to be deleted +/// +/// +/// @return +-(NSNumber*) deleteOrderWithOrderId: (NSString*) orderId + completionHandler: (void (^)(NSError* error)) handler; + + /// /// /// Finds orders by status @@ -56,19 +69,6 @@ (void (^)(NSObject* output, NSError* error)) handler; -/// -/// -/// Place an order for a pet -/// -/// -/// @param body order placed for purchasing the pet -/// -/// -/// @return SWGOrder* --(NSNumber*) placeOrderWithBody: (SWGOrder*) body - completionHandler: (void (^)(SWGOrder* output, NSError* error)) handler; - - /// /// /// Find purchase order by ID @@ -84,15 +84,15 @@ /// /// -/// 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 +/// Place an order for a pet /// /// -/// @return --(NSNumber*) deleteOrderWithOrderId: (NSString*) orderId - completionHandler: (void (^)(NSError* error)) handler; +/// @param body order placed for purchasing the pet +/// +/// +/// @return SWGOrder* +-(NSNumber*) placeOrderWithBody: (SWGOrder*) body + completionHandler: (void (^)(SWGOrder* output, NSError* error)) handler; diff --git a/samples/client/petstore/objc/SwaggerClient/SWGStoreApi.m b/samples/client/petstore/objc/SwaggerClient/SWGStoreApi.m index dbe4564177c..af0002db3b3 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGStoreApi.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGStoreApi.m @@ -38,7 +38,6 @@ static SWGStoreApi* singletonAPI = nil; #pragma mark - +(SWGStoreApi*) apiWithHeader:(NSString*)headerValue key:(NSString*)key { - if (singletonAPI == nil) { singletonAPI = [[SWGStoreApi alloc] init]; [singletonAPI addHeader:headerValue forKey:key]; @@ -47,7 +46,6 @@ static SWGStoreApi* singletonAPI = nil; } +(SWGStoreApi*) sharedAPI { - if (singletonAPI == nil) { singletonAPI = [[SWGStoreApi alloc] init]; } @@ -69,18 +67,86 @@ static SWGStoreApi* singletonAPI = nil; #pragma mark - Api Methods +/// +/// 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 +/// +/// @returns void +/// +-(NSNumber*) deleteOrderWithOrderId: (NSString*) orderId + completionHandler: (void (^)(NSError* error)) handler { + // verify the required parameter 'orderId' is set + if (orderId == nil) { + [NSException raise:@"Invalid parameter" format:@"Missing the required parameter `orderId` when calling `deleteOrder`"]; + } + + NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/store/order/{orderId}"]; + + // remove format in URL if needed + if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { + [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; + } + + NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; + if (orderId != nil) { + pathParams[@"orderId"] = orderId; + } + + NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; + NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; + // HTTP header `Accept` + headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; + if ([headerParams[@"Accept"] length] == 0) { + [headerParams removeObjectForKey:@"Accept"]; + } + + // response content type + NSString *responseContentType; + if ([headerParams objectForKey:@"Accept"]) { + responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0]; + } + else { + responseContentType = @""; + } + + // request content type + NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; + + // Authentication setting + NSArray *authSettings = @[]; + + id bodyParam = nil; + NSMutableDictionary *formParams = [[NSMutableDictionary alloc] init]; + NSMutableDictionary *localVarFiles = [[NSMutableDictionary alloc] init]; + + return [self.apiClient requestWithPath: resourcePath + method: @"DELETE" + pathParams: pathParams + queryParams: queryParams + formParams: formParams + files: localVarFiles + body: bodyParam + headerParams: headerParams + authSettings: authSettings + requestContentType: requestContentType + responseContentType: responseContentType + responseType: nil + completionBlock: ^(id data, NSError *error) { + handler(error); + } + ]; +} + /// /// Finds orders by status /// A single status value can be provided as a string -/// @param status Status value that needs to be considered for query +/// @param status Status value that needs to be considered for query (optional, default to placed) /// /// @returns NSArray* /// -(NSNumber*) findOrdersByStatusWithStatus: (NSString*) status completionHandler: (void (^)(NSArray* output, NSError* error)) handler { - - - NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/store/findByStatus"]; // remove format in URL if needed @@ -89,18 +155,12 @@ static SWGStoreApi* singletonAPI = nil; } NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; - NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; if (status != nil) { - queryParams[@"status"] = status; } - NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; - - - // HTTP header `Accept` headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; if ([headerParams[@"Accept"] length] == 0) { @@ -125,11 +185,7 @@ static SWGStoreApi* singletonAPI = nil; id bodyParam = nil; NSMutableDictionary *formParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary *localVarFiles = [[NSMutableDictionary alloc] init]; - - - - return [self.apiClient requestWithPath: resourcePath method: @"GET" pathParams: pathParams @@ -155,9 +211,6 @@ static SWGStoreApi* singletonAPI = nil; /// -(NSNumber*) getInventoryWithCompletionHandler: (void (^)(NSDictionary* /* NSString, NSNumber */ output, NSError* error)) handler { - - - NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/store/inventory"]; // remove format in URL if needed @@ -166,14 +219,9 @@ static SWGStoreApi* singletonAPI = nil; } NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; - NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; - NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; - - - // HTTP header `Accept` headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; if ([headerParams[@"Accept"] length] == 0) { @@ -198,11 +246,7 @@ static SWGStoreApi* singletonAPI = nil; id bodyParam = nil; NSMutableDictionary *formParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary *localVarFiles = [[NSMutableDictionary alloc] init]; - - - - return [self.apiClient requestWithPath: resourcePath method: @"GET" pathParams: pathParams @@ -228,10 +272,7 @@ static SWGStoreApi* singletonAPI = nil; /// -(NSNumber*) getInventoryInObjectWithCompletionHandler: (void (^)(NSObject* output, NSError* error)) handler { - - - - NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/store/inventory?response=arbitrary_object"]; + NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/store/inventory?response=arbitrary_object"]; // remove format in URL if needed if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { @@ -239,14 +280,9 @@ static SWGStoreApi* singletonAPI = nil; } NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; - NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; - NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; - - - // HTTP header `Accept` headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; if ([headerParams[@"Accept"] length] == 0) { @@ -271,11 +307,7 @@ static SWGStoreApi* singletonAPI = nil; id bodyParam = nil; NSMutableDictionary *formParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary *localVarFiles = [[NSMutableDictionary alloc] init]; - - - - return [self.apiClient requestWithPath: resourcePath method: @"GET" pathParams: pathParams @@ -294,97 +326,19 @@ static SWGStoreApi* singletonAPI = nil; ]; } -/// -/// Place an order for a pet -/// -/// @param body order placed for purchasing the pet -/// -/// @returns SWGOrder* -/// --(NSNumber*) placeOrderWithBody: (SWGOrder*) body - completionHandler: (void (^)(SWGOrder* output, NSError* error)) handler { - - - - NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/store/order"]; - - // remove format in URL if needed - if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { - [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; - } - - NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; - - - NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; - - NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; - - - - // HTTP header `Accept` - headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; - if ([headerParams[@"Accept"] length] == 0) { - [headerParams removeObjectForKey:@"Accept"]; - } - - // response content type - NSString *responseContentType; - if ([headerParams objectForKey:@"Accept"]) { - responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0]; - } - else { - responseContentType = @""; - } - - // request content type - NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; - - // Authentication setting - NSArray *authSettings = @[@"test_api_client_id", @"test_api_client_secret"]; - - id bodyParam = nil; - NSMutableDictionary *formParams = [[NSMutableDictionary alloc] init]; - NSMutableDictionary *localVarFiles = [[NSMutableDictionary alloc] init]; - - bodyParam = body; - - - - return [self.apiClient requestWithPath: resourcePath - method: @"POST" - pathParams: pathParams - queryParams: queryParams - formParams: formParams - files: localVarFiles - body: bodyParam - headerParams: headerParams - authSettings: authSettings - requestContentType: requestContentType - responseContentType: responseContentType - responseType: @"SWGOrder*" - completionBlock: ^(id data, NSError *error) { - handler((SWGOrder*)data, error); - } - ]; -} - /// /// Find purchase order by ID /// For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions -/// @param orderId ID of pet that needs to be fetched +/// @param orderId ID of pet that needs to be fetched /// /// @returns SWGOrder* /// -(NSNumber*) getOrderByIdWithOrderId: (NSString*) orderId completionHandler: (void (^)(SWGOrder* output, NSError* error)) handler { - - // verify the required parameter 'orderId' is set if (orderId == nil) { [NSException raise:@"Invalid parameter" format:@"Missing the required parameter `orderId` when calling `getOrderById`"]; } - NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/store/order/{orderId}"]; @@ -397,14 +351,9 @@ static SWGStoreApi* singletonAPI = nil; if (orderId != nil) { pathParams[@"orderId"] = orderId; } - NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; - NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; - - - // HTTP header `Accept` headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; if ([headerParams[@"Accept"] length] == 0) { @@ -429,11 +378,7 @@ static SWGStoreApi* singletonAPI = nil; id bodyParam = nil; NSMutableDictionary *formParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary *localVarFiles = [[NSMutableDictionary alloc] init]; - - - - return [self.apiClient requestWithPath: resourcePath method: @"GET" pathParams: pathParams @@ -453,23 +398,15 @@ static SWGStoreApi* singletonAPI = nil; } /// -/// 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 +/// Place an order for a pet +/// +/// @param body order placed for purchasing the pet (optional) /// -/// @returns void +/// @returns SWGOrder* /// --(NSNumber*) deleteOrderWithOrderId: (NSString*) orderId - completionHandler: (void (^)(NSError* error)) handler { - - - // verify the required parameter 'orderId' is set - if (orderId == nil) { - [NSException raise:@"Invalid parameter" format:@"Missing the required parameter `orderId` when calling `deleteOrder`"]; - } - - - NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/store/order/{orderId}"]; +-(NSNumber*) placeOrderWithBody: (SWGOrder*) body + completionHandler: (void (^)(SWGOrder* output, NSError* error)) handler { + NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/store/order"]; // remove format in URL if needed if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { @@ -477,17 +414,9 @@ static SWGStoreApi* singletonAPI = nil; } NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; - if (orderId != nil) { - pathParams[@"orderId"] = orderId; - } - NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; - NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; - - - // HTTP header `Accept` headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; if ([headerParams[@"Accept"] length] == 0) { @@ -507,18 +436,15 @@ static SWGStoreApi* singletonAPI = nil; NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; // Authentication setting - NSArray *authSettings = @[]; + NSArray *authSettings = @[@"test_api_client_id", @"test_api_client_secret"]; id bodyParam = nil; NSMutableDictionary *formParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary *localVarFiles = [[NSMutableDictionary alloc] init]; - - - + bodyParam = body; - return [self.apiClient requestWithPath: resourcePath - method: @"DELETE" + method: @"POST" pathParams: pathParams queryParams: queryParams formParams: formParams @@ -528,9 +454,9 @@ static SWGStoreApi* singletonAPI = nil; authSettings: authSettings requestContentType: requestContentType responseContentType: responseContentType - responseType: nil + responseType: @"SWGOrder*" completionBlock: ^(id data, NSError *error) { - handler(error); + handler((SWGOrder*)data, error); } ]; } diff --git a/samples/client/petstore/objc/SwaggerClient/SWGUserApi.h b/samples/client/petstore/objc/SwaggerClient/SWGUserApi.h index 96c0b71da60..aa1c99c6595 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGUserApi.h +++ b/samples/client/petstore/objc/SwaggerClient/SWGUserApi.h @@ -58,6 +58,32 @@ completionHandler: (void (^)(NSError* error)) handler; +/// +/// +/// Delete user +/// This can only be done by the logged in user. +/// +/// @param username The name that needs to be deleted +/// +/// +/// @return +-(NSNumber*) deleteUserWithUsername: (NSString*) username + completionHandler: (void (^)(NSError* error)) handler; + + +/// +/// +/// Get user by user name +/// +/// +/// @param username The name that needs to be fetched. Use user1 for testing. +/// +/// +/// @return SWGUser* +-(NSNumber*) getUserByNameWithUsername: (NSString*) username + completionHandler: (void (^)(SWGUser* output, NSError* error)) handler; + + /// /// /// Logs user into the system @@ -85,19 +111,6 @@ (void (^)(NSError* error)) handler; -/// -/// -/// Get user by user name -/// -/// -/// @param username The name that needs to be fetched. Use user1 for testing. -/// -/// -/// @return SWGUser* --(NSNumber*) getUserByNameWithUsername: (NSString*) username - completionHandler: (void (^)(SWGUser* output, NSError* error)) handler; - - /// /// /// Updated user @@ -113,18 +126,5 @@ completionHandler: (void (^)(NSError* error)) handler; -/// -/// -/// Delete user -/// This can only be done by the logged in user. -/// -/// @param username The name that needs to be deleted -/// -/// -/// @return --(NSNumber*) deleteUserWithUsername: (NSString*) username - completionHandler: (void (^)(NSError* error)) handler; - - @end diff --git a/samples/client/petstore/objc/SwaggerClient/SWGUserApi.m b/samples/client/petstore/objc/SwaggerClient/SWGUserApi.m index 46cda001e52..71e729ef02c 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGUserApi.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGUserApi.m @@ -38,7 +38,6 @@ static SWGUserApi* singletonAPI = nil; #pragma mark - +(SWGUserApi*) apiWithHeader:(NSString*)headerValue key:(NSString*)key { - if (singletonAPI == nil) { singletonAPI = [[SWGUserApi alloc] init]; [singletonAPI addHeader:headerValue forKey:key]; @@ -47,7 +46,6 @@ static SWGUserApi* singletonAPI = nil; } +(SWGUserApi*) sharedAPI { - if (singletonAPI == nil) { singletonAPI = [[SWGUserApi alloc] init]; } @@ -72,15 +70,12 @@ static SWGUserApi* singletonAPI = nil; /// /// Create user /// This can only be done by the logged in user. -/// @param body Created user object +/// @param body Created user object (optional) /// /// @returns void /// -(NSNumber*) createUserWithBody: (SWGUser*) body completionHandler: (void (^)(NSError* error)) handler { - - - NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/user"]; // remove format in URL if needed @@ -89,14 +84,9 @@ static SWGUserApi* singletonAPI = nil; } NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; - NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; - NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; - - - // HTTP header `Accept` headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; if ([headerParams[@"Accept"] length] == 0) { @@ -121,11 +111,8 @@ static SWGUserApi* singletonAPI = nil; id bodyParam = nil; NSMutableDictionary *formParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary *localVarFiles = [[NSMutableDictionary alloc] init]; - bodyParam = body; - - return [self.apiClient requestWithPath: resourcePath method: @"POST" pathParams: pathParams @@ -147,15 +134,12 @@ static SWGUserApi* singletonAPI = nil; /// /// Creates list of users with given input array /// -/// @param body List of user object +/// @param body List of user object (optional) /// /// @returns void /// -(NSNumber*) createUsersWithArrayInputWithBody: (NSArray*) body completionHandler: (void (^)(NSError* error)) handler { - - - NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/user/createWithArray"]; // remove format in URL if needed @@ -164,14 +148,9 @@ static SWGUserApi* singletonAPI = nil; } NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; - NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; - NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; - - - // HTTP header `Accept` headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; if ([headerParams[@"Accept"] length] == 0) { @@ -196,11 +175,8 @@ static SWGUserApi* singletonAPI = nil; id bodyParam = nil; NSMutableDictionary *formParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary *localVarFiles = [[NSMutableDictionary alloc] init]; - bodyParam = body; - - return [self.apiClient requestWithPath: resourcePath method: @"POST" pathParams: pathParams @@ -222,15 +198,12 @@ static SWGUserApi* singletonAPI = nil; /// /// Creates list of users with given input array /// -/// @param body List of user object +/// @param body List of user object (optional) /// /// @returns void /// -(NSNumber*) createUsersWithListInputWithBody: (NSArray*) body completionHandler: (void (^)(NSError* error)) handler { - - - NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/user/createWithList"]; // remove format in URL if needed @@ -239,14 +212,9 @@ static SWGUserApi* singletonAPI = nil; } NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; - NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; - NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; - - - // HTTP header `Accept` headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; if ([headerParams[@"Accept"] length] == 0) { @@ -271,11 +239,8 @@ static SWGUserApi* singletonAPI = nil; id bodyParam = nil; NSMutableDictionary *formParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary *localVarFiles = [[NSMutableDictionary alloc] init]; - bodyParam = body; - - return [self.apiClient requestWithPath: resourcePath method: @"POST" pathParams: pathParams @@ -295,21 +260,20 @@ static SWGUserApi* singletonAPI = nil; } /// -/// Logs user into the system -/// -/// @param username The user name for login +/// Delete user +/// This can only be done by the logged in user. +/// @param username The name that needs to be deleted /// -/// @param password The password for login in clear text +/// @returns void /// -/// @returns NSString* -/// --(NSNumber*) loginUserWithUsername: (NSString*) username - password: (NSString*) password - completionHandler: (void (^)(NSString* output, NSError* error)) handler { +-(NSNumber*) deleteUserWithUsername: (NSString*) username + completionHandler: (void (^)(NSError* error)) handler { + // verify the required parameter 'username' is set + if (username == nil) { + [NSException raise:@"Invalid parameter" format:@"Missing the required parameter `username` when calling `deleteUser`"]; + } - - - NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/user/login"]; + NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/user/{username}"]; // remove format in URL if needed if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { @@ -317,22 +281,155 @@ static SWGUserApi* singletonAPI = nil; } NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; - + if (username != nil) { + pathParams[@"username"] = username; + } NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; - if (username != nil) { - - queryParams[@"username"] = username; - } - if (password != nil) { - - queryParams[@"password"] = password; - } - NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; + // HTTP header `Accept` + headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; + if ([headerParams[@"Accept"] length] == 0) { + [headerParams removeObjectForKey:@"Accept"]; + } - + // response content type + NSString *responseContentType; + if ([headerParams objectForKey:@"Accept"]) { + responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0]; + } + else { + responseContentType = @""; + } + // request content type + NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; + + // Authentication setting + NSArray *authSettings = @[@"test_http_basic"]; + + id bodyParam = nil; + NSMutableDictionary *formParams = [[NSMutableDictionary alloc] init]; + NSMutableDictionary *localVarFiles = [[NSMutableDictionary alloc] init]; + + return [self.apiClient requestWithPath: resourcePath + method: @"DELETE" + pathParams: pathParams + queryParams: queryParams + formParams: formParams + files: localVarFiles + body: bodyParam + headerParams: headerParams + authSettings: authSettings + requestContentType: requestContentType + responseContentType: responseContentType + responseType: nil + completionBlock: ^(id data, NSError *error) { + handler(error); + } + ]; +} + +/// +/// Get user by user name +/// +/// @param username The name that needs to be fetched. Use user1 for testing. +/// +/// @returns SWGUser* +/// +-(NSNumber*) getUserByNameWithUsername: (NSString*) username + completionHandler: (void (^)(SWGUser* output, NSError* error)) handler { + // verify the required parameter 'username' is set + if (username == nil) { + [NSException raise:@"Invalid parameter" format:@"Missing the required parameter `username` when calling `getUserByName`"]; + } + + NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/user/{username}"]; + + // remove format in URL if needed + if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { + [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; + } + + NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; + if (username != nil) { + pathParams[@"username"] = username; + } + + NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; + NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; + // HTTP header `Accept` + headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; + if ([headerParams[@"Accept"] length] == 0) { + [headerParams removeObjectForKey:@"Accept"]; + } + + // response content type + NSString *responseContentType; + if ([headerParams objectForKey:@"Accept"]) { + responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0]; + } + else { + responseContentType = @""; + } + + // request content type + NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; + + // Authentication setting + NSArray *authSettings = @[]; + + id bodyParam = nil; + NSMutableDictionary *formParams = [[NSMutableDictionary alloc] init]; + NSMutableDictionary *localVarFiles = [[NSMutableDictionary alloc] init]; + + return [self.apiClient requestWithPath: resourcePath + method: @"GET" + pathParams: pathParams + queryParams: queryParams + formParams: formParams + files: localVarFiles + body: bodyParam + headerParams: headerParams + authSettings: authSettings + requestContentType: requestContentType + responseContentType: responseContentType + responseType: @"SWGUser*" + completionBlock: ^(id data, NSError *error) { + handler((SWGUser*)data, error); + } + ]; +} + +/// +/// Logs user into the system +/// +/// @param username The user name for login (optional) +/// +/// @param password The password for login in clear text (optional) +/// +/// @returns NSString* +/// +-(NSNumber*) loginUserWithUsername: (NSString*) username + password: (NSString*) password + completionHandler: (void (^)(NSString* output, NSError* error)) handler { + NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/user/login"]; + + // remove format in URL if needed + if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { + [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; + } + + NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; + + NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; + if (username != nil) { + queryParams[@"username"] = username; + } + if (password != nil) { + queryParams[@"password"] = password; + } + NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; // HTTP header `Accept` headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; if ([headerParams[@"Accept"] length] == 0) { @@ -357,11 +454,7 @@ static SWGUserApi* singletonAPI = nil; id bodyParam = nil; NSMutableDictionary *formParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary *localVarFiles = [[NSMutableDictionary alloc] init]; - - - - return [self.apiClient requestWithPath: resourcePath method: @"GET" pathParams: pathParams @@ -387,9 +480,6 @@ static SWGUserApi* singletonAPI = nil; /// -(NSNumber*) logoutUserWithCompletionHandler: (void (^)(NSError* error)) handler { - - - NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/user/logout"]; // remove format in URL if needed @@ -398,14 +488,9 @@ static SWGUserApi* singletonAPI = nil; } NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; - NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; - NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; - - - // HTTP header `Accept` headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; if ([headerParams[@"Accept"] length] == 0) { @@ -430,11 +515,7 @@ static SWGUserApi* singletonAPI = nil; id bodyParam = nil; NSMutableDictionary *formParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary *localVarFiles = [[NSMutableDictionary alloc] init]; - - - - return [self.apiClient requestWithPath: resourcePath method: @"GET" pathParams: pathParams @@ -453,108 +534,22 @@ static SWGUserApi* singletonAPI = nil; ]; } -/// -/// Get user by user name -/// -/// @param username The name that needs to be fetched. Use user1 for testing. -/// -/// @returns SWGUser* -/// --(NSNumber*) getUserByNameWithUsername: (NSString*) username - completionHandler: (void (^)(SWGUser* output, NSError* error)) handler { - - - // verify the required parameter 'username' is set - if (username == nil) { - [NSException raise:@"Invalid parameter" format:@"Missing the required parameter `username` when calling `getUserByName`"]; - } - - - NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/user/{username}"]; - - // remove format in URL if needed - if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { - [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; - } - - NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; - if (username != nil) { - pathParams[@"username"] = username; - } - - - NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; - - NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; - - - - // HTTP header `Accept` - headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; - if ([headerParams[@"Accept"] length] == 0) { - [headerParams removeObjectForKey:@"Accept"]; - } - - // response content type - NSString *responseContentType; - if ([headerParams objectForKey:@"Accept"]) { - responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0]; - } - else { - responseContentType = @""; - } - - // request content type - NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; - - // Authentication setting - NSArray *authSettings = @[]; - - id bodyParam = nil; - NSMutableDictionary *formParams = [[NSMutableDictionary alloc] init]; - NSMutableDictionary *localVarFiles = [[NSMutableDictionary alloc] init]; - - - - - - return [self.apiClient requestWithPath: resourcePath - method: @"GET" - pathParams: pathParams - queryParams: queryParams - formParams: formParams - files: localVarFiles - body: bodyParam - headerParams: headerParams - authSettings: authSettings - requestContentType: requestContentType - responseContentType: responseContentType - responseType: @"SWGUser*" - completionBlock: ^(id data, NSError *error) { - handler((SWGUser*)data, error); - } - ]; -} - /// /// Updated user /// This can only be done by the logged in user. -/// @param username name that need to be deleted +/// @param username name that need to be deleted /// -/// @param body Updated user object +/// @param body Updated user object (optional) /// /// @returns void /// -(NSNumber*) updateUserWithUsername: (NSString*) username body: (SWGUser*) body completionHandler: (void (^)(NSError* error)) handler { - - // verify the required parameter 'username' is set if (username == nil) { [NSException raise:@"Invalid parameter" format:@"Missing the required parameter `username` when calling `updateUser`"]; } - NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/user/{username}"]; @@ -567,14 +562,9 @@ static SWGUserApi* singletonAPI = nil; if (username != nil) { pathParams[@"username"] = username; } - NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; - NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; - - - // HTTP header `Accept` headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; if ([headerParams[@"Accept"] length] == 0) { @@ -599,11 +589,8 @@ static SWGUserApi* singletonAPI = nil; id bodyParam = nil; NSMutableDictionary *formParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary *localVarFiles = [[NSMutableDictionary alloc] init]; - bodyParam = body; - - return [self.apiClient requestWithPath: resourcePath method: @"PUT" pathParams: pathParams @@ -622,89 +609,6 @@ static SWGUserApi* singletonAPI = nil; ]; } -/// -/// Delete user -/// This can only be done by the logged in user. -/// @param username The name that needs to be deleted -/// -/// @returns void -/// --(NSNumber*) deleteUserWithUsername: (NSString*) username - completionHandler: (void (^)(NSError* error)) handler { - - - // verify the required parameter 'username' is set - if (username == nil) { - [NSException raise:@"Invalid parameter" format:@"Missing the required parameter `username` when calling `deleteUser`"]; - } - - - NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/user/{username}"]; - - // remove format in URL if needed - if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { - [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; - } - - NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; - if (username != nil) { - pathParams[@"username"] = username; - } - - - NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; - - NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; - - - - // HTTP header `Accept` - headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; - if ([headerParams[@"Accept"] length] == 0) { - [headerParams removeObjectForKey:@"Accept"]; - } - - // response content type - NSString *responseContentType; - if ([headerParams objectForKey:@"Accept"]) { - responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0]; - } - else { - responseContentType = @""; - } - - // request content type - NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; - - // Authentication setting - NSArray *authSettings = @[]; - - id bodyParam = nil; - NSMutableDictionary *formParams = [[NSMutableDictionary alloc] init]; - NSMutableDictionary *localVarFiles = [[NSMutableDictionary alloc] init]; - - - - - - return [self.apiClient requestWithPath: resourcePath - method: @"DELETE" - pathParams: pathParams - queryParams: queryParams - formParams: formParams - files: localVarFiles - body: bodyParam - headerParams: headerParams - authSettings: authSettings - requestContentType: requestContentType - responseContentType: responseContentType - responseType: nil - completionBlock: ^(id data, NSError *error) { - handler(error); - } - ]; -} - @end diff --git a/samples/client/petstore/objc/git_push.sh b/samples/client/petstore/objc/git_push.sh new file mode 100644 index 00000000000..1a36388db02 --- /dev/null +++ b/samples/client/petstore/objc/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="YOUR_GIT_USR_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="YOUR_GIT_REPO_ID" + 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/perl/.gitignore b/samples/client/petstore/perl/.gitignore new file mode 100644 index 00000000000..ae2ad536abb --- /dev/null +++ b/samples/client/petstore/perl/.gitignore @@ -0,0 +1,20 @@ +/blib/ +/.build/ +_build/ +cover_db/ +inc/ +Build +!Build/ +Build.bat +.last_cover_stats +/Makefile +/Makefile.old +/MANIFEST.bak +/META.yml +/META.json +/MYMETA.* +nytprof.out +/pm_to_blib +*.o +*.bs +/_eumm/ diff --git a/samples/client/petstore/perl/README.md b/samples/client/petstore/perl/README.md index 06dc39ccad2..72fc2e26429 100644 --- a/samples/client/petstore/perl/README.md +++ b/samples/client/petstore/perl/README.md @@ -1,16 +1,17 @@ # NAME -WWW::SwaggerClient::Role - a Moose role for the Swagger Petstore +WWW::SwaggerClient::Role - a Moose role for the Swagger Petstore -## Swagger Petstore version: 1.0.0 +This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters # VERSION -Automatically generated by the Perl Swagger Codegen project: +Automatically generated by the [Swagger Codegen](https://github.com/swagger-api/swagger-codegen) project: -- Build date: 2016-03-04T14:39:09.479+08:00 +- API version: 1.0.0 +- Package version: 1.0.0 +- Build date: 2016-03-30T20:57:51.908+08:00 - Build package: class io.swagger.codegen.languages.PerlClientCodegen -- Codegen version: ## A note on Moose @@ -216,4 +217,174 @@ spec. If so, this is available via the `class_documentation()` and my $omdoc = $api->get_pet_by_id->(pet_id => $pet_id)->method_documentation->{method_name}; -Each of these calls returns a hashref with various useful pieces of information. +Each of these calls returns a hashref with various useful pieces of information. + +# LOAD THE MODULES + +To load the API packages: +```perl +use WWW::SwaggerClient::PetApi; +use WWW::SwaggerClient::StoreApi; +use WWW::SwaggerClient::UserApi; + +``` + +To load the models: +```perl +use WWW::SwaggerClient::Object::Animal; +use WWW::SwaggerClient::Object::Cat; +use WWW::SwaggerClient::Object::Category; +use WWW::SwaggerClient::Object::Dog; +use WWW::SwaggerClient::Object::InlineResponse200; +use WWW::SwaggerClient::Object::Model200Response; +use WWW::SwaggerClient::Object::ModelReturn; +use WWW::SwaggerClient::Object::Name; +use WWW::SwaggerClient::Object::Order; +use WWW::SwaggerClient::Object::Pet; +use WWW::SwaggerClient::Object::SpecialModelName; +use WWW::SwaggerClient::Object::Tag; +use WWW::SwaggerClient::Object::User; + +```` + +# GETTING STARTED +Put the Perl SDK under the 'lib' folder in your project directory, then run the following +```perl +#!/usr/bin/perl +use lib 'lib'; +use strict; +use warnings; +# load the API package +use WWW::SwaggerClient::PetApi; +use WWW::SwaggerClient::StoreApi; +use WWW::SwaggerClient::UserApi; + +# load the models +use WWW::SwaggerClient::Object::Animal; +use WWW::SwaggerClient::Object::Cat; +use WWW::SwaggerClient::Object::Category; +use WWW::SwaggerClient::Object::Dog; +use WWW::SwaggerClient::Object::InlineResponse200; +use WWW::SwaggerClient::Object::Model200Response; +use WWW::SwaggerClient::Object::ModelReturn; +use WWW::SwaggerClient::Object::Name; +use WWW::SwaggerClient::Object::Order; +use WWW::SwaggerClient::Object::Pet; +use WWW::SwaggerClient::Object::SpecialModelName; +use WWW::SwaggerClient::Object::Tag; +use WWW::SwaggerClient::Object::User; + +# for displaying the API response data +use Data::Dumper; + +# Configure OAuth2 access token for authorization: petstore_auth +$WWW::SwaggerClient::Configuration::access_token = 'YOUR_ACCESS_TOKEN'; + +my $api_instance = WWW::SwaggerClient::PetApi->new(); +my $body = WWW::SwaggerClient::Object::Pet->new(); # Pet | Pet object that needs to be added to the store + +eval { + $api_instance->add_pet(body => $body); +}; +if ($@) { + warn "Exception when calling PetApi->add_pet: $@\n"; +} + +``` + +# DOCUMENTATION FOR API ENDPOINTS + +All URIs are relative to *http://petstore.swagger.io/v2* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +*PetApi* | [**add_pet**](docs/PetApi.md#add_pet) | **POST** /pet | Add a new pet to the store +*PetApi* | [**add_pet_using_byte_array**](docs/PetApi.md#add_pet_using_byte_array) | **POST** /pet?testing_byte_array=true | Fake endpoint to test byte array in body parameter for adding a new pet to the store +*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 +*PetApi* | [**find_pets_by_tags**](docs/PetApi.md#find_pets_by_tags) | **GET** /pet/findByTags | Finds Pets by tags +*PetApi* | [**get_pet_by_id**](docs/PetApi.md#get_pet_by_id) | **GET** /pet/{petId} | Find pet by ID +*PetApi* | [**get_pet_by_id_in_object**](docs/PetApi.md#get_pet_by_id_in_object) | **GET** /pet/{petId}?response=inline_arbitrary_object | Fake endpoint to test inline arbitrary object return by 'Find pet by ID' +*PetApi* | [**pet_pet_idtesting_byte_arraytrue_get**](docs/PetApi.md#pet_pet_idtesting_byte_arraytrue_get) | **GET** /pet/{petId}?testing_byte_array=true | Fake endpoint to test byte array return by 'Find pet by ID' +*PetApi* | [**update_pet**](docs/PetApi.md#update_pet) | **PUT** /pet | Update an existing pet +*PetApi* | [**update_pet_with_form**](docs/PetApi.md#update_pet_with_form) | **POST** /pet/{petId} | Updates a pet in the store with form data +*PetApi* | [**upload_file**](docs/PetApi.md#upload_file) | **POST** /pet/{petId}/uploadImage | uploads an image +*StoreApi* | [**delete_order**](docs/StoreApi.md#delete_order) | **DELETE** /store/order/{orderId} | Delete purchase order by ID +*StoreApi* | [**find_orders_by_status**](docs/StoreApi.md#find_orders_by_status) | **GET** /store/findByStatus | Finds orders by status +*StoreApi* | [**get_inventory**](docs/StoreApi.md#get_inventory) | **GET** /store/inventory | Returns pet inventories by status +*StoreApi* | [**get_inventory_in_object**](docs/StoreApi.md#get_inventory_in_object) | **GET** /store/inventory?response=arbitrary_object | Fake endpoint to test arbitrary object return by 'Get inventory' +*StoreApi* | [**get_order_by_id**](docs/StoreApi.md#get_order_by_id) | **GET** /store/order/{orderId} | Find purchase order by ID +*StoreApi* | [**place_order**](docs/StoreApi.md#place_order) | **POST** /store/order | Place an order for a pet +*UserApi* | [**create_user**](docs/UserApi.md#create_user) | **POST** /user | Create user +*UserApi* | [**create_users_with_array_input**](docs/UserApi.md#create_users_with_array_input) | **POST** /user/createWithArray | Creates list of users with given input array +*UserApi* | [**create_users_with_list_input**](docs/UserApi.md#create_users_with_list_input) | **POST** /user/createWithList | Creates list of users with given input array +*UserApi* | [**delete_user**](docs/UserApi.md#delete_user) | **DELETE** /user/{username} | Delete user +*UserApi* | [**get_user_by_name**](docs/UserApi.md#get_user_by_name) | **GET** /user/{username} | Get user by user name +*UserApi* | [**login_user**](docs/UserApi.md#login_user) | **GET** /user/login | Logs user into the system +*UserApi* | [**logout_user**](docs/UserApi.md#logout_user) | **GET** /user/logout | Logs out current logged in user session +*UserApi* | [**update_user**](docs/UserApi.md#update_user) | **PUT** /user/{username} | Updated user + + +# DOCUMENTATION FOR MODELS + - [WWW::SwaggerClient::Object::Animal](docs/Animal.md) + - [WWW::SwaggerClient::Object::Cat](docs/Cat.md) + - [WWW::SwaggerClient::Object::Category](docs/Category.md) + - [WWW::SwaggerClient::Object::Dog](docs/Dog.md) + - [WWW::SwaggerClient::Object::InlineResponse200](docs/InlineResponse200.md) + - [WWW::SwaggerClient::Object::Model200Response](docs/Model200Response.md) + - [WWW::SwaggerClient::Object::ModelReturn](docs/ModelReturn.md) + - [WWW::SwaggerClient::Object::Name](docs/Name.md) + - [WWW::SwaggerClient::Object::Order](docs/Order.md) + - [WWW::SwaggerClient::Object::Pet](docs/Pet.md) + - [WWW::SwaggerClient::Object::SpecialModelName](docs/SpecialModelName.md) + - [WWW::SwaggerClient::Object::Tag](docs/Tag.md) + - [WWW::SwaggerClient::Object::User](docs/User.md) + + +# DOCUMENTATION FOR AUTHORIATION + +## test_api_key_header + +- **Type**: API key +- **API key parameter name**: test_api_key_header +- **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_client_secret + +- **Type**: API key +- **API key parameter name**: x-test_api_client_secret +- **Location**: HTTP header + +## test_api_client_id + +- **Type**: API key +- **API key parameter name**: x-test_api_client_id +- **Location**: HTTP header + +## test_api_key_query + +- **Type**: API key +- **API key parameter name**: test_api_key_query +- **Location**: URL query string + +## 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 + + + diff --git a/samples/client/petstore/perl/docs/Animal.md b/samples/client/petstore/perl/docs/Animal.md new file mode 100644 index 00000000000..d243a90905d --- /dev/null +++ b/samples/client/petstore/perl/docs/Animal.md @@ -0,0 +1,15 @@ +# WWW::SwaggerClient::Object::Animal + +## Load the model package +```perl +use WWW::SwaggerClient::Object::Animal; +``` + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**class_name** | **string** | | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/perl/docs/Cat.md b/samples/client/petstore/perl/docs/Cat.md new file mode 100644 index 00000000000..978e4202394 --- /dev/null +++ b/samples/client/petstore/perl/docs/Cat.md @@ -0,0 +1,16 @@ +# WWW::SwaggerClient::Object::Cat + +## Load the model package +```perl +use WWW::SwaggerClient::Object::Cat; +``` + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**class_name** | **string** | | +**declawed** | **boolean** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/perl/docs/Category.md b/samples/client/petstore/perl/docs/Category.md new file mode 100644 index 00000000000..aa69032fc1c --- /dev/null +++ b/samples/client/petstore/perl/docs/Category.md @@ -0,0 +1,16 @@ +# WWW::SwaggerClient::Object::Category + +## Load the model package +```perl +use WWW::SwaggerClient::Object::Category; +``` + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **int** | | [optional] +**name** | **string** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/perl/docs/Dog.md b/samples/client/petstore/perl/docs/Dog.md new file mode 100644 index 00000000000..16e399c3aae --- /dev/null +++ b/samples/client/petstore/perl/docs/Dog.md @@ -0,0 +1,16 @@ +# WWW::SwaggerClient::Object::Dog + +## Load the model package +```perl +use WWW::SwaggerClient::Object::Dog; +``` + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**class_name** | **string** | | +**breed** | **string** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/perl/docs/InlineResponse200.md b/samples/client/petstore/perl/docs/InlineResponse200.md new file mode 100644 index 00000000000..96d4ec3ff79 --- /dev/null +++ b/samples/client/petstore/perl/docs/InlineResponse200.md @@ -0,0 +1,20 @@ +# WWW::SwaggerClient::Object::InlineResponse200 + +## Load the model package +```perl +use WWW::SwaggerClient::Object::InlineResponse200; +``` + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**tags** | [**ARRAY[Tag]**](Tag.md) | | [optional] +**id** | **int** | | +**category** | **object** | | [optional] +**status** | **string** | pet status in the store | [optional] +**name** | **string** | | [optional] +**photo_urls** | **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/Model200Response.md b/samples/client/petstore/perl/docs/Model200Response.md new file mode 100644 index 00000000000..197c00eeb6a --- /dev/null +++ b/samples/client/petstore/perl/docs/Model200Response.md @@ -0,0 +1,15 @@ +# WWW::SwaggerClient::Object::Model200Response + +## Load the model package +```perl +use WWW::SwaggerClient::Object::Model200Response; +``` + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **int** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/perl/docs/ModelReturn.md b/samples/client/petstore/perl/docs/ModelReturn.md new file mode 100644 index 00000000000..57afb49ae53 --- /dev/null +++ b/samples/client/petstore/perl/docs/ModelReturn.md @@ -0,0 +1,15 @@ +# WWW::SwaggerClient::Object::ModelReturn + +## Load the model package +```perl +use WWW::SwaggerClient::Object::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/perl/docs/Name.md b/samples/client/petstore/perl/docs/Name.md new file mode 100644 index 00000000000..13b5d0dde82 --- /dev/null +++ b/samples/client/petstore/perl/docs/Name.md @@ -0,0 +1,16 @@ +# WWW::SwaggerClient::Object::Name + +## Load the model package +```perl +use WWW::SwaggerClient::Object::Name; +``` + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **int** | | [optional] +**snake_case** | **int** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/perl/docs/ObjectReturn.md b/samples/client/petstore/perl/docs/ObjectReturn.md new file mode 100644 index 00000000000..2bd4ff37640 --- /dev/null +++ b/samples/client/petstore/perl/docs/ObjectReturn.md @@ -0,0 +1,13 @@ +# WWW::SwaggerClient::Object::ObjectReturn + +## Import the module +```perl +use WWW::SwaggerClient::Object::ObjectReturn; +``` + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**return** | **int** | | [optional] + + diff --git a/samples/client/petstore/perl/docs/Order.md b/samples/client/petstore/perl/docs/Order.md new file mode 100644 index 00000000000..542a3a91240 --- /dev/null +++ b/samples/client/petstore/perl/docs/Order.md @@ -0,0 +1,20 @@ +# WWW::SwaggerClient::Object::Order + +## Load the model package +```perl +use WWW::SwaggerClient::Object::Order; +``` + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **int** | | [optional] +**pet_id** | **int** | | [optional] +**quantity** | **int** | | [optional] +**ship_date** | **DateTime** | | [optional] +**status** | **string** | Order Status | [optional] +**complete** | **boolean** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/perl/docs/Pet.md b/samples/client/petstore/perl/docs/Pet.md new file mode 100644 index 00000000000..5931f6bd5f3 --- /dev/null +++ b/samples/client/petstore/perl/docs/Pet.md @@ -0,0 +1,20 @@ +# WWW::SwaggerClient::Object::Pet + +## Load the model package +```perl +use WWW::SwaggerClient::Object::Pet; +``` + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **int** | | [optional] +**category** | [**Category**](Category.md) | | [optional] +**name** | **string** | | +**photo_urls** | **ARRAY[string]** | | +**tags** | [**ARRAY[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/perl/docs/PetApi.md b/samples/client/petstore/perl/docs/PetApi.md new file mode 100644 index 00000000000..971dc0772c8 --- /dev/null +++ b/samples/client/petstore/perl/docs/PetApi.md @@ -0,0 +1,557 @@ +# WWW::SwaggerClient::PetApi + +## Load the API package +```perl +use WWW::SwaggerClient::Object::PetApi; +``` + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**add_pet**](PetApi.md#add_pet) | **POST** /pet | Add a new pet to the store +[**add_pet_using_byte_array**](PetApi.md#add_pet_using_byte_array) | **POST** /pet?testing_byte_array=true | Fake endpoint to test byte array in body parameter for adding a new pet to the store +[**delete_pet**](PetApi.md#delete_pet) | **DELETE** /pet/{petId} | Deletes a pet +[**find_pets_by_status**](PetApi.md#find_pets_by_status) | **GET** /pet/findByStatus | Finds Pets by status +[**find_pets_by_tags**](PetApi.md#find_pets_by_tags) | **GET** /pet/findByTags | Finds Pets by tags +[**get_pet_by_id**](PetApi.md#get_pet_by_id) | **GET** /pet/{petId} | Find pet by ID +[**get_pet_by_id_in_object**](PetApi.md#get_pet_by_id_in_object) | **GET** /pet/{petId}?response=inline_arbitrary_object | Fake endpoint to test inline arbitrary object return by 'Find pet by ID' +[**pet_pet_idtesting_byte_arraytrue_get**](PetApi.md#pet_pet_idtesting_byte_arraytrue_get) | **GET** /pet/{petId}?testing_byte_array=true | Fake endpoint to test byte array return by 'Find pet by ID' +[**update_pet**](PetApi.md#update_pet) | **PUT** /pet | Update an existing pet +[**update_pet_with_form**](PetApi.md#update_pet_with_form) | **POST** /pet/{petId} | Updates a pet in the store with form data +[**upload_file**](PetApi.md#upload_file) | **POST** /pet/{petId}/uploadImage | uploads an image + + +# **add_pet** +> add_pet(body => $body) + +Add a new pet to the store + + + +### Example +```perl +use Data::Dumper; + +# Configure OAuth2 access token for authorization: petstore_auth +$WWW::SwaggerClient::Configuration::access_token = 'YOUR_ACCESS_TOKEN'; + +my $api_instance = WWW::SwaggerClient::PetApi->new(); +my $body = WWW::SwaggerClient::Object::Pet->new(); # Pet | Pet object that needs to be added to the store + +eval { + $api_instance->add_pet(body => $body); +}; +if ($@) { + warn "Exception when calling PetApi->add_pet: $@\n"; +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | [optional] + +### Return type + +void (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP reuqest headers + + - **Content-Type**: application/json, application/xml + - **Accept**: application/json, application/xml + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **add_pet_using_byte_array** +> add_pet_using_byte_array(body => $body) + +Fake endpoint to test byte array in body parameter for adding a new pet to the store + + + +### Example +```perl +use Data::Dumper; + +# Configure OAuth2 access token for authorization: petstore_auth +$WWW::SwaggerClient::Configuration::access_token = 'YOUR_ACCESS_TOKEN'; + +my $api_instance = WWW::SwaggerClient::PetApi->new(); +my $body = WWW::SwaggerClient::Object::string->new(); # string | Pet object in the form of byte array + +eval { + $api_instance->add_pet_using_byte_array(body => $body); +}; +if ($@) { + warn "Exception when calling PetApi->add_pet_using_byte_array: $@\n"; +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | **string**| Pet object in the form of byte array | [optional] + +### Return type + +void (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP reuqest headers + + - **Content-Type**: application/json, application/xml + - **Accept**: application/json, application/xml + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **delete_pet** +> delete_pet(pet_id => $pet_id, api_key => $api_key) + +Deletes a pet + + + +### Example +```perl +use Data::Dumper; + +# Configure OAuth2 access token for authorization: petstore_auth +$WWW::SwaggerClient::Configuration::access_token = 'YOUR_ACCESS_TOKEN'; + +my $api_instance = WWW::SwaggerClient::PetApi->new(); +my $pet_id = 789; # int | Pet id to delete +my $api_key = 'api_key_example'; # string | + +eval { + $api_instance->delete_pet(pet_id => $pet_id, api_key => $api_key); +}; +if ($@) { + warn "Exception when calling PetApi->delete_pet: $@\n"; +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **pet_id** | **int**| Pet id to delete | + **api_key** | **string**| | [optional] + +### Return type + +void (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **find_pets_by_status** +> ARRAY[Pet] find_pets_by_status(status => $status) + +Finds Pets by status + +Multiple status values can be provided with comma separated strings + +### Example +```perl +use Data::Dumper; + +# Configure OAuth2 access token for authorization: petstore_auth +$WWW::SwaggerClient::Configuration::access_token = 'YOUR_ACCESS_TOKEN'; + +my $api_instance = WWW::SwaggerClient::PetApi->new(); +my $status = (); # ARRAY[string] | Status values that need to be considered for query + +eval { + my $result = $api_instance->find_pets_by_status(status => $status); + print Dumper($result); +}; +if ($@) { + warn "Exception when calling PetApi->find_pets_by_status: $@\n"; +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **status** | [**ARRAY[string]**](string.md)| Status values that need to be considered for query | [optional] [default to available] + +### Return type + +[**ARRAY[Pet]**](Pet.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **find_pets_by_tags** +> ARRAY[Pet] find_pets_by_tags(tags => $tags) + +Finds Pets by tags + +Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + +### Example +```perl +use Data::Dumper; + +# Configure OAuth2 access token for authorization: petstore_auth +$WWW::SwaggerClient::Configuration::access_token = 'YOUR_ACCESS_TOKEN'; + +my $api_instance = WWW::SwaggerClient::PetApi->new(); +my $tags = (); # ARRAY[string] | Tags to filter by + +eval { + my $result = $api_instance->find_pets_by_tags(tags => $tags); + print Dumper($result); +}; +if ($@) { + warn "Exception when calling PetApi->find_pets_by_tags: $@\n"; +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **tags** | [**ARRAY[string]**](string.md)| Tags to filter by | [optional] + +### Return type + +[**ARRAY[Pet]**](Pet.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **get_pet_by_id** +> Pet get_pet_by_id(pet_id => $pet_id) + +Find pet by ID + +Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + +### Example +```perl +use Data::Dumper; + +# Configure API key authorization: api_key +$WWW::SwaggerClient::Configuration::api_key->{'api_key'} = 'YOUR_API_KEY'; +# uncomment below to setup prefix (e.g. BEARER) for API key, if needed +#$WWW::SwaggerClient::Configuration::api_key_prefix->{'api_key'} = "BEARER"; +# Configure OAuth2 access token for authorization: petstore_auth +$WWW::SwaggerClient::Configuration::access_token = 'YOUR_ACCESS_TOKEN'; + +my $api_instance = WWW::SwaggerClient::PetApi->new(); +my $pet_id = 789; # int | ID of pet that needs to be fetched + +eval { + my $result = $api_instance->get_pet_by_id(pet_id => $pet_id); + print Dumper($result); +}; +if ($@) { + warn "Exception when calling PetApi->get_pet_by_id: $@\n"; +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **pet_id** | **int**| ID of pet that needs to be fetched | + +### Return type + +[**Pet**](Pet.md) + +### Authorization + +[api_key](../README.md#api_key), [petstore_auth](../README.md#petstore_auth) + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **get_pet_by_id_in_object** +> InlineResponse200 get_pet_by_id_in_object(pet_id => $pet_id) + +Fake endpoint to test inline arbitrary object return by 'Find pet by ID' + +Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + +### Example +```perl +use Data::Dumper; + +# Configure API key authorization: api_key +$WWW::SwaggerClient::Configuration::api_key->{'api_key'} = 'YOUR_API_KEY'; +# uncomment below to setup prefix (e.g. BEARER) for API key, if needed +#$WWW::SwaggerClient::Configuration::api_key_prefix->{'api_key'} = "BEARER"; +# Configure OAuth2 access token for authorization: petstore_auth +$WWW::SwaggerClient::Configuration::access_token = 'YOUR_ACCESS_TOKEN'; + +my $api_instance = WWW::SwaggerClient::PetApi->new(); +my $pet_id = 789; # int | ID of pet that needs to be fetched + +eval { + my $result = $api_instance->get_pet_by_id_in_object(pet_id => $pet_id); + print Dumper($result); +}; +if ($@) { + warn "Exception when calling PetApi->get_pet_by_id_in_object: $@\n"; +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **pet_id** | **int**| ID of pet that needs to be fetched | + +### Return type + +[**InlineResponse200**](InlineResponse200.md) + +### Authorization + +[api_key](../README.md#api_key), [petstore_auth](../README.md#petstore_auth) + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **pet_pet_idtesting_byte_arraytrue_get** +> string pet_pet_idtesting_byte_arraytrue_get(pet_id => $pet_id) + +Fake endpoint to test byte array return by 'Find pet by ID' + +Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + +### Example +```perl +use Data::Dumper; + +# Configure API key authorization: api_key +$WWW::SwaggerClient::Configuration::api_key->{'api_key'} = 'YOUR_API_KEY'; +# uncomment below to setup prefix (e.g. BEARER) for API key, if needed +#$WWW::SwaggerClient::Configuration::api_key_prefix->{'api_key'} = "BEARER"; +# Configure OAuth2 access token for authorization: petstore_auth +$WWW::SwaggerClient::Configuration::access_token = 'YOUR_ACCESS_TOKEN'; + +my $api_instance = WWW::SwaggerClient::PetApi->new(); +my $pet_id = 789; # int | ID of pet that needs to be fetched + +eval { + my $result = $api_instance->pet_pet_idtesting_byte_arraytrue_get(pet_id => $pet_id); + print Dumper($result); +}; +if ($@) { + warn "Exception when calling PetApi->pet_pet_idtesting_byte_arraytrue_get: $@\n"; +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **pet_id** | **int**| ID of pet that needs to be fetched | + +### Return type + +**string** + +### Authorization + +[api_key](../README.md#api_key), [petstore_auth](../README.md#petstore_auth) + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **update_pet** +> update_pet(body => $body) + +Update an existing pet + + + +### Example +```perl +use Data::Dumper; + +# Configure OAuth2 access token for authorization: petstore_auth +$WWW::SwaggerClient::Configuration::access_token = 'YOUR_ACCESS_TOKEN'; + +my $api_instance = WWW::SwaggerClient::PetApi->new(); +my $body = WWW::SwaggerClient::Object::Pet->new(); # Pet | Pet object that needs to be added to the store + +eval { + $api_instance->update_pet(body => $body); +}; +if ($@) { + warn "Exception when calling PetApi->update_pet: $@\n"; +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | [optional] + +### Return type + +void (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP reuqest headers + + - **Content-Type**: application/json, application/xml + - **Accept**: application/json, application/xml + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **update_pet_with_form** +> update_pet_with_form(pet_id => $pet_id, name => $name, status => $status) + +Updates a pet in the store with form data + + + +### Example +```perl +use Data::Dumper; + +# Configure OAuth2 access token for authorization: petstore_auth +$WWW::SwaggerClient::Configuration::access_token = 'YOUR_ACCESS_TOKEN'; + +my $api_instance = WWW::SwaggerClient::PetApi->new(); +my $pet_id = 'pet_id_example'; # string | ID of pet that needs to be updated +my $name = 'name_example'; # string | Updated name of the pet +my $status = 'status_example'; # string | Updated status of the pet + +eval { + $api_instance->update_pet_with_form(pet_id => $pet_id, name => $name, status => $status); +}; +if ($@) { + warn "Exception when calling PetApi->update_pet_with_form: $@\n"; +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **pet_id** | **string**| 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 reuqest headers + + - **Content-Type**: application/x-www-form-urlencoded + - **Accept**: application/json, application/xml + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **upload_file** +> upload_file(pet_id => $pet_id, additional_metadata => $additional_metadata, file => $file) + +uploads an image + + + +### Example +```perl +use Data::Dumper; + +# Configure OAuth2 access token for authorization: petstore_auth +$WWW::SwaggerClient::Configuration::access_token = 'YOUR_ACCESS_TOKEN'; + +my $api_instance = WWW::SwaggerClient::PetApi->new(); +my $pet_id = 789; # int | ID of pet to update +my $additional_metadata = 'additional_metadata_example'; # string | Additional data to pass to server +my $file = '/path/to/file.txt'; # File | file to upload + +eval { + $api_instance->upload_file(pet_id => $pet_id, additional_metadata => $additional_metadata, file => $file); +}; +if ($@) { + warn "Exception when calling PetApi->upload_file: $@\n"; +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **pet_id** | **int**| ID of pet to update | + **additional_metadata** | **string**| Additional data to pass to server | [optional] + **file** | **File**| file to upload | [optional] + +### Return type + +void (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP reuqest headers + + - **Content-Type**: multipart/form-data + - **Accept**: application/json, application/xml + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/perl/docs/SpecialModelName.md b/samples/client/petstore/perl/docs/SpecialModelName.md new file mode 100644 index 00000000000..cab9c8ccef6 --- /dev/null +++ b/samples/client/petstore/perl/docs/SpecialModelName.md @@ -0,0 +1,15 @@ +# WWW::SwaggerClient::Object::SpecialModelName + +## Load the model package +```perl +use WWW::SwaggerClient::Object::SpecialModelName; +``` + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**__special[property/name]** | **int** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/perl/docs/StoreApi.md b/samples/client/petstore/perl/docs/StoreApi.md new file mode 100644 index 00000000000..7b9e35c977d --- /dev/null +++ b/samples/client/petstore/perl/docs/StoreApi.md @@ -0,0 +1,311 @@ +# WWW::SwaggerClient::StoreApi + +## Load the API package +```perl +use WWW::SwaggerClient::Object::StoreApi; +``` + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**delete_order**](StoreApi.md#delete_order) | **DELETE** /store/order/{orderId} | Delete purchase order by ID +[**find_orders_by_status**](StoreApi.md#find_orders_by_status) | **GET** /store/findByStatus | Finds orders by status +[**get_inventory**](StoreApi.md#get_inventory) | **GET** /store/inventory | Returns pet inventories by status +[**get_inventory_in_object**](StoreApi.md#get_inventory_in_object) | **GET** /store/inventory?response=arbitrary_object | Fake endpoint to test arbitrary object return by 'Get inventory' +[**get_order_by_id**](StoreApi.md#get_order_by_id) | **GET** /store/order/{orderId} | Find purchase order by ID +[**place_order**](StoreApi.md#place_order) | **POST** /store/order | Place an order for a pet + + +# **delete_order** +> delete_order(order_id => $order_id) + +Delete purchase order by ID + +For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + +### Example +```perl +use Data::Dumper; + +my $api_instance = WWW::SwaggerClient::StoreApi->new(); +my $order_id = 'order_id_example'; # string | ID of the order that needs to be deleted + +eval { + $api_instance->delete_order(order_id => $order_id); +}; +if ($@) { + warn "Exception when calling StoreApi->delete_order: $@\n"; +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **order_id** | **string**| ID of the order that needs to be deleted | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **find_orders_by_status** +> ARRAY[Order] find_orders_by_status(status => $status) + +Finds orders by status + +A single status value can be provided as a string + +### Example +```perl +use Data::Dumper; + +# Configure API key authorization: test_api_client_id +$WWW::SwaggerClient::Configuration::api_key->{'x-test_api_client_id'} = 'YOUR_API_KEY'; +# uncomment below to setup prefix (e.g. BEARER) for API key, if needed +#$WWW::SwaggerClient::Configuration::api_key_prefix->{'x-test_api_client_id'} = "BEARER"; +# Configure API key authorization: test_api_client_secret +$WWW::SwaggerClient::Configuration::api_key->{'x-test_api_client_secret'} = 'YOUR_API_KEY'; +# uncomment below to setup prefix (e.g. BEARER) for API key, if needed +#$WWW::SwaggerClient::Configuration::api_key_prefix->{'x-test_api_client_secret'} = "BEARER"; + +my $api_instance = WWW::SwaggerClient::StoreApi->new(); +my $status = 'status_example'; # string | Status value that needs to be considered for query + +eval { + my $result = $api_instance->find_orders_by_status(status => $status); + print Dumper($result); +}; +if ($@) { + warn "Exception when calling StoreApi->find_orders_by_status: $@\n"; +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **status** | **string**| Status value that needs to be considered for query | [optional] [default to placed] + +### Return type + +[**ARRAY[Order]**](Order.md) + +### Authorization + +[test_api_client_id](../README.md#test_api_client_id), [test_api_client_secret](../README.md#test_api_client_secret) + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **get_inventory** +> HASH[string,int] get_inventory() + +Returns pet inventories by status + +Returns a map of status codes to quantities + +### Example +```perl +use Data::Dumper; + +# Configure API key authorization: api_key +$WWW::SwaggerClient::Configuration::api_key->{'api_key'} = 'YOUR_API_KEY'; +# uncomment below to setup prefix (e.g. BEARER) for API key, if needed +#$WWW::SwaggerClient::Configuration::api_key_prefix->{'api_key'} = "BEARER"; + +my $api_instance = WWW::SwaggerClient::StoreApi->new(); + +eval { + my $result = $api_instance->get_inventory(); + print Dumper($result); +}; +if ($@) { + warn "Exception when calling StoreApi->get_inventory: $@\n"; +} +``` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +**HASH[string,int]** + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **get_inventory_in_object** +> object get_inventory_in_object() + +Fake endpoint to test arbitrary object return by 'Get inventory' + +Returns an arbitrary object which is actually a map of status codes to quantities + +### Example +```perl +use Data::Dumper; + +# Configure API key authorization: api_key +$WWW::SwaggerClient::Configuration::api_key->{'api_key'} = 'YOUR_API_KEY'; +# uncomment below to setup prefix (e.g. BEARER) for API key, if needed +#$WWW::SwaggerClient::Configuration::api_key_prefix->{'api_key'} = "BEARER"; + +my $api_instance = WWW::SwaggerClient::StoreApi->new(); + +eval { + my $result = $api_instance->get_inventory_in_object(); + print Dumper($result); +}; +if ($@) { + warn "Exception when calling StoreApi->get_inventory_in_object: $@\n"; +} +``` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +**object** + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **get_order_by_id** +> Order get_order_by_id(order_id => $order_id) + +Find purchase order by ID + +For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + +### Example +```perl +use Data::Dumper; + +# Configure API key authorization: test_api_key_header +$WWW::SwaggerClient::Configuration::api_key->{'test_api_key_header'} = 'YOUR_API_KEY'; +# uncomment below to setup prefix (e.g. BEARER) for API key, if needed +#$WWW::SwaggerClient::Configuration::api_key_prefix->{'test_api_key_header'} = "BEARER"; +# Configure API key authorization: test_api_key_query +$WWW::SwaggerClient::Configuration::api_key->{'test_api_key_query'} = 'YOUR_API_KEY'; +# uncomment below to setup prefix (e.g. BEARER) for API key, if needed +#$WWW::SwaggerClient::Configuration::api_key_prefix->{'test_api_key_query'} = "BEARER"; + +my $api_instance = WWW::SwaggerClient::StoreApi->new(); +my $order_id = 'order_id_example'; # string | ID of pet that needs to be fetched + +eval { + my $result = $api_instance->get_order_by_id(order_id => $order_id); + print Dumper($result); +}; +if ($@) { + warn "Exception when calling StoreApi->get_order_by_id: $@\n"; +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **order_id** | **string**| ID of pet that needs to be fetched | + +### Return type + +[**Order**](Order.md) + +### Authorization + +[test_api_key_header](../README.md#test_api_key_header), [test_api_key_query](../README.md#test_api_key_query) + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **place_order** +> Order place_order(body => $body) + +Place an order for a pet + + + +### Example +```perl +use Data::Dumper; + +# Configure API key authorization: test_api_client_id +$WWW::SwaggerClient::Configuration::api_key->{'x-test_api_client_id'} = 'YOUR_API_KEY'; +# uncomment below to setup prefix (e.g. BEARER) for API key, if needed +#$WWW::SwaggerClient::Configuration::api_key_prefix->{'x-test_api_client_id'} = "BEARER"; +# Configure API key authorization: test_api_client_secret +$WWW::SwaggerClient::Configuration::api_key->{'x-test_api_client_secret'} = 'YOUR_API_KEY'; +# uncomment below to setup prefix (e.g. BEARER) for API key, if needed +#$WWW::SwaggerClient::Configuration::api_key_prefix->{'x-test_api_client_secret'} = "BEARER"; + +my $api_instance = WWW::SwaggerClient::StoreApi->new(); +my $body = WWW::SwaggerClient::Object::Order->new(); # Order | order placed for purchasing the pet + +eval { + my $result = $api_instance->place_order(body => $body); + print Dumper($result); +}; +if ($@) { + warn "Exception when calling StoreApi->place_order: $@\n"; +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Order**](Order.md)| order placed for purchasing the pet | [optional] + +### Return type + +[**Order**](Order.md) + +### Authorization + +[test_api_client_id](../README.md#test_api_client_id), [test_api_client_secret](../README.md#test_api_client_secret) + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/perl/docs/Tag.md b/samples/client/petstore/perl/docs/Tag.md new file mode 100644 index 00000000000..961035e41a4 --- /dev/null +++ b/samples/client/petstore/perl/docs/Tag.md @@ -0,0 +1,16 @@ +# WWW::SwaggerClient::Object::Tag + +## Load the model package +```perl +use WWW::SwaggerClient::Object::Tag; +``` + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **int** | | [optional] +**name** | **string** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/perl/docs/User.md b/samples/client/petstore/perl/docs/User.md new file mode 100644 index 00000000000..b0335312e6a --- /dev/null +++ b/samples/client/petstore/perl/docs/User.md @@ -0,0 +1,22 @@ +# WWW::SwaggerClient::Object::User + +## Load the model package +```perl +use WWW::SwaggerClient::Object::User; +``` + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **int** | | [optional] +**username** | **string** | | [optional] +**first_name** | **string** | | [optional] +**last_name** | **string** | | [optional] +**email** | **string** | | [optional] +**password** | **string** | | [optional] +**phone** | **string** | | [optional] +**user_status** | **int** | User Status | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/perl/docs/UserApi.md b/samples/client/petstore/perl/docs/UserApi.md new file mode 100644 index 00000000000..7330c1b3980 --- /dev/null +++ b/samples/client/petstore/perl/docs/UserApi.md @@ -0,0 +1,371 @@ +# WWW::SwaggerClient::UserApi + +## Load the API package +```perl +use WWW::SwaggerClient::Object::UserApi; +``` + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**create_user**](UserApi.md#create_user) | **POST** /user | Create user +[**create_users_with_array_input**](UserApi.md#create_users_with_array_input) | **POST** /user/createWithArray | Creates list of users with given input array +[**create_users_with_list_input**](UserApi.md#create_users_with_list_input) | **POST** /user/createWithList | Creates list of users with given input array +[**delete_user**](UserApi.md#delete_user) | **DELETE** /user/{username} | Delete user +[**get_user_by_name**](UserApi.md#get_user_by_name) | **GET** /user/{username} | Get user by user name +[**login_user**](UserApi.md#login_user) | **GET** /user/login | Logs user into the system +[**logout_user**](UserApi.md#logout_user) | **GET** /user/logout | Logs out current logged in user session +[**update_user**](UserApi.md#update_user) | **PUT** /user/{username} | Updated user + + +# **create_user** +> create_user(body => $body) + +Create user + +This can only be done by the logged in user. + +### Example +```perl +use Data::Dumper; + +my $api_instance = WWW::SwaggerClient::UserApi->new(); +my $body = WWW::SwaggerClient::Object::User->new(); # User | Created user object + +eval { + $api_instance->create_user(body => $body); +}; +if ($@) { + warn "Exception when calling UserApi->create_user: $@\n"; +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**User**](User.md)| Created user object | [optional] + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **create_users_with_array_input** +> create_users_with_array_input(body => $body) + +Creates list of users with given input array + + + +### Example +```perl +use Data::Dumper; + +my $api_instance = WWW::SwaggerClient::UserApi->new(); +my $body = (WWW::SwaggerClient::Object::ARRAY[User]->new()); # ARRAY[User] | List of user object + +eval { + $api_instance->create_users_with_array_input(body => $body); +}; +if ($@) { + warn "Exception when calling UserApi->create_users_with_array_input: $@\n"; +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**ARRAY[User]**](User.md)| List of user object | [optional] + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **create_users_with_list_input** +> create_users_with_list_input(body => $body) + +Creates list of users with given input array + + + +### Example +```perl +use Data::Dumper; + +my $api_instance = WWW::SwaggerClient::UserApi->new(); +my $body = (WWW::SwaggerClient::Object::ARRAY[User]->new()); # ARRAY[User] | List of user object + +eval { + $api_instance->create_users_with_list_input(body => $body); +}; +if ($@) { + warn "Exception when calling UserApi->create_users_with_list_input: $@\n"; +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**ARRAY[User]**](User.md)| List of user object | [optional] + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **delete_user** +> delete_user(username => $username) + +Delete user + +This can only be done by the logged in user. + +### Example +```perl +use Data::Dumper; + +# Configure HTTP basic authorization: test_http_basic +$WWW::SwaggerClient::Configuration::username = 'YOUR_USERNAME'; +$WWW::SwaggerClient::Configuration::password = 'YOUR_PASSWORD'; + +my $api_instance = WWW::SwaggerClient::UserApi->new(); +my $username = 'username_example'; # string | The name that needs to be deleted + +eval { + $api_instance->delete_user(username => $username); +}; +if ($@) { + warn "Exception when calling UserApi->delete_user: $@\n"; +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **string**| The name that needs to be deleted | + +### Return type + +void (empty response body) + +### Authorization + +[test_http_basic](../README.md#test_http_basic) + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **get_user_by_name** +> User get_user_by_name(username => $username) + +Get user by user name + + + +### Example +```perl +use Data::Dumper; + +my $api_instance = WWW::SwaggerClient::UserApi->new(); +my $username = 'username_example'; # string | The name that needs to be fetched. Use user1 for testing. + +eval { + my $result = $api_instance->get_user_by_name(username => $username); + print Dumper($result); +}; +if ($@) { + warn "Exception when calling UserApi->get_user_by_name: $@\n"; +} +``` + +### 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 reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **login_user** +> string login_user(username => $username, password => $password) + +Logs user into the system + + + +### Example +```perl +use Data::Dumper; + +my $api_instance = WWW::SwaggerClient::UserApi->new(); +my $username = 'username_example'; # string | The user name for login +my $password = 'password_example'; # string | The password for login in clear text + +eval { + my $result = $api_instance->login_user(username => $username, password => $password); + print Dumper($result); +}; +if ($@) { + warn "Exception when calling UserApi->login_user: $@\n"; +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **string**| The user name for login | [optional] + **password** | **string**| The password for login in clear text | [optional] + +### Return type + +**string** + +### Authorization + +No authorization required + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **logout_user** +> logout_user() + +Logs out current logged in user session + + + +### Example +```perl +use Data::Dumper; + +my $api_instance = WWW::SwaggerClient::UserApi->new(); + +eval { + $api_instance->logout_user(); +}; +if ($@) { + warn "Exception when calling UserApi->logout_user: $@\n"; +} +``` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **update_user** +> update_user(username => $username, body => $body) + +Updated user + +This can only be done by the logged in user. + +### Example +```perl +use Data::Dumper; + +my $api_instance = WWW::SwaggerClient::UserApi->new(); +my $username = 'username_example'; # string | name that need to be deleted +my $body = WWW::SwaggerClient::Object::User->new(); # User | Updated user object + +eval { + $api_instance->update_user(username => $username, body => $body); +}; +if ($@) { + warn "Exception when calling UserApi->update_user: $@\n"; +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **string**| name that need to be deleted | + **body** | [**User**](User.md)| Updated user object | [optional] + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/perl/git_push.sh b/samples/client/petstore/perl/git_push.sh new file mode 100644 index 00000000000..1a36388db02 --- /dev/null +++ b/samples/client/petstore/perl/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="YOUR_GIT_USR_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="YOUR_GIT_REPO_ID" + 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/perl/lib/WWW/SwaggerClient/ApiClient.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/ApiClient.pm index 3ec07335894..86dba7e1bcd 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/ApiClient.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/ApiClient.pm @@ -333,6 +333,12 @@ sub update_params_for_auth { $header_params->{'api_key'} = $api_key; } } + elsif ($auth eq 'test_http_basic') { + + if ($WWW::SwaggerClient::Configuration::username || $WWW::SwaggerClient::Configuration::password) { + $header_params->{'Authorization'} = 'Basic ' . encode_base64($WWW::SwaggerClient::Configuration::username . ":" . $WWW::SwaggerClient::Configuration::password); + } + } elsif ($auth eq 'test_api_client_secret') { my $api_key = $self->get_api_key_with_prefix('x-test_api_client_secret'); diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Animal.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Animal.pm new file mode 100644 index 00000000000..c2e124ad8b4 --- /dev/null +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Animal.pm @@ -0,0 +1,127 @@ +package WWW::SwaggerClient::Object::Animal; + +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. +# + +__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 => 'Animal', + required => [], # TODO +} ); + +__PACKAGE__->method_documentation({ + 'class_name' => { + datatype => 'string', + base_name => 'className', + description => '', + format => '', + read_only => '', + }, + +}); + +__PACKAGE__->swagger_types( { + 'class_name' => 'string' +} ); + +__PACKAGE__->attribute_map( { + 'class_name' => 'className' +} ); + +__PACKAGE__->mk_accessors(keys %{__PACKAGE__->attribute_map}); + + +1; diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Cat.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Cat.pm new file mode 100644 index 00000000000..05500d61ad0 --- /dev/null +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Cat.pm @@ -0,0 +1,136 @@ +package WWW::SwaggerClient::Object::Cat; + +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. +# + +__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 => 'Cat', + required => [], # TODO +} ); + +__PACKAGE__->method_documentation({ + 'class_name' => { + datatype => 'string', + base_name => 'className', + description => '', + format => '', + read_only => '', + }, + 'declawed' => { + datatype => 'boolean', + base_name => 'declawed', + description => '', + format => '', + read_only => '', + }, + +}); + +__PACKAGE__->swagger_types( { + 'class_name' => 'string', + 'declawed' => 'boolean' +} ); + +__PACKAGE__->attribute_map( { + 'class_name' => 'className', + 'declawed' => 'declawed' +} ); + +__PACKAGE__->mk_accessors(keys %{__PACKAGE__->attribute_map}); + + +1; diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Dog.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Dog.pm new file mode 100644 index 00000000000..b4192ec71cd --- /dev/null +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Dog.pm @@ -0,0 +1,136 @@ +package WWW::SwaggerClient::Object::Dog; + +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. +# + +__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 => 'Dog', + required => [], # TODO +} ); + +__PACKAGE__->method_documentation({ + 'class_name' => { + datatype => 'string', + base_name => 'className', + description => '', + format => '', + read_only => '', + }, + 'breed' => { + datatype => 'string', + base_name => 'breed', + description => '', + format => '', + read_only => '', + }, + +}); + +__PACKAGE__->swagger_types( { + 'class_name' => 'string', + 'breed' => 'string' +} ); + +__PACKAGE__->attribute_map( { + 'class_name' => 'className', + 'breed' => 'breed' +} ); + +__PACKAGE__->mk_accessors(keys %{__PACKAGE__->attribute_map}); + + +1; diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/InlineResponse200.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/InlineResponse200.pm index 61ce10e3a2e..90f7bad236e 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/InlineResponse200.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/InlineResponse200.pm @@ -103,6 +103,13 @@ __PACKAGE__->class_documentation({description => '', } ); __PACKAGE__->method_documentation({ + 'tags' => { + datatype => 'ARRAY[Tag]', + base_name => 'tags', + description => '', + format => '', + read_only => '', + }, 'id' => { datatype => 'int', base_name => 'id', @@ -117,6 +124,13 @@ __PACKAGE__->method_documentation({ format => '', read_only => '', }, + 'status' => { + datatype => 'string', + base_name => 'status', + description => 'pet status in the store', + format => '', + read_only => '', + }, 'name' => { datatype => 'string', base_name => 'name', @@ -124,19 +138,32 @@ __PACKAGE__->method_documentation({ format => '', read_only => '', }, + 'photo_urls' => { + datatype => 'ARRAY[string]', + base_name => 'photoUrls', + description => '', + format => '', + read_only => '', + }, }); __PACKAGE__->swagger_types( { + 'tags' => 'ARRAY[Tag]', 'id' => 'int', 'category' => 'object', - 'name' => 'string' + 'status' => 'string', + 'name' => 'string', + 'photo_urls' => 'ARRAY[string]' } ); __PACKAGE__->attribute_map( { + 'tags' => 'tags', 'id' => 'id', 'category' => 'category', - 'name' => 'name' + 'status' => 'status', + 'name' => 'name', + 'photo_urls' => 'photoUrls' } ); __PACKAGE__->mk_accessors(keys %{__PACKAGE__->attribute_map}); diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Model200Response.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Model200Response.pm new file mode 100644 index 00000000000..8ec16d4b97a --- /dev/null +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Model200Response.pm @@ -0,0 +1,127 @@ +package WWW::SwaggerClient::Object::Model200Response; + +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. +# + +__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 => 'Model200Response', + required => [], # TODO +} ); + +__PACKAGE__->method_documentation({ + 'name' => { + datatype => 'int', + base_name => 'name', + description => '', + format => '', + read_only => '', + }, + +}); + +__PACKAGE__->swagger_types( { + 'name' => 'int' +} ); + +__PACKAGE__->attribute_map( { + 'name' => 'name' +} ); + +__PACKAGE__->mk_accessors(keys %{__PACKAGE__->attribute_map}); + + +1; diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/ModelReturn.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/ModelReturn.pm new file mode 100644 index 00000000000..5436aae64bc --- /dev/null +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/ModelReturn.pm @@ -0,0 +1,127 @@ +package WWW::SwaggerClient::Object::ModelReturn; + +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. +# + +__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 => 'ModelReturn', + required => [], # TODO +} ); + +__PACKAGE__->method_documentation({ + 'return' => { + datatype => 'int', + base_name => 'return', + description => '', + format => '', + read_only => '', + }, + +}); + +__PACKAGE__->swagger_types( { + 'return' => 'int' +} ); + +__PACKAGE__->attribute_map( { + 'return' => 'return' +} ); + +__PACKAGE__->mk_accessors(keys %{__PACKAGE__->attribute_map}); + + +1; diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Name.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Name.pm new file mode 100644 index 00000000000..f136a7f031e --- /dev/null +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Name.pm @@ -0,0 +1,136 @@ +package WWW::SwaggerClient::Object::Name; + +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. +# + +__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 => 'Name', + required => [], # TODO +} ); + +__PACKAGE__->method_documentation({ + 'name' => { + datatype => 'int', + base_name => 'name', + description => '', + format => '', + read_only => '', + }, + 'snake_case' => { + datatype => 'int', + base_name => 'snake_case', + description => '', + format => '', + read_only => '', + }, + +}); + +__PACKAGE__->swagger_types( { + 'name' => 'int', + 'snake_case' => 'int' +} ); + +__PACKAGE__->attribute_map( { + 'name' => 'name', + 'snake_case' => 'snake_case' +} ); + +__PACKAGE__->mk_accessors(keys %{__PACKAGE__->attribute_map}); + + +1; diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/PetApi.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/PetApi.pm index ae57afa1ead..c55c9a5fecf 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/PetApi.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/PetApi.pm @@ -51,71 +51,6 @@ sub new { } -# -# update_pet -# -# Update an existing pet -# -# @param Pet $body Pet object that needs to be added to the store (optional) -{ - my $params = { - 'body' => { - data_type => 'Pet', - description => 'Pet object that needs to be added to the store', - required => '0', - }, - }; - __PACKAGE__->method_documentation->{ update_pet } = { - summary => 'Update an existing pet', - params => $params, - returns => undef, - }; -} -# @return void -# -sub update_pet { - my ($self, %args) = @_; - - - - # parse inputs - my $_resource_path = '/pet'; - $_resource_path =~ s/{format}/json/; # default format to json - - my $_method = 'PUT'; - my $query_params = {}; - my $header_params = {}; - my $form_params = {}; - - # 'Accept' and 'Content-Type' header - my $_header_accept = $self->{api_client}->select_header_accept('application/json', 'application/xml'); - if ($_header_accept) { - $header_params->{'Accept'} = $_header_accept; - } - $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type('application/json', 'application/xml'); - - - - - - my $_body_data; - # body params - if ( exists $args{'body'}) { - $_body_data = $args{'body'}; - } - - # authentication setting, if any - my $auth_settings = [qw(petstore_auth )]; - - # make the API Call - - $self->{api_client}->call_api($_resource_path, $_method, - $query_params, $form_params, - $header_params, $_body_data, $auth_settings); - return; - -} - # # add_pet # @@ -181,12 +116,158 @@ sub add_pet { } +# +# add_pet_using_byte_array +# +# Fake endpoint to test byte array in body parameter for adding a new pet to the store +# +# @param string $body Pet object in the form of byte array (optional) +{ + my $params = { + 'body' => { + data_type => 'string', + description => 'Pet object in the form of byte array', + required => '0', + }, + }; + __PACKAGE__->method_documentation->{ add_pet_using_byte_array } = { + summary => 'Fake endpoint to test byte array in body parameter for adding a new pet to the store', + params => $params, + returns => undef, + }; +} +# @return void +# +sub add_pet_using_byte_array { + my ($self, %args) = @_; + + + + # parse inputs + my $_resource_path = '/pet?testing_byte_array=true'; + $_resource_path =~ s/{format}/json/; # default format to json + + my $_method = 'POST'; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; + + # 'Accept' and 'Content-Type' header + my $_header_accept = $self->{api_client}->select_header_accept('application/json', 'application/xml'); + if ($_header_accept) { + $header_params->{'Accept'} = $_header_accept; + } + $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type('application/json', 'application/xml'); + + + + + + my $_body_data; + # body params + if ( exists $args{'body'}) { + $_body_data = $args{'body'}; + } + + # authentication setting, if any + my $auth_settings = [qw(petstore_auth )]; + + # make the API Call + + $self->{api_client}->call_api($_resource_path, $_method, + $query_params, $form_params, + $header_params, $_body_data, $auth_settings); + return; + +} + +# +# delete_pet +# +# Deletes a pet +# +# @param int $pet_id Pet id to delete (required) +# @param string $api_key (optional) +{ + my $params = { + 'pet_id' => { + data_type => 'int', + description => 'Pet id to delete', + required => '1', + }, + 'api_key' => { + data_type => 'string', + description => '', + required => '0', + }, + }; + __PACKAGE__->method_documentation->{ delete_pet } = { + summary => 'Deletes a pet', + params => $params, + returns => undef, + }; +} +# @return void +# +sub delete_pet { + my ($self, %args) = @_; + + + # verify the required parameter 'pet_id' is set + unless (exists $args{'pet_id'}) { + croak("Missing the required parameter 'pet_id' when calling delete_pet"); + } + + + # parse inputs + my $_resource_path = '/pet/{petId}'; + $_resource_path =~ s/{format}/json/; # default format to json + + my $_method = 'DELETE'; + 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', 'application/xml'); + if ($_header_accept) { + $header_params->{'Accept'} = $_header_accept; + } + $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type(); + + + # header params + if ( exists $args{'api_key'}) { + $header_params->{'api_key'} = $self->{api_client}->to_header_value($args{'api_key'}); + } + # path params + if ( exists $args{'pet_id'}) { + my $_base_variable = "{" . "petId" . "}"; + my $_base_value = $self->{api_client}->to_path_value($args{'pet_id'}); + $_resource_path =~ s/$_base_variable/$_base_value/g; + } + + my $_body_data; + + + # authentication setting, if any + my $auth_settings = [qw(petstore_auth )]; + + # make the API Call + + $self->{api_client}->call_api($_resource_path, $_method, + $query_params, $form_params, + $header_params, $_body_data, $auth_settings); + return; + +} + # # find_pets_by_status # # Finds Pets by status # -# @param ARRAY[string] $status Status values that need to be considered for query (optional) +# @param ARRAY[string] $status Status values that need to be considered for query (optional, default to available) { my $params = { 'status' => { @@ -392,276 +473,6 @@ sub get_pet_by_id { } -# -# update_pet_with_form -# -# Updates a pet in the store with form data -# -# @param string $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) -{ - my $params = { - 'pet_id' => { - data_type => 'string', - description => 'ID of pet that needs to be updated', - required => '1', - }, - 'name' => { - data_type => 'string', - description => 'Updated name of the pet', - required => '0', - }, - 'status' => { - data_type => 'string', - description => 'Updated status of the pet', - required => '0', - }, - }; - __PACKAGE__->method_documentation->{ update_pet_with_form } = { - summary => 'Updates a pet in the store with form data', - params => $params, - returns => undef, - }; -} -# @return void -# -sub update_pet_with_form { - my ($self, %args) = @_; - - - # verify the required parameter 'pet_id' is set - unless (exists $args{'pet_id'}) { - croak("Missing the required parameter 'pet_id' when calling update_pet_with_form"); - } - - - # parse inputs - my $_resource_path = '/pet/{petId}'; - $_resource_path =~ s/{format}/json/; # default format to json - - my $_method = 'POST'; - my $query_params = {}; - my $header_params = {}; - my $form_params = {}; - - # 'Accept' and 'Content-Type' header - my $_header_accept = $self->{api_client}->select_header_accept('application/json', 'application/xml'); - if ($_header_accept) { - $header_params->{'Accept'} = $_header_accept; - } - $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type('application/x-www-form-urlencoded'); - - - - # path params - if ( exists $args{'pet_id'}) { - my $_base_variable = "{" . "petId" . "}"; - my $_base_value = $self->{api_client}->to_path_value($args{'pet_id'}); - $_resource_path =~ s/$_base_variable/$_base_value/g; - } - # form params - if ( exists $args{'name'} ) { - - $form_params->{'name'} = $self->{api_client}->to_form_value($args{'name'}); - - }# form params - if ( exists $args{'status'} ) { - - $form_params->{'status'} = $self->{api_client}->to_form_value($args{'status'}); - - } - my $_body_data; - - - # authentication setting, if any - my $auth_settings = [qw(petstore_auth )]; - - # make the API Call - - $self->{api_client}->call_api($_resource_path, $_method, - $query_params, $form_params, - $header_params, $_body_data, $auth_settings); - return; - -} - -# -# delete_pet -# -# Deletes a pet -# -# @param int $pet_id Pet id to delete (required) -# @param string $api_key (optional) -{ - my $params = { - 'pet_id' => { - data_type => 'int', - description => 'Pet id to delete', - required => '1', - }, - 'api_key' => { - data_type => 'string', - description => '', - required => '0', - }, - }; - __PACKAGE__->method_documentation->{ delete_pet } = { - summary => 'Deletes a pet', - params => $params, - returns => undef, - }; -} -# @return void -# -sub delete_pet { - my ($self, %args) = @_; - - - # verify the required parameter 'pet_id' is set - unless (exists $args{'pet_id'}) { - croak("Missing the required parameter 'pet_id' when calling delete_pet"); - } - - - # parse inputs - my $_resource_path = '/pet/{petId}'; - $_resource_path =~ s/{format}/json/; # default format to json - - my $_method = 'DELETE'; - 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', 'application/xml'); - if ($_header_accept) { - $header_params->{'Accept'} = $_header_accept; - } - $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type(); - - - # header params - if ( exists $args{'api_key'}) { - $header_params->{'api_key'} = $self->{api_client}->to_header_value($args{'api_key'}); - } - # path params - if ( exists $args{'pet_id'}) { - my $_base_variable = "{" . "petId" . "}"; - my $_base_value = $self->{api_client}->to_path_value($args{'pet_id'}); - $_resource_path =~ s/$_base_variable/$_base_value/g; - } - - my $_body_data; - - - # authentication setting, if any - my $auth_settings = [qw(petstore_auth )]; - - # make the API Call - - $self->{api_client}->call_api($_resource_path, $_method, - $query_params, $form_params, - $header_params, $_body_data, $auth_settings); - return; - -} - -# -# upload_file -# -# uploads an image -# -# @param int $pet_id ID of pet to update (required) -# @param string $additional_metadata Additional data to pass to server (optional) -# @param File $file file to upload (optional) -{ - my $params = { - 'pet_id' => { - data_type => 'int', - description => 'ID of pet to update', - required => '1', - }, - 'additional_metadata' => { - data_type => 'string', - description => 'Additional data to pass to server', - required => '0', - }, - 'file' => { - data_type => 'File', - description => 'file to upload', - required => '0', - }, - }; - __PACKAGE__->method_documentation->{ upload_file } = { - summary => 'uploads an image', - params => $params, - returns => undef, - }; -} -# @return void -# -sub upload_file { - my ($self, %args) = @_; - - - # verify the required parameter 'pet_id' is set - unless (exists $args{'pet_id'}) { - croak("Missing the required parameter 'pet_id' when calling upload_file"); - } - - - # parse inputs - my $_resource_path = '/pet/{petId}/uploadImage'; - $_resource_path =~ s/{format}/json/; # default format to json - - my $_method = 'POST'; - my $query_params = {}; - my $header_params = {}; - my $form_params = {}; - - # 'Accept' and 'Content-Type' header - my $_header_accept = $self->{api_client}->select_header_accept('application/json', 'application/xml'); - if ($_header_accept) { - $header_params->{'Accept'} = $_header_accept; - } - $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type('multipart/form-data'); - - - - # path params - if ( exists $args{'pet_id'}) { - my $_base_variable = "{" . "petId" . "}"; - my $_base_value = $self->{api_client}->to_path_value($args{'pet_id'}); - $_resource_path =~ s/$_base_variable/$_base_value/g; - } - # form params - if ( exists $args{'additional_metadata'} ) { - - $form_params->{'additionalMetadata'} = $self->{api_client}->to_form_value($args{'additional_metadata'}); - - }# form params - if ( exists $args{'file'} ) { - $form_params->{'file'} = [] unless defined $form_params->{'file'}; - push @{$form_params->{'file'}}, $args{'file'}; - - - } - my $_body_data; - - - # authentication setting, if any - my $auth_settings = [qw(petstore_auth )]; - - # make the API Call - - $self->{api_client}->call_api($_resource_path, $_method, - $query_params, $form_params, - $header_params, $_body_data, $auth_settings); - return; - -} - # # get_pet_by_id_in_object # @@ -813,37 +624,37 @@ sub pet_pet_idtesting_byte_arraytrue_get { } # -# add_pet_using_byte_array +# update_pet # -# Fake endpoint to test byte array in body parameter for adding a new pet to the store +# Update an existing pet # -# @param string $body Pet object in the form of byte array (optional) +# @param Pet $body Pet object that needs to be added to the store (optional) { my $params = { 'body' => { - data_type => 'string', - description => 'Pet object in the form of byte array', + data_type => 'Pet', + description => 'Pet object that needs to be added to the store', required => '0', }, }; - __PACKAGE__->method_documentation->{ add_pet_using_byte_array } = { - summary => 'Fake endpoint to test byte array in body parameter for adding a new pet to the store', + __PACKAGE__->method_documentation->{ update_pet } = { + summary => 'Update an existing pet', params => $params, returns => undef, }; } # @return void # -sub add_pet_using_byte_array { +sub update_pet { my ($self, %args) = @_; # parse inputs - my $_resource_path = '/pet?testing_byte_array=true'; + my $_resource_path = '/pet'; $_resource_path =~ s/{format}/json/; # default format to json - my $_method = 'POST'; + my $_method = 'PUT'; my $query_params = {}; my $header_params = {}; my $form_params = {}; @@ -877,5 +688,194 @@ sub add_pet_using_byte_array { } +# +# update_pet_with_form +# +# Updates a pet in the store with form data +# +# @param string $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) +{ + my $params = { + 'pet_id' => { + data_type => 'string', + description => 'ID of pet that needs to be updated', + required => '1', + }, + 'name' => { + data_type => 'string', + description => 'Updated name of the pet', + required => '0', + }, + 'status' => { + data_type => 'string', + description => 'Updated status of the pet', + required => '0', + }, + }; + __PACKAGE__->method_documentation->{ update_pet_with_form } = { + summary => 'Updates a pet in the store with form data', + params => $params, + returns => undef, + }; +} +# @return void +# +sub update_pet_with_form { + my ($self, %args) = @_; + + + # verify the required parameter 'pet_id' is set + unless (exists $args{'pet_id'}) { + croak("Missing the required parameter 'pet_id' when calling update_pet_with_form"); + } + + + # parse inputs + my $_resource_path = '/pet/{petId}'; + $_resource_path =~ s/{format}/json/; # default format to json + + my $_method = 'POST'; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; + + # 'Accept' and 'Content-Type' header + my $_header_accept = $self->{api_client}->select_header_accept('application/json', 'application/xml'); + if ($_header_accept) { + $header_params->{'Accept'} = $_header_accept; + } + $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type('application/x-www-form-urlencoded'); + + + + # path params + if ( exists $args{'pet_id'}) { + my $_base_variable = "{" . "petId" . "}"; + my $_base_value = $self->{api_client}->to_path_value($args{'pet_id'}); + $_resource_path =~ s/$_base_variable/$_base_value/g; + } + # form params + if ( exists $args{'name'} ) { + + $form_params->{'name'} = $self->{api_client}->to_form_value($args{'name'}); + + }# form params + if ( exists $args{'status'} ) { + + $form_params->{'status'} = $self->{api_client}->to_form_value($args{'status'}); + + } + my $_body_data; + + + # authentication setting, if any + my $auth_settings = [qw(petstore_auth )]; + + # make the API Call + + $self->{api_client}->call_api($_resource_path, $_method, + $query_params, $form_params, + $header_params, $_body_data, $auth_settings); + return; + +} + +# +# upload_file +# +# uploads an image +# +# @param int $pet_id ID of pet to update (required) +# @param string $additional_metadata Additional data to pass to server (optional) +# @param File $file file to upload (optional) +{ + my $params = { + 'pet_id' => { + data_type => 'int', + description => 'ID of pet to update', + required => '1', + }, + 'additional_metadata' => { + data_type => 'string', + description => 'Additional data to pass to server', + required => '0', + }, + 'file' => { + data_type => 'File', + description => 'file to upload', + required => '0', + }, + }; + __PACKAGE__->method_documentation->{ upload_file } = { + summary => 'uploads an image', + params => $params, + returns => undef, + }; +} +# @return void +# +sub upload_file { + my ($self, %args) = @_; + + + # verify the required parameter 'pet_id' is set + unless (exists $args{'pet_id'}) { + croak("Missing the required parameter 'pet_id' when calling upload_file"); + } + + + # parse inputs + my $_resource_path = '/pet/{petId}/uploadImage'; + $_resource_path =~ s/{format}/json/; # default format to json + + my $_method = 'POST'; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; + + # 'Accept' and 'Content-Type' header + my $_header_accept = $self->{api_client}->select_header_accept('application/json', 'application/xml'); + if ($_header_accept) { + $header_params->{'Accept'} = $_header_accept; + } + $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type('multipart/form-data'); + + + + # path params + if ( exists $args{'pet_id'}) { + my $_base_variable = "{" . "petId" . "}"; + my $_base_value = $self->{api_client}->to_path_value($args{'pet_id'}); + $_resource_path =~ s/$_base_variable/$_base_value/g; + } + # form params + if ( exists $args{'additional_metadata'} ) { + + $form_params->{'additionalMetadata'} = $self->{api_client}->to_form_value($args{'additional_metadata'}); + + }# form params + if ( exists $args{'file'} ) { + $form_params->{'file'} = [] unless defined $form_params->{'file'}; + push @{$form_params->{'file'}}, $args{'file'}; + + + } + my $_body_data; + + + # authentication setting, if any + my $auth_settings = [qw(petstore_auth )]; + + # make the API Call + + $self->{api_client}->call_api($_resource_path, $_method, + $query_params, $form_params, + $header_params, $_body_data, $auth_settings); + return; + +} + 1; diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Role.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Role.pm index 1334b695271..4b1f63cbb2e 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Role.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Role.pm @@ -37,7 +37,7 @@ has version_info => ( is => 'ro', default => sub { { app_name => 'Swagger Petstore', app_version => '1.0.0', - generated_date => '2016-03-04T14:39:09.479+08:00', + generated_date => '2016-03-30T20:57:51.908+08:00', generator_class => 'class io.swagger.codegen.languages.PerlClientCodegen', } }, documentation => 'Information about the application version and the codegen codebase version' @@ -103,7 +103,7 @@ Automatically generated by the Perl Swagger Codegen project: =over 4 -=item Build date: 2016-03-04T14:39:09.479+08:00 +=item Build date: 2016-03-30T20:57:51.908+08:00 =item Build package: class io.swagger.codegen.languages.PerlClientCodegen diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/StoreApi.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/StoreApi.pm index fe001897754..f9af88c0ac9 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/StoreApi.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/StoreApi.pm @@ -51,12 +51,84 @@ sub new { } +# +# delete_order +# +# Delete purchase order by ID +# +# @param string $order_id ID of the order that needs to be deleted (required) +{ + my $params = { + 'order_id' => { + data_type => 'string', + description => 'ID of the order that needs to be deleted', + required => '1', + }, + }; + __PACKAGE__->method_documentation->{ delete_order } = { + summary => 'Delete purchase order by ID', + params => $params, + returns => undef, + }; +} +# @return void +# +sub delete_order { + my ($self, %args) = @_; + + + # verify the required parameter 'order_id' is set + unless (exists $args{'order_id'}) { + croak("Missing the required parameter 'order_id' when calling delete_order"); + } + + + # parse inputs + my $_resource_path = '/store/order/{orderId}'; + $_resource_path =~ s/{format}/json/; # default format to json + + my $_method = 'DELETE'; + 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', 'application/xml'); + if ($_header_accept) { + $header_params->{'Accept'} = $_header_accept; + } + $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type(); + + + + # path params + if ( exists $args{'order_id'}) { + my $_base_variable = "{" . "orderId" . "}"; + my $_base_value = $self->{api_client}->to_path_value($args{'order_id'}); + $_resource_path =~ s/$_base_variable/$_base_value/g; + } + + my $_body_data; + + + # authentication setting, if any + my $auth_settings = [qw()]; + + # make the API Call + + $self->{api_client}->call_api($_resource_path, $_method, + $query_params, $form_params, + $header_params, $_body_data, $auth_settings); + return; + +} + # # find_orders_by_status # # Finds orders by status # -# @param string $status Status value that needs to be considered for query (optional) +# @param string $status Status value that needs to be considered for query (optional, default to placed) { my $params = { 'status' => { @@ -237,74 +309,6 @@ sub get_inventory_in_object { } -# -# place_order -# -# Place an order for a pet -# -# @param Order $body order placed for purchasing the pet (optional) -{ - my $params = { - 'body' => { - data_type => 'Order', - description => 'order placed for purchasing the pet', - required => '0', - }, - }; - __PACKAGE__->method_documentation->{ place_order } = { - summary => 'Place an order for a pet', - params => $params, - returns => 'Order', - }; -} -# @return Order -# -sub place_order { - my ($self, %args) = @_; - - - - # parse inputs - my $_resource_path = '/store/order'; - $_resource_path =~ s/{format}/json/; # default format to json - - my $_method = 'POST'; - my $query_params = {}; - my $header_params = {}; - my $form_params = {}; - - # 'Accept' and 'Content-Type' header - my $_header_accept = $self->{api_client}->select_header_accept('application/json', 'application/xml'); - if ($_header_accept) { - $header_params->{'Accept'} = $_header_accept; - } - $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type(); - - - - - - my $_body_data; - # body params - if ( exists $args{'body'}) { - $_body_data = $args{'body'}; - } - - # authentication setting, if any - my $auth_settings = [qw(test_api_client_id test_api_client_secret )]; - - # make the API Call - my $response = $self->{api_client}->call_api($_resource_path, $_method, - $query_params, $form_params, - $header_params, $_body_data, $auth_settings); - if (!$response) { - return; - } - my $_response_object = $self->{api_client}->deserialize('Order', $response); - return $_response_object; - -} - # # get_order_by_id # @@ -381,42 +385,37 @@ sub get_order_by_id { } # -# delete_order +# place_order # -# Delete purchase order by ID +# Place an order for a pet # -# @param string $order_id ID of the order that needs to be deleted (required) +# @param Order $body order placed for purchasing the pet (optional) { my $params = { - 'order_id' => { - data_type => 'string', - description => 'ID of the order that needs to be deleted', - required => '1', + 'body' => { + data_type => 'Order', + description => 'order placed for purchasing the pet', + required => '0', }, }; - __PACKAGE__->method_documentation->{ delete_order } = { - summary => 'Delete purchase order by ID', + __PACKAGE__->method_documentation->{ place_order } = { + summary => 'Place an order for a pet', params => $params, - returns => undef, + returns => 'Order', }; } -# @return void +# @return Order # -sub delete_order { +sub place_order { my ($self, %args) = @_; - # verify the required parameter 'order_id' is set - unless (exists $args{'order_id'}) { - croak("Missing the required parameter 'order_id' when calling delete_order"); - } - # parse inputs - my $_resource_path = '/store/order/{orderId}'; + my $_resource_path = '/store/order'; $_resource_path =~ s/{format}/json/; # default format to json - my $_method = 'DELETE'; + my $_method = 'POST'; my $query_params = {}; my $header_params = {}; my $form_params = {}; @@ -430,25 +429,26 @@ sub delete_order { - # path params - if ( exists $args{'order_id'}) { - my $_base_variable = "{" . "orderId" . "}"; - my $_base_value = $self->{api_client}->to_path_value($args{'order_id'}); - $_resource_path =~ s/$_base_variable/$_base_value/g; - } + my $_body_data; - + # body params + if ( exists $args{'body'}) { + $_body_data = $args{'body'}; + } # authentication setting, if any - my $auth_settings = [qw()]; + my $auth_settings = [qw(test_api_client_id test_api_client_secret )]; # 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('Order', $response); + return $_response_object; } diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/UserApi.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/UserApi.pm index 5e983e1aa7c..e86cc571a70 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/UserApi.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/UserApi.pm @@ -246,6 +246,153 @@ sub create_users_with_list_input { } +# +# delete_user +# +# Delete user +# +# @param string $username The name that needs to be deleted (required) +{ + my $params = { + 'username' => { + data_type => 'string', + description => 'The name that needs to be deleted', + required => '1', + }, + }; + __PACKAGE__->method_documentation->{ delete_user } = { + summary => 'Delete user', + params => $params, + returns => undef, + }; +} +# @return void +# +sub delete_user { + my ($self, %args) = @_; + + + # verify the required parameter 'username' is set + unless (exists $args{'username'}) { + croak("Missing the required parameter 'username' when calling delete_user"); + } + + + # parse inputs + my $_resource_path = '/user/{username}'; + $_resource_path =~ s/{format}/json/; # default format to json + + my $_method = 'DELETE'; + 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', 'application/xml'); + if ($_header_accept) { + $header_params->{'Accept'} = $_header_accept; + } + $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type(); + + + + # path params + if ( exists $args{'username'}) { + my $_base_variable = "{" . "username" . "}"; + my $_base_value = $self->{api_client}->to_path_value($args{'username'}); + $_resource_path =~ s/$_base_variable/$_base_value/g; + } + + my $_body_data; + + + # authentication setting, if any + my $auth_settings = [qw(test_http_basic )]; + + # make the API Call + + $self->{api_client}->call_api($_resource_path, $_method, + $query_params, $form_params, + $header_params, $_body_data, $auth_settings); + return; + +} + +# +# get_user_by_name +# +# Get user by user name +# +# @param string $username The name that needs to be fetched. Use user1 for testing. (required) +{ + my $params = { + 'username' => { + data_type => 'string', + description => 'The name that needs to be fetched. Use user1 for testing.', + required => '1', + }, + }; + __PACKAGE__->method_documentation->{ get_user_by_name } = { + summary => 'Get user by user name', + params => $params, + returns => 'User', + }; +} +# @return User +# +sub get_user_by_name { + my ($self, %args) = @_; + + + # verify the required parameter 'username' is set + unless (exists $args{'username'}) { + croak("Missing the required parameter 'username' when calling get_user_by_name"); + } + + + # parse inputs + my $_resource_path = '/user/{username}'; + $_resource_path =~ s/{format}/json/; # default format to json + + my $_method = 'GET'; + 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', 'application/xml'); + if ($_header_accept) { + $header_params->{'Accept'} = $_header_accept; + } + $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type(); + + + + # path params + if ( exists $args{'username'}) { + my $_base_variable = "{" . "username" . "}"; + my $_base_value = $self->{api_client}->to_path_value($args{'username'}); + $_resource_path =~ s/$_base_variable/$_base_value/g; + } + + my $_body_data; + + + # authentication setting, if any + my $auth_settings = [qw()]; + + # make the API Call + my $response = $self->{api_client}->call_api($_resource_path, $_method, + $query_params, $form_params, + $header_params, $_body_data, $auth_settings); + if (!$response) { + return; + } + my $_response_object = $self->{api_client}->deserialize('User', $response); + return $_response_object; + +} + # # login_user # @@ -379,81 +526,6 @@ sub logout_user { } -# -# get_user_by_name -# -# Get user by user name -# -# @param string $username The name that needs to be fetched. Use user1 for testing. (required) -{ - my $params = { - 'username' => { - data_type => 'string', - description => 'The name that needs to be fetched. Use user1 for testing.', - required => '1', - }, - }; - __PACKAGE__->method_documentation->{ get_user_by_name } = { - summary => 'Get user by user name', - params => $params, - returns => 'User', - }; -} -# @return User -# -sub get_user_by_name { - my ($self, %args) = @_; - - - # verify the required parameter 'username' is set - unless (exists $args{'username'}) { - croak("Missing the required parameter 'username' when calling get_user_by_name"); - } - - - # parse inputs - my $_resource_path = '/user/{username}'; - $_resource_path =~ s/{format}/json/; # default format to json - - my $_method = 'GET'; - 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', 'application/xml'); - if ($_header_accept) { - $header_params->{'Accept'} = $_header_accept; - } - $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type(); - - - - # path params - if ( exists $args{'username'}) { - my $_base_variable = "{" . "username" . "}"; - my $_base_value = $self->{api_client}->to_path_value($args{'username'}); - $_resource_path =~ s/$_base_variable/$_base_value/g; - } - - my $_body_data; - - - # authentication setting, if any - my $auth_settings = [qw()]; - - # make the API Call - my $response = $self->{api_client}->call_api($_resource_path, $_method, - $query_params, $form_params, - $header_params, $_body_data, $auth_settings); - if (!$response) { - return; - } - my $_response_object = $self->{api_client}->deserialize('User', $response); - return $_response_object; - -} - # # update_user # @@ -535,77 +607,5 @@ sub update_user { } -# -# delete_user -# -# Delete user -# -# @param string $username The name that needs to be deleted (required) -{ - my $params = { - 'username' => { - data_type => 'string', - description => 'The name that needs to be deleted', - required => '1', - }, - }; - __PACKAGE__->method_documentation->{ delete_user } = { - summary => 'Delete user', - params => $params, - returns => undef, - }; -} -# @return void -# -sub delete_user { - my ($self, %args) = @_; - - - # verify the required parameter 'username' is set - unless (exists $args{'username'}) { - croak("Missing the required parameter 'username' when calling delete_user"); - } - - - # parse inputs - my $_resource_path = '/user/{username}'; - $_resource_path =~ s/{format}/json/; # default format to json - - my $_method = 'DELETE'; - 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', 'application/xml'); - if ($_header_accept) { - $header_params->{'Accept'} = $_header_accept; - } - $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type(); - - - - # path params - if ( exists $args{'username'}) { - my $_base_variable = "{" . "username" . "}"; - my $_base_value = $self->{api_client}->to_path_value($args{'username'}); - $_resource_path =~ s/$_base_variable/$_base_value/g; - } - - my $_body_data; - - - # authentication setting, if any - my $auth_settings = [qw()]; - - # make the API Call - - $self->{api_client}->call_api($_resource_path, $_method, - $query_params, $form_params, - $header_params, $_body_data, $auth_settings); - return; - -} - 1; diff --git a/samples/client/petstore/perl/t/AnimalTest.t b/samples/client/petstore/perl/t/AnimalTest.t new file mode 100644 index 00000000000..7d608e30803 --- /dev/null +++ b/samples/client/petstore/perl/t/AnimalTest.t @@ -0,0 +1,17 @@ +# NOTE: This class is auto generated by the Swagger Codegen +# Please update the test case below to test the model. + +use Test::More tests => 2; +use Test::Exception; + +use lib 'lib'; +use strict; +use warnings; + + +use_ok('WWW::SwaggerClient::Object::Animal'); + +my $instance = WWW::SwaggerClient::Object::Animal->new(); + +isa_ok($instance, 'WWW::SwaggerClient::Object::Animal'); + diff --git a/samples/client/petstore/perl/t/CatTest.t b/samples/client/petstore/perl/t/CatTest.t new file mode 100644 index 00000000000..cc1569cab40 --- /dev/null +++ b/samples/client/petstore/perl/t/CatTest.t @@ -0,0 +1,17 @@ +# NOTE: This class is auto generated by the Swagger Codegen +# Please update the test case below to test the model. + +use Test::More tests => 2; +use Test::Exception; + +use lib 'lib'; +use strict; +use warnings; + + +use_ok('WWW::SwaggerClient::Object::Cat'); + +my $instance = WWW::SwaggerClient::Object::Cat->new(); + +isa_ok($instance, 'WWW::SwaggerClient::Object::Cat'); + diff --git a/samples/client/petstore/perl/t/DogTest.t b/samples/client/petstore/perl/t/DogTest.t new file mode 100644 index 00000000000..d99225a0592 --- /dev/null +++ b/samples/client/petstore/perl/t/DogTest.t @@ -0,0 +1,17 @@ +# NOTE: This class is auto generated by the Swagger Codegen +# Please update the test case below to test the model. + +use Test::More tests => 2; +use Test::Exception; + +use lib 'lib'; +use strict; +use warnings; + + +use_ok('WWW::SwaggerClient::Object::Dog'); + +my $instance = WWW::SwaggerClient::Object::Dog->new(); + +isa_ok($instance, 'WWW::SwaggerClient::Object::Dog'); + diff --git a/samples/client/petstore/perl/t/Model200ResponseTest.t b/samples/client/petstore/perl/t/Model200ResponseTest.t new file mode 100644 index 00000000000..d6c0785519e --- /dev/null +++ b/samples/client/petstore/perl/t/Model200ResponseTest.t @@ -0,0 +1,17 @@ +# NOTE: This class is auto generated by the Swagger Codegen +# Please update the test case below to test the model. + +use Test::More tests => 2; +use Test::Exception; + +use lib 'lib'; +use strict; +use warnings; + + +use_ok('WWW::SwaggerClient::Object::Model200Response'); + +my $instance = WWW::SwaggerClient::Object::Model200Response->new(); + +isa_ok($instance, 'WWW::SwaggerClient::Object::Model200Response'); + diff --git a/samples/client/petstore/perl/t/ModelReturnTest.t b/samples/client/petstore/perl/t/ModelReturnTest.t new file mode 100644 index 00000000000..29753c78e5b --- /dev/null +++ b/samples/client/petstore/perl/t/ModelReturnTest.t @@ -0,0 +1,17 @@ +# NOTE: This class is auto generated by the Swagger Codegen +# Please update the test case below to test the model. + +use Test::More tests => 2; +use Test::Exception; + +use lib 'lib'; +use strict; +use warnings; + + +use_ok('WWW::SwaggerClient::Object::ModelReturn'); + +my $instance = WWW::SwaggerClient::Object::ModelReturn->new(); + +isa_ok($instance, 'WWW::SwaggerClient::Object::ModelReturn'); + diff --git a/samples/client/petstore/perl/t/NameTest.t b/samples/client/petstore/perl/t/NameTest.t new file mode 100644 index 00000000000..3714cb140e6 --- /dev/null +++ b/samples/client/petstore/perl/t/NameTest.t @@ -0,0 +1,17 @@ +# NOTE: This class is auto generated by the Swagger Codegen +# Please update the test case below to test the model. + +use Test::More tests => 2; +use Test::Exception; + +use lib 'lib'; +use strict; +use warnings; + + +use_ok('WWW::SwaggerClient::Object::Name'); + +my $instance = WWW::SwaggerClient::Object::Name->new(); + +isa_ok($instance, 'WWW::SwaggerClient::Object::Name'); + diff --git a/samples/client/petstore/perl/t/PetApiTest.t b/samples/client/petstore/perl/t/PetApiTest.t index ec4723812a9..91f87e56f24 100644 --- a/samples/client/petstore/perl/t/PetApiTest.t +++ b/samples/client/petstore/perl/t/PetApiTest.t @@ -29,14 +29,6 @@ use_ok('WWW::SwaggerClient::PetApi'); my $api = WWW::SwaggerClient::PetApi->new(); isa_ok($api, 'WWW::SwaggerClient::PetApi'); -# -# update_pet test -# -{ - my $body = undef; # replace NULL with a proper value - my $result = $api->update_pet(body => $body); -} - # # add_pet test # @@ -45,6 +37,23 @@ isa_ok($api, 'WWW::SwaggerClient::PetApi'); my $result = $api->add_pet(body => $body); } +# +# add_pet_using_byte_array test +# +{ + my $body = undef; # replace NULL with a proper value + my $result = $api->add_pet_using_byte_array(body => $body); +} + +# +# delete_pet test +# +{ + my $pet_id = undef; # replace NULL with a proper value + my $api_key = undef; # replace NULL with a proper value + my $result = $api->delete_pet(pet_id => $pet_id, api_key => $api_key); +} + # # find_pets_by_status test # @@ -69,35 +78,6 @@ isa_ok($api, 'WWW::SwaggerClient::PetApi'); my $result = $api->get_pet_by_id(pet_id => $pet_id); } -# -# update_pet_with_form test -# -{ - my $pet_id = undef; # replace NULL with a proper value - my $name = undef; # replace NULL with a proper value - my $status = undef; # replace NULL with a proper value - my $result = $api->update_pet_with_form(pet_id => $pet_id, name => $name, status => $status); -} - -# -# delete_pet test -# -{ - my $pet_id = undef; # replace NULL with a proper value - my $api_key = undef; # replace NULL with a proper value - my $result = $api->delete_pet(pet_id => $pet_id, api_key => $api_key); -} - -# -# upload_file test -# -{ - my $pet_id = undef; # replace NULL with a proper value - my $additional_metadata = undef; # replace NULL with a proper value - my $file = undef; # replace NULL with a proper value - my $result = $api->upload_file(pet_id => $pet_id, additional_metadata => $additional_metadata, file => $file); -} - # # get_pet_by_id_in_object test # @@ -115,11 +95,31 @@ isa_ok($api, 'WWW::SwaggerClient::PetApi'); } # -# add_pet_using_byte_array test +# update_pet test # { my $body = undef; # replace NULL with a proper value - my $result = $api->add_pet_using_byte_array(body => $body); + my $result = $api->update_pet(body => $body); +} + +# +# update_pet_with_form test +# +{ + my $pet_id = undef; # replace NULL with a proper value + my $name = undef; # replace NULL with a proper value + my $status = undef; # replace NULL with a proper value + my $result = $api->update_pet_with_form(pet_id => $pet_id, name => $name, status => $status); +} + +# +# upload_file test +# +{ + my $pet_id = undef; # replace NULL with a proper value + my $additional_metadata = undef; # replace NULL with a proper value + my $file = undef; # replace NULL with a proper value + my $result = $api->upload_file(pet_id => $pet_id, additional_metadata => $additional_metadata, file => $file); } diff --git a/samples/client/petstore/perl/t/StoreApiTest.t b/samples/client/petstore/perl/t/StoreApiTest.t index 3772914c7aa..a9bc3b3a4f3 100644 --- a/samples/client/petstore/perl/t/StoreApiTest.t +++ b/samples/client/petstore/perl/t/StoreApiTest.t @@ -29,6 +29,14 @@ use_ok('WWW::SwaggerClient::StoreApi'); my $api = WWW::SwaggerClient::StoreApi->new(); isa_ok($api, 'WWW::SwaggerClient::StoreApi'); +# +# delete_order test +# +{ + my $order_id = undef; # replace NULL with a proper value + my $result = $api->delete_order(order_id => $order_id); +} + # # find_orders_by_status test # @@ -51,14 +59,6 @@ isa_ok($api, 'WWW::SwaggerClient::StoreApi'); my $result = $api->get_inventory_in_object(); } -# -# place_order test -# -{ - my $body = undef; # replace NULL with a proper value - my $result = $api->place_order(body => $body); -} - # # get_order_by_id test # @@ -68,11 +68,11 @@ isa_ok($api, 'WWW::SwaggerClient::StoreApi'); } # -# delete_order test +# place_order test # { - my $order_id = undef; # replace NULL with a proper value - my $result = $api->delete_order(order_id => $order_id); + my $body = undef; # replace NULL with a proper value + my $result = $api->place_order(body => $body); } diff --git a/samples/client/petstore/perl/t/UserApiTest.t b/samples/client/petstore/perl/t/UserApiTest.t index e0bf708ca48..108484ed120 100644 --- a/samples/client/petstore/perl/t/UserApiTest.t +++ b/samples/client/petstore/perl/t/UserApiTest.t @@ -53,6 +53,22 @@ isa_ok($api, 'WWW::SwaggerClient::UserApi'); my $result = $api->create_users_with_list_input(body => $body); } +# +# delete_user test +# +{ + my $username = undef; # replace NULL with a proper value + my $result = $api->delete_user(username => $username); +} + +# +# get_user_by_name test +# +{ + my $username = undef; # replace NULL with a proper value + my $result = $api->get_user_by_name(username => $username); +} + # # login_user test # @@ -69,14 +85,6 @@ isa_ok($api, 'WWW::SwaggerClient::UserApi'); my $result = $api->logout_user(); } -# -# get_user_by_name test -# -{ - my $username = undef; # replace NULL with a proper value - my $result = $api->get_user_by_name(username => $username); -} - # # update_user test # @@ -86,13 +94,5 @@ isa_ok($api, 'WWW::SwaggerClient::UserApi'); my $result = $api->update_user(username => $username, body => $body); } -# -# delete_user test -# -{ - my $username = undef; # replace NULL with a proper value - my $result = $api->delete_user(username => $username); -} - 1; diff --git a/samples/client/petstore/perl/test.pl b/samples/client/petstore/perl/test.pl index b12105c9054..626d25357fc 100755 --- a/samples/client/petstore/perl/test.pl +++ b/samples/client/petstore/perl/test.pl @@ -25,6 +25,14 @@ $WWW::SwaggerClient::Configuration::password = 'password'; my $api = WWW::SwaggerClient::PetApi->new(); +# exception handling +#eval { +# print "\nget_pet_by_id:".Dumper $api->get_pet_by_id(pet_id => 9999); +#}; +#if ($@) { +# print "Exception when calling: $@\n"; +#} + my $pet_id = 10008; my $category = WWW::SwaggerClient::Object::Category->new('id' => '2', 'name' => 'perl'); diff --git a/samples/client/petstore/php/SwaggerClient-php/README.md b/samples/client/petstore/php/SwaggerClient-php/README.md index 0566cb0af39..37f92af6e6f 100644 --- a/samples/client/petstore/php/SwaggerClient-php/README.md +++ b/samples/client/petstore/php/SwaggerClient-php/README.md @@ -1,4 +1,12 @@ # SwaggerClient-php +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 + +This PHP package is automatically generated by the [Swagger Codegen](https://github.com/swagger-api/swagger-codegen) project: + +- API version: 1.0.0 +- Package version: 1.0.0 +- Build date: 2016-04-09T18:00:55.578+08:00 +- Build package: class io.swagger.codegen.languages.PhpClientCodegen ## Requirements @@ -7,27 +15,28 @@ PHP 5.4.0 and later ## Installation & Usage ### Composer -You can install the bindings via [Composer](http://getcomposer.org/). Add this to your `composer.json`: +To install the bindings via [Composer](http://getcomposer.org/), add the following to `composer.json`: ``` { "repositories": [ { "type": "git", - "url": "https://github.com/swagger/swagger-client.git" + "url": "https://github.com/YOUR_GIT_USR_ID/YOUR_GIT_REPO_ID.git" } ], "require": { - "swagger/swagger-client": "*@dev" + "YOUR_GIT_USR_ID/YOUR_GIT_REPO_ID": "*@dev" } } ``` -Then install via `composer install` +Then run `composer install` ### Manual Installation -If you do not wish to use Composer, you can download the latest release. Then, to use the bindings, include the `autoload.php` file. +Download the files and include `autoload.php`: + ```php require_once('/path/to/SwaggerClient-php/autoload.php'); ``` @@ -35,11 +44,132 @@ If you do not wish to use Composer, you can download the latest release. Then, t ## Tests To run the unit tests: + ``` composer install ./vendor/bin/phpunit lib/Tests ``` +## Getting Started + +Please follow the [installation procedure](#installation--usage) and then run the following: + +```php +setAccessToken('YOUR_ACCESS_TOKEN'); + +$api_instance = new Swagger\Client\Api\PetApi(); +$body = new \Swagger\Client\Model\Pet(); // \Swagger\Client\Model\Pet | Pet object that needs to be added to the store + +try { + $api_instance->addPet($body); +} catch (Exception $e) { + echo 'Exception when calling PetApi->addPet: ', $e->getMessage(), "\n"; +} + +?> +``` + +## 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 + + +## test_api_key_header + +- **Type**: API key +- **API key parameter name**: test_api_key_header +- **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_client_secret + +- **Type**: API key +- **API key parameter name**: x-test_api_client_secret +- **Location**: HTTP header + +## test_api_client_id + +- **Type**: API key +- **API key parameter name**: x-test_api_client_id +- **Location**: HTTP header + +## test_api_key_query + +- **Type**: API key +- **API key parameter name**: test_api_key_query +- **Location**: URL query string + +## 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 + + ## Author apiteam@swagger.io diff --git a/samples/client/petstore/php/SwaggerClient-php/composer.json b/samples/client/petstore/php/SwaggerClient-php/composer.json index 3b432d83b92..3889aee8a36 100644 --- a/samples/client/petstore/php/SwaggerClient-php/composer.json +++ b/samples/client/petstore/php/SwaggerClient-php/composer.json @@ -1,5 +1,5 @@ { - "name": "swagger/swagger-client", + "name": "YOUR_GIT_USR_ID/YOUR_GIT_REPO_ID", "version": "1.0.0", "description": "", "keywords": [ diff --git a/samples/client/petstore/php/SwaggerClient-php/docs/200Response.md b/samples/client/petstore/php/SwaggerClient-php/docs/200Response.md new file mode 100644 index 00000000000..284a8795c61 --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/docs/200Response.md @@ -0,0 +1,10 @@ +# 200Response + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **int** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/php/SwaggerClient-php/docs/Animal.md b/samples/client/petstore/php/SwaggerClient-php/docs/Animal.md new file mode 100644 index 00000000000..948a992f502 --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/docs/Animal.md @@ -0,0 +1,10 @@ +# Animal + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**class_name** | **string** | | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/php/SwaggerClient-php/docs/Cat.md b/samples/client/petstore/php/SwaggerClient-php/docs/Cat.md new file mode 100644 index 00000000000..8d30565d014 --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/docs/Cat.md @@ -0,0 +1,10 @@ +# Cat + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**declawed** | **bool** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/php/SwaggerClient-php/docs/Category.md b/samples/client/petstore/php/SwaggerClient-php/docs/Category.md new file mode 100644 index 00000000000..80aef312e5e --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/docs/Category.md @@ -0,0 +1,11 @@ +# Category + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **int** | | [optional] +**name** | **string** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/php/SwaggerClient-php/docs/Dog.md b/samples/client/petstore/php/SwaggerClient-php/docs/Dog.md new file mode 100644 index 00000000000..3c04bdf4cf7 --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/docs/Dog.md @@ -0,0 +1,10 @@ +# Dog + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**breed** | **string** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/php/SwaggerClient-php/docs/InlineResponse200.md b/samples/client/petstore/php/SwaggerClient-php/docs/InlineResponse200.md new file mode 100644 index 00000000000..1c0b9237453 --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/docs/InlineResponse200.md @@ -0,0 +1,15 @@ +# InlineResponse200 + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**tags** | [**\Swagger\Client\Model\Tag[]**](Tag.md) | | [optional] +**id** | **int** | | +**category** | **object** | | [optional] +**status** | **string** | pet status in the store | [optional] +**name** | **string** | | [optional] +**photo_urls** | **string[]** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/php/SwaggerClient-php/docs/Model200Response.md b/samples/client/petstore/php/SwaggerClient-php/docs/Model200Response.md new file mode 100644 index 00000000000..e29747a87e7 --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/docs/Model200Response.md @@ -0,0 +1,10 @@ +# Model200Response + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **int** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/php/SwaggerClient-php/docs/ModelReturn.md b/samples/client/petstore/php/SwaggerClient-php/docs/ModelReturn.md new file mode 100644 index 00000000000..9adb62e1e12 --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/docs/ModelReturn.md @@ -0,0 +1,10 @@ +# ModelReturn + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**return** | **int** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/php/SwaggerClient-php/docs/Name.md b/samples/client/petstore/php/SwaggerClient-php/docs/Name.md new file mode 100644 index 00000000000..26473221c32 --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/docs/Name.md @@ -0,0 +1,11 @@ +# Name + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **int** | | [optional] +**snake_case** | **int** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/php/SwaggerClient-php/docs/Order.md b/samples/client/petstore/php/SwaggerClient-php/docs/Order.md new file mode 100644 index 00000000000..8932478b022 --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/docs/Order.md @@ -0,0 +1,15 @@ +# Order + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **int** | | [optional] +**pet_id** | **int** | | [optional] +**quantity** | **int** | | [optional] +**ship_date** | [**\DateTime**](\DateTime.md) | | [optional] +**status** | **string** | Order Status | [optional] +**complete** | **bool** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/php/SwaggerClient-php/docs/Pet.md b/samples/client/petstore/php/SwaggerClient-php/docs/Pet.md new file mode 100644 index 00000000000..4525fe7d776 --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/docs/Pet.md @@ -0,0 +1,15 @@ +# Pet + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **int** | | [optional] +**category** | [**\Swagger\Client\Model\Category**](Category.md) | | [optional] +**name** | **string** | | +**photo_urls** | **string[]** | | +**tags** | [**\Swagger\Client\Model\Tag[]**](Tag.md) | | [optional] +**status** | **string** | pet status in the store | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/php/SwaggerClient-php/docs/PetApi.md b/samples/client/petstore/php/SwaggerClient-php/docs/PetApi.md new file mode 100644 index 00000000000..9164cd27876 --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/docs/PetApi.md @@ -0,0 +1,563 @@ +# Swagger\Client\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 +[**addPetUsingByteArray**](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 +[**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 +[**getPetByIdInObject**](PetApi.md#getPetByIdInObject) | **GET** /pet/{petId}?response=inline_arbitrary_object | Fake endpoint to test inline arbitrary object return by 'Find pet by ID' +[**petPetIdtestingByteArraytrueGet**](PetApi.md#petPetIdtestingByteArraytrueGet) | **GET** /pet/{petId}?testing_byte_array=true | Fake endpoint to test byte array return by '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 +```php +setAccessToken('YOUR_ACCESS_TOKEN'); + +$api_instance = new Swagger\Client\Api\PetApi(); +$body = new \Swagger\Client\Model\Pet(); // \Swagger\Client\Model\Pet | Pet object that needs to be added to the store + +try { + $api_instance->addPet($body); +} catch (Exception $e) { + echo 'Exception when calling PetApi->addPet: ', $e->getMessage(), "\n"; +} +?> +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**\Swagger\Client\Model\Pet**](\Swagger\Client\Model\Pet.md)| Pet object that needs to be added to the store | [optional] + +### Return type + +void (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP reuqest headers + + - **Content-Type**: application/json, application/xml + - **Accept**: application/json, application/xml + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **addPetUsingByteArray** +> addPetUsingByteArray($body) + +Fake endpoint to test byte array in body parameter for adding a new pet to the store + + + +### Example +```php +setAccessToken('YOUR_ACCESS_TOKEN'); + +$api_instance = new Swagger\Client\Api\PetApi(); +$body = "B"; // string | Pet object in the form of byte array + +try { + $api_instance->addPetUsingByteArray($body); +} catch (Exception $e) { + echo 'Exception when calling PetApi->addPetUsingByteArray: ', $e->getMessage(), "\n"; +} +?> +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | **string**| Pet object in the form of byte array | [optional] + +### Return type + +void (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP reuqest headers + + - **Content-Type**: application/json, application/xml + - **Accept**: application/json, application/xml + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **deletePet** +> deletePet($pet_id, $api_key) + +Deletes a pet + + + +### Example +```php +setAccessToken('YOUR_ACCESS_TOKEN'); + +$api_instance = new Swagger\Client\Api\PetApi(); +$pet_id = 789; // int | Pet id to delete +$api_key = "api_key_example"; // string | + +try { + $api_instance->deletePet($pet_id, $api_key); +} catch (Exception $e) { + echo 'Exception when calling PetApi->deletePet: ', $e->getMessage(), "\n"; +} +?> +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **pet_id** | **int**| Pet id to delete | + **api_key** | **string**| | [optional] + +### Return type + +void (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **findPetsByStatus** +> \Swagger\Client\Model\Pet[] findPetsByStatus($status) + +Finds Pets by status + +Multiple status values can be provided with comma separated strings + +### Example +```php +setAccessToken('YOUR_ACCESS_TOKEN'); + +$api_instance = new Swagger\Client\Api\PetApi(); +$status = array("available"); // string[] | Status values that need to be considered for query + +try { + $result = $api_instance->findPetsByStatus($status); + print_r($result); +} catch (Exception $e) { + echo 'Exception when calling PetApi->findPetsByStatus: ', $e->getMessage(), "\n"; +} +?> +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **status** | [**string[]**](string.md)| Status values that need to be considered for query | [optional] [default to available] + +### Return type + +[**\Swagger\Client\Model\Pet[]**](Pet.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **findPetsByTags** +> \Swagger\Client\Model\Pet[] findPetsByTags($tags) + +Finds Pets by tags + +Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + +### Example +```php +setAccessToken('YOUR_ACCESS_TOKEN'); + +$api_instance = new Swagger\Client\Api\PetApi(); +$tags = array("tags_example"); // 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(), "\n"; +} +?> +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **tags** | [**string[]**](string.md)| Tags to filter by | [optional] + +### Return type + +[**\Swagger\Client\Model\Pet[]**](Pet.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **getPetById** +> \Swagger\Client\Model\Pet getPetById($pet_id) + +Find pet by ID + +Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + +### Example +```php +setApiKey('api_key', 'YOUR_API_KEY'); +// Uncomment below to setup prefix (e.g. BEARER) for API key, if needed +// Swagger\Client\Configuration::getDefaultConfiguration()->setApiKeyPrefix('api_key', 'BEARER'); +// Configure OAuth2 access token for authorization: petstore_auth +Swagger\Client\Configuration::getDefaultConfiguration()->setAccessToken('YOUR_ACCESS_TOKEN'); + +$api_instance = new Swagger\Client\Api\PetApi(); +$pet_id = 789; // int | ID of pet that needs to be fetched + +try { + $result = $api_instance->getPetById($pet_id); + print_r($result); +} catch (Exception $e) { + echo 'Exception when calling PetApi->getPetById: ', $e->getMessage(), "\n"; +} +?> +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **pet_id** | **int**| ID of pet that needs to be fetched | + +### Return type + +[**\Swagger\Client\Model\Pet**](Pet.md) + +### Authorization + +[api_key](../README.md#api_key), [petstore_auth](../README.md#petstore_auth) + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **getPetByIdInObject** +> \Swagger\Client\Model\InlineResponse200 getPetByIdInObject($pet_id) + +Fake endpoint to test inline arbitrary object return by 'Find pet by ID' + +Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + +### Example +```php +setApiKey('api_key', 'YOUR_API_KEY'); +// Uncomment below to setup prefix (e.g. BEARER) for API key, if needed +// Swagger\Client\Configuration::getDefaultConfiguration()->setApiKeyPrefix('api_key', 'BEARER'); +// Configure OAuth2 access token for authorization: petstore_auth +Swagger\Client\Configuration::getDefaultConfiguration()->setAccessToken('YOUR_ACCESS_TOKEN'); + +$api_instance = new Swagger\Client\Api\PetApi(); +$pet_id = 789; // int | ID of pet that needs to be fetched + +try { + $result = $api_instance->getPetByIdInObject($pet_id); + print_r($result); +} catch (Exception $e) { + echo 'Exception when calling PetApi->getPetByIdInObject: ', $e->getMessage(), "\n"; +} +?> +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **pet_id** | **int**| ID of pet that needs to be fetched | + +### Return type + +[**\Swagger\Client\Model\InlineResponse200**](InlineResponse200.md) + +### Authorization + +[api_key](../README.md#api_key), [petstore_auth](../README.md#petstore_auth) + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **petPetIdtestingByteArraytrueGet** +> string petPetIdtestingByteArraytrueGet($pet_id) + +Fake endpoint to test byte array return by 'Find pet by ID' + +Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + +### Example +```php +setApiKey('api_key', 'YOUR_API_KEY'); +// Uncomment below to setup prefix (e.g. BEARER) for API key, if needed +// Swagger\Client\Configuration::getDefaultConfiguration()->setApiKeyPrefix('api_key', 'BEARER'); +// Configure OAuth2 access token for authorization: petstore_auth +Swagger\Client\Configuration::getDefaultConfiguration()->setAccessToken('YOUR_ACCESS_TOKEN'); + +$api_instance = new Swagger\Client\Api\PetApi(); +$pet_id = 789; // int | ID of pet that needs to be fetched + +try { + $result = $api_instance->petPetIdtestingByteArraytrueGet($pet_id); + print_r($result); +} catch (Exception $e) { + echo 'Exception when calling PetApi->petPetIdtestingByteArraytrueGet: ', $e->getMessage(), "\n"; +} +?> +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **pet_id** | **int**| ID of pet that needs to be fetched | + +### Return type + +**string** + +### Authorization + +[api_key](../README.md#api_key), [petstore_auth](../README.md#petstore_auth) + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **updatePet** +> updatePet($body) + +Update an existing pet + + + +### Example +```php +setAccessToken('YOUR_ACCESS_TOKEN'); + +$api_instance = new Swagger\Client\Api\PetApi(); +$body = new \Swagger\Client\Model\Pet(); // \Swagger\Client\Model\Pet | Pet object that needs to be added to the store + +try { + $api_instance->updatePet($body); +} catch (Exception $e) { + echo 'Exception when calling PetApi->updatePet: ', $e->getMessage(), "\n"; +} +?> +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**\Swagger\Client\Model\Pet**](\Swagger\Client\Model\Pet.md)| Pet object that needs to be added to the store | [optional] + +### Return type + +void (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP reuqest headers + + - **Content-Type**: application/json, application/xml + - **Accept**: application/json, application/xml + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **updatePetWithForm** +> updatePetWithForm($pet_id, $name, $status) + +Updates a pet in the store with form data + + + +### Example +```php +setAccessToken('YOUR_ACCESS_TOKEN'); + +$api_instance = new Swagger\Client\Api\PetApi(); +$pet_id = "pet_id_example"; // string | ID of pet that needs to be updated +$name = "name_example"; // string | Updated name of the pet +$status = "status_example"; // string | Updated status of the pet + +try { + $api_instance->updatePetWithForm($pet_id, $name, $status); +} catch (Exception $e) { + echo 'Exception when calling PetApi->updatePetWithForm: ', $e->getMessage(), "\n"; +} +?> +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **pet_id** | **string**| 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 reuqest headers + + - **Content-Type**: application/x-www-form-urlencoded + - **Accept**: application/json, application/xml + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **uploadFile** +> uploadFile($pet_id, $additional_metadata, $file) + +uploads an image + + + +### Example +```php +setAccessToken('YOUR_ACCESS_TOKEN'); + +$api_instance = new Swagger\Client\Api\PetApi(); +$pet_id = 789; // int | ID of pet to update +$additional_metadata = "additional_metadata_example"; // string | Additional data to pass to server +$file = "/path/to/file.txt"; // \SplFileObject | file to upload + +try { + $api_instance->uploadFile($pet_id, $additional_metadata, $file); +} catch (Exception $e) { + echo 'Exception when calling PetApi->uploadFile: ', $e->getMessage(), "\n"; +} +?> +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **pet_id** | **int**| ID of pet to update | + **additional_metadata** | **string**| Additional data to pass to server | [optional] + **file** | **\SplFileObject**| file to upload | [optional] + +### Return type + +void (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP reuqest headers + + - **Content-Type**: multipart/form-data + - **Accept**: application/json, application/xml + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/php/SwaggerClient-php/docs/SpecialModelName.md b/samples/client/petstore/php/SwaggerClient-php/docs/SpecialModelName.md new file mode 100644 index 00000000000..022ee19169c --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/docs/SpecialModelName.md @@ -0,0 +1,10 @@ +# SpecialModelName + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**special_property_name** | **int** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/php/SwaggerClient-php/docs/StoreApi.md b/samples/client/petstore/php/SwaggerClient-php/docs/StoreApi.md new file mode 100644 index 00000000000..c60ac603299 --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/docs/StoreApi.md @@ -0,0 +1,312 @@ +# Swagger\Client\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 +[**findOrdersByStatus**](StoreApi.md#findOrdersByStatus) | **GET** /store/findByStatus | Finds orders by status +[**getInventory**](StoreApi.md#getInventory) | **GET** /store/inventory | Returns pet inventories by status +[**getInventoryInObject**](StoreApi.md#getInventoryInObject) | **GET** /store/inventory?response=arbitrary_object | Fake endpoint to test arbitrary object return by 'Get inventory' +[**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($order_id) + +Delete purchase order by ID + +For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + +### Example +```php +deleteOrder($order_id); +} catch (Exception $e) { + echo 'Exception when calling StoreApi->deleteOrder: ', $e->getMessage(), "\n"; +} +?> +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **order_id** | **string**| ID of the order that needs to be deleted | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **findOrdersByStatus** +> \Swagger\Client\Model\Order[] findOrdersByStatus($status) + +Finds orders by status + +A single status value can be provided as a string + +### Example +```php +setApiKey('x-test_api_client_id', 'YOUR_API_KEY'); +// Uncomment below to setup prefix (e.g. BEARER) for API key, if needed +// Swagger\Client\Configuration::getDefaultConfiguration()->setApiKeyPrefix('x-test_api_client_id', 'BEARER'); +// Configure API key authorization: test_api_client_secret +Swagger\Client\Configuration::getDefaultConfiguration()->setApiKey('x-test_api_client_secret', 'YOUR_API_KEY'); +// Uncomment below to setup prefix (e.g. BEARER) for API key, if needed +// Swagger\Client\Configuration::getDefaultConfiguration()->setApiKeyPrefix('x-test_api_client_secret', 'BEARER'); + +$api_instance = new Swagger\Client\Api\StoreApi(); +$status = "placed"; // string | Status value that needs to be considered for query + +try { + $result = $api_instance->findOrdersByStatus($status); + print_r($result); +} catch (Exception $e) { + echo 'Exception when calling StoreApi->findOrdersByStatus: ', $e->getMessage(), "\n"; +} +?> +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **status** | **string**| Status value that needs to be considered for query | [optional] [default to placed] + +### Return type + +[**\Swagger\Client\Model\Order[]**](Order.md) + +### Authorization + +[test_api_client_id](../README.md#test_api_client_id), [test_api_client_secret](../README.md#test_api_client_secret) + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **getInventory** +> map[string,int] getInventory() + +Returns pet inventories by status + +Returns a map of status codes to quantities + +### Example +```php +setApiKey('api_key', 'YOUR_API_KEY'); +// Uncomment below to setup prefix (e.g. BEARER) for API key, if needed +// Swagger\Client\Configuration::getDefaultConfiguration()->setApiKeyPrefix('api_key', 'BEARER'); + +$api_instance = new Swagger\Client\Api\StoreApi(); + +try { + $result = $api_instance->getInventory(); + print_r($result); +} catch (Exception $e) { + echo 'Exception when calling StoreApi->getInventory: ', $e->getMessage(), "\n"; +} +?> +``` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +[**map[string,int]**](map.md) + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **getInventoryInObject** +> object getInventoryInObject() + +Fake endpoint to test arbitrary object return by 'Get inventory' + +Returns an arbitrary object which is actually a map of status codes to quantities + +### Example +```php +setApiKey('api_key', 'YOUR_API_KEY'); +// Uncomment below to setup prefix (e.g. BEARER) for API key, if needed +// Swagger\Client\Configuration::getDefaultConfiguration()->setApiKeyPrefix('api_key', 'BEARER'); + +$api_instance = new Swagger\Client\Api\StoreApi(); + +try { + $result = $api_instance->getInventoryInObject(); + print_r($result); +} catch (Exception $e) { + echo 'Exception when calling StoreApi->getInventoryInObject: ', $e->getMessage(), "\n"; +} +?> +``` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +**object** + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **getOrderById** +> \Swagger\Client\Model\Order getOrderById($order_id) + +Find purchase order by ID + +For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + +### Example +```php +setApiKey('test_api_key_header', 'YOUR_API_KEY'); +// Uncomment below to setup prefix (e.g. BEARER) for API key, if needed +// Swagger\Client\Configuration::getDefaultConfiguration()->setApiKeyPrefix('test_api_key_header', 'BEARER'); +// Configure API key authorization: test_api_key_query +Swagger\Client\Configuration::getDefaultConfiguration()->setApiKey('test_api_key_query', 'YOUR_API_KEY'); +// Uncomment below to setup prefix (e.g. BEARER) for API key, if needed +// Swagger\Client\Configuration::getDefaultConfiguration()->setApiKeyPrefix('test_api_key_query', 'BEARER'); + +$api_instance = new Swagger\Client\Api\StoreApi(); +$order_id = "order_id_example"; // string | ID of pet that needs to be fetched + +try { + $result = $api_instance->getOrderById($order_id); + print_r($result); +} catch (Exception $e) { + echo 'Exception when calling StoreApi->getOrderById: ', $e->getMessage(), "\n"; +} +?> +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **order_id** | **string**| ID of pet that needs to be fetched | + +### Return type + +[**\Swagger\Client\Model\Order**](Order.md) + +### Authorization + +[test_api_key_header](../README.md#test_api_key_header), [test_api_key_query](../README.md#test_api_key_query) + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **placeOrder** +> \Swagger\Client\Model\Order placeOrder($body) + +Place an order for a pet + + + +### Example +```php +setApiKey('x-test_api_client_id', 'YOUR_API_KEY'); +// Uncomment below to setup prefix (e.g. BEARER) for API key, if needed +// Swagger\Client\Configuration::getDefaultConfiguration()->setApiKeyPrefix('x-test_api_client_id', 'BEARER'); +// Configure API key authorization: test_api_client_secret +Swagger\Client\Configuration::getDefaultConfiguration()->setApiKey('x-test_api_client_secret', 'YOUR_API_KEY'); +// Uncomment below to setup prefix (e.g. BEARER) for API key, if needed +// Swagger\Client\Configuration::getDefaultConfiguration()->setApiKeyPrefix('x-test_api_client_secret', 'BEARER'); + +$api_instance = new Swagger\Client\Api\StoreApi(); +$body = new \Swagger\Client\Model\Order(); // \Swagger\Client\Model\Order | order placed for purchasing the pet + +try { + $result = $api_instance->placeOrder($body); + print_r($result); +} catch (Exception $e) { + echo 'Exception when calling StoreApi->placeOrder: ', $e->getMessage(), "\n"; +} +?> +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**\Swagger\Client\Model\Order**](\Swagger\Client\Model\Order.md)| order placed for purchasing the pet | [optional] + +### Return type + +[**\Swagger\Client\Model\Order**](Order.md) + +### Authorization + +[test_api_client_id](../README.md#test_api_client_id), [test_api_client_secret](../README.md#test_api_client_secret) + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/php/SwaggerClient-php/docs/Tag.md b/samples/client/petstore/php/SwaggerClient-php/docs/Tag.md new file mode 100644 index 00000000000..15ec3e0a91d --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/docs/Tag.md @@ -0,0 +1,11 @@ +# Tag + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **int** | | [optional] +**name** | **string** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/php/SwaggerClient-php/docs/User.md b/samples/client/petstore/php/SwaggerClient-php/docs/User.md new file mode 100644 index 00000000000..ff278fd4889 --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/docs/User.md @@ -0,0 +1,17 @@ +# User + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **int** | | [optional] +**username** | **string** | | [optional] +**first_name** | **string** | | [optional] +**last_name** | **string** | | [optional] +**email** | **string** | | [optional] +**password** | **string** | | [optional] +**phone** | **string** | | [optional] +**user_status** | **int** | User Status | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/php/SwaggerClient-php/docs/UserApi.md b/samples/client/petstore/php/SwaggerClient-php/docs/UserApi.md new file mode 100644 index 00000000000..e6a19891ba5 --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/docs/UserApi.md @@ -0,0 +1,374 @@ +# Swagger\Client\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 +```php +createUser($body); +} catch (Exception $e) { + echo 'Exception when calling UserApi->createUser: ', $e->getMessage(), "\n"; +} +?> +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**\Swagger\Client\Model\User**](\Swagger\Client\Model\User.md)| Created user object | [optional] + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **createUsersWithArrayInput** +> createUsersWithArrayInput($body) + +Creates list of users with given input array + + + +### Example +```php +createUsersWithArrayInput($body); +} catch (Exception $e) { + echo 'Exception when calling UserApi->createUsersWithArrayInput: ', $e->getMessage(), "\n"; +} +?> +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**\Swagger\Client\Model\User[]**](User.md)| List of user object | [optional] + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **createUsersWithListInput** +> createUsersWithListInput($body) + +Creates list of users with given input array + + + +### Example +```php +createUsersWithListInput($body); +} catch (Exception $e) { + echo 'Exception when calling UserApi->createUsersWithListInput: ', $e->getMessage(), "\n"; +} +?> +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**\Swagger\Client\Model\User[]**](User.md)| List of user object | [optional] + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **deleteUser** +> deleteUser($username) + +Delete user + +This can only be done by the logged in user. + +### Example +```php +setUsername('YOUR_USERNAME'); +Swagger\Client\Configuration::getDefaultConfiguration()->setPassword('YOUR_PASSWORD'); + +$api_instance = new Swagger\Client\Api\UserApi(); +$username = "username_example"; // string | The name that needs to be deleted + +try { + $api_instance->deleteUser($username); +} catch (Exception $e) { + echo 'Exception when calling UserApi->deleteUser: ', $e->getMessage(), "\n"; +} +?> +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **string**| The name that needs to be deleted | + +### Return type + +void (empty response body) + +### Authorization + +[test_http_basic](../README.md#test_http_basic) + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **getUserByName** +> \Swagger\Client\Model\User getUserByName($username) + +Get user by user name + + + +### Example +```php +getUserByName($username); + print_r($result); +} catch (Exception $e) { + echo 'Exception when calling UserApi->getUserByName: ', $e->getMessage(), "\n"; +} +?> +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **string**| The name that needs to be fetched. Use user1 for testing. | + +### Return type + +[**\Swagger\Client\Model\User**](User.md) + +### Authorization + +No authorization required + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **loginUser** +> string loginUser($username, $password) + +Logs user into the system + + + +### Example +```php +loginUser($username, $password); + print_r($result); +} catch (Exception $e) { + echo 'Exception when calling UserApi->loginUser: ', $e->getMessage(), "\n"; +} +?> +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **string**| The user name for login | [optional] + **password** | **string**| The password for login in clear text | [optional] + +### Return type + +**string** + +### Authorization + +No authorization required + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **logoutUser** +> logoutUser() + +Logs out current logged in user session + + + +### Example +```php +logoutUser(); +} catch (Exception $e) { + echo 'Exception when calling UserApi->logoutUser: ', $e->getMessage(), "\n"; +} +?> +``` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **updateUser** +> updateUser($username, $body) + +Updated user + +This can only be done by the logged in user. + +### Example +```php +updateUser($username, $body); +} catch (Exception $e) { + echo 'Exception when calling UserApi->updateUser: ', $e->getMessage(), "\n"; +} +?> +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **string**| name that need to be deleted | + **body** | [**\Swagger\Client\Model\User**](\Swagger\Client\Model\User.md)| Updated user object | [optional] + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/php/SwaggerClient-php/git_push.sh b/samples/client/petstore/php/SwaggerClient-php/git_push.sh new file mode 100644 index 00000000000..1a36388db02 --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/git_push.sh @@ -0,0 +1,52 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 swagger-petstore-perl "minor update" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 + +if [ "$git_user_id" = "" ]; then + git_user_id="YOUR_GIT_USR_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="YOUR_GIT_REPO_ID" + 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/php/SwaggerClient-php/lib/Api/PetApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php index f17476385cb..4661a5b3bd8 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php @@ -90,91 +90,6 @@ class PetApi return $this; } - - /** - * updatePet - * - * Update an existing pet - * - * @param \Swagger\Client\Model\Pet $body Pet object that needs to be added to the store (optional) - * @return void - * @throws \Swagger\Client\ApiException on non-2xx response - */ - public function updatePet($body = null) - { - list($response, $statusCode, $httpHeader) = $this->updatePetWithHttpInfo ($body); - return $response; - } - - - /** - * updatePetWithHttpInfo - * - * Update an existing pet - * - * @param \Swagger\Client\Model\Pet $body Pet object that needs to be added to the store (optional) - * @return Array of null, HTTP status code, HTTP response headers (array of strings) - * @throws \Swagger\Client\ApiException on non-2xx response - */ - public function updatePetWithHttpInfo($body = null) - { - - - // parse inputs - $resourcePath = "/pet"; - $httpBody = ''; - $queryParams = array(); - $headerParams = array(); - $formParams = array(); - $_header_accept = ApiClient::selectHeaderAccept(array('application/json', 'application/xml')); - if (!is_null($_header_accept)) { - $headerParams['Accept'] = $_header_accept; - } - $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array('application/json','application/xml')); - - - - - // default format to json - $resourcePath = str_replace("{format}", "json", $resourcePath); - - - // 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 - } elseif (count($formParams) > 0) { - $httpBody = $formParams; // for HTTP post (form) - } - - // this endpoint requires OAuth (access token) - if (strlen($this->apiClient->getConfig()->getAccessToken()) !== 0) { - $headerParams['Authorization'] = 'Bearer ' . $this->apiClient->getConfig()->getAccessToken(); - } - - // make the API Call - try { - list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, 'PUT', - $queryParams, $httpBody, - $headerParams - ); - - return array(null, $statusCode, $httpHeader); - - } catch (ApiException $e) { - switch ($e->getCode()) { - } - - throw $e; - } - } - /** * addPet * @@ -186,7 +101,7 @@ class PetApi */ public function addPet($body = null) { - list($response, $statusCode, $httpHeader) = $this->addPetWithHttpInfo ($body); + list($response) = $this->addPetWithHttpInfo ($body); return $response; } @@ -210,11 +125,11 @@ class PetApi $queryParams = array(); $headerParams = array(); $formParams = array(); - $_header_accept = ApiClient::selectHeaderAccept(array('application/json', 'application/xml')); + $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array('application/json','application/xml')); + $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array('application/json','application/xml')); @@ -240,7 +155,6 @@ class PetApi if (strlen($this->apiClient->getConfig()->getAccessToken()) !== 0) { $headerParams['Authorization'] = 'Bearer ' . $this->apiClient->getConfig()->getAccessToken(); } - // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( @@ -248,9 +162,182 @@ class PetApi $queryParams, $httpBody, $headerParams ); - + + return array(null, $statusCode, $httpHeader); + } catch (ApiException $e) { + switch ($e->getCode()) { + } + + throw $e; + } + } + /** + * addPetUsingByteArray + * + * Fake endpoint to test byte array in body parameter for adding a new pet to the store + * + * @param string $body Pet object in the form of byte array (optional) + * @return void + * @throws \Swagger\Client\ApiException on non-2xx response + */ + public function addPetUsingByteArray($body = null) + { + list($response) = $this->addPetUsingByteArrayWithHttpInfo ($body); + return $response; + } + + + /** + * addPetUsingByteArrayWithHttpInfo + * + * Fake endpoint to test byte array in body parameter for adding a new pet to the store + * + * @param string $body Pet object in the form of byte array (optional) + * @return Array of null, HTTP status code, HTTP response headers (array of strings) + * @throws \Swagger\Client\ApiException on non-2xx response + */ + public function addPetUsingByteArrayWithHttpInfo($body = null) + { + + + // parse inputs + $resourcePath = "/pet?testing_byte_array=true"; + $httpBody = ''; + $queryParams = array(); + $headerParams = array(); + $formParams = array(); + $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); + if (!is_null($_header_accept)) { + $headerParams['Accept'] = $_header_accept; + } + $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array('application/json','application/xml')); + + + + + // default format to json + $resourcePath = str_replace("{format}", "json", $resourcePath); + + + // 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 + } elseif (count($formParams) > 0) { + $httpBody = $formParams; // for HTTP post (form) + } + + // this endpoint requires OAuth (access token) + if (strlen($this->apiClient->getConfig()->getAccessToken()) !== 0) { + $headerParams['Authorization'] = 'Bearer ' . $this->apiClient->getConfig()->getAccessToken(); + } + // make the API Call + try { + list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( + $resourcePath, 'POST', + $queryParams, $httpBody, + $headerParams + ); + + return array(null, $statusCode, $httpHeader); + } catch (ApiException $e) { + switch ($e->getCode()) { + } + + throw $e; + } + } + /** + * deletePet + * + * Deletes a pet + * + * @param int $pet_id Pet id to delete (required) + * @param string $api_key (optional) + * @return void + * @throws \Swagger\Client\ApiException on non-2xx response + */ + public function deletePet($pet_id, $api_key = null) + { + list($response) = $this->deletePetWithHttpInfo ($pet_id, $api_key); + return $response; + } + + + /** + * deletePetWithHttpInfo + * + * Deletes a pet + * + * @param int $pet_id Pet id to delete (required) + * @param string $api_key (optional) + * @return Array of null, HTTP status code, HTTP response headers (array of strings) + * @throws \Swagger\Client\ApiException on non-2xx response + */ + public function deletePetWithHttpInfo($pet_id, $api_key = null) + { + + // verify the required parameter 'pet_id' is set + if ($pet_id === null) { + throw new \InvalidArgumentException('Missing the required parameter $pet_id when calling deletePet'); + } + + // parse inputs + $resourcePath = "/pet/{petId}"; + $httpBody = ''; + $queryParams = array(); + $headerParams = array(); + $formParams = array(); + $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); + if (!is_null($_header_accept)) { + $headerParams['Accept'] = $_header_accept; + } + $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); + + + // header params + if ($api_key !== null) { + $headerParams['api_key'] = $this->apiClient->getSerializer()->toHeaderValue($api_key); + } + // path params + if ($pet_id !== null) { + $resourcePath = str_replace( + "{" . "petId" . "}", + $this->apiClient->getSerializer()->toPathValue($pet_id), + $resourcePath + ); + } + // default format to json + $resourcePath = str_replace("{format}", "json", $resourcePath); + + + + + // for model (json/xml) + if (isset($_tempBody)) { + $httpBody = $_tempBody; // $_tempBody is the method argument, if present + } elseif (count($formParams) > 0) { + $httpBody = $formParams; // for HTTP post (form) + } + + // this endpoint requires OAuth (access token) + if (strlen($this->apiClient->getConfig()->getAccessToken()) !== 0) { + $headerParams['Authorization'] = 'Bearer ' . $this->apiClient->getConfig()->getAccessToken(); + } + // make the API Call + try { + list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( + $resourcePath, 'DELETE', + $queryParams, $httpBody, + $headerParams + ); + return array(null, $statusCode, $httpHeader); - } catch (ApiException $e) { switch ($e->getCode()) { } @@ -258,19 +345,18 @@ class PetApi throw $e; } } - /** * findPetsByStatus * * Finds Pets by status * - * @param string[] $status Status values that need to be considered for query (optional) + * @param string[] $status Status values that need to be considered for query (optional, default to available) * @return \Swagger\Client\Model\Pet[] * @throws \Swagger\Client\ApiException on non-2xx response */ public function findPetsByStatus($status = null) { - list($response, $statusCode, $httpHeader) = $this->findPetsByStatusWithHttpInfo ($status); + list($response) = $this->findPetsByStatusWithHttpInfo ($status); return $response; } @@ -280,7 +366,7 @@ class PetApi * * Finds Pets by status * - * @param string[] $status Status values that need to be considered for query (optional) + * @param string[] $status Status values that need to be considered for query (optional, default to available) * @return Array of \Swagger\Client\Model\Pet[], HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response */ @@ -294,18 +380,16 @@ class PetApi $queryParams = array(); $headerParams = array(); $formParams = array(); - $_header_accept = ApiClient::selectHeaderAccept(array('application/json', 'application/xml')); + $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array()); + $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); // query params - if (is_array($status)) { $status = $this->apiClient->getSerializer()->serializeCollection($status, 'multi', true); } - if ($status !== null) { $queryParams['status'] = $this->apiClient->getSerializer()->toQueryValue($status); } @@ -328,7 +412,6 @@ class PetApi if (strlen($this->apiClient->getConfig()->getAccessToken()) !== 0) { $headerParams['Authorization'] = 'Bearer ' . $this->apiClient->getConfig()->getAccessToken(); } - // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( @@ -336,17 +419,15 @@ class PetApi $queryParams, $httpBody, $headerParams, '\Swagger\Client\Model\Pet[]' ); - if (!$response) { return array(null, $statusCode, $httpHeader); } - return array(\Swagger\Client\ObjectSerializer::deserialize($response, '\Swagger\Client\Model\Pet[]', $httpHeader), $statusCode, $httpHeader); - - } catch (ApiException $e) { + return array($this->apiClient->getSerializer()->deserialize($response, '\Swagger\Client\Model\Pet[]', $httpHeader), $statusCode, $httpHeader); + } catch (ApiException $e) { switch ($e->getCode()) { case 200: - $data = \Swagger\Client\ObjectSerializer::deserialize($e->getResponseBody(), '\Swagger\Client\Model\Pet[]', $e->getResponseHeaders()); + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\Pet[]', $e->getResponseHeaders()); $e->setResponseObject($data); break; } @@ -354,7 +435,6 @@ class PetApi throw $e; } } - /** * findPetsByTags * @@ -366,7 +446,7 @@ class PetApi */ public function findPetsByTags($tags = null) { - list($response, $statusCode, $httpHeader) = $this->findPetsByTagsWithHttpInfo ($tags); + list($response) = $this->findPetsByTagsWithHttpInfo ($tags); return $response; } @@ -390,18 +470,16 @@ class PetApi $queryParams = array(); $headerParams = array(); $formParams = array(); - $_header_accept = ApiClient::selectHeaderAccept(array('application/json', 'application/xml')); + $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array()); + $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); // query params - if (is_array($tags)) { $tags = $this->apiClient->getSerializer()->serializeCollection($tags, 'multi', true); } - if ($tags !== null) { $queryParams['tags'] = $this->apiClient->getSerializer()->toQueryValue($tags); } @@ -424,7 +502,6 @@ class PetApi if (strlen($this->apiClient->getConfig()->getAccessToken()) !== 0) { $headerParams['Authorization'] = 'Bearer ' . $this->apiClient->getConfig()->getAccessToken(); } - // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( @@ -432,17 +509,15 @@ class PetApi $queryParams, $httpBody, $headerParams, '\Swagger\Client\Model\Pet[]' ); - if (!$response) { return array(null, $statusCode, $httpHeader); } - return array(\Swagger\Client\ObjectSerializer::deserialize($response, '\Swagger\Client\Model\Pet[]', $httpHeader), $statusCode, $httpHeader); - - } catch (ApiException $e) { + return array($this->apiClient->getSerializer()->deserialize($response, '\Swagger\Client\Model\Pet[]', $httpHeader), $statusCode, $httpHeader); + } catch (ApiException $e) { switch ($e->getCode()) { case 200: - $data = \Swagger\Client\ObjectSerializer::deserialize($e->getResponseBody(), '\Swagger\Client\Model\Pet[]', $e->getResponseHeaders()); + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\Pet[]', $e->getResponseHeaders()); $e->setResponseObject($data); break; } @@ -450,7 +525,6 @@ class PetApi throw $e; } } - /** * getPetById * @@ -462,7 +536,7 @@ class PetApi */ public function getPetById($pet_id) { - list($response, $statusCode, $httpHeader) = $this->getPetByIdWithHttpInfo ($pet_id); + list($response) = $this->getPetByIdWithHttpInfo ($pet_id); return $response; } @@ -490,16 +564,15 @@ class PetApi $queryParams = array(); $headerParams = array(); $formParams = array(); - $_header_accept = ApiClient::selectHeaderAccept(array('application/json', 'application/xml')); + $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array()); + $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); // path params - if ($pet_id !== null) { $resourcePath = str_replace( "{" . "petId" . "}", @@ -526,12 +599,11 @@ class PetApi $headerParams['api_key'] = $apiKey; } - + // this endpoint requires OAuth (access token) if (strlen($this->apiClient->getConfig()->getAccessToken()) !== 0) { $headerParams['Authorization'] = 'Bearer ' . $this->apiClient->getConfig()->getAccessToken(); } - // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( @@ -539,17 +611,15 @@ class PetApi $queryParams, $httpBody, $headerParams, '\Swagger\Client\Model\Pet' ); - if (!$response) { return array(null, $statusCode, $httpHeader); } - return array(\Swagger\Client\ObjectSerializer::deserialize($response, '\Swagger\Client\Model\Pet', $httpHeader), $statusCode, $httpHeader); - - } catch (ApiException $e) { + return array($this->apiClient->getSerializer()->deserialize($response, '\Swagger\Client\Model\Pet', $httpHeader), $statusCode, $httpHeader); + } catch (ApiException $e) { switch ($e->getCode()) { case 200: - $data = \Swagger\Client\ObjectSerializer::deserialize($e->getResponseBody(), '\Swagger\Client\Model\Pet', $e->getResponseHeaders()); + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\Pet', $e->getResponseHeaders()); $e->setResponseObject($data); break; } @@ -557,7 +627,291 @@ class PetApi throw $e; } } - + /** + * getPetByIdInObject + * + * Fake endpoint to test inline arbitrary object return by 'Find pet by ID' + * + * @param int $pet_id ID of pet that needs to be fetched (required) + * @return \Swagger\Client\Model\InlineResponse200 + * @throws \Swagger\Client\ApiException on non-2xx response + */ + public function getPetByIdInObject($pet_id) + { + list($response) = $this->getPetByIdInObjectWithHttpInfo ($pet_id); + return $response; + } + + + /** + * getPetByIdInObjectWithHttpInfo + * + * Fake endpoint to test inline arbitrary object return by 'Find pet by ID' + * + * @param int $pet_id ID of pet that needs to be fetched (required) + * @return Array of \Swagger\Client\Model\InlineResponse200, HTTP status code, HTTP response headers (array of strings) + * @throws \Swagger\Client\ApiException on non-2xx response + */ + public function getPetByIdInObjectWithHttpInfo($pet_id) + { + + // verify the required parameter 'pet_id' is set + if ($pet_id === null) { + throw new \InvalidArgumentException('Missing the required parameter $pet_id when calling getPetByIdInObject'); + } + + // parse inputs + $resourcePath = "/pet/{petId}?response=inline_arbitrary_object"; + $httpBody = ''; + $queryParams = array(); + $headerParams = array(); + $formParams = array(); + $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); + if (!is_null($_header_accept)) { + $headerParams['Accept'] = $_header_accept; + } + $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); + + + + // path params + if ($pet_id !== null) { + $resourcePath = str_replace( + "{" . "petId" . "}", + $this->apiClient->getSerializer()->toPathValue($pet_id), + $resourcePath + ); + } + // default format to json + $resourcePath = str_replace("{format}", "json", $resourcePath); + + + + + // for model (json/xml) + if (isset($_tempBody)) { + $httpBody = $_tempBody; // $_tempBody is the method argument, if present + } elseif (count($formParams) > 0) { + $httpBody = $formParams; // for HTTP post (form) + } + + // this endpoint requires API key authentication + $apiKey = $this->apiClient->getApiKeyWithPrefix('api_key'); + if (strlen($apiKey) !== 0) { + $headerParams['api_key'] = $apiKey; + } + + + // this endpoint requires OAuth (access token) + if (strlen($this->apiClient->getConfig()->getAccessToken()) !== 0) { + $headerParams['Authorization'] = 'Bearer ' . $this->apiClient->getConfig()->getAccessToken(); + } + // make the API Call + try { + list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( + $resourcePath, 'GET', + $queryParams, $httpBody, + $headerParams, '\Swagger\Client\Model\InlineResponse200' + ); + if (!$response) { + return array(null, $statusCode, $httpHeader); + } + + return array($this->apiClient->getSerializer()->deserialize($response, '\Swagger\Client\Model\InlineResponse200', $httpHeader), $statusCode, $httpHeader); + } catch (ApiException $e) { + switch ($e->getCode()) { + case 200: + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\InlineResponse200', $e->getResponseHeaders()); + $e->setResponseObject($data); + break; + } + + throw $e; + } + } + /** + * petPetIdtestingByteArraytrueGet + * + * Fake endpoint to test byte array return by 'Find pet by ID' + * + * @param int $pet_id ID of pet that needs to be fetched (required) + * @return string + * @throws \Swagger\Client\ApiException on non-2xx response + */ + public function petPetIdtestingByteArraytrueGet($pet_id) + { + list($response) = $this->petPetIdtestingByteArraytrueGetWithHttpInfo ($pet_id); + return $response; + } + + + /** + * petPetIdtestingByteArraytrueGetWithHttpInfo + * + * Fake endpoint to test byte array return by 'Find pet by ID' + * + * @param int $pet_id ID of pet that needs to be fetched (required) + * @return Array of string, HTTP status code, HTTP response headers (array of strings) + * @throws \Swagger\Client\ApiException on non-2xx response + */ + public function petPetIdtestingByteArraytrueGetWithHttpInfo($pet_id) + { + + // verify the required parameter 'pet_id' is set + if ($pet_id === null) { + throw new \InvalidArgumentException('Missing the required parameter $pet_id when calling petPetIdtestingByteArraytrueGet'); + } + + // parse inputs + $resourcePath = "/pet/{petId}?testing_byte_array=true"; + $httpBody = ''; + $queryParams = array(); + $headerParams = array(); + $formParams = array(); + $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); + if (!is_null($_header_accept)) { + $headerParams['Accept'] = $_header_accept; + } + $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); + + + + // path params + if ($pet_id !== null) { + $resourcePath = str_replace( + "{" . "petId" . "}", + $this->apiClient->getSerializer()->toPathValue($pet_id), + $resourcePath + ); + } + // default format to json + $resourcePath = str_replace("{format}", "json", $resourcePath); + + + + + // for model (json/xml) + if (isset($_tempBody)) { + $httpBody = $_tempBody; // $_tempBody is the method argument, if present + } elseif (count($formParams) > 0) { + $httpBody = $formParams; // for HTTP post (form) + } + + // this endpoint requires API key authentication + $apiKey = $this->apiClient->getApiKeyWithPrefix('api_key'); + if (strlen($apiKey) !== 0) { + $headerParams['api_key'] = $apiKey; + } + + + // this endpoint requires OAuth (access token) + if (strlen($this->apiClient->getConfig()->getAccessToken()) !== 0) { + $headerParams['Authorization'] = 'Bearer ' . $this->apiClient->getConfig()->getAccessToken(); + } + // make the API Call + try { + list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( + $resourcePath, 'GET', + $queryParams, $httpBody, + $headerParams, 'string' + ); + if (!$response) { + return array(null, $statusCode, $httpHeader); + } + + return array($this->apiClient->getSerializer()->deserialize($response, 'string', $httpHeader), $statusCode, $httpHeader); + } catch (ApiException $e) { + switch ($e->getCode()) { + case 200: + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), 'string', $e->getResponseHeaders()); + $e->setResponseObject($data); + break; + } + + throw $e; + } + } + /** + * updatePet + * + * Update an existing pet + * + * @param \Swagger\Client\Model\Pet $body Pet object that needs to be added to the store (optional) + * @return void + * @throws \Swagger\Client\ApiException on non-2xx response + */ + public function updatePet($body = null) + { + list($response) = $this->updatePetWithHttpInfo ($body); + return $response; + } + + + /** + * updatePetWithHttpInfo + * + * Update an existing pet + * + * @param \Swagger\Client\Model\Pet $body Pet object that needs to be added to the store (optional) + * @return Array of null, HTTP status code, HTTP response headers (array of strings) + * @throws \Swagger\Client\ApiException on non-2xx response + */ + public function updatePetWithHttpInfo($body = null) + { + + + // parse inputs + $resourcePath = "/pet"; + $httpBody = ''; + $queryParams = array(); + $headerParams = array(); + $formParams = array(); + $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); + if (!is_null($_header_accept)) { + $headerParams['Accept'] = $_header_accept; + } + $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array('application/json','application/xml')); + + + + + // default format to json + $resourcePath = str_replace("{format}", "json", $resourcePath); + + + // 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 + } elseif (count($formParams) > 0) { + $httpBody = $formParams; // for HTTP post (form) + } + + // this endpoint requires OAuth (access token) + if (strlen($this->apiClient->getConfig()->getAccessToken()) !== 0) { + $headerParams['Authorization'] = 'Bearer ' . $this->apiClient->getConfig()->getAccessToken(); + } + // make the API Call + try { + list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( + $resourcePath, 'PUT', + $queryParams, $httpBody, + $headerParams + ); + + return array(null, $statusCode, $httpHeader); + } catch (ApiException $e) { + switch ($e->getCode()) { + } + + throw $e; + } + } /** * updatePetWithForm * @@ -571,7 +925,7 @@ class PetApi */ public function updatePetWithForm($pet_id, $name = null, $status = null) { - list($response, $statusCode, $httpHeader) = $this->updatePetWithFormWithHttpInfo ($pet_id, $name, $status); + list($response) = $this->updatePetWithFormWithHttpInfo ($pet_id, $name, $status); return $response; } @@ -601,16 +955,15 @@ class PetApi $queryParams = array(); $headerParams = array(); $formParams = array(); - $_header_accept = ApiClient::selectHeaderAccept(array('application/json', 'application/xml')); + $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array('application/x-www-form-urlencoded')); + $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array('application/x-www-form-urlencoded')); // path params - if ($pet_id !== null) { $resourcePath = str_replace( "{" . "petId" . "}", @@ -623,16 +976,10 @@ class PetApi // form params if ($name !== null) { - - $formParams['name'] = $this->apiClient->getSerializer()->toFormValue($name); - }// form params if ($status !== null) { - - $formParams['status'] = $this->apiClient->getSerializer()->toFormValue($status); - } @@ -647,7 +994,6 @@ class PetApi if (strlen($this->apiClient->getConfig()->getAccessToken()) !== 0) { $headerParams['Authorization'] = 'Bearer ' . $this->apiClient->getConfig()->getAccessToken(); } - // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( @@ -655,9 +1001,8 @@ class PetApi $queryParams, $httpBody, $headerParams ); - + return array(null, $statusCode, $httpHeader); - } catch (ApiException $e) { switch ($e->getCode()) { } @@ -665,105 +1010,6 @@ class PetApi throw $e; } } - - /** - * deletePet - * - * Deletes a pet - * - * @param int $pet_id Pet id to delete (required) - * @param string $api_key (optional) - * @return void - * @throws \Swagger\Client\ApiException on non-2xx response - */ - public function deletePet($pet_id, $api_key = null) - { - list($response, $statusCode, $httpHeader) = $this->deletePetWithHttpInfo ($pet_id, $api_key); - return $response; - } - - - /** - * deletePetWithHttpInfo - * - * Deletes a pet - * - * @param int $pet_id Pet id to delete (required) - * @param string $api_key (optional) - * @return Array of null, HTTP status code, HTTP response headers (array of strings) - * @throws \Swagger\Client\ApiException on non-2xx response - */ - public function deletePetWithHttpInfo($pet_id, $api_key = null) - { - - // verify the required parameter 'pet_id' is set - if ($pet_id === null) { - throw new \InvalidArgumentException('Missing the required parameter $pet_id when calling deletePet'); - } - - // parse inputs - $resourcePath = "/pet/{petId}"; - $httpBody = ''; - $queryParams = array(); - $headerParams = array(); - $formParams = array(); - $_header_accept = ApiClient::selectHeaderAccept(array('application/json', 'application/xml')); - if (!is_null($_header_accept)) { - $headerParams['Accept'] = $_header_accept; - } - $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array()); - - - // header params - - if ($api_key !== null) { - $headerParams['api_key'] = $this->apiClient->getSerializer()->toHeaderValue($api_key); - } - // path params - - if ($pet_id !== null) { - $resourcePath = str_replace( - "{" . "petId" . "}", - $this->apiClient->getSerializer()->toPathValue($pet_id), - $resourcePath - ); - } - // default format to json - $resourcePath = str_replace("{format}", "json", $resourcePath); - - - - - // for model (json/xml) - if (isset($_tempBody)) { - $httpBody = $_tempBody; // $_tempBody is the method argument, if present - } elseif (count($formParams) > 0) { - $httpBody = $formParams; // for HTTP post (form) - } - - // this endpoint requires OAuth (access token) - if (strlen($this->apiClient->getConfig()->getAccessToken()) !== 0) { - $headerParams['Authorization'] = 'Bearer ' . $this->apiClient->getConfig()->getAccessToken(); - } - - // make the API Call - try { - list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, 'DELETE', - $queryParams, $httpBody, - $headerParams - ); - - return array(null, $statusCode, $httpHeader); - - } catch (ApiException $e) { - switch ($e->getCode()) { - } - - throw $e; - } - } - /** * uploadFile * @@ -777,7 +1023,7 @@ class PetApi */ public function uploadFile($pet_id, $additional_metadata = null, $file = null) { - list($response, $statusCode, $httpHeader) = $this->uploadFileWithHttpInfo ($pet_id, $additional_metadata, $file); + list($response) = $this->uploadFileWithHttpInfo ($pet_id, $additional_metadata, $file); return $response; } @@ -807,16 +1053,15 @@ class PetApi $queryParams = array(); $headerParams = array(); $formParams = array(); - $_header_accept = ApiClient::selectHeaderAccept(array('application/json', 'application/xml')); + $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array('multipart/form-data')); + $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array('multipart/form-data')); // path params - if ($pet_id !== null) { $resourcePath = str_replace( "{" . "petId" . "}", @@ -829,13 +1074,9 @@ class PetApi // form params if ($additional_metadata !== null) { - - $formParams['additionalMetadata'] = $this->apiClient->getSerializer()->toFormValue($additional_metadata); - }// form params if ($file !== null) { - // PHP 5.5 introduced a CurlFile object that deprecates the old @filename syntax // See: https://wiki.php.net/rfc/curl-file-upload if (function_exists('curl_file_create')) { @@ -843,8 +1084,6 @@ class PetApi } else { $formParams['file'] = '@' . $this->apiClient->getSerializer()->toFormValue($file); } - - } @@ -859,7 +1098,6 @@ class PetApi if (strlen($this->apiClient->getConfig()->getAccessToken()) !== 0) { $headerParams['Authorization'] = 'Bearer ' . $this->apiClient->getConfig()->getAccessToken(); } - // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( @@ -867,9 +1105,8 @@ class PetApi $queryParams, $httpBody, $headerParams ); - + return array(null, $statusCode, $httpHeader); - } catch (ApiException $e) { switch ($e->getCode()) { } @@ -877,303 +1114,4 @@ class PetApi throw $e; } } - - /** - * getPetByIdInObject - * - * Fake endpoint to test inline arbitrary object return by 'Find pet by ID' - * - * @param int $pet_id ID of pet that needs to be fetched (required) - * @return \Swagger\Client\Model\InlineResponse200 - * @throws \Swagger\Client\ApiException on non-2xx response - */ - public function getPetByIdInObject($pet_id) - { - list($response, $statusCode, $httpHeader) = $this->getPetByIdInObjectWithHttpInfo ($pet_id); - return $response; - } - - - /** - * getPetByIdInObjectWithHttpInfo - * - * Fake endpoint to test inline arbitrary object return by 'Find pet by ID' - * - * @param int $pet_id ID of pet that needs to be fetched (required) - * @return Array of \Swagger\Client\Model\InlineResponse200, HTTP status code, HTTP response headers (array of strings) - * @throws \Swagger\Client\ApiException on non-2xx response - */ - public function getPetByIdInObjectWithHttpInfo($pet_id) - { - - // verify the required parameter 'pet_id' is set - if ($pet_id === null) { - throw new \InvalidArgumentException('Missing the required parameter $pet_id when calling getPetByIdInObject'); - } - - // parse inputs - $resourcePath = "/pet/{petId}?response=inline_arbitrary_object"; - $httpBody = ''; - $queryParams = array(); - $headerParams = array(); - $formParams = array(); - $_header_accept = ApiClient::selectHeaderAccept(array('application/json', 'application/xml')); - if (!is_null($_header_accept)) { - $headerParams['Accept'] = $_header_accept; - } - $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array()); - - - - // path params - - if ($pet_id !== null) { - $resourcePath = str_replace( - "{" . "petId" . "}", - $this->apiClient->getSerializer()->toPathValue($pet_id), - $resourcePath - ); - } - // default format to json - $resourcePath = str_replace("{format}", "json", $resourcePath); - - - - - // for model (json/xml) - if (isset($_tempBody)) { - $httpBody = $_tempBody; // $_tempBody is the method argument, if present - } elseif (count($formParams) > 0) { - $httpBody = $formParams; // for HTTP post (form) - } - - // this endpoint requires API key authentication - $apiKey = $this->apiClient->getApiKeyWithPrefix('api_key'); - if (strlen($apiKey) !== 0) { - $headerParams['api_key'] = $apiKey; - } - - - // this endpoint requires OAuth (access token) - if (strlen($this->apiClient->getConfig()->getAccessToken()) !== 0) { - $headerParams['Authorization'] = 'Bearer ' . $this->apiClient->getConfig()->getAccessToken(); - } - - // make the API Call - try { - list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, 'GET', - $queryParams, $httpBody, - $headerParams, '\Swagger\Client\Model\InlineResponse200' - ); - - if (!$response) { - return array(null, $statusCode, $httpHeader); - } - - return array(\Swagger\Client\ObjectSerializer::deserialize($response, '\Swagger\Client\Model\InlineResponse200', $httpHeader), $statusCode, $httpHeader); - - } catch (ApiException $e) { - switch ($e->getCode()) { - case 200: - $data = \Swagger\Client\ObjectSerializer::deserialize($e->getResponseBody(), '\Swagger\Client\Model\InlineResponse200', $e->getResponseHeaders()); - $e->setResponseObject($data); - break; - } - - throw $e; - } - } - - /** - * petPetIdtestingByteArraytrueGet - * - * Fake endpoint to test byte array return by 'Find pet by ID' - * - * @param int $pet_id ID of pet that needs to be fetched (required) - * @return string - * @throws \Swagger\Client\ApiException on non-2xx response - */ - public function petPetIdtestingByteArraytrueGet($pet_id) - { - list($response, $statusCode, $httpHeader) = $this->petPetIdtestingByteArraytrueGetWithHttpInfo ($pet_id); - return $response; - } - - - /** - * petPetIdtestingByteArraytrueGetWithHttpInfo - * - * Fake endpoint to test byte array return by 'Find pet by ID' - * - * @param int $pet_id ID of pet that needs to be fetched (required) - * @return Array of string, HTTP status code, HTTP response headers (array of strings) - * @throws \Swagger\Client\ApiException on non-2xx response - */ - public function petPetIdtestingByteArraytrueGetWithHttpInfo($pet_id) - { - - // verify the required parameter 'pet_id' is set - if ($pet_id === null) { - throw new \InvalidArgumentException('Missing the required parameter $pet_id when calling petPetIdtestingByteArraytrueGet'); - } - - // parse inputs - $resourcePath = "/pet/{petId}?testing_byte_array=true"; - $httpBody = ''; - $queryParams = array(); - $headerParams = array(); - $formParams = array(); - $_header_accept = ApiClient::selectHeaderAccept(array('application/json', 'application/xml')); - if (!is_null($_header_accept)) { - $headerParams['Accept'] = $_header_accept; - } - $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array()); - - - - // path params - - if ($pet_id !== null) { - $resourcePath = str_replace( - "{" . "petId" . "}", - $this->apiClient->getSerializer()->toPathValue($pet_id), - $resourcePath - ); - } - // default format to json - $resourcePath = str_replace("{format}", "json", $resourcePath); - - - - - // for model (json/xml) - if (isset($_tempBody)) { - $httpBody = $_tempBody; // $_tempBody is the method argument, if present - } elseif (count($formParams) > 0) { - $httpBody = $formParams; // for HTTP post (form) - } - - // this endpoint requires API key authentication - $apiKey = $this->apiClient->getApiKeyWithPrefix('api_key'); - if (strlen($apiKey) !== 0) { - $headerParams['api_key'] = $apiKey; - } - - - // this endpoint requires OAuth (access token) - if (strlen($this->apiClient->getConfig()->getAccessToken()) !== 0) { - $headerParams['Authorization'] = 'Bearer ' . $this->apiClient->getConfig()->getAccessToken(); - } - - // make the API Call - try { - list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, 'GET', - $queryParams, $httpBody, - $headerParams, 'string' - ); - - if (!$response) { - return array(null, $statusCode, $httpHeader); - } - - return array(\Swagger\Client\ObjectSerializer::deserialize($response, 'string', $httpHeader), $statusCode, $httpHeader); - - } catch (ApiException $e) { - switch ($e->getCode()) { - case 200: - $data = \Swagger\Client\ObjectSerializer::deserialize($e->getResponseBody(), 'string', $e->getResponseHeaders()); - $e->setResponseObject($data); - break; - } - - throw $e; - } - } - - /** - * addPetUsingByteArray - * - * Fake endpoint to test byte array in body parameter for adding a new pet to the store - * - * @param string $body Pet object in the form of byte array (optional) - * @return void - * @throws \Swagger\Client\ApiException on non-2xx response - */ - public function addPetUsingByteArray($body = null) - { - list($response, $statusCode, $httpHeader) = $this->addPetUsingByteArrayWithHttpInfo ($body); - return $response; - } - - - /** - * addPetUsingByteArrayWithHttpInfo - * - * Fake endpoint to test byte array in body parameter for adding a new pet to the store - * - * @param string $body Pet object in the form of byte array (optional) - * @return Array of null, HTTP status code, HTTP response headers (array of strings) - * @throws \Swagger\Client\ApiException on non-2xx response - */ - public function addPetUsingByteArrayWithHttpInfo($body = null) - { - - - // parse inputs - $resourcePath = "/pet?testing_byte_array=true"; - $httpBody = ''; - $queryParams = array(); - $headerParams = array(); - $formParams = array(); - $_header_accept = ApiClient::selectHeaderAccept(array('application/json', 'application/xml')); - if (!is_null($_header_accept)) { - $headerParams['Accept'] = $_header_accept; - } - $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array('application/json','application/xml')); - - - - - // default format to json - $resourcePath = str_replace("{format}", "json", $resourcePath); - - - // 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 - } elseif (count($formParams) > 0) { - $httpBody = $formParams; // for HTTP post (form) - } - - // this endpoint requires OAuth (access token) - if (strlen($this->apiClient->getConfig()->getAccessToken()) !== 0) { - $headerParams['Authorization'] = 'Bearer ' . $this->apiClient->getConfig()->getAccessToken(); - } - - // make the API Call - try { - list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, 'POST', - $queryParams, $httpBody, - $headerParams - ); - - return array(null, $statusCode, $httpHeader); - - } catch (ApiException $e) { - switch ($e->getCode()) { - } - - 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 5e9705df3e3..387cd476c55 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php @@ -90,494 +90,6 @@ class StoreApi return $this; } - - /** - * findOrdersByStatus - * - * Finds orders by status - * - * @param string $status Status value that needs to be considered for query (optional) - * @return \Swagger\Client\Model\Order[] - * @throws \Swagger\Client\ApiException on non-2xx response - */ - public function findOrdersByStatus($status = null) - { - list($response, $statusCode, $httpHeader) = $this->findOrdersByStatusWithHttpInfo ($status); - return $response; - } - - - /** - * findOrdersByStatusWithHttpInfo - * - * Finds orders by status - * - * @param string $status Status value that needs to be considered for query (optional) - * @return Array of \Swagger\Client\Model\Order[], HTTP status code, HTTP response headers (array of strings) - * @throws \Swagger\Client\ApiException on non-2xx response - */ - public function findOrdersByStatusWithHttpInfo($status = null) - { - - - // parse inputs - $resourcePath = "/store/findByStatus"; - $httpBody = ''; - $queryParams = array(); - $headerParams = array(); - $formParams = array(); - $_header_accept = ApiClient::selectHeaderAccept(array('application/json', 'application/xml')); - if (!is_null($_header_accept)) { - $headerParams['Accept'] = $_header_accept; - } - $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array()); - - // query params - - if ($status !== null) { - $queryParams['status'] = $this->apiClient->getSerializer()->toQueryValue($status); - } - - - // default format to json - $resourcePath = str_replace("{format}", "json", $resourcePath); - - - - - // for model (json/xml) - if (isset($_tempBody)) { - $httpBody = $_tempBody; // $_tempBody is the method argument, if present - } elseif (count($formParams) > 0) { - $httpBody = $formParams; // for HTTP post (form) - } - - // this endpoint requires API key authentication - $apiKey = $this->apiClient->getApiKeyWithPrefix('x-test_api_client_id'); - if (strlen($apiKey) !== 0) { - $headerParams['x-test_api_client_id'] = $apiKey; - } - - - // this endpoint requires API key authentication - $apiKey = $this->apiClient->getApiKeyWithPrefix('x-test_api_client_secret'); - if (strlen($apiKey) !== 0) { - $headerParams['x-test_api_client_secret'] = $apiKey; - } - - - // make the API Call - try { - list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, 'GET', - $queryParams, $httpBody, - $headerParams, '\Swagger\Client\Model\Order[]' - ); - - if (!$response) { - return array(null, $statusCode, $httpHeader); - } - - return array(\Swagger\Client\ObjectSerializer::deserialize($response, '\Swagger\Client\Model\Order[]', $httpHeader), $statusCode, $httpHeader); - - } catch (ApiException $e) { - switch ($e->getCode()) { - case 200: - $data = \Swagger\Client\ObjectSerializer::deserialize($e->getResponseBody(), '\Swagger\Client\Model\Order[]', $e->getResponseHeaders()); - $e->setResponseObject($data); - break; - } - - throw $e; - } - } - - /** - * getInventory - * - * Returns pet inventories by status - * - * @return map[string,int] - * @throws \Swagger\Client\ApiException on non-2xx response - */ - public function getInventory() - { - list($response, $statusCode, $httpHeader) = $this->getInventoryWithHttpInfo (); - return $response; - } - - - /** - * getInventoryWithHttpInfo - * - * Returns pet inventories by status - * - * @return Array of map[string,int], HTTP status code, HTTP response headers (array of strings) - * @throws \Swagger\Client\ApiException on non-2xx response - */ - public function getInventoryWithHttpInfo() - { - - - // parse inputs - $resourcePath = "/store/inventory"; - $httpBody = ''; - $queryParams = array(); - $headerParams = array(); - $formParams = array(); - $_header_accept = ApiClient::selectHeaderAccept(array('application/json', 'application/xml')); - if (!is_null($_header_accept)) { - $headerParams['Accept'] = $_header_accept; - } - $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array()); - - - - - // default format to json - $resourcePath = str_replace("{format}", "json", $resourcePath); - - - - - // for model (json/xml) - if (isset($_tempBody)) { - $httpBody = $_tempBody; // $_tempBody is the method argument, if present - } elseif (count($formParams) > 0) { - $httpBody = $formParams; // for HTTP post (form) - } - - // this endpoint requires API key authentication - $apiKey = $this->apiClient->getApiKeyWithPrefix('api_key'); - if (strlen($apiKey) !== 0) { - $headerParams['api_key'] = $apiKey; - } - - - // make the API Call - try { - list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, 'GET', - $queryParams, $httpBody, - $headerParams, 'map[string,int]' - ); - - if (!$response) { - return array(null, $statusCode, $httpHeader); - } - - return array(\Swagger\Client\ObjectSerializer::deserialize($response, 'map[string,int]', $httpHeader), $statusCode, $httpHeader); - - } catch (ApiException $e) { - switch ($e->getCode()) { - case 200: - $data = \Swagger\Client\ObjectSerializer::deserialize($e->getResponseBody(), 'map[string,int]', $e->getResponseHeaders()); - $e->setResponseObject($data); - break; - } - - throw $e; - } - } - - /** - * getInventoryInObject - * - * Fake endpoint to test arbitrary object return by 'Get inventory' - * - * @return object - * @throws \Swagger\Client\ApiException on non-2xx response - */ - public function getInventoryInObject() - { - list($response, $statusCode, $httpHeader) = $this->getInventoryInObjectWithHttpInfo (); - return $response; - } - - - /** - * getInventoryInObjectWithHttpInfo - * - * Fake endpoint to test arbitrary object return by 'Get inventory' - * - * @return Array of object, HTTP status code, HTTP response headers (array of strings) - * @throws \Swagger\Client\ApiException on non-2xx response - */ - public function getInventoryInObjectWithHttpInfo() - { - - - // parse inputs - $resourcePath = "/store/inventory?response=arbitrary_object"; - $httpBody = ''; - $queryParams = array(); - $headerParams = array(); - $formParams = array(); - $_header_accept = ApiClient::selectHeaderAccept(array('application/json', 'application/xml')); - if (!is_null($_header_accept)) { - $headerParams['Accept'] = $_header_accept; - } - $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array()); - - - - - // default format to json - $resourcePath = str_replace("{format}", "json", $resourcePath); - - - - - // for model (json/xml) - if (isset($_tempBody)) { - $httpBody = $_tempBody; // $_tempBody is the method argument, if present - } elseif (count($formParams) > 0) { - $httpBody = $formParams; // for HTTP post (form) - } - - // this endpoint requires API key authentication - $apiKey = $this->apiClient->getApiKeyWithPrefix('api_key'); - if (strlen($apiKey) !== 0) { - $headerParams['api_key'] = $apiKey; - } - - - // make the API Call - try { - list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, 'GET', - $queryParams, $httpBody, - $headerParams, 'object' - ); - - if (!$response) { - return array(null, $statusCode, $httpHeader); - } - - return array(\Swagger\Client\ObjectSerializer::deserialize($response, 'object', $httpHeader), $statusCode, $httpHeader); - - } catch (ApiException $e) { - switch ($e->getCode()) { - case 200: - $data = \Swagger\Client\ObjectSerializer::deserialize($e->getResponseBody(), 'object', $e->getResponseHeaders()); - $e->setResponseObject($data); - break; - } - - throw $e; - } - } - - /** - * placeOrder - * - * Place an order for a pet - * - * @param \Swagger\Client\Model\Order $body order placed for purchasing the pet (optional) - * @return \Swagger\Client\Model\Order - * @throws \Swagger\Client\ApiException on non-2xx response - */ - public function placeOrder($body = null) - { - list($response, $statusCode, $httpHeader) = $this->placeOrderWithHttpInfo ($body); - return $response; - } - - - /** - * placeOrderWithHttpInfo - * - * Place an order for a pet - * - * @param \Swagger\Client\Model\Order $body order placed for purchasing the pet (optional) - * @return Array of \Swagger\Client\Model\Order, HTTP status code, HTTP response headers (array of strings) - * @throws \Swagger\Client\ApiException on non-2xx response - */ - public function placeOrderWithHttpInfo($body = null) - { - - - // parse inputs - $resourcePath = "/store/order"; - $httpBody = ''; - $queryParams = array(); - $headerParams = array(); - $formParams = array(); - $_header_accept = ApiClient::selectHeaderAccept(array('application/json', 'application/xml')); - if (!is_null($_header_accept)) { - $headerParams['Accept'] = $_header_accept; - } - $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array()); - - - - - // default format to json - $resourcePath = str_replace("{format}", "json", $resourcePath); - - - // 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 - } elseif (count($formParams) > 0) { - $httpBody = $formParams; // for HTTP post (form) - } - - // this endpoint requires API key authentication - $apiKey = $this->apiClient->getApiKeyWithPrefix('x-test_api_client_id'); - if (strlen($apiKey) !== 0) { - $headerParams['x-test_api_client_id'] = $apiKey; - } - - - // this endpoint requires API key authentication - $apiKey = $this->apiClient->getApiKeyWithPrefix('x-test_api_client_secret'); - if (strlen($apiKey) !== 0) { - $headerParams['x-test_api_client_secret'] = $apiKey; - } - - - // make the API Call - try { - list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, 'POST', - $queryParams, $httpBody, - $headerParams, '\Swagger\Client\Model\Order' - ); - - if (!$response) { - return array(null, $statusCode, $httpHeader); - } - - return array(\Swagger\Client\ObjectSerializer::deserialize($response, '\Swagger\Client\Model\Order', $httpHeader), $statusCode, $httpHeader); - - } catch (ApiException $e) { - switch ($e->getCode()) { - case 200: - $data = \Swagger\Client\ObjectSerializer::deserialize($e->getResponseBody(), '\Swagger\Client\Model\Order', $e->getResponseHeaders()); - $e->setResponseObject($data); - break; - } - - throw $e; - } - } - - /** - * getOrderById - * - * Find purchase order by ID - * - * @param string $order_id ID of pet that needs to be fetched (required) - * @return \Swagger\Client\Model\Order - * @throws \Swagger\Client\ApiException on non-2xx response - */ - public function getOrderById($order_id) - { - list($response, $statusCode, $httpHeader) = $this->getOrderByIdWithHttpInfo ($order_id); - return $response; - } - - - /** - * getOrderByIdWithHttpInfo - * - * Find purchase order by ID - * - * @param string $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 - */ - public function getOrderByIdWithHttpInfo($order_id) - { - - // verify the required parameter 'order_id' is set - if ($order_id === null) { - throw new \InvalidArgumentException('Missing the required parameter $order_id when calling getOrderById'); - } - - // parse inputs - $resourcePath = "/store/order/{orderId}"; - $httpBody = ''; - $queryParams = array(); - $headerParams = array(); - $formParams = array(); - $_header_accept = ApiClient::selectHeaderAccept(array('application/json', 'application/xml')); - if (!is_null($_header_accept)) { - $headerParams['Accept'] = $_header_accept; - } - $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array()); - - - - // path params - - if ($order_id !== null) { - $resourcePath = str_replace( - "{" . "orderId" . "}", - $this->apiClient->getSerializer()->toPathValue($order_id), - $resourcePath - ); - } - // default format to json - $resourcePath = str_replace("{format}", "json", $resourcePath); - - - - - // for model (json/xml) - if (isset($_tempBody)) { - $httpBody = $_tempBody; // $_tempBody is the method argument, if present - } elseif (count($formParams) > 0) { - $httpBody = $formParams; // for HTTP post (form) - } - - // this endpoint requires API key authentication - $apiKey = $this->apiClient->getApiKeyWithPrefix('test_api_key_header'); - if (strlen($apiKey) !== 0) { - $headerParams['test_api_key_header'] = $apiKey; - } - - - // this endpoint requires API key authentication - $apiKey = $this->apiClient->getApiKeyWithPrefix('test_api_key_query'); - if (strlen($apiKey) !== 0) { - $queryParams['test_api_key_query'] = $apiKey; - } - - - // make the API Call - try { - list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, 'GET', - $queryParams, $httpBody, - $headerParams, '\Swagger\Client\Model\Order' - ); - - if (!$response) { - return array(null, $statusCode, $httpHeader); - } - - return array(\Swagger\Client\ObjectSerializer::deserialize($response, '\Swagger\Client\Model\Order', $httpHeader), $statusCode, $httpHeader); - - } catch (ApiException $e) { - switch ($e->getCode()) { - case 200: - $data = \Swagger\Client\ObjectSerializer::deserialize($e->getResponseBody(), '\Swagger\Client\Model\Order', $e->getResponseHeaders()); - $e->setResponseObject($data); - break; - } - - throw $e; - } - } - /** * deleteOrder * @@ -589,7 +101,7 @@ class StoreApi */ public function deleteOrder($order_id) { - list($response, $statusCode, $httpHeader) = $this->deleteOrderWithHttpInfo ($order_id); + list($response) = $this->deleteOrderWithHttpInfo ($order_id); return $response; } @@ -617,16 +129,362 @@ class StoreApi $queryParams = array(); $headerParams = array(); $formParams = array(); - $_header_accept = ApiClient::selectHeaderAccept(array('application/json', 'application/xml')); + $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array()); + $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); // path params + if ($order_id !== null) { + $resourcePath = str_replace( + "{" . "orderId" . "}", + $this->apiClient->getSerializer()->toPathValue($order_id), + $resourcePath + ); + } + // default format to json + $resourcePath = str_replace("{format}", "json", $resourcePath); + + + + // for model (json/xml) + if (isset($_tempBody)) { + $httpBody = $_tempBody; // $_tempBody is the method argument, if present + } elseif (count($formParams) > 0) { + $httpBody = $formParams; // for HTTP post (form) + } + // make the API Call + try { + list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( + $resourcePath, 'DELETE', + $queryParams, $httpBody, + $headerParams + ); + + return array(null, $statusCode, $httpHeader); + } catch (ApiException $e) { + switch ($e->getCode()) { + } + + throw $e; + } + } + /** + * findOrdersByStatus + * + * Finds orders by status + * + * @param string $status Status value that needs to be considered for query (optional, default to placed) + * @return \Swagger\Client\Model\Order[] + * @throws \Swagger\Client\ApiException on non-2xx response + */ + public function findOrdersByStatus($status = null) + { + list($response) = $this->findOrdersByStatusWithHttpInfo ($status); + return $response; + } + + + /** + * findOrdersByStatusWithHttpInfo + * + * Finds orders by status + * + * @param string $status Status value that needs to be considered for query (optional, default to placed) + * @return Array of \Swagger\Client\Model\Order[], HTTP status code, HTTP response headers (array of strings) + * @throws \Swagger\Client\ApiException on non-2xx response + */ + public function findOrdersByStatusWithHttpInfo($status = null) + { + + + // parse inputs + $resourcePath = "/store/findByStatus"; + $httpBody = ''; + $queryParams = array(); + $headerParams = array(); + $formParams = array(); + $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); + if (!is_null($_header_accept)) { + $headerParams['Accept'] = $_header_accept; + } + $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); + + // query params + if ($status !== null) { + $queryParams['status'] = $this->apiClient->getSerializer()->toQueryValue($status); + } + + + // default format to json + $resourcePath = str_replace("{format}", "json", $resourcePath); + + + + + // for model (json/xml) + if (isset($_tempBody)) { + $httpBody = $_tempBody; // $_tempBody is the method argument, if present + } elseif (count($formParams) > 0) { + $httpBody = $formParams; // for HTTP post (form) + } + + // this endpoint requires API key authentication + $apiKey = $this->apiClient->getApiKeyWithPrefix('x-test_api_client_id'); + if (strlen($apiKey) !== 0) { + $headerParams['x-test_api_client_id'] = $apiKey; + } + + + // this endpoint requires API key authentication + $apiKey = $this->apiClient->getApiKeyWithPrefix('x-test_api_client_secret'); + if (strlen($apiKey) !== 0) { + $headerParams['x-test_api_client_secret'] = $apiKey; + } + + // make the API Call + try { + list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( + $resourcePath, 'GET', + $queryParams, $httpBody, + $headerParams, '\Swagger\Client\Model\Order[]' + ); + if (!$response) { + return array(null, $statusCode, $httpHeader); + } + + return array($this->apiClient->getSerializer()->deserialize($response, '\Swagger\Client\Model\Order[]', $httpHeader), $statusCode, $httpHeader); + } catch (ApiException $e) { + switch ($e->getCode()) { + case 200: + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\Order[]', $e->getResponseHeaders()); + $e->setResponseObject($data); + break; + } + + throw $e; + } + } + /** + * getInventory + * + * Returns pet inventories by status + * + * @return map[string,int] + * @throws \Swagger\Client\ApiException on non-2xx response + */ + public function getInventory() + { + list($response) = $this->getInventoryWithHttpInfo (); + return $response; + } + + + /** + * getInventoryWithHttpInfo + * + * Returns pet inventories by status + * + * @return Array of map[string,int], HTTP status code, HTTP response headers (array of strings) + * @throws \Swagger\Client\ApiException on non-2xx response + */ + public function getInventoryWithHttpInfo() + { + + + // parse inputs + $resourcePath = "/store/inventory"; + $httpBody = ''; + $queryParams = array(); + $headerParams = array(); + $formParams = array(); + $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); + if (!is_null($_header_accept)) { + $headerParams['Accept'] = $_header_accept; + } + $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); + + + + + // default format to json + $resourcePath = str_replace("{format}", "json", $resourcePath); + + + + + // for model (json/xml) + if (isset($_tempBody)) { + $httpBody = $_tempBody; // $_tempBody is the method argument, if present + } elseif (count($formParams) > 0) { + $httpBody = $formParams; // for HTTP post (form) + } + + // this endpoint requires API key authentication + $apiKey = $this->apiClient->getApiKeyWithPrefix('api_key'); + if (strlen($apiKey) !== 0) { + $headerParams['api_key'] = $apiKey; + } + + // make the API Call + try { + list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( + $resourcePath, 'GET', + $queryParams, $httpBody, + $headerParams, 'map[string,int]' + ); + if (!$response) { + return array(null, $statusCode, $httpHeader); + } + + return array($this->apiClient->getSerializer()->deserialize($response, 'map[string,int]', $httpHeader), $statusCode, $httpHeader); + } catch (ApiException $e) { + switch ($e->getCode()) { + case 200: + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), 'map[string,int]', $e->getResponseHeaders()); + $e->setResponseObject($data); + break; + } + + throw $e; + } + } + /** + * getInventoryInObject + * + * Fake endpoint to test arbitrary object return by 'Get inventory' + * + * @return object + * @throws \Swagger\Client\ApiException on non-2xx response + */ + public function getInventoryInObject() + { + list($response) = $this->getInventoryInObjectWithHttpInfo (); + return $response; + } + + + /** + * getInventoryInObjectWithHttpInfo + * + * Fake endpoint to test arbitrary object return by 'Get inventory' + * + * @return Array of object, HTTP status code, HTTP response headers (array of strings) + * @throws \Swagger\Client\ApiException on non-2xx response + */ + public function getInventoryInObjectWithHttpInfo() + { + + + // parse inputs + $resourcePath = "/store/inventory?response=arbitrary_object"; + $httpBody = ''; + $queryParams = array(); + $headerParams = array(); + $formParams = array(); + $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); + if (!is_null($_header_accept)) { + $headerParams['Accept'] = $_header_accept; + } + $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); + + + + + // default format to json + $resourcePath = str_replace("{format}", "json", $resourcePath); + + + + + // for model (json/xml) + if (isset($_tempBody)) { + $httpBody = $_tempBody; // $_tempBody is the method argument, if present + } elseif (count($formParams) > 0) { + $httpBody = $formParams; // for HTTP post (form) + } + + // this endpoint requires API key authentication + $apiKey = $this->apiClient->getApiKeyWithPrefix('api_key'); + if (strlen($apiKey) !== 0) { + $headerParams['api_key'] = $apiKey; + } + + // make the API Call + try { + list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( + $resourcePath, 'GET', + $queryParams, $httpBody, + $headerParams, 'object' + ); + if (!$response) { + return array(null, $statusCode, $httpHeader); + } + + return array($this->apiClient->getSerializer()->deserialize($response, 'object', $httpHeader), $statusCode, $httpHeader); + } catch (ApiException $e) { + switch ($e->getCode()) { + case 200: + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), 'object', $e->getResponseHeaders()); + $e->setResponseObject($data); + break; + } + + throw $e; + } + } + /** + * getOrderById + * + * Find purchase order by ID + * + * @param string $order_id ID of pet that needs to be fetched (required) + * @return \Swagger\Client\Model\Order + * @throws \Swagger\Client\ApiException on non-2xx response + */ + public function getOrderById($order_id) + { + list($response) = $this->getOrderByIdWithHttpInfo ($order_id); + return $response; + } + + + /** + * getOrderByIdWithHttpInfo + * + * Find purchase order by ID + * + * @param string $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 + */ + public function getOrderByIdWithHttpInfo($order_id) + { + + // verify the required parameter 'order_id' is set + if ($order_id === null) { + throw new \InvalidArgumentException('Missing the required parameter $order_id when calling getOrderById'); + } + + // parse inputs + $resourcePath = "/store/order/{orderId}"; + $httpBody = ''; + $queryParams = array(); + $headerParams = array(); + $formParams = array(); + $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); + if (!is_null($_header_accept)) { + $headerParams['Accept'] = $_header_accept; + } + $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); + + + + // path params if ($order_id !== null) { $resourcePath = str_replace( "{" . "orderId" . "}", @@ -647,22 +505,137 @@ class StoreApi $httpBody = $formParams; // for HTTP post (form) } + // this endpoint requires API key authentication + $apiKey = $this->apiClient->getApiKeyWithPrefix('test_api_key_header'); + if (strlen($apiKey) !== 0) { + $headerParams['test_api_key_header'] = $apiKey; + } + + + // this endpoint requires API key authentication + $apiKey = $this->apiClient->getApiKeyWithPrefix('test_api_key_query'); + if (strlen($apiKey) !== 0) { + $queryParams['test_api_key_query'] = $apiKey; + } + // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, 'DELETE', + $resourcePath, 'GET', $queryParams, $httpBody, - $headerParams + $headerParams, '\Swagger\Client\Model\Order' ); - - return array(null, $statusCode, $httpHeader); - - } catch (ApiException $e) { + if (!$response) { + return array(null, $statusCode, $httpHeader); + } + + return array($this->apiClient->getSerializer()->deserialize($response, '\Swagger\Client\Model\Order', $httpHeader), $statusCode, $httpHeader); + } catch (ApiException $e) { switch ($e->getCode()) { + case 200: + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\Order', $e->getResponseHeaders()); + $e->setResponseObject($data); + break; + } + + throw $e; + } + } + /** + * placeOrder + * + * Place an order for a pet + * + * @param \Swagger\Client\Model\Order $body order placed for purchasing the pet (optional) + * @return \Swagger\Client\Model\Order + * @throws \Swagger\Client\ApiException on non-2xx response + */ + public function placeOrder($body = null) + { + list($response) = $this->placeOrderWithHttpInfo ($body); + return $response; + } + + + /** + * placeOrderWithHttpInfo + * + * Place an order for a pet + * + * @param \Swagger\Client\Model\Order $body order placed for purchasing the pet (optional) + * @return Array of \Swagger\Client\Model\Order, HTTP status code, HTTP response headers (array of strings) + * @throws \Swagger\Client\ApiException on non-2xx response + */ + public function placeOrderWithHttpInfo($body = null) + { + + + // parse inputs + $resourcePath = "/store/order"; + $httpBody = ''; + $queryParams = array(); + $headerParams = array(); + $formParams = array(); + $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); + if (!is_null($_header_accept)) { + $headerParams['Accept'] = $_header_accept; + } + $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); + + + + + // default format to json + $resourcePath = str_replace("{format}", "json", $resourcePath); + + + // 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 + } elseif (count($formParams) > 0) { + $httpBody = $formParams; // for HTTP post (form) + } + + // this endpoint requires API key authentication + $apiKey = $this->apiClient->getApiKeyWithPrefix('x-test_api_client_id'); + if (strlen($apiKey) !== 0) { + $headerParams['x-test_api_client_id'] = $apiKey; + } + + + // this endpoint requires API key authentication + $apiKey = $this->apiClient->getApiKeyWithPrefix('x-test_api_client_secret'); + if (strlen($apiKey) !== 0) { + $headerParams['x-test_api_client_secret'] = $apiKey; + } + + // make the API Call + try { + list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( + $resourcePath, 'POST', + $queryParams, $httpBody, + $headerParams, '\Swagger\Client\Model\Order' + ); + if (!$response) { + return array(null, $statusCode, $httpHeader); + } + + return array($this->apiClient->getSerializer()->deserialize($response, '\Swagger\Client\Model\Order', $httpHeader), $statusCode, $httpHeader); + } catch (ApiException $e) { + switch ($e->getCode()) { + case 200: + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\Order', $e->getResponseHeaders()); + $e->setResponseObject($data); + break; } 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 595d82fffc1..23f682e4943 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php @@ -90,7 +90,6 @@ class UserApi return $this; } - /** * createUser * @@ -102,7 +101,7 @@ class UserApi */ public function createUser($body = null) { - list($response, $statusCode, $httpHeader) = $this->createUserWithHttpInfo ($body); + list($response) = $this->createUserWithHttpInfo ($body); return $response; } @@ -126,11 +125,11 @@ class UserApi $queryParams = array(); $headerParams = array(); $formParams = array(); - $_header_accept = ApiClient::selectHeaderAccept(array('application/json', 'application/xml')); + $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array()); + $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); @@ -151,17 +150,15 @@ class UserApi } elseif (count($formParams) > 0) { $httpBody = $formParams; // for HTTP post (form) } - - // make the API Call + // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( $resourcePath, 'POST', $queryParams, $httpBody, $headerParams ); - + return array(null, $statusCode, $httpHeader); - } catch (ApiException $e) { switch ($e->getCode()) { } @@ -169,7 +166,6 @@ class UserApi throw $e; } } - /** * createUsersWithArrayInput * @@ -181,7 +177,7 @@ class UserApi */ public function createUsersWithArrayInput($body = null) { - list($response, $statusCode, $httpHeader) = $this->createUsersWithArrayInputWithHttpInfo ($body); + list($response) = $this->createUsersWithArrayInputWithHttpInfo ($body); return $response; } @@ -205,11 +201,11 @@ class UserApi $queryParams = array(); $headerParams = array(); $formParams = array(); - $_header_accept = ApiClient::selectHeaderAccept(array('application/json', 'application/xml')); + $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array()); + $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); @@ -230,17 +226,15 @@ class UserApi } elseif (count($formParams) > 0) { $httpBody = $formParams; // for HTTP post (form) } - - // make the API Call + // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( $resourcePath, 'POST', $queryParams, $httpBody, $headerParams ); - + return array(null, $statusCode, $httpHeader); - } catch (ApiException $e) { switch ($e->getCode()) { } @@ -248,7 +242,6 @@ class UserApi throw $e; } } - /** * createUsersWithListInput * @@ -260,7 +253,7 @@ class UserApi */ public function createUsersWithListInput($body = null) { - list($response, $statusCode, $httpHeader) = $this->createUsersWithListInputWithHttpInfo ($body); + list($response) = $this->createUsersWithListInputWithHttpInfo ($body); return $response; } @@ -284,11 +277,11 @@ class UserApi $queryParams = array(); $headerParams = array(); $formParams = array(); - $_header_accept = ApiClient::selectHeaderAccept(array('application/json', 'application/xml')); + $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array()); + $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); @@ -309,17 +302,15 @@ class UserApi } elseif (count($formParams) > 0) { $httpBody = $formParams; // for HTTP post (form) } - - // make the API Call + // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( $resourcePath, 'POST', $queryParams, $httpBody, $headerParams ); - + return array(null, $statusCode, $httpHeader); - } catch (ApiException $e) { switch ($e->getCode()) { } @@ -327,7 +318,184 @@ class UserApi throw $e; } } - + /** + * deleteUser + * + * Delete user + * + * @param string $username The name that needs to be deleted (required) + * @return void + * @throws \Swagger\Client\ApiException on non-2xx response + */ + public function deleteUser($username) + { + list($response) = $this->deleteUserWithHttpInfo ($username); + return $response; + } + + + /** + * deleteUserWithHttpInfo + * + * 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 + */ + public function deleteUserWithHttpInfo($username) + { + + // verify the required parameter 'username' is set + if ($username === null) { + throw new \InvalidArgumentException('Missing the required parameter $username when calling deleteUser'); + } + + // parse inputs + $resourcePath = "/user/{username}"; + $httpBody = ''; + $queryParams = array(); + $headerParams = array(); + $formParams = array(); + $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); + if (!is_null($_header_accept)) { + $headerParams['Accept'] = $_header_accept; + } + $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); + + + + // path params + if ($username !== null) { + $resourcePath = str_replace( + "{" . "username" . "}", + $this->apiClient->getSerializer()->toPathValue($username), + $resourcePath + ); + } + // default format to json + $resourcePath = str_replace("{format}", "json", $resourcePath); + + + + + // for model (json/xml) + if (isset($_tempBody)) { + $httpBody = $_tempBody; // $_tempBody is the method argument, if present + } 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( + $resourcePath, 'DELETE', + $queryParams, $httpBody, + $headerParams + ); + + return array(null, $statusCode, $httpHeader); + } catch (ApiException $e) { + switch ($e->getCode()) { + } + + throw $e; + } + } + /** + * getUserByName + * + * 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 + */ + public function getUserByName($username) + { + list($response) = $this->getUserByNameWithHttpInfo ($username); + return $response; + } + + + /** + * getUserByNameWithHttpInfo + * + * 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 + */ + public function getUserByNameWithHttpInfo($username) + { + + // verify the required parameter 'username' is set + if ($username === null) { + throw new \InvalidArgumentException('Missing the required parameter $username when calling getUserByName'); + } + + // parse inputs + $resourcePath = "/user/{username}"; + $httpBody = ''; + $queryParams = array(); + $headerParams = array(); + $formParams = array(); + $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); + if (!is_null($_header_accept)) { + $headerParams['Accept'] = $_header_accept; + } + $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); + + + + // path params + if ($username !== null) { + $resourcePath = str_replace( + "{" . "username" . "}", + $this->apiClient->getSerializer()->toPathValue($username), + $resourcePath + ); + } + // default format to json + $resourcePath = str_replace("{format}", "json", $resourcePath); + + + + + // for model (json/xml) + if (isset($_tempBody)) { + $httpBody = $_tempBody; // $_tempBody is the method argument, if present + } elseif (count($formParams) > 0) { + $httpBody = $formParams; // for HTTP post (form) + } + // make the API Call + try { + list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( + $resourcePath, 'GET', + $queryParams, $httpBody, + $headerParams, '\Swagger\Client\Model\User' + ); + if (!$response) { + return array(null, $statusCode, $httpHeader); + } + + return array($this->apiClient->getSerializer()->deserialize($response, '\Swagger\Client\Model\User', $httpHeader), $statusCode, $httpHeader); + } catch (ApiException $e) { + switch ($e->getCode()) { + case 200: + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\User', $e->getResponseHeaders()); + $e->setResponseObject($data); + break; + } + + throw $e; + } + } /** * loginUser * @@ -340,7 +508,7 @@ class UserApi */ public function loginUser($username = null, $password = null) { - list($response, $statusCode, $httpHeader) = $this->loginUserWithHttpInfo ($username, $password); + list($response) = $this->loginUserWithHttpInfo ($username, $password); return $response; } @@ -365,18 +533,16 @@ class UserApi $queryParams = array(); $headerParams = array(); $formParams = array(); - $_header_accept = ApiClient::selectHeaderAccept(array('application/json', 'application/xml')); + $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array()); + $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); // query params - if ($username !== null) { $queryParams['username'] = $this->apiClient->getSerializer()->toQueryValue($username); }// query params - if ($password !== null) { $queryParams['password'] = $this->apiClient->getSerializer()->toQueryValue($password); } @@ -394,25 +560,22 @@ class UserApi } elseif (count($formParams) > 0) { $httpBody = $formParams; // for HTTP post (form) } - - // make the API Call + // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( $resourcePath, 'GET', $queryParams, $httpBody, $headerParams, 'string' ); - if (!$response) { return array(null, $statusCode, $httpHeader); } - return array(\Swagger\Client\ObjectSerializer::deserialize($response, 'string', $httpHeader), $statusCode, $httpHeader); - - } catch (ApiException $e) { + return array($this->apiClient->getSerializer()->deserialize($response, 'string', $httpHeader), $statusCode, $httpHeader); + } catch (ApiException $e) { switch ($e->getCode()) { case 200: - $data = \Swagger\Client\ObjectSerializer::deserialize($e->getResponseBody(), 'string', $e->getResponseHeaders()); + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), 'string', $e->getResponseHeaders()); $e->setResponseObject($data); break; } @@ -420,7 +583,6 @@ class UserApi throw $e; } } - /** * logoutUser * @@ -431,7 +593,7 @@ class UserApi */ public function logoutUser() { - list($response, $statusCode, $httpHeader) = $this->logoutUserWithHttpInfo (); + list($response) = $this->logoutUserWithHttpInfo (); return $response; } @@ -454,11 +616,11 @@ class UserApi $queryParams = array(); $headerParams = array(); $formParams = array(); - $_header_accept = ApiClient::selectHeaderAccept(array('application/json', 'application/xml')); + $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array()); + $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); @@ -475,17 +637,15 @@ class UserApi } elseif (count($formParams) > 0) { $httpBody = $formParams; // for HTTP post (form) } - - // make the API Call + // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( $resourcePath, 'GET', $queryParams, $httpBody, $headerParams ); - + return array(null, $statusCode, $httpHeader); - } catch (ApiException $e) { switch ($e->getCode()) { } @@ -493,102 +653,6 @@ class UserApi throw $e; } } - - /** - * getUserByName - * - * 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 - */ - public function getUserByName($username) - { - list($response, $statusCode, $httpHeader) = $this->getUserByNameWithHttpInfo ($username); - return $response; - } - - - /** - * getUserByNameWithHttpInfo - * - * 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 - */ - public function getUserByNameWithHttpInfo($username) - { - - // verify the required parameter 'username' is set - if ($username === null) { - throw new \InvalidArgumentException('Missing the required parameter $username when calling getUserByName'); - } - - // parse inputs - $resourcePath = "/user/{username}"; - $httpBody = ''; - $queryParams = array(); - $headerParams = array(); - $formParams = array(); - $_header_accept = ApiClient::selectHeaderAccept(array('application/json', 'application/xml')); - if (!is_null($_header_accept)) { - $headerParams['Accept'] = $_header_accept; - } - $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array()); - - - - // path params - - if ($username !== null) { - $resourcePath = str_replace( - "{" . "username" . "}", - $this->apiClient->getSerializer()->toPathValue($username), - $resourcePath - ); - } - // default format to json - $resourcePath = str_replace("{format}", "json", $resourcePath); - - - - - // for model (json/xml) - if (isset($_tempBody)) { - $httpBody = $_tempBody; // $_tempBody is the method argument, if present - } elseif (count($formParams) > 0) { - $httpBody = $formParams; // for HTTP post (form) - } - - // make the API Call - try { - list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, 'GET', - $queryParams, $httpBody, - $headerParams, '\Swagger\Client\Model\User' - ); - - if (!$response) { - return array(null, $statusCode, $httpHeader); - } - - return array(\Swagger\Client\ObjectSerializer::deserialize($response, '\Swagger\Client\Model\User', $httpHeader), $statusCode, $httpHeader); - - } catch (ApiException $e) { - switch ($e->getCode()) { - case 200: - $data = \Swagger\Client\ObjectSerializer::deserialize($e->getResponseBody(), '\Swagger\Client\Model\User', $e->getResponseHeaders()); - $e->setResponseObject($data); - break; - } - - throw $e; - } - } - /** * updateUser * @@ -601,7 +665,7 @@ class UserApi */ public function updateUser($username, $body = null) { - list($response, $statusCode, $httpHeader) = $this->updateUserWithHttpInfo ($username, $body); + list($response) = $this->updateUserWithHttpInfo ($username, $body); return $response; } @@ -630,16 +694,15 @@ class UserApi $queryParams = array(); $headerParams = array(); $formParams = array(); - $_header_accept = ApiClient::selectHeaderAccept(array('application/json', 'application/xml')); + $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array()); + $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); // path params - if ($username !== null) { $resourcePath = str_replace( "{" . "username" . "}", @@ -663,17 +726,15 @@ class UserApi } elseif (count($formParams) > 0) { $httpBody = $formParams; // for HTTP post (form) } - - // make the API Call + // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( $resourcePath, 'PUT', $queryParams, $httpBody, $headerParams ); - + return array(null, $statusCode, $httpHeader); - } catch (ApiException $e) { switch ($e->getCode()) { } @@ -681,92 +742,4 @@ class UserApi throw $e; } } - - /** - * deleteUser - * - * Delete user - * - * @param string $username The name that needs to be deleted (required) - * @return void - * @throws \Swagger\Client\ApiException on non-2xx response - */ - public function deleteUser($username) - { - list($response, $statusCode, $httpHeader) = $this->deleteUserWithHttpInfo ($username); - return $response; - } - - - /** - * deleteUserWithHttpInfo - * - * 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 - */ - public function deleteUserWithHttpInfo($username) - { - - // verify the required parameter 'username' is set - if ($username === null) { - throw new \InvalidArgumentException('Missing the required parameter $username when calling deleteUser'); - } - - // parse inputs - $resourcePath = "/user/{username}"; - $httpBody = ''; - $queryParams = array(); - $headerParams = array(); - $formParams = array(); - $_header_accept = ApiClient::selectHeaderAccept(array('application/json', 'application/xml')); - if (!is_null($_header_accept)) { - $headerParams['Accept'] = $_header_accept; - } - $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array()); - - - - // path params - - if ($username !== null) { - $resourcePath = str_replace( - "{" . "username" . "}", - $this->apiClient->getSerializer()->toPathValue($username), - $resourcePath - ); - } - // default format to json - $resourcePath = str_replace("{format}", "json", $resourcePath); - - - - - // for model (json/xml) - if (isset($_tempBody)) { - $httpBody = $_tempBody; // $_tempBody is the method argument, if present - } elseif (count($formParams) > 0) { - $httpBody = $formParams; // for HTTP post (form) - } - - // make the API Call - try { - list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, 'DELETE', - $queryParams, $httpBody, - $headerParams - ); - - return array(null, $statusCode, $httpHeader); - - } catch (ApiException $e) { - switch ($e->getCode()) { - } - - throw $e; - } - } - } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/ApiClient.php b/samples/client/petstore/php/SwaggerClient-php/lib/ApiClient.php index df38b989f88..65ee9d27f29 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/ApiClient.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/ApiClient.php @@ -259,7 +259,7 @@ class ApiClient * * @return string Accept (e.g. application/json) */ - public static function selectHeaderAccept($accept) + public function selectHeaderAccept($accept) { if (count($accept) === 0 or (count($accept) === 1 and $accept[0] === '')) { return null; @@ -277,7 +277,7 @@ class ApiClient * * @return string Content-Type (e.g. application/json) */ - public static function selectHeaderContentType($content_type) + public function selectHeaderContentType($content_type) { if (count($content_type) === 0 or (count($content_type) === 1 and $content_type[0] === '')) { return 'application/json'; @@ -299,9 +299,9 @@ class ApiClient { // ref/credit: http://php.net/manual/en/function.http-parse-headers.php#112986 $headers = array(); - $key = ''; // [+] + $key = ''; - foreach(explode("\n", $raw_headers) as $i => $h) + foreach(explode("\n", $raw_headers) as $h) { $h = explode(':', $h, 2); @@ -311,26 +311,22 @@ class ApiClient $headers[$h[0]] = trim($h[1]); elseif (is_array($headers[$h[0]])) { - // $tmp = array_merge($headers[$h[0]], array(trim($h[1]))); // [-] - // $headers[$h[0]] = $tmp; // [-] - $headers[$h[0]] = array_merge($headers[$h[0]], array(trim($h[1]))); // [+] + $headers[$h[0]] = array_merge($headers[$h[0]], array(trim($h[1]))); } else { - // $tmp = array_merge(array($headers[$h[0]]), array(trim($h[1]))); // [-] - // $headers[$h[0]] = $tmp; // [-] - $headers[$h[0]] = array_merge(array($headers[$h[0]]), array(trim($h[1]))); // [+] + $headers[$h[0]] = array_merge(array($headers[$h[0]]), array(trim($h[1]))); } - $key = $h[0]; // [+] + $key = $h[0]; + } + else + { + if (substr($h[0], 0, 1) == "\t") + $headers[$key] .= "\r\n\t".trim($h[0]); + elseif (!$key) + $headers[0] = trim($h[0]);trim($h[0]); } - else // [+] - { // [+] - if (substr($h[0], 0, 1) == "\t") // [+] - $headers[$key] .= "\r\n\t".trim($h[0]); // [+] - elseif (!$key) // [+] - $headers[0] = trim($h[0]);trim($h[0]); // [+] - } // [+] } return $headers; diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php b/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php index 108092f91b1..9da9c7edac0 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php @@ -110,7 +110,7 @@ class Configuration * * @var string */ - protected $userAgent = "PHP-Swagger/1.0.0"; + protected $userAgent = "Swagger-Codegen/1.0.0/php"; /** * Debug switch (default set to false) diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Animal.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Animal.php new file mode 100644 index 00000000000..c267c81b18e --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Animal.php @@ -0,0 +1,187 @@ + 'string' + ); + + static function swaggerTypes() { + return self::$swaggerTypes; + } + + /** + * Array of attributes where the key is the local name, and the value is the original name + * @var string[] + */ + static $attributeMap = array( + 'class_name' => 'className' + ); + + static function attributeMap() { + return self::$attributeMap; + } + + /** + * Array of attributes to setter functions (for deserialization of responses) + * @var string[] + */ + static $setters = array( + 'class_name' => 'setClassName' + ); + + static function setters() { + return self::$setters; + } + + /** + * Array of attributes to getter functions (for serialization of requests) + * @var string[] + */ + static $getters = array( + 'class_name' => 'getClassName' + ); + + static function getters() { + return self::$getters; + } + + /** + * $class_name + * @var string + */ + protected $class_name; + + /** + * Constructor + * @param mixed[] $data Associated array of property value initalizing the model + */ + public function __construct(array $data = null) + { + + if ($data != null) { + $this->class_name = $data["class_name"]; + } + } + /** + * Gets class_name + * @return string + */ + public function getClassName() + { + return $this->class_name; + } + + /** + * Sets class_name + * @param string $class_name + * @return $this + */ + public function setClassName($class_name) + { + + $this->class_name = $class_name; + return $this; + } + /** + * Returns true if offset exists. False otherwise. + * @param integer $offset Offset + * @return boolean + */ + public function offsetExists($offset) + { + return isset($this->$offset); + } + + /** + * Gets offset. + * @param integer $offset Offset + * @return mixed + */ + public function offsetGet($offset) + { + return $this->$offset; + } + + /** + * Sets value based on offset. + * @param integer $offset Offset + * @param mixed $value Value to be set + * @return void + */ + public function offsetSet($offset, $value) + { + $this->$offset = $value; + } + + /** + * Unsets offset. + * @param integer $offset Offset + * @return void + */ + public function offsetUnset($offset) + { + unset($this->$offset); + } + + /** + * Gets the string presentation of the object + * @return string + */ + public function __toString() + { + if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print + return json_encode(\Swagger\Client\ObjectSerializer::sanitizeForSerialization($this), JSON_PRETTY_PRINT); + } + + return json_encode(\Swagger\Client\ObjectSerializer::sanitizeForSerialization($this)); + } +} diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Cat.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Cat.php new file mode 100644 index 00000000000..79acd0d1f22 --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Cat.php @@ -0,0 +1,187 @@ + 'bool' + ); + + static function swaggerTypes() { + return self::$swaggerTypes + parent::swaggerTypes(); + } + + /** + * Array of attributes where the key is the local name, and the value is the original name + * @var string[] + */ + static $attributeMap = array( + 'declawed' => 'declawed' + ); + + static function attributeMap() { + return parent::attributeMap() + self::$attributeMap; + } + + /** + * Array of attributes to setter functions (for deserialization of responses) + * @var string[] + */ + static $setters = array( + 'declawed' => 'setDeclawed' + ); + + static function setters() { + return parent::setters() + self::$setters; + } + + /** + * Array of attributes to getter functions (for serialization of requests) + * @var string[] + */ + static $getters = array( + 'declawed' => 'getDeclawed' + ); + + static function getters() { + return parent::getters() + self::$getters; + } + + /** + * $declawed + * @var bool + */ + protected $declawed; + + /** + * Constructor + * @param mixed[] $data Associated array of property value initalizing the model + */ + public function __construct(array $data = null) + { + parent::__construct($data); + if ($data != null) { + $this->declawed = $data["declawed"]; + } + } + /** + * Gets declawed + * @return bool + */ + public function getDeclawed() + { + return $this->declawed; + } + + /** + * Sets declawed + * @param bool $declawed + * @return $this + */ + public function setDeclawed($declawed) + { + + $this->declawed = $declawed; + return $this; + } + /** + * Returns true if offset exists. False otherwise. + * @param integer $offset Offset + * @return boolean + */ + public function offsetExists($offset) + { + return isset($this->$offset); + } + + /** + * Gets offset. + * @param integer $offset Offset + * @return mixed + */ + public function offsetGet($offset) + { + return $this->$offset; + } + + /** + * Sets value based on offset. + * @param integer $offset Offset + * @param mixed $value Value to be set + * @return void + */ + public function offsetSet($offset, $value) + { + $this->$offset = $value; + } + + /** + * Unsets offset. + * @param integer $offset Offset + * @return void + */ + public function offsetUnset($offset) + { + unset($this->$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/Category.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Category.php index 723617198b5..0f359589d0e 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Category.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Category.php @@ -55,6 +55,10 @@ class Category implements ArrayAccess 'name' => 'string' ); + 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[] @@ -64,6 +68,10 @@ class Category implements ArrayAccess 'name' => 'name' ); + static function attributeMap() { + return self::$attributeMap; + } + /** * Array of attributes to setter functions (for deserialization of responses) * @var string[] @@ -73,6 +81,10 @@ class Category implements ArrayAccess 'name' => 'setName' ); + static function setters() { + return self::$setters; + } + /** * Array of attributes to getter functions (for serialization of requests) * @var string[] @@ -82,19 +94,20 @@ class Category implements ArrayAccess 'name' => 'getName' ); - + static function getters() { + return self::$getters; + } + /** * $id * @var int */ protected $id; - /** * $name * @var string */ protected $name; - /** * Constructor @@ -102,12 +115,12 @@ class Category implements ArrayAccess */ public function __construct(array $data = null) { + if ($data != null) { $this->id = $data["id"]; $this->name = $data["name"]; } } - /** * Gets id * @return int @@ -128,7 +141,6 @@ class Category implements ArrayAccess $this->id = $id; return $this; } - /** * Gets name * @return string @@ -149,7 +161,6 @@ class Category implements ArrayAccess $this->name = $name; return $this; } - /** * Returns true if offset exists. False otherwise. * @param integer $offset Offset @@ -197,10 +208,10 @@ class Category implements ArrayAccess */ public function __toString() { - if (defined('JSON_PRETTY_PRINT')) { + if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print return json_encode(\Swagger\Client\ObjectSerializer::sanitizeForSerialization($this), JSON_PRETTY_PRINT); - } else { - return json_encode(\Swagger\Client\ObjectSerializer::sanitizeForSerialization($this)); } + + 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 new file mode 100644 index 00000000000..d12bde293fd --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Dog.php @@ -0,0 +1,187 @@ + 'string' + ); + + static function swaggerTypes() { + return self::$swaggerTypes + parent::swaggerTypes(); + } + + /** + * Array of attributes where the key is the local name, and the value is the original name + * @var string[] + */ + static $attributeMap = array( + 'breed' => 'breed' + ); + + static function attributeMap() { + return parent::attributeMap() + self::$attributeMap; + } + + /** + * Array of attributes to setter functions (for deserialization of responses) + * @var string[] + */ + static $setters = array( + 'breed' => 'setBreed' + ); + + static function setters() { + return parent::setters() + self::$setters; + } + + /** + * Array of attributes to getter functions (for serialization of requests) + * @var string[] + */ + static $getters = array( + 'breed' => 'getBreed' + ); + + static function getters() { + return parent::getters() + self::$getters; + } + + /** + * $breed + * @var string + */ + protected $breed; + + /** + * Constructor + * @param mixed[] $data Associated array of property value initalizing the model + */ + public function __construct(array $data = null) + { + parent::__construct($data); + if ($data != null) { + $this->breed = $data["breed"]; + } + } + /** + * Gets breed + * @return string + */ + public function getBreed() + { + return $this->breed; + } + + /** + * Sets breed + * @param string $breed + * @return $this + */ + public function setBreed($breed) + { + + $this->breed = $breed; + return $this; + } + /** + * Returns true if offset exists. False otherwise. + * @param integer $offset Offset + * @return boolean + */ + public function offsetExists($offset) + { + return isset($this->$offset); + } + + /** + * Gets offset. + * @param integer $offset Offset + * @return mixed + */ + public function offsetGet($offset) + { + return $this->$offset; + } + + /** + * Sets value based on offset. + * @param integer $offset Offset + * @param mixed $value Value to be set + * @return void + */ + public function offsetSet($offset, $value) + { + $this->$offset = $value; + } + + /** + * Unsets offset. + * @param integer $offset Offset + * @return void + */ + public function offsetUnset($offset) + { + unset($this->$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/InlineResponse200.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/InlineResponse200.php index 321f400d0f4..c3bb9d03315 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/InlineResponse200.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/InlineResponse200.php @@ -59,6 +59,10 @@ class InlineResponse200 implements ArrayAccess 'photo_urls' => 'string[]' ); + 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[] @@ -72,6 +76,10 @@ class InlineResponse200 implements ArrayAccess 'photo_urls' => 'photoUrls' ); + static function attributeMap() { + return self::$attributeMap; + } + /** * Array of attributes to setter functions (for deserialization of responses) * @var string[] @@ -85,6 +93,10 @@ class InlineResponse200 implements ArrayAccess 'photo_urls' => 'setPhotoUrls' ); + static function setters() { + return self::$setters; + } + /** * Array of attributes to getter functions (for serialization of requests) * @var string[] @@ -98,43 +110,40 @@ class InlineResponse200 implements ArrayAccess 'photo_urls' => 'getPhotoUrls' ); - + static function getters() { + return self::$getters; + } + /** * $tags * @var \Swagger\Client\Model\Tag[] */ protected $tags; - /** * $id * @var int */ protected $id; - /** * $category * @var object */ protected $category; - /** * $status pet status in the store * @var string */ protected $status; - /** * $name * @var string */ protected $name; - /** * $photo_urls * @var string[] */ protected $photo_urls; - /** * Constructor @@ -142,6 +151,7 @@ class InlineResponse200 implements ArrayAccess */ public function __construct(array $data = null) { + if ($data != null) { $this->tags = $data["tags"]; $this->id = $data["id"]; @@ -151,7 +161,6 @@ class InlineResponse200 implements ArrayAccess $this->photo_urls = $data["photo_urls"]; } } - /** * Gets tags * @return \Swagger\Client\Model\Tag[] @@ -172,7 +181,6 @@ class InlineResponse200 implements ArrayAccess $this->tags = $tags; return $this; } - /** * Gets id * @return int @@ -193,7 +201,6 @@ class InlineResponse200 implements ArrayAccess $this->id = $id; return $this; } - /** * Gets category * @return object @@ -214,7 +221,6 @@ class InlineResponse200 implements ArrayAccess $this->category = $category; return $this; } - /** * Gets status * @return string @@ -238,7 +244,6 @@ class InlineResponse200 implements ArrayAccess $this->status = $status; return $this; } - /** * Gets name * @return string @@ -259,7 +264,6 @@ class InlineResponse200 implements ArrayAccess $this->name = $name; return $this; } - /** * Gets photo_urls * @return string[] @@ -280,7 +284,6 @@ class InlineResponse200 implements ArrayAccess $this->photo_urls = $photo_urls; return $this; } - /** * Returns true if offset exists. False otherwise. * @param integer $offset Offset @@ -328,10 +331,10 @@ class InlineResponse200 implements ArrayAccess */ public function __toString() { - if (defined('JSON_PRETTY_PRINT')) { + if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print return json_encode(\Swagger\Client\ObjectSerializer::sanitizeForSerialization($this), JSON_PRETTY_PRINT); - } else { - return json_encode(\Swagger\Client\ObjectSerializer::sanitizeForSerialization($this)); } + + 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 new file mode 100644 index 00000000000..a2b4d7691ed --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Model200Response.php @@ -0,0 +1,187 @@ + 'int' + ); + + static function swaggerTypes() { + return self::$swaggerTypes; + } + + /** + * Array of attributes where the key is the local name, and the value is the original name + * @var string[] + */ + static $attributeMap = array( + 'name' => 'name' + ); + + static function attributeMap() { + return self::$attributeMap; + } + + /** + * Array of attributes to setter functions (for deserialization of responses) + * @var string[] + */ + static $setters = array( + 'name' => 'setName' + ); + + static function setters() { + return self::$setters; + } + + /** + * Array of attributes to getter functions (for serialization of requests) + * @var string[] + */ + static $getters = array( + 'name' => 'getName' + ); + + static function getters() { + return self::$getters; + } + + /** + * $name + * @var int + */ + protected $name; + + /** + * Constructor + * @param mixed[] $data Associated array of property value initalizing the model + */ + public function __construct(array $data = null) + { + + if ($data != null) { + $this->name = $data["name"]; + } + } + /** + * Gets name + * @return int + */ + public function getName() + { + return $this->name; + } + + /** + * Sets name + * @param int $name + * @return $this + */ + public function setName($name) + { + + $this->name = $name; + return $this; + } + /** + * Returns true if offset exists. False otherwise. + * @param integer $offset Offset + * @return boolean + */ + public function offsetExists($offset) + { + return isset($this->$offset); + } + + /** + * Gets offset. + * @param integer $offset Offset + * @return mixed + */ + public function offsetGet($offset) + { + return $this->$offset; + } + + /** + * Sets value based on offset. + * @param integer $offset Offset + * @param mixed $value Value to be set + * @return void + */ + public function offsetSet($offset, $value) + { + $this->$offset = $value; + } + + /** + * Unsets offset. + * @param integer $offset Offset + * @return void + */ + public function offsetUnset($offset) + { + unset($this->$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/ObjectReturn.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ModelReturn.php similarity index 86% rename from samples/client/petstore/php/SwaggerClient-php/lib/Model/ObjectReturn.php rename to samples/client/petstore/php/SwaggerClient-php/lib/Model/ModelReturn.php index bb0dd842706..d92e61cdcd6 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ObjectReturn.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ModelReturn.php @@ -1,6 +1,6 @@ 'int' ); + 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[] @@ -62,6 +66,10 @@ class ObjectReturn implements ArrayAccess 'return' => 'return' ); + static function attributeMap() { + return self::$attributeMap; + } + /** * Array of attributes to setter functions (for deserialization of responses) * @var string[] @@ -70,6 +78,10 @@ class ObjectReturn implements ArrayAccess 'return' => 'setReturn' ); + static function setters() { + return self::$setters; + } + /** * Array of attributes to getter functions (for serialization of requests) * @var string[] @@ -78,13 +90,15 @@ class ObjectReturn implements ArrayAccess 'return' => 'getReturn' ); - + static function getters() { + return self::$getters; + } + /** * $return * @var int */ protected $return; - /** * Constructor @@ -92,11 +106,11 @@ class ObjectReturn implements ArrayAccess */ public function __construct(array $data = null) { + if ($data != null) { $this->return = $data["return"]; } } - /** * Gets return * @return int @@ -117,7 +131,6 @@ class ObjectReturn implements ArrayAccess $this->return = $return; return $this; } - /** * Returns true if offset exists. False otherwise. * @param integer $offset Offset @@ -165,10 +178,10 @@ class ObjectReturn implements ArrayAccess */ public function __toString() { - if (defined('JSON_PRETTY_PRINT')) { + if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print return json_encode(\Swagger\Client\ObjectSerializer::sanitizeForSerialization($this), JSON_PRETTY_PRINT); - } else { - return json_encode(\Swagger\Client\ObjectSerializer::sanitizeForSerialization($this)); } + + 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 new file mode 100644 index 00000000000..dbe1349ab88 --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Name.php @@ -0,0 +1,217 @@ + 'int', + 'snake_case' => 'int' + ); + + static function swaggerTypes() { + return self::$swaggerTypes; + } + + /** + * Array of attributes where the key is the local name, and the value is the original name + * @var string[] + */ + static $attributeMap = array( + 'name' => 'name', + 'snake_case' => 'snake_case' + ); + + static function attributeMap() { + return self::$attributeMap; + } + + /** + * Array of attributes to setter functions (for deserialization of responses) + * @var string[] + */ + static $setters = array( + 'name' => 'setName', + 'snake_case' => 'setSnakeCase' + ); + + static function setters() { + return self::$setters; + } + + /** + * Array of attributes to getter functions (for serialization of requests) + * @var string[] + */ + static $getters = array( + 'name' => 'getName', + 'snake_case' => 'getSnakeCase' + ); + + static function getters() { + return self::$getters; + } + + /** + * $name + * @var int + */ + protected $name; + /** + * $snake_case + * @var int + */ + protected $snake_case; + + /** + * Constructor + * @param mixed[] $data Associated array of property value initalizing the model + */ + public function __construct(array $data = null) + { + + if ($data != null) { + $this->name = $data["name"]; + $this->snake_case = $data["snake_case"]; + } + } + /** + * Gets name + * @return int + */ + public function getName() + { + return $this->name; + } + + /** + * Sets name + * @param int $name + * @return $this + */ + public function setName($name) + { + + $this->name = $name; + return $this; + } + /** + * Gets snake_case + * @return int + */ + public function getSnakeCase() + { + return $this->snake_case; + } + + /** + * Sets snake_case + * @param int $snake_case + * @return $this + */ + public function setSnakeCase($snake_case) + { + + $this->snake_case = $snake_case; + return $this; + } + /** + * Returns true if offset exists. False otherwise. + * @param integer $offset Offset + * @return boolean + */ + public function offsetExists($offset) + { + return isset($this->$offset); + } + + /** + * Gets offset. + * @param integer $offset Offset + * @return mixed + */ + public function offsetGet($offset) + { + return $this->$offset; + } + + /** + * Sets value based on offset. + * @param integer $offset Offset + * @param mixed $value Value to be set + * @return void + */ + public function offsetSet($offset, $value) + { + $this->$offset = $value; + } + + /** + * Unsets offset. + * @param integer $offset Offset + * @return void + */ + public function offsetUnset($offset) + { + unset($this->$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/Order.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Order.php index f2540992e2d..ae29bd61271 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Order.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Order.php @@ -59,6 +59,10 @@ class Order implements ArrayAccess 'complete' => 'bool' ); + 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[] @@ -72,6 +76,10 @@ class Order implements ArrayAccess 'complete' => 'complete' ); + static function attributeMap() { + return self::$attributeMap; + } + /** * Array of attributes to setter functions (for deserialization of responses) * @var string[] @@ -85,6 +93,10 @@ class Order implements ArrayAccess 'complete' => 'setComplete' ); + static function setters() { + return self::$setters; + } + /** * Array of attributes to getter functions (for serialization of requests) * @var string[] @@ -98,43 +110,40 @@ class Order implements ArrayAccess 'complete' => 'getComplete' ); - + static function getters() { + return self::$getters; + } + /** * $id * @var int */ protected $id; - /** * $pet_id * @var int */ protected $pet_id; - /** * $quantity * @var int */ protected $quantity; - /** * $ship_date * @var \DateTime */ protected $ship_date; - /** * $status Order Status * @var string */ protected $status; - /** * $complete * @var bool */ protected $complete; - /** * Constructor @@ -142,6 +151,7 @@ class Order implements ArrayAccess */ public function __construct(array $data = null) { + if ($data != null) { $this->id = $data["id"]; $this->pet_id = $data["pet_id"]; @@ -151,7 +161,6 @@ class Order implements ArrayAccess $this->complete = $data["complete"]; } } - /** * Gets id * @return int @@ -172,7 +181,6 @@ class Order implements ArrayAccess $this->id = $id; return $this; } - /** * Gets pet_id * @return int @@ -193,7 +201,6 @@ class Order implements ArrayAccess $this->pet_id = $pet_id; return $this; } - /** * Gets quantity * @return int @@ -214,7 +221,6 @@ class Order implements ArrayAccess $this->quantity = $quantity; return $this; } - /** * Gets ship_date * @return \DateTime @@ -235,7 +241,6 @@ class Order implements ArrayAccess $this->ship_date = $ship_date; return $this; } - /** * Gets status * @return string @@ -259,7 +264,6 @@ class Order implements ArrayAccess $this->status = $status; return $this; } - /** * Gets complete * @return bool @@ -280,7 +284,6 @@ class Order implements ArrayAccess $this->complete = $complete; return $this; } - /** * Returns true if offset exists. False otherwise. * @param integer $offset Offset @@ -328,10 +331,10 @@ class Order implements ArrayAccess */ public function __toString() { - if (defined('JSON_PRETTY_PRINT')) { + if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print return json_encode(\Swagger\Client\ObjectSerializer::sanitizeForSerialization($this), JSON_PRETTY_PRINT); - } else { - return json_encode(\Swagger\Client\ObjectSerializer::sanitizeForSerialization($this)); } + + 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 aa8c6d67a8f..7a790869349 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Pet.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Pet.php @@ -59,6 +59,10 @@ class Pet implements ArrayAccess 'status' => 'string' ); + 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[] @@ -72,6 +76,10 @@ class Pet implements ArrayAccess 'status' => 'status' ); + static function attributeMap() { + return self::$attributeMap; + } + /** * Array of attributes to setter functions (for deserialization of responses) * @var string[] @@ -85,6 +93,10 @@ class Pet implements ArrayAccess 'status' => 'setStatus' ); + static function setters() { + return self::$setters; + } + /** * Array of attributes to getter functions (for serialization of requests) * @var string[] @@ -98,43 +110,40 @@ class Pet implements ArrayAccess 'status' => 'getStatus' ); - + static function getters() { + return self::$getters; + } + /** * $id * @var int */ protected $id; - /** * $category * @var \Swagger\Client\Model\Category */ protected $category; - /** * $name * @var string */ protected $name; - /** * $photo_urls * @var string[] */ protected $photo_urls; - /** * $tags * @var \Swagger\Client\Model\Tag[] */ protected $tags; - /** * $status pet status in the store * @var string */ protected $status; - /** * Constructor @@ -142,6 +151,7 @@ class Pet implements ArrayAccess */ public function __construct(array $data = null) { + if ($data != null) { $this->id = $data["id"]; $this->category = $data["category"]; @@ -151,7 +161,6 @@ class Pet implements ArrayAccess $this->status = $data["status"]; } } - /** * Gets id * @return int @@ -172,7 +181,6 @@ class Pet implements ArrayAccess $this->id = $id; return $this; } - /** * Gets category * @return \Swagger\Client\Model\Category @@ -193,7 +201,6 @@ class Pet implements ArrayAccess $this->category = $category; return $this; } - /** * Gets name * @return string @@ -214,7 +221,6 @@ class Pet implements ArrayAccess $this->name = $name; return $this; } - /** * Gets photo_urls * @return string[] @@ -235,7 +241,6 @@ class Pet implements ArrayAccess $this->photo_urls = $photo_urls; return $this; } - /** * Gets tags * @return \Swagger\Client\Model\Tag[] @@ -256,7 +261,6 @@ class Pet implements ArrayAccess $this->tags = $tags; return $this; } - /** * Gets status * @return string @@ -280,7 +284,6 @@ class Pet implements ArrayAccess $this->status = $status; return $this; } - /** * Returns true if offset exists. False otherwise. * @param integer $offset Offset @@ -328,10 +331,10 @@ class Pet implements ArrayAccess */ public function __toString() { - if (defined('JSON_PRETTY_PRINT')) { + if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print return json_encode(\Swagger\Client\ObjectSerializer::sanitizeForSerialization($this), JSON_PRETTY_PRINT); - } else { - return json_encode(\Swagger\Client\ObjectSerializer::sanitizeForSerialization($this)); } + + 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 52de7d06863..25248d949cf 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/SpecialModelName.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/SpecialModelName.php @@ -54,6 +54,10 @@ class SpecialModelName implements ArrayAccess 'special_property_name' => 'int' ); + 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[] @@ -62,6 +66,10 @@ class SpecialModelName implements ArrayAccess 'special_property_name' => '$special[property.name]' ); + static function attributeMap() { + return self::$attributeMap; + } + /** * Array of attributes to setter functions (for deserialization of responses) * @var string[] @@ -70,6 +78,10 @@ class SpecialModelName implements ArrayAccess 'special_property_name' => 'setSpecialPropertyName' ); + static function setters() { + return self::$setters; + } + /** * Array of attributes to getter functions (for serialization of requests) * @var string[] @@ -78,13 +90,15 @@ class SpecialModelName implements ArrayAccess 'special_property_name' => 'getSpecialPropertyName' ); - + static function getters() { + return self::$getters; + } + /** * $special_property_name * @var int */ protected $special_property_name; - /** * Constructor @@ -92,11 +106,11 @@ class SpecialModelName implements ArrayAccess */ public function __construct(array $data = null) { + if ($data != null) { $this->special_property_name = $data["special_property_name"]; } } - /** * Gets special_property_name * @return int @@ -117,7 +131,6 @@ class SpecialModelName implements ArrayAccess $this->special_property_name = $special_property_name; return $this; } - /** * Returns true if offset exists. False otherwise. * @param integer $offset Offset @@ -165,10 +178,10 @@ class SpecialModelName implements ArrayAccess */ public function __toString() { - if (defined('JSON_PRETTY_PRINT')) { + if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print return json_encode(\Swagger\Client\ObjectSerializer::sanitizeForSerialization($this), JSON_PRETTY_PRINT); - } else { - return json_encode(\Swagger\Client\ObjectSerializer::sanitizeForSerialization($this)); } + + 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 7288e39eff9..8396a774e80 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Tag.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Tag.php @@ -55,6 +55,10 @@ class Tag implements ArrayAccess 'name' => 'string' ); + 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[] @@ -64,6 +68,10 @@ class Tag implements ArrayAccess 'name' => 'name' ); + static function attributeMap() { + return self::$attributeMap; + } + /** * Array of attributes to setter functions (for deserialization of responses) * @var string[] @@ -73,6 +81,10 @@ class Tag implements ArrayAccess 'name' => 'setName' ); + static function setters() { + return self::$setters; + } + /** * Array of attributes to getter functions (for serialization of requests) * @var string[] @@ -82,19 +94,20 @@ class Tag implements ArrayAccess 'name' => 'getName' ); - + static function getters() { + return self::$getters; + } + /** * $id * @var int */ protected $id; - /** * $name * @var string */ protected $name; - /** * Constructor @@ -102,12 +115,12 @@ class Tag implements ArrayAccess */ public function __construct(array $data = null) { + if ($data != null) { $this->id = $data["id"]; $this->name = $data["name"]; } } - /** * Gets id * @return int @@ -128,7 +141,6 @@ class Tag implements ArrayAccess $this->id = $id; return $this; } - /** * Gets name * @return string @@ -149,7 +161,6 @@ class Tag implements ArrayAccess $this->name = $name; return $this; } - /** * Returns true if offset exists. False otherwise. * @param integer $offset Offset @@ -197,10 +208,10 @@ class Tag implements ArrayAccess */ public function __toString() { - if (defined('JSON_PRETTY_PRINT')) { + if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print return json_encode(\Swagger\Client\ObjectSerializer::sanitizeForSerialization($this), JSON_PRETTY_PRINT); - } else { - return json_encode(\Swagger\Client\ObjectSerializer::sanitizeForSerialization($this)); } + + 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 7de225ec744..6e5c7de36f3 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/User.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/User.php @@ -61,6 +61,10 @@ class User implements ArrayAccess 'user_status' => 'int' ); + 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[] @@ -76,6 +80,10 @@ class User implements ArrayAccess 'user_status' => 'userStatus' ); + static function attributeMap() { + return self::$attributeMap; + } + /** * Array of attributes to setter functions (for deserialization of responses) * @var string[] @@ -91,6 +99,10 @@ class User implements ArrayAccess 'user_status' => 'setUserStatus' ); + static function setters() { + return self::$setters; + } + /** * Array of attributes to getter functions (for serialization of requests) * @var string[] @@ -106,55 +118,50 @@ class User implements ArrayAccess 'user_status' => 'getUserStatus' ); - + static function getters() { + return self::$getters; + } + /** * $id * @var int */ protected $id; - /** * $username * @var string */ protected $username; - /** * $first_name * @var string */ protected $first_name; - /** * $last_name * @var string */ protected $last_name; - /** * $email * @var string */ protected $email; - /** * $password * @var string */ protected $password; - /** * $phone * @var string */ protected $phone; - /** * $user_status User Status * @var int */ protected $user_status; - /** * Constructor @@ -162,6 +169,7 @@ class User implements ArrayAccess */ public function __construct(array $data = null) { + if ($data != null) { $this->id = $data["id"]; $this->username = $data["username"]; @@ -173,7 +181,6 @@ class User implements ArrayAccess $this->user_status = $data["user_status"]; } } - /** * Gets id * @return int @@ -194,7 +201,6 @@ class User implements ArrayAccess $this->id = $id; return $this; } - /** * Gets username * @return string @@ -215,7 +221,6 @@ class User implements ArrayAccess $this->username = $username; return $this; } - /** * Gets first_name * @return string @@ -236,7 +241,6 @@ class User implements ArrayAccess $this->first_name = $first_name; return $this; } - /** * Gets last_name * @return string @@ -257,7 +261,6 @@ class User implements ArrayAccess $this->last_name = $last_name; return $this; } - /** * Gets email * @return string @@ -278,7 +281,6 @@ class User implements ArrayAccess $this->email = $email; return $this; } - /** * Gets password * @return string @@ -299,7 +301,6 @@ class User implements ArrayAccess $this->password = $password; return $this; } - /** * Gets phone * @return string @@ -320,7 +321,6 @@ class User implements ArrayAccess $this->phone = $phone; return $this; } - /** * Gets user_status * @return int @@ -341,7 +341,6 @@ class User implements ArrayAccess $this->user_status = $user_status; return $this; } - /** * Returns true if offset exists. False otherwise. * @param integer $offset Offset @@ -389,10 +388,10 @@ class User implements ArrayAccess */ public function __toString() { - if (defined('JSON_PRETTY_PRINT')) { + if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print return json_encode(\Swagger\Client\ObjectSerializer::sanitizeForSerialization($this), JSON_PRETTY_PRINT); - } else { - return json_encode(\Swagger\Client\ObjectSerializer::sanitizeForSerialization($this)); } + + 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 3ad09a2cd06..3adaa899f5f 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php @@ -55,28 +55,26 @@ class ObjectSerializer public static function sanitizeForSerialization($data) { if (is_scalar($data) || null === $data) { - $sanitized = $data; + return $data; } elseif ($data instanceof \DateTime) { - $sanitized = $data->format(\DateTime::ISO8601); + return $data->format(\DateTime::ATOM); } elseif (is_array($data)) { foreach ($data as $property => $value) { $data[$property] = self::sanitizeForSerialization($value); } - $sanitized = $data; + return $data; } elseif (is_object($data)) { $values = array(); - foreach (array_keys($data::$swaggerTypes) as $property) { - $getter = $data::$getters[$property]; + foreach (array_keys($data::swaggerTypes()) as $property) { + $getter = $data::getters()[$property]; if ($data->$getter() !== null) { - $values[$data::$attributeMap[$property]] = self::sanitizeForSerialization($data->$getter()); + $values[$data::attributeMap()[$property]] = self::sanitizeForSerialization($data->$getter()); } } - $sanitized = (object)$values; + return (object)$values; } else { - $sanitized = (string)$data; + return (string)$data; } - - return $sanitized; } /** @@ -172,7 +170,7 @@ class ObjectSerializer public function toString($value) { if ($value instanceof \DateTime) { // datetime in ISO8601 format - return $value->format(\DateTime::ISO8601); + return $value->format(\DateTime::ATOM); } else { return $value; } @@ -214,16 +212,17 @@ 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 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 */ - public static function deserialize($data, $class, $httpHeaders=null) + public static function deserialize($data, $class, $httpHeaders=null, $discriminator=null) { if (null === $data) { - $deserialized = null; + return null; } elseif (substr($class, 0, 4) === 'map[') { // for associative array e.g. map[string,int] $inner = substr($class, 4, -1); $deserialized = array(); @@ -231,24 +230,35 @@ class ObjectSerializer $subClass_array = explode(',', $inner, 2); $subClass = $subClass_array[1]; foreach ($data as $key => $value) { - $deserialized[$key] = self::deserialize($value, $subClass); + $deserialized[$key] = self::deserialize($value, $subClass, null, $discriminator); } } + return $deserialized; } elseif (strcasecmp(substr($class, -2), '[]') == 0) { $subClass = substr($class, 0, -2); $values = array(); foreach ($data as $key => $value) { - $values[] = self::deserialize($value, $subClass); + $values[] = self::deserialize($value, $subClass, null, $discriminator); } - $deserialized = $values; + return $values; } elseif ($class === 'object') { settype($data, 'array'); - $deserialized = $data; + return $data; } elseif ($class === '\DateTime') { - $deserialized = new \DateTime($data); + // Some API's return an invalid, empty string as a + // date-time property. DateTime::__construct() will return + // the current time for empty input which is probably not + // what is meant. The invalid empty string is probably to + // be interpreted as a missing field/value. Let's handle + // this graceful. + if (!empty($data)) { + return new \DateTime($data); + } else { + return null; + } } elseif (in_array($class, array('integer', 'int', 'void', 'number', 'object', 'double', 'float', 'byte', 'DateTime', 'string', 'mixed', 'boolean', 'bool'))) { settype($data, $class); - $deserialized = $data; + return $data; } elseif ($class === '\SplFileObject') { // determine file name if (array_key_exists('Content-Disposition', $httpHeaders) && preg_match('/inline; filename=[\'"]?([^\'"\s]+)[\'"]?$/i', $httpHeaders['Content-Disposition'], $match)) { @@ -259,24 +269,30 @@ class ObjectSerializer $deserialized = new \SplFileObject($filename, "w"); $byte_written = $deserialized->fwrite($data); error_log("[INFO] Written $byte_written byte to $filename. Please move the file to a proper folder or delete the temp file after processing.\n", 3, Configuration::getDefaultConfiguration()->getDebugFile()); - + return $deserialized; + } else { + // If a discriminator is defined and points to a valid subclass, use it. + if (!empty($discriminator) && isset($data->{$discriminator}) && is_string($data->{$discriminator})) { + $subclass = '\Swagger\Client\Model\\' . $data->{$discriminator}; + if (is_subclass_of($subclass, $class)) { + $class = $subclass; + } + } $instance = new $class(); - foreach ($instance::$swaggerTypes as $property => $type) { - $propertySetter = $instance::$setters[$property]; + foreach ($instance::swaggerTypes() as $property => $type) { + $propertySetter = $instance::setters()[$property]; - if (!isset($propertySetter) || !isset($data->{$instance::$attributeMap[$property]})) { + if (!isset($propertySetter) || !isset($data->{$instance::attributeMap()[$property]})) { continue; } - $propertyValue = $data->{$instance::$attributeMap[$property]}; + $propertyValue = $data->{$instance::attributeMap()[$property]}; if (isset($propertyValue)) { - $instance->$propertySetter(self::deserialize($propertyValue, $type)); + $instance->$propertySetter(self::deserialize($propertyValue, $type, null, $discriminator)); } } - $deserialized = $instance; + return $instance; } - - return $deserialized; } } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Tests/ObjectReturnTest.php b/samples/client/petstore/php/SwaggerClient-php/lib/Tests/AnimalTest.php similarity index 90% rename from samples/client/petstore/php/SwaggerClient-php/lib/Tests/ObjectReturnTest.php rename to samples/client/petstore/php/SwaggerClient-php/lib/Tests/AnimalTest.php index de06d6e7a9d..f66fc54f211 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Tests/ObjectReturnTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Tests/AnimalTest.php @@ -1,6 +1,6 @@ setTags(array($tag)); $new_pet->setCategory($category); - $pet_api = new Swagger\Client\Api\PetAPI(); + $pet_api = new Swagger\Client\Api\PetApi(); // add a new pet (model) $add_response = $pet_api->addPet($new_pet); } @@ -74,14 +74,14 @@ class PetApiTest extends \PHPUnit_Framework_TestCase $defaultHeader = $api_client->getConfig()->getDefaultHeaders(); $this->assertFalse(isset($defaultHeader['test2'])); - $pet_api2 = new Swagger\Client\Api\PetAPI(); + $pet_api2 = new Swagger\Client\Api\PetApi(); $config3 = new Swagger\Client\Configuration(); $apiClient3 = new Swagger\Client\ApiClient($config3); $apiClient3->getConfig()->setUserAgent('api client 3'); $config4 = new Swagger\Client\Configuration(); $apiClient4 = new Swagger\Client\ApiClient($config4); $apiClient4->getConfig()->setUserAgent('api client 4'); - $pet_api3 = new Swagger\Client\Api\PetAPI($apiClient3); + $pet_api3 = new Swagger\Client\Api\PetApi($apiClient3); // 2 different api clients are not the same $this->assertNotEquals($apiClient3, $apiClient4); @@ -98,7 +98,7 @@ class PetApiTest extends \PHPUnit_Framework_TestCase { // initialize the API client without host $pet_id = 10005; // ID of pet that needs to be fetched - $pet_api = new Swagger\Client\Api\PetAPI(); + $pet_api = new Swagger\Client\Api\PetApi(); $pet_api->getApiClient()->getConfig()->setApiKey('api_key', '111222333444555'); // return Pet (model) $response = $pet_api->getPetById($pet_id); @@ -116,7 +116,7 @@ class PetApiTest extends \PHPUnit_Framework_TestCase { // initialize the API client without host $pet_id = 10005; // ID of pet that needs to be fetched - $pet_api = new Swagger\Client\Api\PetAPI(); + $pet_api = new Swagger\Client\Api\PetApi(); $pet_api->getApiClient()->getConfig()->setApiKey('api_key', '111222333444555'); // return Pet (inline model) $response = $pet_api->getPetByIdInObject($pet_id); @@ -139,7 +139,7 @@ class PetApiTest extends \PHPUnit_Framework_TestCase { // initialize the API client without host $pet_id = 10005; // ID of pet that needs to be fetched - $pet_api = new Swagger\Client\Api\PetAPI(); + $pet_api = new Swagger\Client\Api\PetApi(); $pet_api->getApiClient()->getConfig()->setApiKey('api_key', '111222333444555'); // return Pet (model) list($response, $status_code, $response_headers) = $pet_api->getPetByIdWithHttpInfo($pet_id); @@ -159,7 +159,7 @@ class PetApiTest extends \PHPUnit_Framework_TestCase // initialize the API client $config = (new Swagger\Client\Configuration())->setHost('http://petstore.swagger.io/v2'); $api_client = new Swagger\Client\ApiClient($config); - $pet_api = new Swagger\Client\Api\PetAPI($api_client); + $pet_api = new Swagger\Client\Api\PetApi($api_client); // return Pet (model) $response = $pet_api->findPetsByStatus("available"); $this->assertGreaterThan(0, count($response)); // at least one object returned @@ -179,7 +179,7 @@ class PetApiTest extends \PHPUnit_Framework_TestCase // initialize the API client $config = (new Swagger\Client\Configuration())->setHost('http://petstore.swagger.io/v2'); $api_client = new Swagger\Client\ApiClient($config); - $pet_api = new Swagger\Client\Api\PetAPI($api_client); + $pet_api = new Swagger\Client\Api\PetApi($api_client); // return Pet (model) $response = $pet_api->findPetsByTags("test php tag"); $this->assertGreaterThan(0, count($response)); // at least one object returned @@ -200,7 +200,7 @@ class PetApiTest extends \PHPUnit_Framework_TestCase $config = (new Swagger\Client\Configuration())->setHost('http://petstore.swagger.io/v2'); $api_client = new Swagger\Client\ApiClient($config); $pet_id = 10001; // ID of pet that needs to be fetched - $pet_api = new Swagger\Client\Api\PetAPI($api_client); + $pet_api = new Swagger\Client\Api\PetApi($api_client); // create updated pet object $updated_pet = new Swagger\Client\Model\Pet; $updated_pet->setId($pet_id); @@ -224,7 +224,7 @@ class PetApiTest extends \PHPUnit_Framework_TestCase $config = (new Swagger\Client\Configuration())->setHost('http://petstore.swagger.io/v2'); $api_client = new Swagger\Client\ApiClient($config); $pet_id = 10001; // ID of pet that needs to be fetched - $pet_api = new Swagger\Client\Api\PetAPI($api_client); + $pet_api = new Swagger\Client\Api\PetApi($api_client); // update Pet (form) list($update_response, $status_code, $http_headers) = $pet_api->updatePetWithFormWithHttpInfo($pet_id, 'update pet with form with http info'); // return nothing (void) @@ -243,7 +243,7 @@ class PetApiTest extends \PHPUnit_Framework_TestCase $config = (new Swagger\Client\Configuration())->setHost('http://petstore.swagger.io/v2'); $api_client = new Swagger\Client\ApiClient($config); $pet_id = 10001; // ID of pet that needs to be fetched - $pet_api = new Swagger\Client\Api\PetAPI($api_client); + $pet_api = new Swagger\Client\Api\PetApi($api_client); // update Pet (form) $update_response = $pet_api->updatePetWithForm($pet_id, 'update pet with form', 'sold'); // return nothing (void) @@ -264,7 +264,7 @@ class PetApiTest extends \PHPUnit_Framework_TestCase $new_pet = new Swagger\Client\Model\Pet; $new_pet->setId($new_pet_id); $new_pet->setName("PHP Unit Test 2"); - $pet_api = new Swagger\Client\Api\PetAPI($api_client); + $pet_api = new Swagger\Client\Api\PetApi($api_client); // add a new pet (model) $add_response = $pet_api->addPet($new_pet); // return nothing (void) @@ -298,7 +298,7 @@ class PetApiTest extends \PHPUnit_Framework_TestCase $new_pet->setTags(array($tag)); $new_pet->setCategory($category); - $pet_api = new Swagger\Client\Api\PetAPI($api_client); + $pet_api = new Swagger\Client\Api\PetApi($api_client); // add a new pet (model) $object_serializer = new Swagger\Client\ObjectSerializer(); $pet_json_string = json_encode($object_serializer->sanitizeForSerialization($new_pet)); @@ -319,7 +319,7 @@ class PetApiTest extends \PHPUnit_Framework_TestCase // initialize the API client $config = (new Swagger\Client\Configuration())->setHost('http://petstore.swagger.io/v2'); $api_client = new Swagger\Client\ApiClient($config); - $pet_api = new Swagger\Client\Api\PetAPI($api_client); + $pet_api = new Swagger\Client\Api\PetApi($api_client); // upload file $pet_id = 10001; $add_response = $pet_api->uploadFile($pet_id, "test meta", "./composer.json"); @@ -349,7 +349,7 @@ class PetApiTest extends \PHPUnit_Framework_TestCase $config = new Swagger\Client\Configuration(); $config->setHost('http://petstore.swagger.io/v2'); $api_client = new Swagger\Client\APIClient($config); - $pet_api = new Swagger\Client\Api\PetAPI($api_client); + $pet_api = new Swagger\Client\Api\PetApi($api_client); // test getPetByIdWithByteArray $pet_id = 10005; $bytes = $pet_api->petPetIdtestingByteArraytrueGet($pet_id); @@ -375,6 +375,33 @@ class PetApiTest extends \PHPUnit_Framework_TestCase } + // test inheritance in the model + public function testInheritance() + { + $new_dog = new Swagger\Client\Model\Dog; + // the object should be an instance of the derived class + $this->assertInstanceOf('Swagger\Client\Model\Dog', $new_dog); + // the object should also be an instance of the parent class + $this->assertInstanceOf('Swagger\Client\Model\Animal', $new_dog); + } + + // test inheritance constructor is working with data + // initialization + public function testInheritanceConstructorDataInitialization() + { + // initialize the object with data in the constructor + $data = array( + 'class_name' => 'Dog', + 'breed' => 'Great Dane' + ); + $new_dog = new Swagger\Client\Model\Dog($data); + + // the property on the derived class should be set + $this->assertSame('Great Dane', $new_dog->getBreed()); + // the property on the parent class should be set + $this->assertSame('Dog', $new_dog->getClassName()); + } + } ?> diff --git a/samples/client/petstore/python/.gitignore b/samples/client/petstore/python/.gitignore new file mode 100644 index 00000000000..1dbc687de01 --- /dev/null +++ b/samples/client/petstore/python/.gitignore @@ -0,0 +1,62 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +env/ +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +*.egg-info/ +.installed.cfg +*.egg + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*,cover +.hypothesis/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +#Ipython Notebook +.ipynb_checkpoints diff --git a/samples/client/petstore/python/README.md b/samples/client/petstore/python/README.md index 463bbb37a18..9e99ae27370 100644 --- a/samples/client/petstore/python/README.md +++ b/samples/client/petstore/python/README.md @@ -1,28 +1,49 @@ +# swagger_client +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 + +This Python package is automatically generated by the [Swagger Codegen](https://github.com/swagger-api/swagger-codegen) project: + +- API verion: 1.0.0 +- Package version: +- Build date: 2016-03-30T17:18:44.943+08:00 +- Build package: class io.swagger.codegen.languages.PythonClientCodegen + ## Requirements. -Python 2.7 and later. -## Setuptools -You can install the bindings via [Setuptools](http://pypi.python.org/pypi/setuptools). +Python 2.7 and 3.4+ + +## Installation & Usage +### pip install + +If the python package is hosted on Github, you can install directly from Github ```sh -python setup.py install +pip install git+https://github.com/YOUR_GIT_USR_ID/YOUR_GIT_REPO_ID.git +``` +(you may need to run the command with root permission: `sudo pip install git+https://github.com/YOUR_GIT_USR_ID/YOUR_GIT_REPO_ID.git`) + +Import the pacakge: +```python +import swagger_client ``` -Or you can install from Github via pip: +### Setuptools + +Install via [Setuptools](http://pypi.python.org/pypi/setuptools). ```sh -pip install git+https://github.com/geekerzp/swagger_client.git +python setup.py install --user ``` +(or `sudo python setup.py install` to install the package for all users) -To use the bindings, import the pacakge: - +Import the pacakge: ```python import swagger_client ``` -## Manual Installation -If you do not wish to use setuptools, you can download the latest release. -Then, to use the bindings, import the package: +### Manual Installation + +Download the latest release to the project folder (e.g. ./path/to/swagger_client) and import the package: ```python import path.to.swagger_client @@ -30,44 +51,126 @@ import path.to.swagger_client ## Getting Started -TODO +Please follow the [installation procedure](#installation--usage) and then run the following: -## Documentation +```python +import time +import swagger_client +from swagger_client.rest import ApiException +from pprint import pprint -TODO +# Configure OAuth2 access token for authorization: petstore_auth +swagger_client.configuration.access_token = 'YOUR_ACCESS_TOKEN' +# create an instance of the API class +api_instance = swagger_client.PetApi +body = swagger_client.Pet() # Pet | Pet object that needs to be added to the store (optional) -## Tests - -(Please make sure you have [virtualenv](http://docs.python-guide.org/en/latest/dev/virtualenvs/) installed) - - Execute the following command to run the tests in the current Python (v2 or v3) environment: - -```sh -$ make test -[... magically installs dependencies and runs tests on your virtualenv] -Ran 7 tests in 19.289s - -OK -``` -or +try: + # Add a new pet to the store + api_instance.add_pet(body=body); +except ApiException as e: + print "Exception when calling PetApi->add_pet: %s\n" % e ``` -$ mvn integration-test -rf :PythonPetstoreClientTests -Using 2195432783 as seed -[INFO] ------------------------------------------------------------------------ -[INFO] BUILD SUCCESS -[INFO] ------------------------------------------------------------------------ -[INFO] Total time: 37.594 s -[INFO] Finished at: 2015-05-16T18:00:35+08:00 -[INFO] Final Memory: 11M/156M -[INFO] ------------------------------------------------------------------------ -``` -If you want to run the tests in all the python platforms: -```sh -$ make test-all -[... tox creates a virtualenv for every platform and runs tests inside of each] - py27: commands succeeded - py34: commands succeeded - congratulations :) -``` +## Documentation for API Endpoints + +All URIs are relative to *http://petstore.swagger.io/v2* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +*PetApi* | [**add_pet**](docs/PetApi.md#add_pet) | **POST** /pet | Add a new pet to the store +*PetApi* | [**add_pet_using_byte_array**](docs/PetApi.md#add_pet_using_byte_array) | **POST** /pet?testing_byte_array=true | Fake endpoint to test byte array in body parameter for adding a new pet to the store +*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 +*PetApi* | [**find_pets_by_tags**](docs/PetApi.md#find_pets_by_tags) | **GET** /pet/findByTags | Finds Pets by tags +*PetApi* | [**get_pet_by_id**](docs/PetApi.md#get_pet_by_id) | **GET** /pet/{petId} | Find pet by ID +*PetApi* | [**get_pet_by_id_in_object**](docs/PetApi.md#get_pet_by_id_in_object) | **GET** /pet/{petId}?response=inline_arbitrary_object | Fake endpoint to test inline arbitrary object return by 'Find pet by ID' +*PetApi* | [**pet_pet_idtesting_byte_arraytrue_get**](docs/PetApi.md#pet_pet_idtesting_byte_arraytrue_get) | **GET** /pet/{petId}?testing_byte_array=true | Fake endpoint to test byte array return by 'Find pet by ID' +*PetApi* | [**update_pet**](docs/PetApi.md#update_pet) | **PUT** /pet | Update an existing pet +*PetApi* | [**update_pet_with_form**](docs/PetApi.md#update_pet_with_form) | **POST** /pet/{petId} | Updates a pet in the store with form data +*PetApi* | [**upload_file**](docs/PetApi.md#upload_file) | **POST** /pet/{petId}/uploadImage | uploads an image +*StoreApi* | [**delete_order**](docs/StoreApi.md#delete_order) | **DELETE** /store/order/{orderId} | Delete purchase order by ID +*StoreApi* | [**find_orders_by_status**](docs/StoreApi.md#find_orders_by_status) | **GET** /store/findByStatus | Finds orders by status +*StoreApi* | [**get_inventory**](docs/StoreApi.md#get_inventory) | **GET** /store/inventory | Returns pet inventories by status +*StoreApi* | [**get_inventory_in_object**](docs/StoreApi.md#get_inventory_in_object) | **GET** /store/inventory?response=arbitrary_object | Fake endpoint to test arbitrary object return by 'Get inventory' +*StoreApi* | [**get_order_by_id**](docs/StoreApi.md#get_order_by_id) | **GET** /store/order/{orderId} | Find purchase order by ID +*StoreApi* | [**place_order**](docs/StoreApi.md#place_order) | **POST** /store/order | Place an order for a pet +*UserApi* | [**create_user**](docs/UserApi.md#create_user) | **POST** /user | Create user +*UserApi* | [**create_users_with_array_input**](docs/UserApi.md#create_users_with_array_input) | **POST** /user/createWithArray | Creates list of users with given input array +*UserApi* | [**create_users_with_list_input**](docs/UserApi.md#create_users_with_list_input) | **POST** /user/createWithList | Creates list of users with given input array +*UserApi* | [**delete_user**](docs/UserApi.md#delete_user) | **DELETE** /user/{username} | Delete user +*UserApi* | [**get_user_by_name**](docs/UserApi.md#get_user_by_name) | **GET** /user/{username} | Get user by user name +*UserApi* | [**login_user**](docs/UserApi.md#login_user) | **GET** /user/login | Logs user into the system +*UserApi* | [**logout_user**](docs/UserApi.md#logout_user) | **GET** /user/logout | Logs out current logged in user session +*UserApi* | [**update_user**](docs/UserApi.md#update_user) | **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 + + +## test_api_key_header + +- **Type**: API key +- **API key parameter name**: test_api_key_header +- **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_client_secret + +- **Type**: API key +- **API key parameter name**: x-test_api_client_secret +- **Location**: HTTP header + +## test_api_client_id + +- **Type**: API key +- **API key parameter name**: x-test_api_client_id +- **Location**: HTTP header + +## test_api_key_query + +- **Type**: API key +- **API key parameter name**: test_api_key_query +- **Location**: URL query string + +## 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 + + +## Author + +apiteam@swagger.io + diff --git a/samples/client/petstore/python/dev-requirements.txt b/samples/client/petstore/python/dev-requirements.txt new file mode 100644 index 00000000000..01a2e25f1c7 --- /dev/null +++ b/samples/client/petstore/python/dev-requirements.txt @@ -0,0 +1,4 @@ +nose +tox +coverage +randomize diff --git a/samples/client/petstore/python/docs/Animal.md b/samples/client/petstore/python/docs/Animal.md new file mode 100644 index 00000000000..ceb8002b4ab --- /dev/null +++ b/samples/client/petstore/python/docs/Animal.md @@ -0,0 +1,10 @@ +# Animal + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**class_name** | **str** | | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/python/docs/Cat.md b/samples/client/petstore/python/docs/Cat.md new file mode 100644 index 00000000000..fd4cd174fc2 --- /dev/null +++ b/samples/client/petstore/python/docs/Cat.md @@ -0,0 +1,11 @@ +# Cat + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**class_name** | **str** | | +**declawed** | **bool** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/python/docs/Category.md b/samples/client/petstore/python/docs/Category.md new file mode 100644 index 00000000000..7f453539bf8 --- /dev/null +++ b/samples/client/petstore/python/docs/Category.md @@ -0,0 +1,11 @@ +# Category + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **int** | | [optional] +**name** | **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/Dog.md b/samples/client/petstore/python/docs/Dog.md new file mode 100644 index 00000000000..a4b38a70335 --- /dev/null +++ b/samples/client/petstore/python/docs/Dog.md @@ -0,0 +1,11 @@ +# Dog + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**class_name** | **str** | | +**breed** | **str** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/python/docs/InlineResponse200.md b/samples/client/petstore/python/docs/InlineResponse200.md new file mode 100644 index 00000000000..ec171d3a5d2 --- /dev/null +++ b/samples/client/petstore/python/docs/InlineResponse200.md @@ -0,0 +1,15 @@ +# InlineResponse200 + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**tags** | [**list[Tag]**](Tag.md) | | [optional] +**id** | **int** | | +**category** | **object** | | [optional] +**status** | **str** | pet status in the store | [optional] +**name** | **str** | | [optional] +**photo_urls** | **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/Model200Response.md b/samples/client/petstore/python/docs/Model200Response.md new file mode 100644 index 00000000000..e29747a87e7 --- /dev/null +++ b/samples/client/petstore/python/docs/Model200Response.md @@ -0,0 +1,10 @@ +# Model200Response + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **int** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/python/docs/ModelReturn.md b/samples/client/petstore/python/docs/ModelReturn.md new file mode 100644 index 00000000000..2b03798e301 --- /dev/null +++ b/samples/client/petstore/python/docs/ModelReturn.md @@ -0,0 +1,10 @@ +# ModelReturn + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**_return** | **int** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/python/docs/Name.md b/samples/client/petstore/python/docs/Name.md new file mode 100644 index 00000000000..26473221c32 --- /dev/null +++ b/samples/client/petstore/python/docs/Name.md @@ -0,0 +1,11 @@ +# Name + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **int** | | [optional] +**snake_case** | **int** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/python/docs/Order.md b/samples/client/petstore/python/docs/Order.md new file mode 100644 index 00000000000..4499eaa976d --- /dev/null +++ b/samples/client/petstore/python/docs/Order.md @@ -0,0 +1,15 @@ +# Order + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **int** | | [optional] +**pet_id** | **int** | | [optional] +**quantity** | **int** | | [optional] +**ship_date** | **datetime** | | [optional] +**status** | **str** | Order Status | [optional] +**complete** | **bool** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/python/docs/Pet.md b/samples/client/petstore/python/docs/Pet.md new file mode 100644 index 00000000000..9e15090300f --- /dev/null +++ b/samples/client/petstore/python/docs/Pet.md @@ -0,0 +1,15 @@ +# Pet + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **int** | | [optional] +**category** | [**Category**](Category.md) | | [optional] +**name** | **str** | | +**photo_urls** | **list[str]** | | +**tags** | [**list[Tag]**](Tag.md) | | [optional] +**status** | **str** | 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/python/docs/PetApi.md b/samples/client/petstore/python/docs/PetApi.md new file mode 100644 index 00000000000..3349a3cb7d4 --- /dev/null +++ b/samples/client/petstore/python/docs/PetApi.md @@ -0,0 +1,596 @@ +# swagger_client\PetApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**add_pet**](PetApi.md#add_pet) | **POST** /pet | Add a new pet to the store +[**add_pet_using_byte_array**](PetApi.md#add_pet_using_byte_array) | **POST** /pet?testing_byte_array=true | Fake endpoint to test byte array in body parameter for adding a new pet to the store +[**delete_pet**](PetApi.md#delete_pet) | **DELETE** /pet/{petId} | Deletes a pet +[**find_pets_by_status**](PetApi.md#find_pets_by_status) | **GET** /pet/findByStatus | Finds Pets by status +[**find_pets_by_tags**](PetApi.md#find_pets_by_tags) | **GET** /pet/findByTags | Finds Pets by tags +[**get_pet_by_id**](PetApi.md#get_pet_by_id) | **GET** /pet/{petId} | Find pet by ID +[**get_pet_by_id_in_object**](PetApi.md#get_pet_by_id_in_object) | **GET** /pet/{petId}?response=inline_arbitrary_object | Fake endpoint to test inline arbitrary object return by 'Find pet by ID' +[**pet_pet_idtesting_byte_arraytrue_get**](PetApi.md#pet_pet_idtesting_byte_arraytrue_get) | **GET** /pet/{petId}?testing_byte_array=true | Fake endpoint to test byte array return by 'Find pet by ID' +[**update_pet**](PetApi.md#update_pet) | **PUT** /pet | Update an existing pet +[**update_pet_with_form**](PetApi.md#update_pet_with_form) | **POST** /pet/{petId} | Updates a pet in the store with form data +[**upload_file**](PetApi.md#upload_file) | **POST** /pet/{petId}/uploadImage | uploads an image + + +# **add_pet** +> add_pet(body=body) + +Add a new pet to the store + + + +### Example +```python +import swagger_client +from swagger_client.rest import ApiException +from pprint import pprint +import time + + +# Configure OAuth2 access token for authorization: petstore_auth +swagger_client.configuration.access_token = 'YOUR_ACCESS_TOKEN' + +# create an instance of the API class +api_instance = swagger_client.PetApi() +body = swagger_client.Pet() # Pet | Pet object that needs to be added to the store (optional) + +try: + # Add a new pet to the store + api_instance.add_pet(body=body); +except ApiException as e: + print "Exception when calling PetApi->add_pet: %s\n" % e +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | [optional] + +### Return type + +void (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP reuqest headers + + - **Content-Type**: application/json, application/xml + - **Accept**: application/json, application/xml + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **add_pet_using_byte_array** +> add_pet_using_byte_array(body=body) + +Fake endpoint to test byte array in body parameter for adding a new pet to the store + + + +### Example +```python +import swagger_client +from swagger_client.rest import ApiException +from pprint import pprint +import time + + +# Configure OAuth2 access token for authorization: petstore_auth +swagger_client.configuration.access_token = 'YOUR_ACCESS_TOKEN' + +# create an instance of the API class +api_instance = swagger_client.PetApi() +body = 'B' # str | Pet object in the form of byte array (optional) + +try: + # Fake endpoint to test byte array in body parameter for adding a new pet to the store + api_instance.add_pet_using_byte_array(body=body); +except ApiException as e: + print "Exception when calling PetApi->add_pet_using_byte_array: %s\n" % e +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | **str**| Pet object in the form of byte array | [optional] + +### Return type + +void (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP reuqest headers + + - **Content-Type**: application/json, application/xml + - **Accept**: application/json, application/xml + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **delete_pet** +> delete_pet(pet_id, api_key=api_key) + +Deletes a pet + + + +### Example +```python +import swagger_client +from swagger_client.rest import ApiException +from pprint import pprint +import time + + +# Configure OAuth2 access token for authorization: petstore_auth +swagger_client.configuration.access_token = 'YOUR_ACCESS_TOKEN' + +# create an instance of the API class +api_instance = swagger_client.PetApi() +pet_id = 789 # int | Pet id to delete +api_key = 'api_key_example' # str | (optional) + +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 +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **pet_id** | **int**| Pet id to delete | + **api_key** | **str**| | [optional] + +### Return type + +void (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **find_pets_by_status** +> list[Pet] find_pets_by_status(status=status) + +Finds Pets by status + +Multiple status values can be provided with comma separated strings + +### Example +```python +import swagger_client +from swagger_client.rest import ApiException +from pprint import pprint +import time + + +# Configure OAuth2 access token for authorization: petstore_auth +swagger_client.configuration.access_token = 'YOUR_ACCESS_TOKEN' + +# create an instance of the API class +api_instance = swagger_client.PetApi() +status = ['available'] # list[str] | Status values that need to be considered for query (optional) (default to available) + +try: + # Finds Pets by status + api_response = api_instance.find_pets_by_status(status=status); + pprint(api_response) +except ApiException as e: + print "Exception when calling PetApi->find_pets_by_status: %s\n" % e +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **status** | [**list[str]**](str.md)| Status values that need to be considered for query | [optional] [default to available] + +### Return type + +[**list[Pet]**](Pet.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **find_pets_by_tags** +> list[Pet] find_pets_by_tags(tags=tags) + +Finds Pets by tags + +Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + +### Example +```python +import swagger_client +from swagger_client.rest import ApiException +from pprint import pprint +import time + + +# Configure OAuth2 access token for authorization: petstore_auth +swagger_client.configuration.access_token = 'YOUR_ACCESS_TOKEN' + +# create an instance of the API class +api_instance = swagger_client.PetApi() +tags = ['tags_example'] # list[str] | Tags to filter by (optional) + +try: + # Finds Pets by tags + api_response = api_instance.find_pets_by_tags(tags=tags); + pprint(api_response) +except ApiException as e: + print "Exception when calling PetApi->find_pets_by_tags: %s\n" % e +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **tags** | [**list[str]**](str.md)| Tags to filter by | [optional] + +### Return type + +[**list[Pet]**](Pet.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **get_pet_by_id** +> Pet get_pet_by_id(pet_id) + +Find pet by ID + +Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + +### Example +```python +import swagger_client +from swagger_client.rest import ApiException +from pprint import pprint +import time + + +# Configure API key authorization: api_key +swagger_client.configuration.api_key['api_key'] = 'YOUR_API_KEY'; +# Uncomment below to setup prefix (e.g. BEARER) for API key, if needed +# swagger_client.configuration.api_key_prefix['api_key'] = 'BEARER' +# Configure OAuth2 access token for authorization: petstore_auth +swagger_client.configuration.access_token = 'YOUR_ACCESS_TOKEN' + +# create an instance of the API class +api_instance = swagger_client.PetApi() +pet_id = 789 # int | ID of pet that needs to be fetched + +try: + # Find pet by ID + 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 +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **pet_id** | **int**| ID of pet that needs to be fetched | + +### Return type + +[**Pet**](Pet.md) + +### Authorization + +[api_key](../README.md#api_key), [petstore_auth](../README.md#petstore_auth) + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **get_pet_by_id_in_object** +> InlineResponse200 get_pet_by_id_in_object(pet_id) + +Fake endpoint to test inline arbitrary object return by 'Find pet by ID' + +Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + +### Example +```python +import swagger_client +from swagger_client.rest import ApiException +from pprint import pprint +import time + + +# Configure API key authorization: api_key +swagger_client.configuration.api_key['api_key'] = 'YOUR_API_KEY'; +# Uncomment below to setup prefix (e.g. BEARER) for API key, if needed +# swagger_client.configuration.api_key_prefix['api_key'] = 'BEARER' +# Configure OAuth2 access token for authorization: petstore_auth +swagger_client.configuration.access_token = 'YOUR_ACCESS_TOKEN' + +# create an instance of the API class +api_instance = swagger_client.PetApi() +pet_id = 789 # int | ID of pet that needs to be fetched + +try: + # Fake endpoint to test inline arbitrary object return by 'Find pet by ID' + api_response = api_instance.get_pet_by_id_in_object(pet_id); + pprint(api_response) +except ApiException as e: + print "Exception when calling PetApi->get_pet_by_id_in_object: %s\n" % e +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **pet_id** | **int**| ID of pet that needs to be fetched | + +### Return type + +[**InlineResponse200**](InlineResponse200.md) + +### Authorization + +[api_key](../README.md#api_key), [petstore_auth](../README.md#petstore_auth) + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **pet_pet_idtesting_byte_arraytrue_get** +> str pet_pet_idtesting_byte_arraytrue_get(pet_id) + +Fake endpoint to test byte array return by 'Find pet by ID' + +Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + +### Example +```python +import swagger_client +from swagger_client.rest import ApiException +from pprint import pprint +import time + + +# Configure API key authorization: api_key +swagger_client.configuration.api_key['api_key'] = 'YOUR_API_KEY'; +# Uncomment below to setup prefix (e.g. BEARER) for API key, if needed +# swagger_client.configuration.api_key_prefix['api_key'] = 'BEARER' +# Configure OAuth2 access token for authorization: petstore_auth +swagger_client.configuration.access_token = 'YOUR_ACCESS_TOKEN' + +# create an instance of the API class +api_instance = swagger_client.PetApi() +pet_id = 789 # int | ID of pet that needs to be fetched + +try: + # Fake endpoint to test byte array return by 'Find pet by ID' + api_response = api_instance.pet_pet_idtesting_byte_arraytrue_get(pet_id); + pprint(api_response) +except ApiException as e: + print "Exception when calling PetApi->pet_pet_idtesting_byte_arraytrue_get: %s\n" % e +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **pet_id** | **int**| ID of pet that needs to be fetched | + +### Return type + +**str** + +### Authorization + +[api_key](../README.md#api_key), [petstore_auth](../README.md#petstore_auth) + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **update_pet** +> update_pet(body=body) + +Update an existing pet + + + +### Example +```python +import swagger_client +from swagger_client.rest import ApiException +from pprint import pprint +import time + + +# Configure OAuth2 access token for authorization: petstore_auth +swagger_client.configuration.access_token = 'YOUR_ACCESS_TOKEN' + +# create an instance of the API class +api_instance = swagger_client.PetApi() +body = swagger_client.Pet() # Pet | Pet object that needs to be added to the store (optional) + +try: + # Update an existing pet + api_instance.update_pet(body=body); +except ApiException as e: + print "Exception when calling PetApi->update_pet: %s\n" % e +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | [optional] + +### Return type + +void (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP reuqest headers + + - **Content-Type**: application/json, application/xml + - **Accept**: application/json, application/xml + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **update_pet_with_form** +> update_pet_with_form(pet_id, name=name, status=status) + +Updates a pet in the store with form data + + + +### Example +```python +import swagger_client +from swagger_client.rest import ApiException +from pprint import pprint +import time + + +# Configure OAuth2 access token for authorization: petstore_auth +swagger_client.configuration.access_token = 'YOUR_ACCESS_TOKEN' + +# create an instance of the API class +api_instance = swagger_client.PetApi() +pet_id = 'pet_id_example' # str | ID of pet that needs to be updated +name = 'name_example' # str | Updated name of the pet (optional) +status = 'status_example' # str | Updated status of the pet (optional) + +try: + # 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 +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **pet_id** | **str**| ID of pet that needs to be updated | + **name** | **str**| Updated name of the pet | [optional] + **status** | **str**| Updated status of the pet | [optional] + +### Return type + +void (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP reuqest headers + + - **Content-Type**: application/x-www-form-urlencoded + - **Accept**: application/json, application/xml + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **upload_file** +> upload_file(pet_id, additional_metadata=additional_metadata, file=file) + +uploads an image + + + +### Example +```python +import swagger_client +from swagger_client.rest import ApiException +from pprint import pprint +import time + + +# Configure OAuth2 access token for authorization: petstore_auth +swagger_client.configuration.access_token = 'YOUR_ACCESS_TOKEN' + +# create an instance of the API class +api_instance = swagger_client.PetApi() +pet_id = 789 # int | ID of pet to update +additional_metadata = 'additional_metadata_example' # str | Additional data to pass to server (optional) +file = '/path/to/file.txt' # file | file to upload (optional) + +try: + # uploads an image + api_instance.upload_file(pet_id, additional_metadata=additional_metadata, file=file); +except ApiException as e: + print "Exception when calling PetApi->upload_file: %s\n" % e +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **pet_id** | **int**| ID of pet to update | + **additional_metadata** | **str**| Additional data to pass to server | [optional] + **file** | **file**| file to upload | [optional] + +### Return type + +void (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP reuqest headers + + - **Content-Type**: multipart/form-data + - **Accept**: application/json, application/xml + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/python/docs/SpecialModelName.md b/samples/client/petstore/python/docs/SpecialModelName.md new file mode 100644 index 00000000000..022ee19169c --- /dev/null +++ b/samples/client/petstore/python/docs/SpecialModelName.md @@ -0,0 +1,10 @@ +# SpecialModelName + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**special_property_name** | **int** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/python/docs/StoreApi.md b/samples/client/petstore/python/docs/StoreApi.md new file mode 100644 index 00000000000..bbffc6e384b --- /dev/null +++ b/samples/client/petstore/python/docs/StoreApi.md @@ -0,0 +1,330 @@ +# swagger_client\StoreApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**delete_order**](StoreApi.md#delete_order) | **DELETE** /store/order/{orderId} | Delete purchase order by ID +[**find_orders_by_status**](StoreApi.md#find_orders_by_status) | **GET** /store/findByStatus | Finds orders by status +[**get_inventory**](StoreApi.md#get_inventory) | **GET** /store/inventory | Returns pet inventories by status +[**get_inventory_in_object**](StoreApi.md#get_inventory_in_object) | **GET** /store/inventory?response=arbitrary_object | Fake endpoint to test arbitrary object return by 'Get inventory' +[**get_order_by_id**](StoreApi.md#get_order_by_id) | **GET** /store/order/{orderId} | Find purchase order by ID +[**place_order**](StoreApi.md#place_order) | **POST** /store/order | Place an order for a pet + + +# **delete_order** +> delete_order(order_id) + +Delete purchase order by ID + +For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + +### Example +```python +import swagger_client +from swagger_client.rest import ApiException +from pprint import pprint +import time + + +# create an instance of the API class +api_instance = swagger_client.StoreApi() +order_id = 'order_id_example' # str | ID of the order that needs to be deleted + +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 +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **order_id** | **str**| ID of the order that needs to be deleted | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **find_orders_by_status** +> list[Order] find_orders_by_status(status=status) + +Finds orders by status + +A single status value can be provided as a string + +### Example +```python +import swagger_client +from swagger_client.rest import ApiException +from pprint import pprint +import time + + +# Configure API key authorization: test_api_client_id +swagger_client.configuration.api_key['x-test_api_client_id'] = 'YOUR_API_KEY'; +# Uncomment below to setup prefix (e.g. BEARER) for API key, if needed +# swagger_client.configuration.api_key_prefix['x-test_api_client_id'] = 'BEARER' +# Configure API key authorization: test_api_client_secret +swagger_client.configuration.api_key['x-test_api_client_secret'] = 'YOUR_API_KEY'; +# Uncomment below to setup prefix (e.g. BEARER) for API key, if needed +# swagger_client.configuration.api_key_prefix['x-test_api_client_secret'] = 'BEARER' + +# create an instance of the API class +api_instance = swagger_client.StoreApi() +status = 'placed' # str | Status value that needs to be considered for query (optional) (default to placed) + +try: + # Finds orders by status + api_response = api_instance.find_orders_by_status(status=status); + pprint(api_response) +except ApiException as e: + print "Exception when calling StoreApi->find_orders_by_status: %s\n" % e +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **status** | **str**| Status value that needs to be considered for query | [optional] [default to placed] + +### Return type + +[**list[Order]**](Order.md) + +### Authorization + +[test_api_client_id](../README.md#test_api_client_id), [test_api_client_secret](../README.md#test_api_client_secret) + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **get_inventory** +> dict(str, int) get_inventory() + +Returns pet inventories by status + +Returns a map of status codes to quantities + +### Example +```python +import swagger_client +from swagger_client.rest import ApiException +from pprint import pprint +import time + + +# Configure API key authorization: api_key +swagger_client.configuration.api_key['api_key'] = 'YOUR_API_KEY'; +# Uncomment below to setup prefix (e.g. BEARER) for API key, if needed +# swagger_client.configuration.api_key_prefix['api_key'] = 'BEARER' + +# create an instance of the API class +api_instance = swagger_client.StoreApi() + +try: + # Returns pet inventories by status + api_response = api_instance.get_inventory(); + pprint(api_response) +except ApiException as e: + print "Exception when calling StoreApi->get_inventory: %s\n" % e +``` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +[**dict(str, int)**](dict.md) + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **get_inventory_in_object** +> object get_inventory_in_object() + +Fake endpoint to test arbitrary object return by 'Get inventory' + +Returns an arbitrary object which is actually a map of status codes to quantities + +### Example +```python +import swagger_client +from swagger_client.rest import ApiException +from pprint import pprint +import time + + +# Configure API key authorization: api_key +swagger_client.configuration.api_key['api_key'] = 'YOUR_API_KEY'; +# Uncomment below to setup prefix (e.g. BEARER) for API key, if needed +# swagger_client.configuration.api_key_prefix['api_key'] = 'BEARER' + +# create an instance of the API class +api_instance = swagger_client.StoreApi() + +try: + # Fake endpoint to test arbitrary object return by 'Get inventory' + api_response = api_instance.get_inventory_in_object(); + pprint(api_response) +except ApiException as e: + print "Exception when calling StoreApi->get_inventory_in_object: %s\n" % e +``` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +**object** + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **get_order_by_id** +> Order get_order_by_id(order_id) + +Find purchase order by ID + +For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + +### Example +```python +import swagger_client +from swagger_client.rest import ApiException +from pprint import pprint +import time + + +# Configure API key authorization: test_api_key_header +swagger_client.configuration.api_key['test_api_key_header'] = 'YOUR_API_KEY'; +# Uncomment below to setup prefix (e.g. BEARER) for API key, if needed +# swagger_client.configuration.api_key_prefix['test_api_key_header'] = 'BEARER' +# Configure API key authorization: test_api_key_query +swagger_client.configuration.api_key['test_api_key_query'] = 'YOUR_API_KEY'; +# Uncomment below to setup prefix (e.g. BEARER) for API key, if needed +# swagger_client.configuration.api_key_prefix['test_api_key_query'] = 'BEARER' + +# create an instance of the API class +api_instance = swagger_client.StoreApi() +order_id = 'order_id_example' # str | ID of pet that needs to be fetched + +try: + # Find purchase order by ID + 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 +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **order_id** | **str**| ID of pet that needs to be fetched | + +### Return type + +[**Order**](Order.md) + +### Authorization + +[test_api_key_header](../README.md#test_api_key_header), [test_api_key_query](../README.md#test_api_key_query) + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **place_order** +> Order place_order(body=body) + +Place an order for a pet + + + +### Example +```python +import swagger_client +from swagger_client.rest import ApiException +from pprint import pprint +import time + + +# Configure API key authorization: test_api_client_id +swagger_client.configuration.api_key['x-test_api_client_id'] = 'YOUR_API_KEY'; +# Uncomment below to setup prefix (e.g. BEARER) for API key, if needed +# swagger_client.configuration.api_key_prefix['x-test_api_client_id'] = 'BEARER' +# Configure API key authorization: test_api_client_secret +swagger_client.configuration.api_key['x-test_api_client_secret'] = 'YOUR_API_KEY'; +# Uncomment below to setup prefix (e.g. BEARER) for API key, if needed +# swagger_client.configuration.api_key_prefix['x-test_api_client_secret'] = 'BEARER' + +# create an instance of the API class +api_instance = swagger_client.StoreApi() +body = swagger_client.Order() # Order | order placed for purchasing the pet (optional) + +try: + # Place an order for a pet + api_response = api_instance.place_order(body=body); + pprint(api_response) +except ApiException as e: + print "Exception when calling StoreApi->place_order: %s\n" % e +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Order**](Order.md)| order placed for purchasing the pet | [optional] + +### Return type + +[**Order**](Order.md) + +### Authorization + +[test_api_client_id](../README.md#test_api_client_id), [test_api_client_secret](../README.md#test_api_client_secret) + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/python/docs/Tag.md b/samples/client/petstore/python/docs/Tag.md new file mode 100644 index 00000000000..243cd98eda6 --- /dev/null +++ b/samples/client/petstore/python/docs/Tag.md @@ -0,0 +1,11 @@ +# Tag + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **int** | | [optional] +**name** | **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/User.md b/samples/client/petstore/python/docs/User.md new file mode 100644 index 00000000000..443ac123fdc --- /dev/null +++ b/samples/client/petstore/python/docs/User.md @@ -0,0 +1,17 @@ +# User + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **int** | | [optional] +**username** | **str** | | [optional] +**first_name** | **str** | | [optional] +**last_name** | **str** | | [optional] +**email** | **str** | | [optional] +**password** | **str** | | [optional] +**phone** | **str** | | [optional] +**user_status** | **int** | User Status | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/python/docs/UserApi.md b/samples/client/petstore/python/docs/UserApi.md new file mode 100644 index 00000000000..8145147a6ff --- /dev/null +++ b/samples/client/petstore/python/docs/UserApi.md @@ -0,0 +1,398 @@ +# swagger_client\UserApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**create_user**](UserApi.md#create_user) | **POST** /user | Create user +[**create_users_with_array_input**](UserApi.md#create_users_with_array_input) | **POST** /user/createWithArray | Creates list of users with given input array +[**create_users_with_list_input**](UserApi.md#create_users_with_list_input) | **POST** /user/createWithList | Creates list of users with given input array +[**delete_user**](UserApi.md#delete_user) | **DELETE** /user/{username} | Delete user +[**get_user_by_name**](UserApi.md#get_user_by_name) | **GET** /user/{username} | Get user by user name +[**login_user**](UserApi.md#login_user) | **GET** /user/login | Logs user into the system +[**logout_user**](UserApi.md#logout_user) | **GET** /user/logout | Logs out current logged in user session +[**update_user**](UserApi.md#update_user) | **PUT** /user/{username} | Updated user + + +# **create_user** +> create_user(body=body) + +Create user + +This can only be done by the logged in user. + +### Example +```python +import swagger_client +from swagger_client.rest import ApiException +from pprint import pprint +import time + + +# create an instance of the API class +api_instance = swagger_client.UserApi() +body = swagger_client.User() # User | Created user object (optional) + +try: + # Create user + api_instance.create_user(body=body); +except ApiException as e: + print "Exception when calling UserApi->create_user: %s\n" % e +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**User**](User.md)| Created user object | [optional] + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **create_users_with_array_input** +> create_users_with_array_input(body=body) + +Creates list of users with given input array + + + +### Example +```python +import swagger_client +from swagger_client.rest import ApiException +from pprint import pprint +import time + + +# create an instance of the API class +api_instance = swagger_client.UserApi() +body = [swagger_client.User()] # list[User] | List of user object (optional) + +try: + # Creates list of users with given input array + api_instance.create_users_with_array_input(body=body); +except ApiException as e: + print "Exception when calling UserApi->create_users_with_array_input: %s\n" % e +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**list[User]**](User.md)| List of user object | [optional] + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **create_users_with_list_input** +> create_users_with_list_input(body=body) + +Creates list of users with given input array + + + +### Example +```python +import swagger_client +from swagger_client.rest import ApiException +from pprint import pprint +import time + + +# create an instance of the API class +api_instance = swagger_client.UserApi() +body = [swagger_client.User()] # list[User] | List of user object (optional) + +try: + # Creates list of users with given input array + api_instance.create_users_with_list_input(body=body); +except ApiException as e: + print "Exception when calling UserApi->create_users_with_list_input: %s\n" % e +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**list[User]**](User.md)| List of user object | [optional] + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **delete_user** +> delete_user(username) + +Delete user + +This can only be done by the logged in user. + +### Example +```python +import swagger_client +from swagger_client.rest import ApiException +from pprint import pprint +import time + + +# Configure HTTP basic authorization: test_http_basic +swagger_client.configuration.username = 'YOUR_USERNAME' +swagger_client.configuration.password = 'YOUR_PASSWORD' + +# create an instance of the API class +api_instance = swagger_client.UserApi() +username = 'username_example' # str | The name that needs to be deleted + +try: + # Delete user + api_instance.delete_user(username); +except ApiException as e: + print "Exception when calling UserApi->delete_user: %s\n" % e +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **str**| The name that needs to be deleted | + +### Return type + +void (empty response body) + +### Authorization + +[test_http_basic](../README.md#test_http_basic) + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **get_user_by_name** +> User get_user_by_name(username) + +Get user by user name + + + +### Example +```python +import swagger_client +from swagger_client.rest import ApiException +from pprint import pprint +import time + + +# create an instance of the API class +api_instance = swagger_client.UserApi() +username = 'username_example' # str | The name that needs to be fetched. Use user1 for testing. + +try: + # Get user by user name + 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 +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **str**| The name that needs to be fetched. Use user1 for testing. | + +### Return type + +[**User**](User.md) + +### Authorization + +No authorization required + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **login_user** +> str login_user(username=username, password=password) + +Logs user into the system + + + +### Example +```python +import swagger_client +from swagger_client.rest import ApiException +from pprint import pprint +import time + + +# create an instance of the API class +api_instance = swagger_client.UserApi() +username = 'username_example' # str | The user name for login (optional) +password = 'password_example' # str | The password for login in clear text (optional) + +try: + # Logs user into the system + api_response = api_instance.login_user(username=username, password=password); + pprint(api_response) +except ApiException as e: + print "Exception when calling UserApi->login_user: %s\n" % e +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **str**| The user name for login | [optional] + **password** | **str**| The password for login in clear text | [optional] + +### Return type + +**str** + +### Authorization + +No authorization required + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **logout_user** +> logout_user() + +Logs out current logged in user session + + + +### Example +```python +import swagger_client +from swagger_client.rest import ApiException +from pprint import pprint +import time + + +# create an instance of the API class +api_instance = swagger_client.UserApi() + +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 +``` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **update_user** +> update_user(username, body=body) + +Updated user + +This can only be done by the logged in user. + +### Example +```python +import swagger_client +from swagger_client.rest import ApiException +from pprint import pprint +import time + + +# create an instance of the API class +api_instance = swagger_client.UserApi() +username = 'username_example' # str | name that need to be deleted +body = swagger_client.User() # User | Updated user object (optional) + +try: + # Updated user + api_instance.update_user(username, body=body); +except ApiException as e: + print "Exception when calling UserApi->update_user: %s\n" % e +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **str**| name that need to be deleted | + **body** | [**User**](User.md)| Updated user object | [optional] + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/python/git_push.sh b/samples/client/petstore/python/git_push.sh new file mode 100644 index 00000000000..1a36388db02 --- /dev/null +++ b/samples/client/petstore/python/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="YOUR_GIT_USR_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="YOUR_GIT_REPO_ID" + 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/python/swagger_client/__init__.py b/samples/client/petstore/python/swagger_client/__init__.py index 8c6fd5bc618..dbdd791ada2 100644 --- a/samples/client/petstore/python/swagger_client/__init__.py +++ b/samples/client/petstore/python/swagger_client/__init__.py @@ -1,19 +1,24 @@ from __future__ import absolute_import # import models into sdk package -from .models.user import User +from .models.animal import Animal +from .models.cat import Cat from .models.category import Category -from .models.pet import Pet -from .models.tag import Tag -from .models.object_return import ObjectReturn -from .models.order import Order -from .models.special_model_name import SpecialModelName +from .models.dog import Dog from .models.inline_response_200 import InlineResponse200 +from .models.model_200_response import Model200Response +from .models.model_return import ModelReturn +from .models.name import Name +from .models.order import Order +from .models.pet import Pet +from .models.special_model_name import SpecialModelName +from .models.tag import Tag +from .models.user import User # import apis into sdk package -from .apis.user_api import UserApi from .apis.pet_api import PetApi from .apis.store_api import StoreApi +from .apis.user_api import UserApi # import ApiClient from .api_client import ApiClient diff --git a/samples/client/petstore/python/swagger_client/api_client.py b/samples/client/petstore/python/swagger_client/api_client.py index 7e8c7a0e266..5d5a5fccc4c 100644 --- a/samples/client/petstore/python/swagger_client/api_client.py +++ b/samples/client/petstore/python/swagger_client/api_client.py @@ -81,7 +81,7 @@ class ApiClient(object): self.host = host self.cookie = cookie # Set default User-Agent. - self.user_agent = 'Python-Swagger/1.0.0' + self.user_agent = 'Swagger-Codegen/1.0.0/python' @property def user_agent(self): @@ -371,7 +371,8 @@ class ApiClient(object): elif method == "DELETE": return self.rest_client.DELETE(url, query_params=query_params, - headers=headers) + headers=headers, + body=body) else: raise ValueError( "http method must be `GET`, `HEAD`," diff --git a/samples/client/petstore/python/swagger_client/apis/__init__.py b/samples/client/petstore/python/swagger_client/apis/__init__.py index 592a56e282d..a3a12ea9ac1 100644 --- a/samples/client/petstore/python/swagger_client/apis/__init__.py +++ b/samples/client/petstore/python/swagger_client/apis/__init__.py @@ -1,6 +1,6 @@ from __future__ import absolute_import # import apis into api package -from .user_api import UserApi from .pet_api import PetApi from .store_api import StoreApi +from .user_api import UserApi diff --git a/samples/client/petstore/python/swagger_client/apis/pet_api.py b/samples/client/petstore/python/swagger_client/apis/pet_api.py index d4291093b13..8b081e077dc 100644 --- a/samples/client/petstore/python/swagger_client/apis/pet_api.py +++ b/samples/client/petstore/python/swagger_client/apis/pet_api.py @@ -45,80 +45,6 @@ class PetApi(object): config.api_client = ApiClient() self.api_client = config.api_client - def update_pet(self, **kwargs): - """ - Update an existing pet - - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please define a `callback` function - to be invoked when receiving the response. - >>> def callback_function(response): - >>> pprint(response) - >>> - >>> thread = api.update_pet(callback=callback_function) - - :param callback function: The callback function - for asynchronous request. (optional) - :param Pet body: Pet object that needs to be added to the store - :return: None - If the method is called asynchronously, - returns the request thread. - """ - - all_params = ['body'] - all_params.append('callback') - - params = locals() - for key, val in iteritems(params['kwargs']): - if key not in all_params: - raise TypeError( - "Got an unexpected keyword argument '%s'" - " to method update_pet" % key - ) - params[key] = val - del params['kwargs'] - - - resource_path = '/pet'.replace('{format}', 'json') - path_params = {} - - query_params = {} - - header_params = {} - - form_params = [] - local_var_files = {} - - body_params = None - if 'body' in params: - body_params = params['body'] - - # HTTP header `Accept` - header_params['Accept'] = self.api_client.\ - select_header_accept(['application/json', 'application/xml']) - 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', 'application/xml']) - - # Authentication setting - auth_settings = ['petstore_auth'] - - response = self.api_client.call_api(resource_path, 'PUT', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type=None, - auth_settings=auth_settings, - callback=params.get('callback')) - return response - def add_pet(self, **kwargs): """ Add a new pet to the store @@ -193,6 +119,160 @@ class PetApi(object): callback=params.get('callback')) return response + def add_pet_using_byte_array(self, **kwargs): + """ + Fake endpoint to test byte array in body parameter for adding a new pet to the store + + + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please define a `callback` function + to be invoked when receiving the response. + >>> def callback_function(response): + >>> pprint(response) + >>> + >>> thread = api.add_pet_using_byte_array(callback=callback_function) + + :param callback function: The callback function + for asynchronous request. (optional) + :param str body: Pet object in the form of byte array + :return: None + If the method is called asynchronously, + returns the request thread. + """ + + all_params = ['body'] + all_params.append('callback') + + params = locals() + for key, val in iteritems(params['kwargs']): + if key not in all_params: + raise TypeError( + "Got an unexpected keyword argument '%s'" + " to method add_pet_using_byte_array" % key + ) + params[key] = val + del params['kwargs'] + + + resource_path = '/pet?testing_byte_array=true'.replace('{format}', 'json') + path_params = {} + + query_params = {} + + header_params = {} + + form_params = [] + local_var_files = {} + + body_params = None + if 'body' in params: + body_params = params['body'] + + # HTTP header `Accept` + header_params['Accept'] = self.api_client.\ + select_header_accept(['application/json', 'application/xml']) + 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', 'application/xml']) + + # Authentication setting + auth_settings = ['petstore_auth'] + + response = self.api_client.call_api(resource_path, 'POST', + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type=None, + auth_settings=auth_settings, + callback=params.get('callback')) + return response + + def delete_pet(self, pet_id, **kwargs): + """ + Deletes a pet + + + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please define a `callback` function + to be invoked when receiving the response. + >>> def callback_function(response): + >>> pprint(response) + >>> + >>> thread = api.delete_pet(pet_id, callback=callback_function) + + :param callback function: The callback function + for asynchronous request. (optional) + :param int pet_id: Pet id to delete (required) + :param str api_key: + :return: None + If the method is called asynchronously, + returns the request thread. + """ + + all_params = ['pet_id', 'api_key'] + all_params.append('callback') + + params = locals() + for key, val in iteritems(params['kwargs']): + if key not in all_params: + raise TypeError( + "Got an unexpected keyword argument '%s'" + " to method delete_pet" % key + ) + params[key] = val + del params['kwargs'] + + # verify the required parameter 'pet_id' is set + if ('pet_id' not in params) or (params['pet_id'] is None): + raise ValueError("Missing the required parameter `pet_id` when calling `delete_pet`") + + resource_path = '/pet/{petId}'.replace('{format}', 'json') + path_params = {} + if 'pet_id' in params: + path_params['petId'] = params['pet_id'] + + query_params = {} + + header_params = {} + if 'api_key' in params: + header_params['api_key'] = params['api_key'] + + form_params = [] + local_var_files = {} + + body_params = None + + # HTTP header `Accept` + header_params['Accept'] = self.api_client.\ + select_header_accept(['application/json', 'application/xml']) + if not header_params['Accept']: + del header_params['Accept'] + + # HTTP header `Content-Type` + header_params['Content-Type'] = self.api_client.\ + select_header_content_type([]) + + # Authentication setting + auth_settings = ['petstore_auth'] + + response = self.api_client.call_api(resource_path, 'DELETE', + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type=None, + auth_settings=auth_settings, + callback=params.get('callback')) + return response + def find_pets_by_status(self, **kwargs): """ Finds Pets by status @@ -418,252 +498,6 @@ class PetApi(object): callback=params.get('callback')) return response - def update_pet_with_form(self, pet_id, **kwargs): - """ - Updates a pet in the store with form data - - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please define a `callback` function - to be invoked when receiving the response. - >>> def callback_function(response): - >>> pprint(response) - >>> - >>> thread = api.update_pet_with_form(pet_id, callback=callback_function) - - :param callback function: The callback function - for asynchronous request. (optional) - :param str pet_id: ID of pet that needs to be updated (required) - :param str name: Updated name of the pet - :param str status: Updated status of the pet - :return: None - If the method is called asynchronously, - returns the request thread. - """ - - all_params = ['pet_id', 'name', 'status'] - all_params.append('callback') - - params = locals() - for key, val in iteritems(params['kwargs']): - if key not in all_params: - raise TypeError( - "Got an unexpected keyword argument '%s'" - " to method update_pet_with_form" % key - ) - params[key] = val - del params['kwargs'] - - # verify the required parameter 'pet_id' is set - if ('pet_id' not in params) or (params['pet_id'] is None): - raise ValueError("Missing the required parameter `pet_id` when calling `update_pet_with_form`") - - resource_path = '/pet/{petId}'.replace('{format}', 'json') - path_params = {} - if 'pet_id' in params: - path_params['petId'] = params['pet_id'] - - query_params = {} - - header_params = {} - - form_params = [] - local_var_files = {} - if 'name' in params: - form_params.append(('name', params['name'])) - if 'status' in params: - form_params.append(('status', params['status'])) - - body_params = None - - # HTTP header `Accept` - header_params['Accept'] = self.api_client.\ - select_header_accept(['application/json', 'application/xml']) - 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/x-www-form-urlencoded']) - - # Authentication setting - auth_settings = ['petstore_auth'] - - response = self.api_client.call_api(resource_path, 'POST', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type=None, - auth_settings=auth_settings, - callback=params.get('callback')) - return response - - def delete_pet(self, pet_id, **kwargs): - """ - Deletes a pet - - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please define a `callback` function - to be invoked when receiving the response. - >>> def callback_function(response): - >>> pprint(response) - >>> - >>> thread = api.delete_pet(pet_id, callback=callback_function) - - :param callback function: The callback function - for asynchronous request. (optional) - :param int pet_id: Pet id to delete (required) - :param str api_key: - :return: None - If the method is called asynchronously, - returns the request thread. - """ - - all_params = ['pet_id', 'api_key'] - all_params.append('callback') - - params = locals() - for key, val in iteritems(params['kwargs']): - if key not in all_params: - raise TypeError( - "Got an unexpected keyword argument '%s'" - " to method delete_pet" % key - ) - params[key] = val - del params['kwargs'] - - # verify the required parameter 'pet_id' is set - if ('pet_id' not in params) or (params['pet_id'] is None): - raise ValueError("Missing the required parameter `pet_id` when calling `delete_pet`") - - resource_path = '/pet/{petId}'.replace('{format}', 'json') - path_params = {} - if 'pet_id' in params: - path_params['petId'] = params['pet_id'] - - query_params = {} - - header_params = {} - if 'api_key' in params: - header_params['api_key'] = params['api_key'] - - form_params = [] - local_var_files = {} - - body_params = None - - # HTTP header `Accept` - header_params['Accept'] = self.api_client.\ - select_header_accept(['application/json', 'application/xml']) - if not header_params['Accept']: - del header_params['Accept'] - - # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.\ - select_header_content_type([]) - - # Authentication setting - auth_settings = ['petstore_auth'] - - response = self.api_client.call_api(resource_path, 'DELETE', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type=None, - auth_settings=auth_settings, - callback=params.get('callback')) - return response - - def upload_file(self, pet_id, **kwargs): - """ - uploads an image - - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please define a `callback` function - to be invoked when receiving the response. - >>> def callback_function(response): - >>> pprint(response) - >>> - >>> thread = api.upload_file(pet_id, callback=callback_function) - - :param callback function: The callback function - for asynchronous request. (optional) - :param int pet_id: ID of pet to update (required) - :param str additional_metadata: Additional data to pass to server - :param file file: file to upload - :return: None - If the method is called asynchronously, - returns the request thread. - """ - - all_params = ['pet_id', 'additional_metadata', 'file'] - all_params.append('callback') - - params = locals() - for key, val in iteritems(params['kwargs']): - if key not in all_params: - raise TypeError( - "Got an unexpected keyword argument '%s'" - " to method upload_file" % key - ) - params[key] = val - del params['kwargs'] - - # verify the required parameter 'pet_id' is set - if ('pet_id' not in params) or (params['pet_id'] is None): - raise ValueError("Missing the required parameter `pet_id` when calling `upload_file`") - - resource_path = '/pet/{petId}/uploadImage'.replace('{format}', 'json') - path_params = {} - if 'pet_id' in params: - path_params['petId'] = params['pet_id'] - - query_params = {} - - header_params = {} - - form_params = [] - local_var_files = {} - if 'additional_metadata' in params: - form_params.append(('additionalMetadata', params['additional_metadata'])) - if 'file' in params: - local_var_files['file'] = params['file'] - - body_params = None - - # HTTP header `Accept` - header_params['Accept'] = self.api_client.\ - select_header_accept(['application/json', 'application/xml']) - if not header_params['Accept']: - del header_params['Accept'] - - # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.\ - select_header_content_type(['multipart/form-data']) - - # Authentication setting - auth_settings = ['petstore_auth'] - - response = self.api_client.call_api(resource_path, 'POST', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type=None, - auth_settings=auth_settings, - callback=params.get('callback')) - return response - def get_pet_by_id_in_object(self, pet_id, **kwargs): """ Fake endpoint to test inline arbitrary object return by 'Find pet by ID' @@ -818,9 +652,9 @@ class PetApi(object): callback=params.get('callback')) return response - def add_pet_using_byte_array(self, **kwargs): + def update_pet(self, **kwargs): """ - Fake endpoint to test byte array in body parameter for adding a new pet to the store + Update an existing pet This method makes a synchronous HTTP request by default. To make an @@ -829,11 +663,11 @@ class PetApi(object): >>> def callback_function(response): >>> pprint(response) >>> - >>> thread = api.add_pet_using_byte_array(callback=callback_function) + >>> thread = api.update_pet(callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) - :param str body: Pet object in the form of byte array + :param Pet body: Pet object that needs to be added to the store :return: None If the method is called asynchronously, returns the request thread. @@ -847,13 +681,13 @@ class PetApi(object): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" - " to method add_pet_using_byte_array" % key + " to method update_pet" % key ) params[key] = val del params['kwargs'] - resource_path = '/pet?testing_byte_array=true'.replace('{format}', 'json') + resource_path = '/pet'.replace('{format}', 'json') path_params = {} query_params = {} @@ -880,6 +714,172 @@ class PetApi(object): # Authentication setting auth_settings = ['petstore_auth'] + response = self.api_client.call_api(resource_path, 'PUT', + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type=None, + auth_settings=auth_settings, + callback=params.get('callback')) + return response + + def update_pet_with_form(self, pet_id, **kwargs): + """ + Updates a pet in the store with form data + + + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please define a `callback` function + to be invoked when receiving the response. + >>> def callback_function(response): + >>> pprint(response) + >>> + >>> thread = api.update_pet_with_form(pet_id, callback=callback_function) + + :param callback function: The callback function + for asynchronous request. (optional) + :param str pet_id: ID of pet that needs to be updated (required) + :param str name: Updated name of the pet + :param str status: Updated status of the pet + :return: None + If the method is called asynchronously, + returns the request thread. + """ + + all_params = ['pet_id', 'name', 'status'] + all_params.append('callback') + + params = locals() + for key, val in iteritems(params['kwargs']): + if key not in all_params: + raise TypeError( + "Got an unexpected keyword argument '%s'" + " to method update_pet_with_form" % key + ) + params[key] = val + del params['kwargs'] + + # verify the required parameter 'pet_id' is set + if ('pet_id' not in params) or (params['pet_id'] is None): + raise ValueError("Missing the required parameter `pet_id` when calling `update_pet_with_form`") + + resource_path = '/pet/{petId}'.replace('{format}', 'json') + path_params = {} + if 'pet_id' in params: + path_params['petId'] = params['pet_id'] + + query_params = {} + + header_params = {} + + form_params = [] + local_var_files = {} + if 'name' in params: + form_params.append(('name', params['name'])) + if 'status' in params: + form_params.append(('status', params['status'])) + + body_params = None + + # HTTP header `Accept` + header_params['Accept'] = self.api_client.\ + select_header_accept(['application/json', 'application/xml']) + 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/x-www-form-urlencoded']) + + # Authentication setting + auth_settings = ['petstore_auth'] + + response = self.api_client.call_api(resource_path, 'POST', + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type=None, + auth_settings=auth_settings, + callback=params.get('callback')) + return response + + def upload_file(self, pet_id, **kwargs): + """ + uploads an image + + + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please define a `callback` function + to be invoked when receiving the response. + >>> def callback_function(response): + >>> pprint(response) + >>> + >>> thread = api.upload_file(pet_id, callback=callback_function) + + :param callback function: The callback function + for asynchronous request. (optional) + :param int pet_id: ID of pet to update (required) + :param str additional_metadata: Additional data to pass to server + :param file file: file to upload + :return: None + If the method is called asynchronously, + returns the request thread. + """ + + all_params = ['pet_id', 'additional_metadata', 'file'] + all_params.append('callback') + + params = locals() + for key, val in iteritems(params['kwargs']): + if key not in all_params: + raise TypeError( + "Got an unexpected keyword argument '%s'" + " to method upload_file" % key + ) + params[key] = val + del params['kwargs'] + + # verify the required parameter 'pet_id' is set + if ('pet_id' not in params) or (params['pet_id'] is None): + raise ValueError("Missing the required parameter `pet_id` when calling `upload_file`") + + resource_path = '/pet/{petId}/uploadImage'.replace('{format}', 'json') + path_params = {} + if 'pet_id' in params: + path_params['petId'] = params['pet_id'] + + query_params = {} + + header_params = {} + + form_params = [] + local_var_files = {} + if 'additional_metadata' in params: + form_params.append(('additionalMetadata', params['additional_metadata'])) + if 'file' in params: + local_var_files['file'] = params['file'] + + body_params = None + + # HTTP header `Accept` + header_params['Accept'] = self.api_client.\ + select_header_accept(['application/json', 'application/xml']) + if not header_params['Accept']: + del header_params['Accept'] + + # HTTP header `Content-Type` + header_params['Content-Type'] = self.api_client.\ + select_header_content_type(['multipart/form-data']) + + # Authentication setting + auth_settings = ['petstore_auth'] + response = self.api_client.call_api(resource_path, 'POST', path_params, query_params, diff --git a/samples/client/petstore/python/swagger_client/apis/store_api.py b/samples/client/petstore/python/swagger_client/apis/store_api.py index 220447d7c01..85bb90ed40c 100644 --- a/samples/client/petstore/python/swagger_client/apis/store_api.py +++ b/samples/client/petstore/python/swagger_client/apis/store_api.py @@ -45,6 +45,83 @@ class StoreApi(object): config.api_client = ApiClient() self.api_client = config.api_client + def delete_order(self, order_id, **kwargs): + """ + Delete purchase order by ID + For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please define a `callback` function + to be invoked when receiving the response. + >>> def callback_function(response): + >>> pprint(response) + >>> + >>> thread = api.delete_order(order_id, callback=callback_function) + + :param callback function: The callback function + for asynchronous request. (optional) + :param str order_id: ID of the order that needs to be deleted (required) + :return: None + If the method is called asynchronously, + returns the request thread. + """ + + all_params = ['order_id'] + all_params.append('callback') + + params = locals() + for key, val in iteritems(params['kwargs']): + if key not in all_params: + raise TypeError( + "Got an unexpected keyword argument '%s'" + " to method delete_order" % key + ) + params[key] = val + del params['kwargs'] + + # verify the required parameter 'order_id' is set + if ('order_id' not in params) or (params['order_id'] is None): + raise ValueError("Missing the required parameter `order_id` when calling `delete_order`") + + resource_path = '/store/order/{orderId}'.replace('{format}', 'json') + path_params = {} + if 'order_id' in params: + path_params['orderId'] = params['order_id'] + + query_params = {} + + header_params = {} + + form_params = [] + local_var_files = {} + + body_params = None + + # HTTP header `Accept` + header_params['Accept'] = self.api_client.\ + select_header_accept(['application/json', 'application/xml']) + if not header_params['Accept']: + del header_params['Accept'] + + # HTTP header `Content-Type` + header_params['Content-Type'] = self.api_client.\ + select_header_content_type([]) + + # Authentication setting + auth_settings = [] + + response = self.api_client.call_api(resource_path, 'DELETE', + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type=None, + auth_settings=auth_settings, + callback=params.get('callback')) + return response + def find_orders_by_status(self, **kwargs): """ Finds orders by status @@ -261,80 +338,6 @@ class StoreApi(object): callback=params.get('callback')) return response - def place_order(self, **kwargs): - """ - Place an order for a pet - - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please define a `callback` function - to be invoked when receiving the response. - >>> def callback_function(response): - >>> pprint(response) - >>> - >>> thread = api.place_order(callback=callback_function) - - :param callback function: The callback function - for asynchronous request. (optional) - :param Order body: order placed for purchasing the pet - :return: Order - If the method is called asynchronously, - returns the request thread. - """ - - all_params = ['body'] - all_params.append('callback') - - params = locals() - for key, val in iteritems(params['kwargs']): - if key not in all_params: - raise TypeError( - "Got an unexpected keyword argument '%s'" - " to method place_order" % key - ) - params[key] = val - del params['kwargs'] - - - resource_path = '/store/order'.replace('{format}', 'json') - path_params = {} - - query_params = {} - - header_params = {} - - form_params = [] - local_var_files = {} - - body_params = None - if 'body' in params: - body_params = params['body'] - - # HTTP header `Accept` - header_params['Accept'] = self.api_client.\ - select_header_accept(['application/json', 'application/xml']) - if not header_params['Accept']: - del header_params['Accept'] - - # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.\ - select_header_content_type([]) - - # Authentication setting - auth_settings = ['test_api_client_id', 'test_api_client_secret'] - - response = self.api_client.call_api(resource_path, 'POST', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='Order', - auth_settings=auth_settings, - callback=params.get('callback')) - return response - def get_order_by_id(self, order_id, **kwargs): """ Find purchase order by ID @@ -412,10 +415,10 @@ class StoreApi(object): callback=params.get('callback')) return response - def delete_order(self, order_id, **kwargs): + def place_order(self, **kwargs): """ - Delete purchase order by ID - For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + Place an order for a pet + This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function @@ -423,17 +426,17 @@ class StoreApi(object): >>> def callback_function(response): >>> pprint(response) >>> - >>> thread = api.delete_order(order_id, callback=callback_function) + >>> thread = api.place_order(callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) - :param str order_id: ID of the order that needs to be deleted (required) - :return: None + :param Order body: order placed for purchasing the pet + :return: Order If the method is called asynchronously, returns the request thread. """ - all_params = ['order_id'] + all_params = ['body'] all_params.append('callback') params = locals() @@ -441,19 +444,14 @@ class StoreApi(object): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" - " to method delete_order" % key + " to method place_order" % key ) params[key] = val del params['kwargs'] - # verify the required parameter 'order_id' is set - if ('order_id' not in params) or (params['order_id'] is None): - raise ValueError("Missing the required parameter `order_id` when calling `delete_order`") - resource_path = '/store/order/{orderId}'.replace('{format}', 'json') + resource_path = '/store/order'.replace('{format}', 'json') path_params = {} - if 'order_id' in params: - path_params['orderId'] = params['order_id'] query_params = {} @@ -463,6 +461,8 @@ class StoreApi(object): local_var_files = {} body_params = None + if 'body' in params: + body_params = params['body'] # HTTP header `Accept` header_params['Accept'] = self.api_client.\ @@ -475,16 +475,16 @@ class StoreApi(object): select_header_content_type([]) # Authentication setting - auth_settings = [] + auth_settings = ['test_api_client_id', 'test_api_client_secret'] - response = self.api_client.call_api(resource_path, 'DELETE', + response = self.api_client.call_api(resource_path, 'POST', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, - response_type=None, + response_type='Order', auth_settings=auth_settings, callback=params.get('callback')) return response diff --git a/samples/client/petstore/python/swagger_client/apis/user_api.py b/samples/client/petstore/python/swagger_client/apis/user_api.py index a83243cc245..07d976b0bf5 100644 --- a/samples/client/petstore/python/swagger_client/apis/user_api.py +++ b/samples/client/petstore/python/swagger_client/apis/user_api.py @@ -267,6 +267,160 @@ class UserApi(object): callback=params.get('callback')) return response + def delete_user(self, username, **kwargs): + """ + Delete user + This can only be done by the logged in user. + + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please define a `callback` function + to be invoked when receiving the response. + >>> def callback_function(response): + >>> pprint(response) + >>> + >>> thread = api.delete_user(username, callback=callback_function) + + :param callback function: The callback function + for asynchronous request. (optional) + :param str username: The name that needs to be deleted (required) + :return: None + If the method is called asynchronously, + returns the request thread. + """ + + all_params = ['username'] + all_params.append('callback') + + params = locals() + for key, val in iteritems(params['kwargs']): + if key not in all_params: + raise TypeError( + "Got an unexpected keyword argument '%s'" + " to method delete_user" % key + ) + params[key] = val + del params['kwargs'] + + # verify the required parameter 'username' is set + if ('username' not in params) or (params['username'] is None): + raise ValueError("Missing the required parameter `username` when calling `delete_user`") + + resource_path = '/user/{username}'.replace('{format}', 'json') + path_params = {} + if 'username' in params: + path_params['username'] = params['username'] + + query_params = {} + + header_params = {} + + form_params = [] + local_var_files = {} + + body_params = None + + # HTTP header `Accept` + header_params['Accept'] = self.api_client.\ + select_header_accept(['application/json', 'application/xml']) + if not header_params['Accept']: + del header_params['Accept'] + + # HTTP header `Content-Type` + header_params['Content-Type'] = self.api_client.\ + select_header_content_type([]) + + # Authentication setting + auth_settings = ['test_http_basic'] + + response = self.api_client.call_api(resource_path, 'DELETE', + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type=None, + auth_settings=auth_settings, + callback=params.get('callback')) + return response + + def get_user_by_name(self, username, **kwargs): + """ + Get user by user name + + + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please define a `callback` function + to be invoked when receiving the response. + >>> def callback_function(response): + >>> pprint(response) + >>> + >>> thread = api.get_user_by_name(username, callback=callback_function) + + :param callback function: The callback function + for asynchronous request. (optional) + :param str username: The name that needs to be fetched. Use user1 for testing. (required) + :return: User + If the method is called asynchronously, + returns the request thread. + """ + + all_params = ['username'] + all_params.append('callback') + + params = locals() + for key, val in iteritems(params['kwargs']): + if key not in all_params: + raise TypeError( + "Got an unexpected keyword argument '%s'" + " to method get_user_by_name" % key + ) + params[key] = val + del params['kwargs'] + + # verify the required parameter 'username' is set + if ('username' not in params) or (params['username'] is None): + raise ValueError("Missing the required parameter `username` when calling `get_user_by_name`") + + resource_path = '/user/{username}'.replace('{format}', 'json') + path_params = {} + if 'username' in params: + path_params['username'] = params['username'] + + query_params = {} + + header_params = {} + + form_params = [] + local_var_files = {} + + body_params = None + + # HTTP header `Accept` + header_params['Accept'] = self.api_client.\ + select_header_accept(['application/json', 'application/xml']) + if not header_params['Accept']: + del header_params['Accept'] + + # HTTP header `Content-Type` + header_params['Content-Type'] = self.api_client.\ + select_header_content_type([]) + + # Authentication setting + auth_settings = [] + + response = self.api_client.call_api(resource_path, 'GET', + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type='User', + auth_settings=auth_settings, + callback=params.get('callback')) + return response + def login_user(self, **kwargs): """ Logs user into the system @@ -415,83 +569,6 @@ class UserApi(object): callback=params.get('callback')) return response - def get_user_by_name(self, username, **kwargs): - """ - Get user by user name - - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please define a `callback` function - to be invoked when receiving the response. - >>> def callback_function(response): - >>> pprint(response) - >>> - >>> thread = api.get_user_by_name(username, callback=callback_function) - - :param callback function: The callback function - for asynchronous request. (optional) - :param str username: The name that needs to be fetched. Use user1 for testing. (required) - :return: User - If the method is called asynchronously, - returns the request thread. - """ - - all_params = ['username'] - all_params.append('callback') - - params = locals() - for key, val in iteritems(params['kwargs']): - if key not in all_params: - raise TypeError( - "Got an unexpected keyword argument '%s'" - " to method get_user_by_name" % key - ) - params[key] = val - del params['kwargs'] - - # verify the required parameter 'username' is set - if ('username' not in params) or (params['username'] is None): - raise ValueError("Missing the required parameter `username` when calling `get_user_by_name`") - - resource_path = '/user/{username}'.replace('{format}', 'json') - path_params = {} - if 'username' in params: - path_params['username'] = params['username'] - - query_params = {} - - header_params = {} - - form_params = [] - local_var_files = {} - - body_params = None - - # HTTP header `Accept` - header_params['Accept'] = self.api_client.\ - select_header_accept(['application/json', 'application/xml']) - if not header_params['Accept']: - del header_params['Accept'] - - # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.\ - select_header_content_type([]) - - # Authentication setting - auth_settings = [] - - response = self.api_client.call_api(resource_path, 'GET', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='User', - auth_settings=auth_settings, - callback=params.get('callback')) - return response - def update_user(self, username, **kwargs): """ Updated user @@ -571,80 +648,3 @@ class UserApi(object): auth_settings=auth_settings, callback=params.get('callback')) return response - - def delete_user(self, username, **kwargs): - """ - Delete user - This can only be done by the logged in user. - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please define a `callback` function - to be invoked when receiving the response. - >>> def callback_function(response): - >>> pprint(response) - >>> - >>> thread = api.delete_user(username, callback=callback_function) - - :param callback function: The callback function - for asynchronous request. (optional) - :param str username: The name that needs to be deleted (required) - :return: None - If the method is called asynchronously, - returns the request thread. - """ - - all_params = ['username'] - all_params.append('callback') - - params = locals() - for key, val in iteritems(params['kwargs']): - if key not in all_params: - raise TypeError( - "Got an unexpected keyword argument '%s'" - " to method delete_user" % key - ) - params[key] = val - del params['kwargs'] - - # verify the required parameter 'username' is set - if ('username' not in params) or (params['username'] is None): - raise ValueError("Missing the required parameter `username` when calling `delete_user`") - - resource_path = '/user/{username}'.replace('{format}', 'json') - path_params = {} - if 'username' in params: - path_params['username'] = params['username'] - - query_params = {} - - header_params = {} - - form_params = [] - local_var_files = {} - - body_params = None - - # HTTP header `Accept` - header_params['Accept'] = self.api_client.\ - select_header_accept(['application/json', 'application/xml']) - if not header_params['Accept']: - del header_params['Accept'] - - # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.\ - select_header_content_type([]) - - # Authentication setting - auth_settings = [] - - response = self.api_client.call_api(resource_path, 'DELETE', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type=None, - auth_settings=auth_settings, - callback=params.get('callback')) - return response diff --git a/samples/client/petstore/python/swagger_client/configuration.py b/samples/client/petstore/python/swagger_client/configuration.py index 1a25cff0c58..8f66e4428c5 100644 --- a/samples/client/petstore/python/swagger_client/configuration.py +++ b/samples/client/petstore/python/swagger_client/configuration.py @@ -231,6 +231,13 @@ class Configuration(object): 'key': 'api_key', 'value': self.get_api_key_with_prefix('api_key') }, + 'test_http_basic': + { + 'type': 'basic', + 'in': 'header', + 'key': 'Authorization', + 'value': self.get_basic_auth_token() + }, 'test_api_client_secret': { 'type': 'api_key', diff --git a/samples/client/petstore/python/swagger_client/models/__init__.py b/samples/client/petstore/python/swagger_client/models/__init__.py index 399e634fe30..c441500bc40 100644 --- a/samples/client/petstore/python/swagger_client/models/__init__.py +++ b/samples/client/petstore/python/swagger_client/models/__init__.py @@ -1,11 +1,16 @@ from __future__ import absolute_import # import models into model package -from .user import User +from .animal import Animal +from .cat import Cat from .category import Category -from .pet import Pet -from .tag import Tag -from .object_return import ObjectReturn -from .order import Order -from .special_model_name import SpecialModelName +from .dog import Dog from .inline_response_200 import InlineResponse200 +from .model_200_response import Model200Response +from .model_return import ModelReturn +from .name import Name +from .order import Order +from .pet import Pet +from .special_model_name import SpecialModelName +from .tag import Tag +from .user import User diff --git a/samples/client/petstore/python/swagger_client/models/animal.py b/samples/client/petstore/python/swagger_client/models/animal.py new file mode 100644 index 00000000000..762e3df5b37 --- /dev/null +++ b/samples/client/petstore/python/swagger_client/models/animal.py @@ -0,0 +1,120 @@ +# coding: utf-8 + +""" +Copyright 2016 SmartBear Software + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Ref: https://github.com/swagger-api/swagger-codegen +""" + +from pprint import pformat +from six import iteritems + + +class Animal(object): + """ + NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. + """ + def __init__(self): + """ + Animal - 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 = { + 'class_name': 'str' + } + + self.attribute_map = { + 'class_name': 'className' + } + + self._class_name = None + + @property + def class_name(self): + """ + Gets the class_name of this Animal. + + + :return: The class_name of this Animal. + :rtype: str + """ + return self._class_name + + @class_name.setter + def class_name(self, class_name): + """ + Sets the class_name of this Animal. + + + :param class_name: The class_name of this Animal. + :type: str + """ + self._class_name = class_name + + def to_dict(self): + """ + Returns the model properties as a dict + """ + result = {} + + for attr, _ in iteritems(self.swagger_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list(map( + lambda x: x.to_dict() if hasattr(x, "to_dict") else x, + value + )) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict(map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") else item, + value.items() + )) + else: + result[attr] = value + + return result + + def to_str(self): + """ + Returns the string representation of the model + """ + return pformat(self.to_dict()) + + def __repr__(self): + """ + For `print` and `pprint` + """ + return self.to_str() + + def __eq__(self, other): + """ + Returns true if both objects are equal + """ + return self.__dict__ == other.__dict__ + + def __ne__(self, other): + """ + Returns true if both objects are not equal + """ + return not self == other + diff --git a/samples/client/petstore/python/swagger_client/models/cat.py b/samples/client/petstore/python/swagger_client/models/cat.py new file mode 100644 index 00000000000..4744fc4821c --- /dev/null +++ b/samples/client/petstore/python/swagger_client/models/cat.py @@ -0,0 +1,145 @@ +# coding: utf-8 + +""" +Copyright 2016 SmartBear Software + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Ref: https://github.com/swagger-api/swagger-codegen +""" + +from pprint import pformat +from six import iteritems + + +class Cat(object): + """ + NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. + """ + def __init__(self): + """ + Cat - 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 = { + 'class_name': 'str', + 'declawed': 'bool' + } + + self.attribute_map = { + 'class_name': 'className', + 'declawed': 'declawed' + } + + self._class_name = None + self._declawed = None + + @property + def class_name(self): + """ + Gets the class_name of this Cat. + + + :return: The class_name of this Cat. + :rtype: str + """ + return self._class_name + + @class_name.setter + def class_name(self, class_name): + """ + Sets the class_name of this Cat. + + + :param class_name: The class_name of this Cat. + :type: str + """ + self._class_name = class_name + + @property + def declawed(self): + """ + Gets the declawed of this Cat. + + + :return: The declawed of this Cat. + :rtype: bool + """ + return self._declawed + + @declawed.setter + def declawed(self, declawed): + """ + Sets the declawed of this Cat. + + + :param declawed: The declawed of this Cat. + :type: bool + """ + self._declawed = declawed + + def to_dict(self): + """ + Returns the model properties as a dict + """ + result = {} + + for attr, _ in iteritems(self.swagger_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list(map( + lambda x: x.to_dict() if hasattr(x, "to_dict") else x, + value + )) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict(map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") else item, + value.items() + )) + else: + result[attr] = value + + return result + + def to_str(self): + """ + Returns the string representation of the model + """ + return pformat(self.to_dict()) + + def __repr__(self): + """ + For `print` and `pprint` + """ + return self.to_str() + + def __eq__(self, other): + """ + Returns true if both objects are equal + """ + return self.__dict__ == other.__dict__ + + def __ne__(self, other): + """ + Returns true if both objects are not equal + """ + return not self == other + diff --git a/samples/client/petstore/python/swagger_client/models/dog.py b/samples/client/petstore/python/swagger_client/models/dog.py new file mode 100644 index 00000000000..3885dd314ef --- /dev/null +++ b/samples/client/petstore/python/swagger_client/models/dog.py @@ -0,0 +1,145 @@ +# coding: utf-8 + +""" +Copyright 2016 SmartBear Software + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Ref: https://github.com/swagger-api/swagger-codegen +""" + +from pprint import pformat +from six import iteritems + + +class Dog(object): + """ + NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. + """ + def __init__(self): + """ + Dog - 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 = { + 'class_name': 'str', + 'breed': 'str' + } + + self.attribute_map = { + 'class_name': 'className', + 'breed': 'breed' + } + + self._class_name = None + self._breed = None + + @property + def class_name(self): + """ + Gets the class_name of this Dog. + + + :return: The class_name of this Dog. + :rtype: str + """ + return self._class_name + + @class_name.setter + def class_name(self, class_name): + """ + Sets the class_name of this Dog. + + + :param class_name: The class_name of this Dog. + :type: str + """ + self._class_name = class_name + + @property + def breed(self): + """ + Gets the breed of this Dog. + + + :return: The breed of this Dog. + :rtype: str + """ + return self._breed + + @breed.setter + def breed(self, breed): + """ + Sets the breed of this Dog. + + + :param breed: The breed of this Dog. + :type: str + """ + self._breed = breed + + def to_dict(self): + """ + Returns the model properties as a dict + """ + result = {} + + for attr, _ in iteritems(self.swagger_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list(map( + lambda x: x.to_dict() if hasattr(x, "to_dict") else x, + value + )) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict(map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") else item, + value.items() + )) + else: + result[attr] = value + + return result + + def to_str(self): + """ + Returns the string representation of the model + """ + return pformat(self.to_dict()) + + def __repr__(self): + """ + For `print` and `pprint` + """ + return self.to_str() + + def __eq__(self, other): + """ + Returns true if both objects are equal + """ + return self.__dict__ == other.__dict__ + + def __ne__(self, other): + """ + Returns true if both objects are not equal + """ + return not self == other + diff --git a/samples/client/petstore/python/swagger_client/models/inline_response_200.py b/samples/client/petstore/python/swagger_client/models/inline_response_200.py new file mode 100644 index 00000000000..f55ff5ee4d5 --- /dev/null +++ b/samples/client/petstore/python/swagger_client/models/inline_response_200.py @@ -0,0 +1,251 @@ +# coding: utf-8 + +""" +Copyright 2016 SmartBear Software + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Ref: https://github.com/swagger-api/swagger-codegen +""" + +from pprint import pformat +from six import iteritems + + +class InlineResponse200(object): + """ + NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. + """ + def __init__(self): + """ + InlineResponse200 - a model defined in Swagger + + :param dict swaggerTypes: The key is attribute name + and the value is attribute type. + :param dict attributeMap: The key is attribute name + and the value is json key in definition. + """ + self.swagger_types = { + 'tags': 'list[Tag]', + 'id': 'int', + 'category': 'object', + 'status': 'str', + 'name': 'str', + 'photo_urls': 'list[str]' + } + + self.attribute_map = { + 'tags': 'tags', + 'id': 'id', + 'category': 'category', + 'status': 'status', + 'name': 'name', + 'photo_urls': 'photoUrls' + } + + self._tags = None + self._id = None + self._category = None + self._status = None + self._name = None + self._photo_urls = None + + @property + def tags(self): + """ + Gets the tags of this InlineResponse200. + + + :return: The tags of this InlineResponse200. + :rtype: list[Tag] + """ + return self._tags + + @tags.setter + def tags(self, tags): + """ + Sets the tags of this InlineResponse200. + + + :param tags: The tags of this InlineResponse200. + :type: list[Tag] + """ + self._tags = tags + + @property + def id(self): + """ + Gets the id of this InlineResponse200. + + + :return: The id of this InlineResponse200. + :rtype: int + """ + return self._id + + @id.setter + def id(self, id): + """ + Sets the id of this InlineResponse200. + + + :param id: The id of this InlineResponse200. + :type: int + """ + self._id = id + + @property + def category(self): + """ + Gets the category of this InlineResponse200. + + + :return: The category of this InlineResponse200. + :rtype: object + """ + return self._category + + @category.setter + def category(self, category): + """ + Sets the category of this InlineResponse200. + + + :param category: The category of this InlineResponse200. + :type: object + """ + self._category = category + + @property + def status(self): + """ + Gets the status of this InlineResponse200. + pet status in the store + + :return: The status of this InlineResponse200. + :rtype: str + """ + return self._status + + @status.setter + def status(self, status): + """ + Sets the status of this InlineResponse200. + pet status in the store + + :param status: The status of this InlineResponse200. + :type: str + """ + allowed_values = ["available", "pending", "sold"] + if status not in allowed_values: + raise ValueError( + "Invalid value for `status`, must be one of {0}" + .format(allowed_values) + ) + self._status = status + + @property + def name(self): + """ + Gets the name of this InlineResponse200. + + + :return: The name of this InlineResponse200. + :rtype: str + """ + return self._name + + @name.setter + def name(self, name): + """ + Sets the name of this InlineResponse200. + + + :param name: The name of this InlineResponse200. + :type: str + """ + self._name = name + + @property + def photo_urls(self): + """ + Gets the photo_urls of this InlineResponse200. + + + :return: The photo_urls of this InlineResponse200. + :rtype: list[str] + """ + return self._photo_urls + + @photo_urls.setter + def photo_urls(self, photo_urls): + """ + Sets the photo_urls of this InlineResponse200. + + + :param photo_urls: The photo_urls of this InlineResponse200. + :type: list[str] + """ + self._photo_urls = photo_urls + + def to_dict(self): + """ + Returns the model properties as a dict + """ + result = {} + + for attr, _ in iteritems(self.swagger_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list(map( + lambda x: x.to_dict() if hasattr(x, "to_dict") else x, + value + )) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict(map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") else item, + value.items() + )) + else: + result[attr] = value + + return result + + def to_str(self): + """ + Returns the string representation of the model + """ + return pformat(self.to_dict()) + + def __repr__(self): + """ + For `print` and `pprint` + """ + return self.to_str() + + def __eq__(self, other): + """ + Returns true if both objects are equal + """ + return self.__dict__ == other.__dict__ + + def __ne__(self, other): + """ + Returns true if both objects are not equal + """ + return not self == other + diff --git a/samples/client/petstore/python/swagger_client/models/model_200_response.py b/samples/client/petstore/python/swagger_client/models/model_200_response.py new file mode 100644 index 00000000000..681de963e6e --- /dev/null +++ b/samples/client/petstore/python/swagger_client/models/model_200_response.py @@ -0,0 +1,120 @@ +# coding: utf-8 + +""" +Copyright 2016 SmartBear Software + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Ref: https://github.com/swagger-api/swagger-codegen +""" + +from pprint import pformat +from six import iteritems + + +class Model200Response(object): + """ + NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. + """ + def __init__(self): + """ + Model200Response - 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 = { + 'name': 'int' + } + + self.attribute_map = { + 'name': 'name' + } + + self._name = None + + @property + def name(self): + """ + Gets the name of this Model200Response. + + + :return: The name of this Model200Response. + :rtype: int + """ + return self._name + + @name.setter + def name(self, name): + """ + Sets the name of this Model200Response. + + + :param name: The name of this Model200Response. + :type: int + """ + self._name = name + + def to_dict(self): + """ + Returns the model properties as a dict + """ + result = {} + + for attr, _ in iteritems(self.swagger_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list(map( + lambda x: x.to_dict() if hasattr(x, "to_dict") else x, + value + )) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict(map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") else item, + value.items() + )) + else: + result[attr] = value + + return result + + def to_str(self): + """ + Returns the string representation of the model + """ + return pformat(self.to_dict()) + + def __repr__(self): + """ + For `print` and `pprint` + """ + return self.to_str() + + def __eq__(self, other): + """ + Returns true if both objects are equal + """ + return self.__dict__ == other.__dict__ + + def __ne__(self, other): + """ + Returns true if both objects are not equal + """ + return not self == other + diff --git a/samples/client/petstore/python/swagger_client/models/model_return.py b/samples/client/petstore/python/swagger_client/models/model_return.py new file mode 100644 index 00000000000..75b46259d6f --- /dev/null +++ b/samples/client/petstore/python/swagger_client/models/model_return.py @@ -0,0 +1,120 @@ +# coding: utf-8 + +""" +Copyright 2016 SmartBear Software + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Ref: https://github.com/swagger-api/swagger-codegen +""" + +from pprint import pformat +from six import iteritems + + +class ModelReturn(object): + """ + NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. + """ + def __init__(self): + """ + ModelReturn - 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 = { + '_return': 'int' + } + + self.attribute_map = { + '_return': 'return' + } + + self.__return = None + + @property + def _return(self): + """ + Gets the _return of this ModelReturn. + + + :return: The _return of this ModelReturn. + :rtype: int + """ + return self.__return + + @_return.setter + def _return(self, _return): + """ + Sets the _return of this ModelReturn. + + + :param _return: The _return of this ModelReturn. + :type: int + """ + self.__return = _return + + def to_dict(self): + """ + Returns the model properties as a dict + """ + result = {} + + for attr, _ in iteritems(self.swagger_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list(map( + lambda x: x.to_dict() if hasattr(x, "to_dict") else x, + value + )) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict(map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") else item, + value.items() + )) + else: + result[attr] = value + + return result + + def to_str(self): + """ + Returns the string representation of the model + """ + return pformat(self.to_dict()) + + def __repr__(self): + """ + For `print` and `pprint` + """ + return self.to_str() + + def __eq__(self, other): + """ + Returns true if both objects are equal + """ + return self.__dict__ == other.__dict__ + + def __ne__(self, other): + """ + Returns true if both objects are not equal + """ + return not self == other + diff --git a/samples/client/petstore/python/swagger_client/models/name.py b/samples/client/petstore/python/swagger_client/models/name.py new file mode 100644 index 00000000000..068bca97eea --- /dev/null +++ b/samples/client/petstore/python/swagger_client/models/name.py @@ -0,0 +1,145 @@ +# coding: utf-8 + +""" +Copyright 2016 SmartBear Software + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Ref: https://github.com/swagger-api/swagger-codegen +""" + +from pprint import pformat +from six import iteritems + + +class Name(object): + """ + NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. + """ + def __init__(self): + """ + Name - 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 = { + 'name': 'int', + 'snake_case': 'int' + } + + self.attribute_map = { + 'name': 'name', + 'snake_case': 'snake_case' + } + + self._name = None + self._snake_case = None + + @property + def name(self): + """ + Gets the name of this Name. + + + :return: The name of this Name. + :rtype: int + """ + return self._name + + @name.setter + def name(self, name): + """ + Sets the name of this Name. + + + :param name: The name of this Name. + :type: int + """ + self._name = name + + @property + def snake_case(self): + """ + Gets the snake_case of this Name. + + + :return: The snake_case of this Name. + :rtype: int + """ + 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 + + def to_dict(self): + """ + Returns the model properties as a dict + """ + result = {} + + for attr, _ in iteritems(self.swagger_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list(map( + lambda x: x.to_dict() if hasattr(x, "to_dict") else x, + value + )) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict(map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") else item, + value.items() + )) + else: + result[attr] = value + + return result + + def to_str(self): + """ + Returns the string representation of the model + """ + return pformat(self.to_dict()) + + def __repr__(self): + """ + For `print` and `pprint` + """ + return self.to_str() + + def __eq__(self, other): + """ + Returns true if both objects are equal + """ + return self.__dict__ == other.__dict__ + + def __ne__(self, other): + """ + Returns true if both objects are not equal + """ + return not self == other + diff --git a/samples/client/petstore/python/swagger_client/models/special_model_name.py b/samples/client/petstore/python/swagger_client/models/special_model_name.py new file mode 100644 index 00000000000..191798d7d9a --- /dev/null +++ b/samples/client/petstore/python/swagger_client/models/special_model_name.py @@ -0,0 +1,120 @@ +# coding: utf-8 + +""" +Copyright 2016 SmartBear Software + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Ref: https://github.com/swagger-api/swagger-codegen +""" + +from pprint import pformat +from six import iteritems + + +class SpecialModelName(object): + """ + NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. + """ + def __init__(self): + """ + SpecialModelName - 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 = { + 'special_property_name': 'int' + } + + self.attribute_map = { + 'special_property_name': '$special[property.name]' + } + + self._special_property_name = None + + @property + def special_property_name(self): + """ + Gets the special_property_name of this SpecialModelName. + + + :return: The special_property_name of this SpecialModelName. + :rtype: int + """ + return self._special_property_name + + @special_property_name.setter + def special_property_name(self, special_property_name): + """ + Sets the special_property_name of this SpecialModelName. + + + :param special_property_name: The special_property_name of this SpecialModelName. + :type: int + """ + self._special_property_name = special_property_name + + def to_dict(self): + """ + Returns the model properties as a dict + """ + result = {} + + for attr, _ in iteritems(self.swagger_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list(map( + lambda x: x.to_dict() if hasattr(x, "to_dict") else x, + value + )) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict(map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") else item, + value.items() + )) + else: + result[attr] = value + + return result + + def to_str(self): + """ + Returns the string representation of the model + """ + return pformat(self.to_dict()) + + def __repr__(self): + """ + For `print` and `pprint` + """ + return self.to_str() + + def __eq__(self, other): + """ + Returns true if both objects are equal + """ + return self.__dict__ == other.__dict__ + + def __ne__(self, other): + """ + Returns true if both objects are not equal + """ + return not self == other + diff --git a/samples/client/petstore/python/swagger_client/rest.py b/samples/client/petstore/python/swagger_client/rest.py index c5b9a4e6f91..352bb503ac5 100644 --- a/samples/client/petstore/python/swagger_client/rest.py +++ b/samples/client/petstore/python/swagger_client/rest.py @@ -133,8 +133,8 @@ class RESTClientObject(object): headers['Content-Type'] = 'application/json' try: - # For `POST`, `PUT`, `PATCH`, `OPTIONS` - if method in ['POST', 'PUT', 'PATCH', 'OPTIONS']: + # For `POST`, `PUT`, `PATCH`, `OPTIONS`, `DELETE` + if method in ['POST', 'PUT', 'PATCH', 'OPTIONS', 'DELETE']: if query_params: url += '?' + urlencode(query_params) if headers['Content-Type'] == 'application/json': @@ -154,7 +154,7 @@ class RESTClientObject(object): fields=post_params, encode_multipart=True, headers=headers) - # For `GET`, `HEAD`, `DELETE` + # For `GET`, `HEAD` else: r = self.pool_manager.request(method, url, fields=query_params, @@ -195,10 +195,11 @@ class RESTClientObject(object): post_params=post_params, body=body) - def DELETE(self, url, headers=None, query_params=None): + def DELETE(self, url, headers=None, query_params=None, body=None): return self.request("DELETE", url, headers=headers, - query_params=query_params) + query_params=query_params, + body=body) def POST(self, url, headers=None, query_params=None, post_params=None, body=None): return self.request("POST", url, diff --git a/samples/client/petstore/python/tests/test_api_exception.py b/samples/client/petstore/python/tests/test_api_exception.py index a60594b3edd..790a18dffd0 100644 --- a/samples/client/petstore/python/tests/test_api_exception.py +++ b/samples/client/petstore/python/tests/test_api_exception.py @@ -8,6 +8,7 @@ $ nosetests -v """ import os +import sys import time import unittest @@ -44,7 +45,7 @@ class ApiExceptionTests(unittest.TestCase): self.pet_api.add_pet(body=self.pet) self.pet_api.delete_pet(pet_id=self.pet.id) - with self.assertRaisesRegexp(ApiException, "Pet not found"): + with self.checkRaiseRegex(ApiException, "Pet not found"): self.pet_api.get_pet_by_id(pet_id=self.pet.id) try: @@ -52,12 +53,12 @@ class ApiExceptionTests(unittest.TestCase): except ApiException as e: self.assertEqual(e.status, 404) self.assertEqual(e.reason, "Not Found") - self.assertRegexpMatches(e.body, "Pet not found") + self.checkRegex(e.body, "Pet not found") def test_500_error(self): self.pet_api.add_pet(body=self.pet) - with self.assertRaisesRegexp(ApiException, "Internal Server Error"): + with self.checkRaiseRegex(ApiException, "Internal Server Error"): self.pet_api.upload_file( pet_id=self.pet.id, additional_metadata="special", @@ -73,4 +74,17 @@ class ApiExceptionTests(unittest.TestCase): except ApiException as e: self.assertEqual(e.status, 500) self.assertEqual(e.reason, "Internal Server Error") - self.assertRegexpMatches(e.body, "Error 500 Internal Server Error") + self.checkRegex(e.body, "Error 500 Internal Server Error") + + def checkRaiseRegex(self, expected_exception, expected_regex): + if sys.version_info < (3, 0): + return self.assertRaisesRegexp(expected_exception, expected_regex) + + return self.assertRaisesRegex(expected_exception, expected_regex) + + def checkRegex(self, text, expected_regex): + if sys.version_info < (3, 0): + return self.assertRegexpMatches(text, expected_regex) + + return self.assertRegex(text, expected_regex) + diff --git a/samples/client/petstore/ruby/.gitignore b/samples/client/petstore/ruby/.gitignore new file mode 100644 index 00000000000..a8b1cda23f8 --- /dev/null +++ b/samples/client/petstore/ruby/.gitignore @@ -0,0 +1,36 @@ +*.gem +*.rbc +/.config +/coverage/ +/InstalledFiles +/pkg/ +/spec/reports/ +/spec/examples.txt +/test/tmp/ +/test/version_tmp/ +/tmp/ + +## Specific to RubyMotion: +.dat* +.repl_history +build/ + +## Documentation cache and generated files: +/.yardoc/ +/_yardoc/ +/doc/ +/rdoc/ + +## Environment normalization: +/.bundle/ +/vendor/bundle +/lib/bundler/man/ + +# for a library or gem, you might want to ignore these files since the code is +# intended to run in multiple environments; otherwise, check them in: +# Gemfile.lock +# .ruby-version +# .ruby-gemset + +# unless supporting rvm < 1.11.0 or doing something fancy, ignore this: +.rvmrc diff --git a/samples/client/petstore/ruby/README.md b/samples/client/petstore/ruby/README.md index dd6258ec696..9294e57a882 100644 --- a/samples/client/petstore/ruby/README.md +++ b/samples/client/petstore/ruby/README.md @@ -1,37 +1,47 @@ +# petstore + +Petstore - the Ruby gem for the 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 + +This SDK is automatically generated by the [Swagger Codegen](https://github.com/swagger-api/swagger-codegen) project: + +- API version: 1.0.0 +- Package version: 1.0.0 +- Build date: 2016-04-09T17:50:53.781+08:00 +- Build package: class io.swagger.codegen.languages.RubyClientCodegen + ## Installation ### Build a gem -You can build the generated client into a gem: +To build the Ruby code into a gem: ```shell gem build petstore.gemspec ``` -Then you can either install the gem: +Then either install the gem locally: ```shell gem install ./petstore-1.0.0.gem ``` -or publish the gem to a gem server like [RubyGems](https://rubygems.org/). +or publish the gem to a gem hosting service, e.g. [RubyGems](https://rubygems.org/). -Finally add this to your Gemfile: +Finally add this to the Gemfile: gem 'petstore', '~> 1.0.0' -### Host as a git repository +### Install from Git -You can also choose to host the generated client as a git repository, e.g. on github: -https://github.com/xhh/swagger-petstore-ruby +If the Ruby gem is hosted at a git repository: https://github.com/YOUR_GIT_USR_ID/YOUR_GIT_REPO_ID, then add the following in the Gemfile: -Then you can reference it in Gemfile: + gem 'petstore', :git => 'https://github.com/YOUR_GIT_USR_ID/YOUR_GIT_REPO_ID.git' - gem 'petstore', :git => 'https://github.com/xhh/swagger-petstore-ruby.git' +### Include the Ruby code directly -### Use without installation - -You can also use the client directly like this: +Include the Ruby code directly using `-I` as follows: ```shell ruby -Ilib script.rb @@ -39,18 +49,125 @@ ruby -Ilib script.rb ## Getting Started +Please follow the [installation](#installation) procedure and then run the following code: ```ruby +# Load the gem require 'petstore' +# Setup authorization Petstore.configure do |config| - config.api_key['api_key'] = 'special-key' - config.host = 'petstore.swagger.io' - config.base_path = '/v2' - # enable debugging (default is disabled) - config.debugging = true + # Configure OAuth2 access token for authorization: petstore_auth + config.access_token = 'YOUR ACCESS TOKEN' +end + +api_instance = Petstore::PetApi.new + +opts = { + body: Petstore::Pet.new # Pet | Pet object that needs to be added to the store +} + +begin + #Add a new pet to the store + api_instance.add_pet(opts) +rescue Petstore::ApiError => e + puts "Exception when calling PetApi->add_pet: #{e}" end -pet_api = Petstore::PetApi.new -pet = pet_api.get_pet_by_id(5) -puts pet.to_body ``` + +## Documentation for API Endpoints + +All URIs are relative to *http://petstore.swagger.io/v2* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +*Petstore::PetApi* | [**add_pet**](docs/PetApi.md#add_pet) | **POST** /pet | Add a new pet to the store +*Petstore::PetApi* | [**add_pet_using_byte_array**](docs/PetApi.md#add_pet_using_byte_array) | **POST** /pet?testing_byte_array=true | Fake endpoint to test byte array in body parameter for adding a new pet to the store +*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 +*Petstore::PetApi* | [**find_pets_by_tags**](docs/PetApi.md#find_pets_by_tags) | **GET** /pet/findByTags | Finds Pets by tags +*Petstore::PetApi* | [**get_pet_by_id**](docs/PetApi.md#get_pet_by_id) | **GET** /pet/{petId} | Find pet by ID +*Petstore::PetApi* | [**get_pet_by_id_in_object**](docs/PetApi.md#get_pet_by_id_in_object) | **GET** /pet/{petId}?response=inline_arbitrary_object | Fake endpoint to test inline arbitrary object return by 'Find pet by ID' +*Petstore::PetApi* | [**pet_pet_idtesting_byte_arraytrue_get**](docs/PetApi.md#pet_pet_idtesting_byte_arraytrue_get) | **GET** /pet/{petId}?testing_byte_array=true | Fake endpoint to test byte array return by 'Find pet by ID' +*Petstore::PetApi* | [**update_pet**](docs/PetApi.md#update_pet) | **PUT** /pet | Update an existing pet +*Petstore::PetApi* | [**update_pet_with_form**](docs/PetApi.md#update_pet_with_form) | **POST** /pet/{petId} | Updates a pet in the store with form data +*Petstore::PetApi* | [**upload_file**](docs/PetApi.md#upload_file) | **POST** /pet/{petId}/uploadImage | uploads an image +*Petstore::StoreApi* | [**delete_order**](docs/StoreApi.md#delete_order) | **DELETE** /store/order/{orderId} | Delete purchase order by ID +*Petstore::StoreApi* | [**find_orders_by_status**](docs/StoreApi.md#find_orders_by_status) | **GET** /store/findByStatus | Finds orders by status +*Petstore::StoreApi* | [**get_inventory**](docs/StoreApi.md#get_inventory) | **GET** /store/inventory | Returns pet inventories by status +*Petstore::StoreApi* | [**get_inventory_in_object**](docs/StoreApi.md#get_inventory_in_object) | **GET** /store/inventory?response=arbitrary_object | Fake endpoint to test arbitrary object return by 'Get inventory' +*Petstore::StoreApi* | [**get_order_by_id**](docs/StoreApi.md#get_order_by_id) | **GET** /store/order/{orderId} | Find purchase order by ID +*Petstore::StoreApi* | [**place_order**](docs/StoreApi.md#place_order) | **POST** /store/order | Place an order for a pet +*Petstore::UserApi* | [**create_user**](docs/UserApi.md#create_user) | **POST** /user | Create user +*Petstore::UserApi* | [**create_users_with_array_input**](docs/UserApi.md#create_users_with_array_input) | **POST** /user/createWithArray | Creates list of users with given input array +*Petstore::UserApi* | [**create_users_with_list_input**](docs/UserApi.md#create_users_with_list_input) | **POST** /user/createWithList | Creates list of users with given input array +*Petstore::UserApi* | [**delete_user**](docs/UserApi.md#delete_user) | **DELETE** /user/{username} | Delete user +*Petstore::UserApi* | [**get_user_by_name**](docs/UserApi.md#get_user_by_name) | **GET** /user/{username} | Get user by user name +*Petstore::UserApi* | [**login_user**](docs/UserApi.md#login_user) | **GET** /user/login | Logs user into the system +*Petstore::UserApi* | [**logout_user**](docs/UserApi.md#logout_user) | **GET** /user/logout | Logs out current logged in user session +*Petstore::UserApi* | [**update_user**](docs/UserApi.md#update_user) | **PUT** /user/{username} | Updated user + + +## Documentation for Models + + - [Petstore::Animal](docs/Animal.md) + - [Petstore::Cat](docs/Cat.md) + - [Petstore::Category](docs/Category.md) + - [Petstore::Dog](docs/Dog.md) + - [Petstore::InlineResponse200](docs/InlineResponse200.md) + - [Petstore::Model200Response](docs/Model200Response.md) + - [Petstore::ModelReturn](docs/ModelReturn.md) + - [Petstore::Name](docs/Name.md) + - [Petstore::Order](docs/Order.md) + - [Petstore::Pet](docs/Pet.md) + - [Petstore::SpecialModelName](docs/SpecialModelName.md) + - [Petstore::Tag](docs/Tag.md) + - [Petstore::User](docs/User.md) + + +## Documentation for Authorization + + +### test_api_key_header + +- **Type**: API key +- **API key parameter name**: test_api_key_header +- **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_client_secret + +- **Type**: API key +- **API key parameter name**: x-test_api_client_secret +- **Location**: HTTP header + +### test_api_client_id + +- **Type**: API key +- **API key parameter name**: x-test_api_client_id +- **Location**: HTTP header + +### test_api_key_query + +- **Type**: API key +- **API key parameter name**: test_api_key_query +- **Location**: URL query string + +### 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 + diff --git a/samples/client/petstore/ruby/docs/Animal.md b/samples/client/petstore/ruby/docs/Animal.md new file mode 100644 index 00000000000..0e262c78726 --- /dev/null +++ b/samples/client/petstore/ruby/docs/Animal.md @@ -0,0 +1,8 @@ +# Petstore::Animal + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**class_name** | **String** | | + + diff --git a/samples/client/petstore/ruby/docs/Cat.md b/samples/client/petstore/ruby/docs/Cat.md new file mode 100644 index 00000000000..6b7dfb710df --- /dev/null +++ b/samples/client/petstore/ruby/docs/Cat.md @@ -0,0 +1,9 @@ +# Petstore::Cat + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**class_name** | **String** | | +**declawed** | **BOOLEAN** | | [optional] + + diff --git a/samples/client/petstore/ruby/docs/Category.md b/samples/client/petstore/ruby/docs/Category.md new file mode 100644 index 00000000000..f642a3d6b86 --- /dev/null +++ b/samples/client/petstore/ruby/docs/Category.md @@ -0,0 +1,9 @@ +# Petstore::Category + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Integer** | | [optional] +**name** | **String** | | [optional] + + diff --git a/samples/client/petstore/ruby/docs/Dog.md b/samples/client/petstore/ruby/docs/Dog.md new file mode 100644 index 00000000000..7af6f549d5d --- /dev/null +++ b/samples/client/petstore/ruby/docs/Dog.md @@ -0,0 +1,9 @@ +# Petstore::Dog + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**class_name** | **String** | | +**breed** | **String** | | [optional] + + diff --git a/samples/client/petstore/ruby/docs/InlineResponse200.md b/samples/client/petstore/ruby/docs/InlineResponse200.md new file mode 100644 index 00000000000..c3b0d978c07 --- /dev/null +++ b/samples/client/petstore/ruby/docs/InlineResponse200.md @@ -0,0 +1,13 @@ +# Petstore::InlineResponse200 + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**tags** | [**Array<Tag>**](Tag.md) | | [optional] +**id** | **Integer** | | +**category** | **Object** | | [optional] +**status** | **String** | pet status in the store | [optional] +**name** | **String** | | [optional] +**photo_urls** | **Array<String>** | | [optional] + + diff --git a/samples/client/petstore/ruby/docs/Model200Response.md b/samples/client/petstore/ruby/docs/Model200Response.md new file mode 100644 index 00000000000..f440810f2b8 --- /dev/null +++ b/samples/client/petstore/ruby/docs/Model200Response.md @@ -0,0 +1,8 @@ +# Petstore::Model200Response + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **Integer** | | [optional] + + diff --git a/samples/client/petstore/ruby/docs/ModelReturn.md b/samples/client/petstore/ruby/docs/ModelReturn.md new file mode 100644 index 00000000000..dfcfff1dd06 --- /dev/null +++ b/samples/client/petstore/ruby/docs/ModelReturn.md @@ -0,0 +1,8 @@ +# Petstore::ModelReturn + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**_return** | **Integer** | | [optional] + + diff --git a/samples/client/petstore/ruby/docs/Name.md b/samples/client/petstore/ruby/docs/Name.md new file mode 100644 index 00000000000..d4d89f6c4ce --- /dev/null +++ b/samples/client/petstore/ruby/docs/Name.md @@ -0,0 +1,9 @@ +# Petstore::Name + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **Integer** | | [optional] +**snake_case** | **Integer** | | [optional] + + diff --git a/samples/client/petstore/ruby/docs/Order.md b/samples/client/petstore/ruby/docs/Order.md new file mode 100644 index 00000000000..ed1b69874ee --- /dev/null +++ b/samples/client/petstore/ruby/docs/Order.md @@ -0,0 +1,13 @@ +# Petstore::Order + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Integer** | | [optional] +**pet_id** | **Integer** | | [optional] +**quantity** | **Integer** | | [optional] +**ship_date** | **DateTime** | | [optional] +**status** | **String** | Order Status | [optional] +**complete** | **BOOLEAN** | | [optional] + + diff --git a/samples/client/petstore/ruby/docs/Pet.md b/samples/client/petstore/ruby/docs/Pet.md new file mode 100644 index 00000000000..f4320a0b72b --- /dev/null +++ b/samples/client/petstore/ruby/docs/Pet.md @@ -0,0 +1,13 @@ +# Petstore::Pet + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Integer** | | [optional] +**category** | [**Category**](Category.md) | | [optional] +**name** | **String** | | +**photo_urls** | **Array<String>** | | +**tags** | [**Array<Tag>**](Tag.md) | | [optional] +**status** | **String** | pet status in the store | [optional] + + diff --git a/samples/client/petstore/ruby/docs/PetApi.md b/samples/client/petstore/ruby/docs/PetApi.md new file mode 100644 index 00000000000..f817316359b --- /dev/null +++ b/samples/client/petstore/ruby/docs/PetApi.md @@ -0,0 +1,621 @@ +# Petstore::PetApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**add_pet**](PetApi.md#add_pet) | **POST** /pet | Add a new pet to the store +[**add_pet_using_byte_array**](PetApi.md#add_pet_using_byte_array) | **POST** /pet?testing_byte_array=true | Fake endpoint to test byte array in body parameter for adding a new pet to the store +[**delete_pet**](PetApi.md#delete_pet) | **DELETE** /pet/{petId} | Deletes a pet +[**find_pets_by_status**](PetApi.md#find_pets_by_status) | **GET** /pet/findByStatus | Finds Pets by status +[**find_pets_by_tags**](PetApi.md#find_pets_by_tags) | **GET** /pet/findByTags | Finds Pets by tags +[**get_pet_by_id**](PetApi.md#get_pet_by_id) | **GET** /pet/{petId} | Find pet by ID +[**get_pet_by_id_in_object**](PetApi.md#get_pet_by_id_in_object) | **GET** /pet/{petId}?response=inline_arbitrary_object | Fake endpoint to test inline arbitrary object return by 'Find pet by ID' +[**pet_pet_idtesting_byte_arraytrue_get**](PetApi.md#pet_pet_idtesting_byte_arraytrue_get) | **GET** /pet/{petId}?testing_byte_array=true | Fake endpoint to test byte array return by 'Find pet by ID' +[**update_pet**](PetApi.md#update_pet) | **PUT** /pet | Update an existing pet +[**update_pet_with_form**](PetApi.md#update_pet_with_form) | **POST** /pet/{petId} | Updates a pet in the store with form data +[**upload_file**](PetApi.md#upload_file) | **POST** /pet/{petId}/uploadImage | uploads an image + + +# **add_pet** +> add_pet(opts) + +Add a new pet to the store + + + +### Example +```ruby +# load the gem +require 'petstore' +# setup authorization +Petstore.configure do |config| + # Configure OAuth2 access token for authorization: petstore_auth + config.access_token = 'YOUR ACCESS TOKEN' +end + +api_instance = Petstore::PetApi.new + +opts = { + body: Petstore::Pet.new # Pet | Pet object that needs to be added to the store +} + +begin + #Add a new pet to the store + api_instance.add_pet(opts) +rescue Petstore::ApiError => e + puts "Exception when calling PetApi->add_pet: #{e}" +end +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | [optional] + +### Return type + +nil (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP reuqest headers + + - **Content-Type**: application/json, application/xml + - **Accept**: application/json, application/xml + + + +# **add_pet_using_byte_array** +> add_pet_using_byte_array(opts) + +Fake endpoint to test byte array in body parameter for adding a new pet to the store + + + +### Example +```ruby +# load the gem +require 'petstore' +# setup authorization +Petstore.configure do |config| + # Configure OAuth2 access token for authorization: petstore_auth + config.access_token = 'YOUR ACCESS TOKEN' +end + +api_instance = Petstore::PetApi.new + +opts = { + body: "B" # String | Pet object in the form of byte array +} + +begin + #Fake endpoint to test byte array in body parameter for adding a new pet to the store + api_instance.add_pet_using_byte_array(opts) +rescue Petstore::ApiError => e + puts "Exception when calling PetApi->add_pet_using_byte_array: #{e}" +end +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | **String**| Pet object in the form of byte array | [optional] + +### Return type + +nil (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP reuqest headers + + - **Content-Type**: application/json, application/xml + - **Accept**: application/json, application/xml + + + +# **delete_pet** +> delete_pet(pet_id, opts) + +Deletes a pet + + + +### Example +```ruby +# load the gem +require 'petstore' +# setup authorization +Petstore.configure do |config| + # Configure OAuth2 access token for authorization: petstore_auth + config.access_token = 'YOUR ACCESS TOKEN' +end + +api_instance = Petstore::PetApi.new + +pet_id = 789 # Integer | Pet id to delete + +opts = { + api_key: "api_key_example" # String | +} + +begin + #Deletes a pet + api_instance.delete_pet(pet_id, opts) +rescue Petstore::ApiError => e + puts "Exception when calling PetApi->delete_pet: #{e}" +end +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **pet_id** | **Integer**| Pet id to delete | + **api_key** | **String**| | [optional] + +### Return type + +nil (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + + + +# **find_pets_by_status** +> Array<Pet> find_pets_by_status(opts) + +Finds Pets by status + +Multiple status values can be provided with comma separated strings + +### Example +```ruby +# load the gem +require 'petstore' +# setup authorization +Petstore.configure do |config| + # Configure OAuth2 access token for authorization: petstore_auth + config.access_token = 'YOUR ACCESS TOKEN' +end + +api_instance = Petstore::PetApi.new + +opts = { + status: ["available"] # Array | Status values that need to be considered for query +} + +begin + #Finds Pets by status + result = api_instance.find_pets_by_status(opts) + p result +rescue Petstore::ApiError => e + puts "Exception when calling PetApi->find_pets_by_status: #{e}" +end +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **status** | [**Array<String>**](String.md)| Status values that need to be considered for query | [optional] [default to available] + +### Return type + +[**Array<Pet>**](Pet.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + + + +# **find_pets_by_tags** +> Array<Pet> find_pets_by_tags(opts) + +Finds Pets by tags + +Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + +### Example +```ruby +# load the gem +require 'petstore' +# setup authorization +Petstore.configure do |config| + # Configure OAuth2 access token for authorization: petstore_auth + config.access_token = 'YOUR ACCESS TOKEN' +end + +api_instance = Petstore::PetApi.new + +opts = { + tags: ["tags_example"] # Array | Tags to filter by +} + +begin + #Finds Pets by tags + result = api_instance.find_pets_by_tags(opts) + p result +rescue Petstore::ApiError => e + puts "Exception when calling PetApi->find_pets_by_tags: #{e}" +end +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **tags** | [**Array<String>**](String.md)| Tags to filter by | [optional] + +### Return type + +[**Array<Pet>**](Pet.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + + + +# **get_pet_by_id** +> Pet get_pet_by_id(pet_id) + +Find pet by ID + +Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + +### Example +```ruby +# load the gem +require 'petstore' +# setup authorization +Petstore.configure do |config| + # Configure API key authorization: api_key + config.api_key['api_key'] = 'YOUR API KEY' + # Uncomment the following line to set a prefix for the API key, e.g. 'BEARER' (defaults to nil) + #config.api_key_prefix['api_key'] = 'BEARER' + + # Configure OAuth2 access token for authorization: petstore_auth + config.access_token = 'YOUR ACCESS TOKEN' +end + +api_instance = Petstore::PetApi.new + +pet_id = 789 # Integer | ID of pet that needs to be fetched + + +begin + #Find pet by ID + result = api_instance.get_pet_by_id(pet_id) + p result +rescue Petstore::ApiError => e + puts "Exception when calling PetApi->get_pet_by_id: #{e}" +end +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **pet_id** | **Integer**| ID of pet that needs to be fetched | + +### Return type + +[**Pet**](Pet.md) + +### Authorization + +[api_key](../README.md#api_key), [petstore_auth](../README.md#petstore_auth) + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + + + +# **get_pet_by_id_in_object** +> InlineResponse200 get_pet_by_id_in_object(pet_id) + +Fake endpoint to test inline arbitrary object return by 'Find pet by ID' + +Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + +### Example +```ruby +# load the gem +require 'petstore' +# setup authorization +Petstore.configure do |config| + # Configure API key authorization: api_key + config.api_key['api_key'] = 'YOUR API KEY' + # Uncomment the following line to set a prefix for the API key, e.g. 'BEARER' (defaults to nil) + #config.api_key_prefix['api_key'] = 'BEARER' + + # Configure OAuth2 access token for authorization: petstore_auth + config.access_token = 'YOUR ACCESS TOKEN' +end + +api_instance = Petstore::PetApi.new + +pet_id = 789 # Integer | ID of pet that needs to be fetched + + +begin + #Fake endpoint to test inline arbitrary object return by 'Find pet by ID' + result = api_instance.get_pet_by_id_in_object(pet_id) + p result +rescue Petstore::ApiError => e + puts "Exception when calling PetApi->get_pet_by_id_in_object: #{e}" +end +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **pet_id** | **Integer**| ID of pet that needs to be fetched | + +### Return type + +[**InlineResponse200**](InlineResponse200.md) + +### Authorization + +[api_key](../README.md#api_key), [petstore_auth](../README.md#petstore_auth) + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + + + +# **pet_pet_idtesting_byte_arraytrue_get** +> String pet_pet_idtesting_byte_arraytrue_get(pet_id) + +Fake endpoint to test byte array return by 'Find pet by ID' + +Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + +### Example +```ruby +# load the gem +require 'petstore' +# setup authorization +Petstore.configure do |config| + # Configure API key authorization: api_key + config.api_key['api_key'] = 'YOUR API KEY' + # Uncomment the following line to set a prefix for the API key, e.g. 'BEARER' (defaults to nil) + #config.api_key_prefix['api_key'] = 'BEARER' + + # Configure OAuth2 access token for authorization: petstore_auth + config.access_token = 'YOUR ACCESS TOKEN' +end + +api_instance = Petstore::PetApi.new + +pet_id = 789 # Integer | ID of pet that needs to be fetched + + +begin + #Fake endpoint to test byte array return by 'Find pet by ID' + result = api_instance.pet_pet_idtesting_byte_arraytrue_get(pet_id) + p result +rescue Petstore::ApiError => e + puts "Exception when calling PetApi->pet_pet_idtesting_byte_arraytrue_get: #{e}" +end +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **pet_id** | **Integer**| ID of pet that needs to be fetched | + +### Return type + +**String** + +### Authorization + +[api_key](../README.md#api_key), [petstore_auth](../README.md#petstore_auth) + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + + + +# **update_pet** +> update_pet(opts) + +Update an existing pet + + + +### Example +```ruby +# load the gem +require 'petstore' +# setup authorization +Petstore.configure do |config| + # Configure OAuth2 access token for authorization: petstore_auth + config.access_token = 'YOUR ACCESS TOKEN' +end + +api_instance = Petstore::PetApi.new + +opts = { + body: Petstore::Pet.new # Pet | Pet object that needs to be added to the store +} + +begin + #Update an existing pet + api_instance.update_pet(opts) +rescue Petstore::ApiError => e + puts "Exception when calling PetApi->update_pet: #{e}" +end +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | [optional] + +### Return type + +nil (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP reuqest headers + + - **Content-Type**: application/json, application/xml + - **Accept**: application/json, application/xml + + + +# **update_pet_with_form** +> update_pet_with_form(pet_id, opts) + +Updates a pet in the store with form data + + + +### Example +```ruby +# load the gem +require 'petstore' +# setup authorization +Petstore.configure do |config| + # Configure OAuth2 access token for authorization: petstore_auth + config.access_token = 'YOUR ACCESS TOKEN' +end + +api_instance = Petstore::PetApi.new + +pet_id = "pet_id_example" # String | ID of pet that needs to be updated + +opts = { + name: "name_example", # String | Updated name of the pet + status: "status_example" # String | Updated status of the pet +} + +begin + #Updates a pet in the store with form data + api_instance.update_pet_with_form(pet_id, opts) +rescue Petstore::ApiError => e + puts "Exception when calling PetApi->update_pet_with_form: #{e}" +end +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **pet_id** | **String**| 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 + +nil (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP reuqest headers + + - **Content-Type**: application/x-www-form-urlencoded + - **Accept**: application/json, application/xml + + + +# **upload_file** +> upload_file(pet_id, opts) + +uploads an image + + + +### Example +```ruby +# load the gem +require 'petstore' +# setup authorization +Petstore.configure do |config| + # Configure OAuth2 access token for authorization: petstore_auth + config.access_token = 'YOUR ACCESS TOKEN' +end + +api_instance = Petstore::PetApi.new + +pet_id = 789 # Integer | ID of pet to update + +opts = { + additional_metadata: "additional_metadata_example", # String | Additional data to pass to server + file: File.new("/path/to/file.txt") # File | file to upload +} + +begin + #uploads an image + api_instance.upload_file(pet_id, opts) +rescue Petstore::ApiError => e + puts "Exception when calling PetApi->upload_file: #{e}" +end +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **pet_id** | **Integer**| ID of pet to update | + **additional_metadata** | **String**| Additional data to pass to server | [optional] + **file** | **File**| file to upload | [optional] + +### Return type + +nil (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP reuqest headers + + - **Content-Type**: multipart/form-data + - **Accept**: application/json, application/xml + + + diff --git a/samples/client/petstore/ruby/docs/SpecialModelName.md b/samples/client/petstore/ruby/docs/SpecialModelName.md new file mode 100644 index 00000000000..581ab6907ef --- /dev/null +++ b/samples/client/petstore/ruby/docs/SpecialModelName.md @@ -0,0 +1,8 @@ +# Petstore::SpecialModelName + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**special_property_name** | **Integer** | | [optional] + + diff --git a/samples/client/petstore/ruby/docs/StoreApi.md b/samples/client/petstore/ruby/docs/StoreApi.md new file mode 100644 index 00000000000..1ed9970698c --- /dev/null +++ b/samples/client/petstore/ruby/docs/StoreApi.md @@ -0,0 +1,335 @@ +# Petstore::StoreApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**delete_order**](StoreApi.md#delete_order) | **DELETE** /store/order/{orderId} | Delete purchase order by ID +[**find_orders_by_status**](StoreApi.md#find_orders_by_status) | **GET** /store/findByStatus | Finds orders by status +[**get_inventory**](StoreApi.md#get_inventory) | **GET** /store/inventory | Returns pet inventories by status +[**get_inventory_in_object**](StoreApi.md#get_inventory_in_object) | **GET** /store/inventory?response=arbitrary_object | Fake endpoint to test arbitrary object return by 'Get inventory' +[**get_order_by_id**](StoreApi.md#get_order_by_id) | **GET** /store/order/{orderId} | Find purchase order by ID +[**place_order**](StoreApi.md#place_order) | **POST** /store/order | Place an order for a pet + + +# **delete_order** +> delete_order(order_id) + +Delete purchase order by ID + +For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + +### Example +```ruby +# load the gem +require 'petstore' + +api_instance = Petstore::StoreApi.new + +order_id = "order_id_example" # String | ID of the order that needs to be deleted + + +begin + #Delete purchase order by ID + api_instance.delete_order(order_id) +rescue Petstore::ApiError => e + puts "Exception when calling StoreApi->delete_order: #{e}" +end +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **order_id** | **String**| ID of the order that needs to be deleted | + +### Return type + +nil (empty response body) + +### Authorization + +No authorization required + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + + + +# **find_orders_by_status** +> Array<Order> find_orders_by_status(opts) + +Finds orders by status + +A single status value can be provided as a string + +### Example +```ruby +# load the gem +require 'petstore' +# setup authorization +Petstore.configure do |config| + # Configure API key authorization: test_api_client_id + config.api_key['x-test_api_client_id'] = 'YOUR API KEY' + # Uncomment the following line to set a prefix for the API key, e.g. 'BEARER' (defaults to nil) + #config.api_key_prefix['x-test_api_client_id'] = 'BEARER' + + # Configure API key authorization: test_api_client_secret + config.api_key['x-test_api_client_secret'] = 'YOUR API KEY' + # Uncomment the following line to set a prefix for the API key, e.g. 'BEARER' (defaults to nil) + #config.api_key_prefix['x-test_api_client_secret'] = 'BEARER' +end + +api_instance = Petstore::StoreApi.new + +opts = { + status: "placed" # String | Status value that needs to be considered for query +} + +begin + #Finds orders by status + result = api_instance.find_orders_by_status(opts) + p result +rescue Petstore::ApiError => e + puts "Exception when calling StoreApi->find_orders_by_status: #{e}" +end +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **status** | **String**| Status value that needs to be considered for query | [optional] [default to placed] + +### Return type + +[**Array<Order>**](Order.md) + +### Authorization + +[test_api_client_id](../README.md#test_api_client_id), [test_api_client_secret](../README.md#test_api_client_secret) + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + + + +# **get_inventory** +> Hash<String, Integer> get_inventory + +Returns pet inventories by status + +Returns a map of status codes to quantities + +### Example +```ruby +# load the gem +require 'petstore' +# setup authorization +Petstore.configure do |config| + # Configure API key authorization: api_key + config.api_key['api_key'] = 'YOUR API KEY' + # Uncomment the following line to set a prefix for the API key, e.g. 'BEARER' (defaults to nil) + #config.api_key_prefix['api_key'] = 'BEARER' +end + +api_instance = Petstore::StoreApi.new + +begin + #Returns pet inventories by status + result = api_instance.get_inventory + p result +rescue Petstore::ApiError => e + puts "Exception when calling StoreApi->get_inventory: #{e}" +end +``` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +**Hash<String, Integer>** + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + + + +# **get_inventory_in_object** +> Object get_inventory_in_object + +Fake endpoint to test arbitrary object return by 'Get inventory' + +Returns an arbitrary object which is actually a map of status codes to quantities + +### Example +```ruby +# load the gem +require 'petstore' +# setup authorization +Petstore.configure do |config| + # Configure API key authorization: api_key + config.api_key['api_key'] = 'YOUR API KEY' + # Uncomment the following line to set a prefix for the API key, e.g. 'BEARER' (defaults to nil) + #config.api_key_prefix['api_key'] = 'BEARER' +end + +api_instance = Petstore::StoreApi.new + +begin + #Fake endpoint to test arbitrary object return by 'Get inventory' + result = api_instance.get_inventory_in_object + p result +rescue Petstore::ApiError => e + puts "Exception when calling StoreApi->get_inventory_in_object: #{e}" +end +``` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +**Object** + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + + + +# **get_order_by_id** +> Order get_order_by_id(order_id) + +Find purchase order by ID + +For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + +### Example +```ruby +# load the gem +require 'petstore' +# setup authorization +Petstore.configure do |config| + # Configure API key authorization: test_api_key_header + config.api_key['test_api_key_header'] = 'YOUR API KEY' + # Uncomment the following line to set a prefix for the API key, e.g. 'BEARER' (defaults to nil) + #config.api_key_prefix['test_api_key_header'] = 'BEARER' + + # Configure API key authorization: test_api_key_query + config.api_key['test_api_key_query'] = 'YOUR API KEY' + # Uncomment the following line to set a prefix for the API key, e.g. 'BEARER' (defaults to nil) + #config.api_key_prefix['test_api_key_query'] = 'BEARER' +end + +api_instance = Petstore::StoreApi.new + +order_id = "order_id_example" # String | ID of pet that needs to be fetched + + +begin + #Find purchase order by ID + result = api_instance.get_order_by_id(order_id) + p result +rescue Petstore::ApiError => e + puts "Exception when calling StoreApi->get_order_by_id: #{e}" +end +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **order_id** | **String**| ID of pet that needs to be fetched | + +### Return type + +[**Order**](Order.md) + +### Authorization + +[test_api_key_header](../README.md#test_api_key_header), [test_api_key_query](../README.md#test_api_key_query) + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + + + +# **place_order** +> Order place_order(opts) + +Place an order for a pet + + + +### Example +```ruby +# load the gem +require 'petstore' +# setup authorization +Petstore.configure do |config| + # Configure API key authorization: test_api_client_id + config.api_key['x-test_api_client_id'] = 'YOUR API KEY' + # Uncomment the following line to set a prefix for the API key, e.g. 'BEARER' (defaults to nil) + #config.api_key_prefix['x-test_api_client_id'] = 'BEARER' + + # Configure API key authorization: test_api_client_secret + config.api_key['x-test_api_client_secret'] = 'YOUR API KEY' + # Uncomment the following line to set a prefix for the API key, e.g. 'BEARER' (defaults to nil) + #config.api_key_prefix['x-test_api_client_secret'] = 'BEARER' +end + +api_instance = Petstore::StoreApi.new + +opts = { + body: Petstore::Order.new # Order | order placed for purchasing the pet +} + +begin + #Place an order for a pet + result = api_instance.place_order(opts) + p result +rescue Petstore::ApiError => e + puts "Exception when calling StoreApi->place_order: #{e}" +end +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Order**](Order.md)| order placed for purchasing the pet | [optional] + +### Return type + +[**Order**](Order.md) + +### Authorization + +[test_api_client_id](../README.md#test_api_client_id), [test_api_client_secret](../README.md#test_api_client_secret) + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + + + diff --git a/samples/client/petstore/ruby/docs/Tag.md b/samples/client/petstore/ruby/docs/Tag.md new file mode 100644 index 00000000000..5bd94d6c04e --- /dev/null +++ b/samples/client/petstore/ruby/docs/Tag.md @@ -0,0 +1,9 @@ +# Petstore::Tag + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Integer** | | [optional] +**name** | **String** | | [optional] + + diff --git a/samples/client/petstore/ruby/docs/User.md b/samples/client/petstore/ruby/docs/User.md new file mode 100644 index 00000000000..bd76116e023 --- /dev/null +++ b/samples/client/petstore/ruby/docs/User.md @@ -0,0 +1,15 @@ +# Petstore::User + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Integer** | | [optional] +**username** | **String** | | [optional] +**first_name** | **String** | | [optional] +**last_name** | **String** | | [optional] +**email** | **String** | | [optional] +**password** | **String** | | [optional] +**phone** | **String** | | [optional] +**user_status** | **Integer** | User Status | [optional] + + diff --git a/samples/client/petstore/ruby/docs/UserApi.md b/samples/client/petstore/ruby/docs/UserApi.md new file mode 100644 index 00000000000..7b1e241f835 --- /dev/null +++ b/samples/client/petstore/ruby/docs/UserApi.md @@ -0,0 +1,396 @@ +# Petstore::UserApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**create_user**](UserApi.md#create_user) | **POST** /user | Create user +[**create_users_with_array_input**](UserApi.md#create_users_with_array_input) | **POST** /user/createWithArray | Creates list of users with given input array +[**create_users_with_list_input**](UserApi.md#create_users_with_list_input) | **POST** /user/createWithList | Creates list of users with given input array +[**delete_user**](UserApi.md#delete_user) | **DELETE** /user/{username} | Delete user +[**get_user_by_name**](UserApi.md#get_user_by_name) | **GET** /user/{username} | Get user by user name +[**login_user**](UserApi.md#login_user) | **GET** /user/login | Logs user into the system +[**logout_user**](UserApi.md#logout_user) | **GET** /user/logout | Logs out current logged in user session +[**update_user**](UserApi.md#update_user) | **PUT** /user/{username} | Updated user + + +# **create_user** +> create_user(opts) + +Create user + +This can only be done by the logged in user. + +### Example +```ruby +# load the gem +require 'petstore' + +api_instance = Petstore::UserApi.new + +opts = { + body: Petstore::User.new # User | Created user object +} + +begin + #Create user + api_instance.create_user(opts) +rescue Petstore::ApiError => e + puts "Exception when calling UserApi->create_user: #{e}" +end +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**User**](User.md)| Created user object | [optional] + +### Return type + +nil (empty response body) + +### Authorization + +No authorization required + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + + + +# **create_users_with_array_input** +> create_users_with_array_input(opts) + +Creates list of users with given input array + + + +### Example +```ruby +# load the gem +require 'petstore' + +api_instance = Petstore::UserApi.new + +opts = { + body: [Petstore::User.new] # Array | List of user object +} + +begin + #Creates list of users with given input array + api_instance.create_users_with_array_input(opts) +rescue Petstore::ApiError => e + puts "Exception when calling UserApi->create_users_with_array_input: #{e}" +end +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Array<User>**](User.md)| List of user object | [optional] + +### Return type + +nil (empty response body) + +### Authorization + +No authorization required + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + + + +# **create_users_with_list_input** +> create_users_with_list_input(opts) + +Creates list of users with given input array + + + +### Example +```ruby +# load the gem +require 'petstore' + +api_instance = Petstore::UserApi.new + +opts = { + body: [Petstore::User.new] # Array | List of user object +} + +begin + #Creates list of users with given input array + api_instance.create_users_with_list_input(opts) +rescue Petstore::ApiError => e + puts "Exception when calling UserApi->create_users_with_list_input: #{e}" +end +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Array<User>**](User.md)| List of user object | [optional] + +### Return type + +nil (empty response body) + +### Authorization + +No authorization required + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + + + +# **delete_user** +> delete_user(username) + +Delete user + +This can only be done by the logged in user. + +### Example +```ruby +# load the gem +require 'petstore' +# setup authorization +Petstore.configure do |config| + # Configure HTTP basic authorization: test_http_basic + config.username = 'YOUR USERNAME' + config.password = 'YOUR PASSWORD' +end + +api_instance = Petstore::UserApi.new + +username = "username_example" # String | The name that needs to be deleted + + +begin + #Delete user + api_instance.delete_user(username) +rescue Petstore::ApiError => e + puts "Exception when calling UserApi->delete_user: #{e}" +end +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **String**| The name that needs to be deleted | + +### Return type + +nil (empty response body) + +### Authorization + +[test_http_basic](../README.md#test_http_basic) + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + + + +# **get_user_by_name** +> User get_user_by_name(username) + +Get user by user name + + + +### Example +```ruby +# load the gem +require 'petstore' + +api_instance = Petstore::UserApi.new + +username = "username_example" # String | The name that needs to be fetched. Use user1 for testing. + + +begin + #Get user by user name + result = api_instance.get_user_by_name(username) + p result +rescue Petstore::ApiError => e + puts "Exception when calling UserApi->get_user_by_name: #{e}" +end +``` + +### 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 reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + + + +# **login_user** +> String login_user(opts) + +Logs user into the system + + + +### Example +```ruby +# load the gem +require 'petstore' + +api_instance = Petstore::UserApi.new + +opts = { + username: "username_example", # String | The user name for login + password: "password_example" # String | The password for login in clear text +} + +begin + #Logs user into the system + result = api_instance.login_user(opts) + p result +rescue Petstore::ApiError => e + puts "Exception when calling UserApi->login_user: #{e}" +end +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **String**| The user name for login | [optional] + **password** | **String**| The password for login in clear text | [optional] + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + + + +# **logout_user** +> logout_user + +Logs out current logged in user session + + + +### Example +```ruby +# load the gem +require 'petstore' + +api_instance = Petstore::UserApi.new + +begin + #Logs out current logged in user session + api_instance.logout_user +rescue Petstore::ApiError => e + puts "Exception when calling UserApi->logout_user: #{e}" +end +``` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +nil (empty response body) + +### Authorization + +No authorization required + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + + + +# **update_user** +> update_user(username, opts) + +Updated user + +This can only be done by the logged in user. + +### Example +```ruby +# load the gem +require 'petstore' + +api_instance = Petstore::UserApi.new + +username = "username_example" # String | name that need to be deleted + +opts = { + body: Petstore::User.new # User | Updated user object +} + +begin + #Updated user + api_instance.update_user(username, opts) +rescue Petstore::ApiError => e + puts "Exception when calling UserApi->update_user: #{e}" +end +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **String**| name that need to be deleted | + **body** | [**User**](User.md)| Updated user object | [optional] + +### Return type + +nil (empty response body) + +### Authorization + +No authorization required + +### HTTP reuqest headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + + + diff --git a/samples/client/petstore/ruby/git_push.sh b/samples/client/petstore/ruby/git_push.sh new file mode 100644 index 00000000000..1a36388db02 --- /dev/null +++ b/samples/client/petstore/ruby/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="YOUR_GIT_USR_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="YOUR_GIT_REPO_ID" + 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/ruby/lib/petstore.rb b/samples/client/petstore/ruby/lib/petstore.rb index a493758e7d0..4b848d0c3a0 100644 --- a/samples/client/petstore/ruby/lib/petstore.rb +++ b/samples/client/petstore/ruby/lib/petstore.rb @@ -21,19 +21,24 @@ require 'petstore/version' require 'petstore/configuration' # Models -require 'petstore/models/order' -require 'petstore/models/special_model_name' -require 'petstore/models/user' +require 'petstore/models/animal' +require 'petstore/models/cat' require 'petstore/models/category' -require 'petstore/models/object_return' +require 'petstore/models/dog' require 'petstore/models/inline_response_200' -require 'petstore/models/tag' +require 'petstore/models/model_200_response' +require 'petstore/models/model_return' +require 'petstore/models/name' +require 'petstore/models/order' require 'petstore/models/pet' +require 'petstore/models/special_model_name' +require 'petstore/models/tag' +require 'petstore/models/user' # APIs -require 'petstore/api/user_api' -require 'petstore/api/store_api' require 'petstore/api/pet_api' +require 'petstore/api/store_api' +require 'petstore/api/user_api' module Petstore class << self diff --git a/samples/client/petstore/ruby/lib/petstore/api/pet_api.rb b/samples/client/petstore/ruby/lib/petstore/api/pet_api.rb index 8f7e91495b5..3bff1eda69a 100644 --- a/samples/client/petstore/ruby/lib/petstore/api/pet_api.rb +++ b/samples/client/petstore/ruby/lib/petstore/api/pet_api.rb @@ -24,62 +24,6 @@ module Petstore @api_client = api_client end - # Update an existing pet - # - # @param [Hash] opts the optional parameters - # @option opts [Pet] :body Pet object that needs to be added to the store - # @return [nil] - def update_pet(opts = {}) - update_pet_with_http_info(opts) - return nil - end - - # Update an existing pet - # - # @param [Hash] opts the optional parameters - # @option opts [Pet] :body Pet object that needs to be added to the store - # @return [Array<(nil, Fixnum, Hash)>] nil, response status code and response headers - def update_pet_with_http_info(opts = {}) - if @api_client.config.debugging - @api_client.config.logger.debug "Calling API: PetApi#update_pet ..." - end - - # resource path - local_var_path = "/pet".sub('{format}','json') - - # query parameters - query_params = {} - - # header parameters - header_params = {} - - # HTTP header 'Accept' (if needed) - _header_accept = ['application/json', 'application/xml'] - _header_accept_result = @api_client.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result - - # HTTP header 'Content-Type' - _header_content_type = ['application/json', 'application/xml'] - header_params['Content-Type'] = @api_client.select_header_content_type(_header_content_type) - - # form parameters - form_params = {} - - # http body (model) - post_body = @api_client.object_to_http_body(opts[:'body']) - - auth_names = ['petstore_auth'] - data, status_code, headers = @api_client.call_api(:PUT, local_var_path, - :header_params => header_params, - :query_params => query_params, - :form_params => form_params, - :body => post_body, - :auth_names => auth_names) - if @api_client.config.debugging - @api_client.config.logger.debug "API called: PetApi#update_pet\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" - end - return data, status_code, headers - end - # Add a new pet to the store # # @param [Hash] opts the optional parameters @@ -110,19 +54,18 @@ module Petstore header_params = {} # HTTP header 'Accept' (if needed) - _header_accept = ['application/json', 'application/xml'] - _header_accept_result = @api_client.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + local_header_accept = ['application/json', 'application/xml'] + local_header_accept_result = @api_client.select_header_accept(local_header_accept) and header_params['Accept'] = local_header_accept_result # HTTP header 'Content-Type' - _header_content_type = ['application/json', 'application/xml'] - header_params['Content-Type'] = @api_client.select_header_content_type(_header_content_type) + local_header_content_type = ['application/json', 'application/xml'] + header_params['Content-Type'] = @api_client.select_header_content_type(local_header_content_type) # form parameters form_params = {} # http body (model) post_body = @api_client.object_to_http_body(opts[:'body']) - auth_names = ['petstore_auth'] data, status_code, headers = @api_client.call_api(:POST, local_var_path, :header_params => header_params, @@ -136,13 +79,129 @@ module Petstore return data, status_code, headers end + # Fake endpoint to test byte array in body parameter for adding a new pet to the store + # + # @param [Hash] opts the optional parameters + # @option opts [String] :body Pet object in the form of byte array + # @return [nil] + def add_pet_using_byte_array(opts = {}) + add_pet_using_byte_array_with_http_info(opts) + return nil + end + + # Fake endpoint to test byte array in body parameter for adding a new pet to the store + # + # @param [Hash] opts the optional parameters + # @option opts [String] :body Pet object in the form of byte array + # @return [Array<(nil, Fixnum, Hash)>] nil, response status code and response headers + def add_pet_using_byte_array_with_http_info(opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug "Calling API: PetApi#add_pet_using_byte_array ..." + end + + # resource path + local_var_path = "/pet?testing_byte_array=true".sub('{format}','json') + + # query parameters + query_params = {} + + # header parameters + header_params = {} + + # HTTP header 'Accept' (if needed) + local_header_accept = ['application/json', 'application/xml'] + 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', 'application/xml'] + header_params['Content-Type'] = @api_client.select_header_content_type(local_header_content_type) + + # form parameters + form_params = {} + + # http body (model) + post_body = @api_client.object_to_http_body(opts[:'body']) + auth_names = ['petstore_auth'] + data, status_code, headers = @api_client.call_api(:POST, local_var_path, + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names) + if @api_client.config.debugging + @api_client.config.logger.debug "API called: PetApi#add_pet_using_byte_array\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + + # Deletes a pet + # + # @param pet_id Pet id to delete + # @param [Hash] opts the optional parameters + # @option opts [String] :api_key + # @return [nil] + def delete_pet(pet_id, opts = {}) + delete_pet_with_http_info(pet_id, opts) + return nil + end + + # Deletes a pet + # + # @param pet_id Pet id to delete + # @param [Hash] opts the optional parameters + # @option opts [String] :api_key + # @return [Array<(nil, Fixnum, Hash)>] nil, response status code and response headers + def delete_pet_with_http_info(pet_id, opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug "Calling API: PetApi#delete_pet ..." + end + + # verify the required parameter 'pet_id' is set + fail "Missing the required parameter 'pet_id' when calling delete_pet" if pet_id.nil? + + # resource path + local_var_path = "/pet/{petId}".sub('{format}','json').sub('{' + 'petId' + '}', pet_id.to_s) + + # query parameters + query_params = {} + + # header parameters + header_params = {} + + # HTTP header 'Accept' (if needed) + local_header_accept = ['application/json', 'application/xml'] + 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 = [] + header_params['Content-Type'] = @api_client.select_header_content_type(local_header_content_type) + header_params[:'api_key'] = opts[:'api_key'] if opts[:'api_key'] + + # form parameters + form_params = {} + + # http body (model) + post_body = nil + auth_names = ['petstore_auth'] + data, status_code, headers = @api_client.call_api(:DELETE, local_var_path, + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names) + if @api_client.config.debugging + @api_client.config.logger.debug "API called: PetApi#delete_pet\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + # Finds Pets by status # Multiple status values can be provided with comma separated strings # @param [Hash] opts the optional parameters - # @option opts [Array] :status Status values that need to be considered for query + # @option opts [Array] :status Status values that need to be considered for query (default to available) # @return [Array] def find_pets_by_status(opts = {}) - data, status_code, headers = find_pets_by_status_with_http_info(opts) + data, _status_code, _headers = find_pets_by_status_with_http_info(opts) return data end @@ -167,20 +226,19 @@ module Petstore header_params = {} # HTTP header 'Accept' (if needed) - _header_accept = ['application/json', 'application/xml'] - _header_accept_result = @api_client.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + local_header_accept = ['application/json', 'application/xml'] + local_header_accept_result = @api_client.select_header_accept(local_header_accept) and header_params['Accept'] = local_header_accept_result # HTTP header 'Content-Type' - _header_content_type = [] - header_params['Content-Type'] = @api_client.select_header_content_type(_header_content_type) + local_header_content_type = [] + header_params['Content-Type'] = @api_client.select_header_content_type(local_header_content_type) # form parameters form_params = {} # http body (model) post_body = nil - - auth_names = ['petstore_auth'] + auth_names = ['petstore_auth'] data, status_code, headers = @api_client.call_api(:GET, local_var_path, :header_params => header_params, :query_params => query_params, @@ -200,7 +258,7 @@ module Petstore # @option opts [Array] :tags Tags to filter by # @return [Array] def find_pets_by_tags(opts = {}) - data, status_code, headers = find_pets_by_tags_with_http_info(opts) + data, _status_code, _headers = find_pets_by_tags_with_http_info(opts) return data end @@ -225,20 +283,19 @@ module Petstore header_params = {} # HTTP header 'Accept' (if needed) - _header_accept = ['application/json', 'application/xml'] - _header_accept_result = @api_client.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + local_header_accept = ['application/json', 'application/xml'] + local_header_accept_result = @api_client.select_header_accept(local_header_accept) and header_params['Accept'] = local_header_accept_result # HTTP header 'Content-Type' - _header_content_type = [] - header_params['Content-Type'] = @api_client.select_header_content_type(_header_content_type) + local_header_content_type = [] + header_params['Content-Type'] = @api_client.select_header_content_type(local_header_content_type) # form parameters form_params = {} # http body (model) post_body = nil - - auth_names = ['petstore_auth'] + auth_names = ['petstore_auth'] data, status_code, headers = @api_client.call_api(:GET, local_var_path, :header_params => header_params, :query_params => query_params, @@ -253,12 +310,12 @@ module Petstore end # Find pet by ID - # Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + # Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions # @param pet_id ID of pet that needs to be fetched # @param [Hash] opts the optional parameters # @return [Pet] def get_pet_by_id(pet_id, opts = {}) - data, status_code, headers = get_pet_by_id_with_http_info(pet_id, opts) + data, _status_code, _headers = get_pet_by_id_with_http_info(pet_id, opts) return data end @@ -285,20 +342,19 @@ module Petstore header_params = {} # HTTP header 'Accept' (if needed) - _header_accept = ['application/json', 'application/xml'] - _header_accept_result = @api_client.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + local_header_accept = ['application/json', 'application/xml'] + local_header_accept_result = @api_client.select_header_accept(local_header_accept) and header_params['Accept'] = local_header_accept_result # HTTP header 'Content-Type' - _header_content_type = [] - header_params['Content-Type'] = @api_client.select_header_content_type(_header_content_type) + local_header_content_type = [] + header_params['Content-Type'] = @api_client.select_header_content_type(local_header_content_type) # form parameters form_params = {} # http body (model) post_body = nil - - auth_names = ['petstore_auth', 'api_key'] + auth_names = ['api_key', 'petstore_auth'] data, status_code, headers = @api_client.call_api(:GET, local_var_path, :header_params => header_params, :query_params => query_params, @@ -312,6 +368,179 @@ module Petstore return data, status_code, headers end + # Fake endpoint to test inline arbitrary object return by 'Find pet by ID' + # Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + # @param pet_id ID of pet that needs to be fetched + # @param [Hash] opts the optional parameters + # @return [InlineResponse200] + def get_pet_by_id_in_object(pet_id, opts = {}) + data, _status_code, _headers = get_pet_by_id_in_object_with_http_info(pet_id, opts) + return data + end + + # Fake endpoint to test inline arbitrary object return by 'Find pet by ID' + # Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + # @param pet_id ID of pet that needs to be fetched + # @param [Hash] opts the optional parameters + # @return [Array<(InlineResponse200, Fixnum, Hash)>] InlineResponse200 data, response status code and response headers + def get_pet_by_id_in_object_with_http_info(pet_id, opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug "Calling API: PetApi#get_pet_by_id_in_object ..." + end + + # verify the required parameter 'pet_id' is set + fail "Missing the required parameter 'pet_id' when calling get_pet_by_id_in_object" if pet_id.nil? + + # resource path + local_var_path = "/pet/{petId}?response=inline_arbitrary_object".sub('{format}','json').sub('{' + 'petId' + '}', pet_id.to_s) + + # query parameters + query_params = {} + + # header parameters + header_params = {} + + # HTTP header 'Accept' (if needed) + local_header_accept = ['application/json', 'application/xml'] + 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 = [] + header_params['Content-Type'] = @api_client.select_header_content_type(local_header_content_type) + + # form parameters + form_params = {} + + # http body (model) + post_body = nil + auth_names = ['api_key', 'petstore_auth'] + data, status_code, headers = @api_client.call_api(:GET, local_var_path, + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => 'InlineResponse200') + if @api_client.config.debugging + @api_client.config.logger.debug "API called: PetApi#get_pet_by_id_in_object\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + + # Fake endpoint to test byte array return by 'Find pet by ID' + # Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + # @param pet_id ID of pet that needs to be fetched + # @param [Hash] opts the optional parameters + # @return [String] + def pet_pet_idtesting_byte_arraytrue_get(pet_id, opts = {}) + data, _status_code, _headers = pet_pet_idtesting_byte_arraytrue_get_with_http_info(pet_id, opts) + return data + end + + # Fake endpoint to test byte array return by 'Find pet by ID' + # Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + # @param pet_id ID of pet that needs to be fetched + # @param [Hash] opts the optional parameters + # @return [Array<(String, Fixnum, Hash)>] String data, response status code and response headers + def pet_pet_idtesting_byte_arraytrue_get_with_http_info(pet_id, opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug "Calling API: PetApi#pet_pet_idtesting_byte_arraytrue_get ..." + end + + # verify the required parameter 'pet_id' is set + fail "Missing the required parameter 'pet_id' when calling pet_pet_idtesting_byte_arraytrue_get" if pet_id.nil? + + # resource path + local_var_path = "/pet/{petId}?testing_byte_array=true".sub('{format}','json').sub('{' + 'petId' + '}', pet_id.to_s) + + # query parameters + query_params = {} + + # header parameters + header_params = {} + + # HTTP header 'Accept' (if needed) + local_header_accept = ['application/json', 'application/xml'] + 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 = [] + header_params['Content-Type'] = @api_client.select_header_content_type(local_header_content_type) + + # form parameters + form_params = {} + + # http body (model) + post_body = nil + auth_names = ['api_key', 'petstore_auth'] + data, status_code, headers = @api_client.call_api(:GET, local_var_path, + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => 'String') + if @api_client.config.debugging + @api_client.config.logger.debug "API called: PetApi#pet_pet_idtesting_byte_arraytrue_get\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + + # Update an existing pet + # + # @param [Hash] opts the optional parameters + # @option opts [Pet] :body Pet object that needs to be added to the store + # @return [nil] + def update_pet(opts = {}) + update_pet_with_http_info(opts) + return nil + end + + # Update an existing pet + # + # @param [Hash] opts the optional parameters + # @option opts [Pet] :body Pet object that needs to be added to the store + # @return [Array<(nil, Fixnum, Hash)>] nil, response status code and response headers + def update_pet_with_http_info(opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug "Calling API: PetApi#update_pet ..." + end + + # resource path + local_var_path = "/pet".sub('{format}','json') + + # query parameters + query_params = {} + + # header parameters + header_params = {} + + # HTTP header 'Accept' (if needed) + local_header_accept = ['application/json', 'application/xml'] + 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', 'application/xml'] + header_params['Content-Type'] = @api_client.select_header_content_type(local_header_content_type) + + # form parameters + form_params = {} + + # http body (model) + post_body = @api_client.object_to_http_body(opts[:'body']) + auth_names = ['petstore_auth'] + data, status_code, headers = @api_client.call_api(:PUT, local_var_path, + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names) + if @api_client.config.debugging + @api_client.config.logger.debug "API called: PetApi#update_pet\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + # Updates a pet in the store with form data # # @param pet_id ID of pet that needs to be updated @@ -349,12 +578,12 @@ module Petstore header_params = {} # HTTP header 'Accept' (if needed) - _header_accept = ['application/json', 'application/xml'] - _header_accept_result = @api_client.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + local_header_accept = ['application/json', 'application/xml'] + local_header_accept_result = @api_client.select_header_accept(local_header_accept) and header_params['Accept'] = local_header_accept_result # HTTP header 'Content-Type' - _header_content_type = ['application/x-www-form-urlencoded'] - header_params['Content-Type'] = @api_client.select_header_content_type(_header_content_type) + local_header_content_type = ['application/x-www-form-urlencoded'] + header_params['Content-Type'] = @api_client.select_header_content_type(local_header_content_type) # form parameters form_params = {} @@ -363,8 +592,7 @@ module Petstore # http body (model) post_body = nil - - auth_names = ['petstore_auth'] + auth_names = ['petstore_auth'] data, status_code, headers = @api_client.call_api(:POST, local_var_path, :header_params => header_params, :query_params => query_params, @@ -377,68 +605,6 @@ module Petstore return data, status_code, headers end - # Deletes a pet - # - # @param pet_id Pet id to delete - # @param [Hash] opts the optional parameters - # @option opts [String] :api_key - # @return [nil] - def delete_pet(pet_id, opts = {}) - delete_pet_with_http_info(pet_id, opts) - return nil - end - - # Deletes a pet - # - # @param pet_id Pet id to delete - # @param [Hash] opts the optional parameters - # @option opts [String] :api_key - # @return [Array<(nil, Fixnum, Hash)>] nil, response status code and response headers - def delete_pet_with_http_info(pet_id, opts = {}) - if @api_client.config.debugging - @api_client.config.logger.debug "Calling API: PetApi#delete_pet ..." - end - - # verify the required parameter 'pet_id' is set - fail "Missing the required parameter 'pet_id' when calling delete_pet" if pet_id.nil? - - # resource path - local_var_path = "/pet/{petId}".sub('{format}','json').sub('{' + 'petId' + '}', pet_id.to_s) - - # query parameters - query_params = {} - - # header parameters - header_params = {} - - # HTTP header 'Accept' (if needed) - _header_accept = ['application/json', 'application/xml'] - _header_accept_result = @api_client.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result - - # HTTP header 'Content-Type' - _header_content_type = [] - header_params['Content-Type'] = @api_client.select_header_content_type(_header_content_type) - header_params[:'api_key'] = opts[:'api_key'] if opts[:'api_key'] - - # form parameters - form_params = {} - - # http body (model) - post_body = nil - - auth_names = ['petstore_auth'] - data, status_code, headers = @api_client.call_api(:DELETE, local_var_path, - :header_params => header_params, - :query_params => query_params, - :form_params => form_params, - :body => post_body, - :auth_names => auth_names) - if @api_client.config.debugging - @api_client.config.logger.debug "API called: PetApi#delete_pet\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" - end - return data, status_code, headers - end - # uploads an image # # @param pet_id ID of pet to update @@ -476,12 +642,12 @@ module Petstore header_params = {} # HTTP header 'Accept' (if needed) - _header_accept = ['application/json', 'application/xml'] - _header_accept_result = @api_client.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + local_header_accept = ['application/json', 'application/xml'] + local_header_accept_result = @api_client.select_header_accept(local_header_accept) and header_params['Accept'] = local_header_accept_result # HTTP header 'Content-Type' - _header_content_type = ['multipart/form-data'] - header_params['Content-Type'] = @api_client.select_header_content_type(_header_content_type) + local_header_content_type = ['multipart/form-data'] + header_params['Content-Type'] = @api_client.select_header_content_type(local_header_content_type) # form parameters form_params = {} @@ -490,8 +656,7 @@ module Petstore # http body (model) post_body = nil - - auth_names = ['petstore_auth'] + auth_names = ['petstore_auth'] data, status_code, headers = @api_client.call_api(:POST, local_var_path, :header_params => header_params, :query_params => query_params, @@ -503,181 +668,5 @@ module Petstore end return data, status_code, headers end - - # Fake endpoint to test inline arbitrary object return by 'Find pet by ID' - # Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions - # @param pet_id ID of pet that needs to be fetched - # @param [Hash] opts the optional parameters - # @return [InlineResponse200] - def get_pet_by_id_in_object(pet_id, opts = {}) - data, status_code, headers = get_pet_by_id_in_object_with_http_info(pet_id, opts) - return data - end - - # Fake endpoint to test inline arbitrary object return by 'Find pet by ID' - # Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions - # @param pet_id ID of pet that needs to be fetched - # @param [Hash] opts the optional parameters - # @return [Array<(InlineResponse200, Fixnum, Hash)>] InlineResponse200 data, response status code and response headers - def get_pet_by_id_in_object_with_http_info(pet_id, opts = {}) - if @api_client.config.debugging - @api_client.config.logger.debug "Calling API: PetApi#get_pet_by_id_in_object ..." - end - - # verify the required parameter 'pet_id' is set - fail "Missing the required parameter 'pet_id' when calling get_pet_by_id_in_object" if pet_id.nil? - - # resource path - local_var_path = "/pet/{petId}?response=inline_arbitrary_object".sub('{format}','json').sub('{' + 'petId' + '}', pet_id.to_s) - - # query parameters - query_params = {} - - # header parameters - header_params = {} - - # HTTP header 'Accept' (if needed) - _header_accept = ['application/json', 'application/xml'] - _header_accept_result = @api_client.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result - - # HTTP header 'Content-Type' - _header_content_type = [] - header_params['Content-Type'] = @api_client.select_header_content_type(_header_content_type) - - # form parameters - form_params = {} - - # http body (model) - post_body = nil - - auth_names = ['petstore_auth', 'api_key'] - data, status_code, headers = @api_client.call_api(:GET, local_var_path, - :header_params => header_params, - :query_params => query_params, - :form_params => form_params, - :body => post_body, - :auth_names => auth_names, - :return_type => 'InlineResponse200') - if @api_client.config.debugging - @api_client.config.logger.debug "API called: PetApi#get_pet_by_id_in_object\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" - end - return data, status_code, headers - end - - # Fake endpoint to test byte array return by 'Find pet by ID' - # Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions - # @param pet_id ID of pet that needs to be fetched - # @param [Hash] opts the optional parameters - # @return [String] - def pet_pet_idtesting_byte_arraytrue_get(pet_id, opts = {}) - data, status_code, headers = pet_pet_idtesting_byte_arraytrue_get_with_http_info(pet_id, opts) - return data - end - - # Fake endpoint to test byte array return by 'Find pet by ID' - # Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions - # @param pet_id ID of pet that needs to be fetched - # @param [Hash] opts the optional parameters - # @return [Array<(String, Fixnum, Hash)>] String data, response status code and response headers - def pet_pet_idtesting_byte_arraytrue_get_with_http_info(pet_id, opts = {}) - if @api_client.config.debugging - @api_client.config.logger.debug "Calling API: PetApi#pet_pet_idtesting_byte_arraytrue_get ..." - end - - # verify the required parameter 'pet_id' is set - fail "Missing the required parameter 'pet_id' when calling pet_pet_idtesting_byte_arraytrue_get" if pet_id.nil? - - # resource path - local_var_path = "/pet/{petId}?testing_byte_array=true".sub('{format}','json').sub('{' + 'petId' + '}', pet_id.to_s) - - # query parameters - query_params = {} - - # header parameters - header_params = {} - - # HTTP header 'Accept' (if needed) - _header_accept = ['application/json', 'application/xml'] - _header_accept_result = @api_client.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result - - # HTTP header 'Content-Type' - _header_content_type = [] - header_params['Content-Type'] = @api_client.select_header_content_type(_header_content_type) - - # form parameters - form_params = {} - - # http body (model) - post_body = nil - - auth_names = ['petstore_auth', 'api_key'] - data, status_code, headers = @api_client.call_api(:GET, local_var_path, - :header_params => header_params, - :query_params => query_params, - :form_params => form_params, - :body => post_body, - :auth_names => auth_names, - :return_type => 'String') - if @api_client.config.debugging - @api_client.config.logger.debug "API called: PetApi#pet_pet_idtesting_byte_arraytrue_get\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" - end - return data, status_code, headers - end - - # Fake endpoint to test byte array in body parameter for adding a new pet to the store - # - # @param [Hash] opts the optional parameters - # @option opts [String] :body Pet object in the form of byte array - # @return [nil] - def add_pet_using_byte_array(opts = {}) - add_pet_using_byte_array_with_http_info(opts) - return nil - end - - # Fake endpoint to test byte array in body parameter for adding a new pet to the store - # - # @param [Hash] opts the optional parameters - # @option opts [String] :body Pet object in the form of byte array - # @return [Array<(nil, Fixnum, Hash)>] nil, response status code and response headers - def add_pet_using_byte_array_with_http_info(opts = {}) - if @api_client.config.debugging - @api_client.config.logger.debug "Calling API: PetApi#add_pet_using_byte_array ..." - end - - # resource path - local_var_path = "/pet?testing_byte_array=true".sub('{format}','json') - - # query parameters - query_params = {} - - # header parameters - header_params = {} - - # HTTP header 'Accept' (if needed) - _header_accept = ['application/json', 'application/xml'] - _header_accept_result = @api_client.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result - - # HTTP header 'Content-Type' - _header_content_type = ['application/json', 'application/xml'] - header_params['Content-Type'] = @api_client.select_header_content_type(_header_content_type) - - # form parameters - form_params = {} - - # http body (model) - post_body = @api_client.object_to_http_body(opts[:'body']) - - auth_names = ['petstore_auth'] - data, status_code, headers = @api_client.call_api(:POST, local_var_path, - :header_params => header_params, - :query_params => query_params, - :form_params => form_params, - :body => post_body, - :auth_names => auth_names) - if @api_client.config.debugging - @api_client.config.logger.debug "API called: PetApi#add_pet_using_byte_array\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" - end - return data, status_code, headers - end end end diff --git a/samples/client/petstore/ruby/lib/petstore/api/store_api.rb b/samples/client/petstore/ruby/lib/petstore/api/store_api.rb index a6bb3a33938..548b5a355e0 100644 --- a/samples/client/petstore/ruby/lib/petstore/api/store_api.rb +++ b/samples/client/petstore/ruby/lib/petstore/api/store_api.rb @@ -24,297 +24,8 @@ module Petstore @api_client = api_client end - # Finds orders by status - # A single status value can be provided as a string - # @param [Hash] opts the optional parameters - # @option opts [String] :status Status value that needs to be considered for query - # @return [Array] - def find_orders_by_status(opts = {}) - data, status_code, headers = find_orders_by_status_with_http_info(opts) - return data - end - - # Finds orders by status - # A single status value can be provided as a string - # @param [Hash] opts the optional parameters - # @option opts [String] :status Status value that needs to be considered for query - # @return [Array<(Array, Fixnum, Hash)>] Array data, response status code and response headers - def find_orders_by_status_with_http_info(opts = {}) - if @api_client.config.debugging - @api_client.config.logger.debug "Calling API: StoreApi#find_orders_by_status ..." - end - - if opts[:'status'] && !['placed', 'approved', 'delivered'].include?(opts[:'status']) - fail 'invalid value for "status", must be one of placed, approved, delivered' - end - - # resource path - local_var_path = "/store/findByStatus".sub('{format}','json') - - # query parameters - query_params = {} - query_params[:'status'] = opts[:'status'] if opts[:'status'] - - # header parameters - header_params = {} - - # HTTP header 'Accept' (if needed) - _header_accept = ['application/json', 'application/xml'] - _header_accept_result = @api_client.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result - - # HTTP header 'Content-Type' - _header_content_type = [] - header_params['Content-Type'] = @api_client.select_header_content_type(_header_content_type) - - # form parameters - form_params = {} - - # http body (model) - post_body = nil - - auth_names = ['test_api_client_id', 'test_api_client_secret'] - data, status_code, headers = @api_client.call_api(:GET, local_var_path, - :header_params => header_params, - :query_params => query_params, - :form_params => form_params, - :body => post_body, - :auth_names => auth_names, - :return_type => 'Array') - if @api_client.config.debugging - @api_client.config.logger.debug "API called: StoreApi#find_orders_by_status\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" - end - return data, status_code, headers - end - - # Returns pet inventories by status - # Returns a map of status codes to quantities - # @param [Hash] opts the optional parameters - # @return [Hash] - def get_inventory(opts = {}) - data, status_code, headers = get_inventory_with_http_info(opts) - return data - end - - # Returns pet inventories by status - # Returns a map of status codes to quantities - # @param [Hash] opts the optional parameters - # @return [Array<(Hash, Fixnum, Hash)>] Hash data, response status code and response headers - def get_inventory_with_http_info(opts = {}) - if @api_client.config.debugging - @api_client.config.logger.debug "Calling API: StoreApi#get_inventory ..." - end - - # resource path - local_var_path = "/store/inventory".sub('{format}','json') - - # query parameters - query_params = {} - - # header parameters - header_params = {} - - # HTTP header 'Accept' (if needed) - _header_accept = ['application/json', 'application/xml'] - _header_accept_result = @api_client.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result - - # HTTP header 'Content-Type' - _header_content_type = [] - header_params['Content-Type'] = @api_client.select_header_content_type(_header_content_type) - - # form parameters - form_params = {} - - # http body (model) - post_body = nil - - auth_names = ['api_key'] - data, status_code, headers = @api_client.call_api(:GET, local_var_path, - :header_params => header_params, - :query_params => query_params, - :form_params => form_params, - :body => post_body, - :auth_names => auth_names, - :return_type => 'Hash') - if @api_client.config.debugging - @api_client.config.logger.debug "API called: StoreApi#get_inventory\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" - end - return data, status_code, headers - end - - # Fake endpoint to test arbitrary object return by 'Get inventory' - # Returns an arbitrary object which is actually a map of status codes to quantities - # @param [Hash] opts the optional parameters - # @return [Object] - def get_inventory_in_object(opts = {}) - data, status_code, headers = get_inventory_in_object_with_http_info(opts) - return data - end - - # Fake endpoint to test arbitrary object return by 'Get inventory' - # Returns an arbitrary object which is actually a map of status codes to quantities - # @param [Hash] opts the optional parameters - # @return [Array<(Object, Fixnum, Hash)>] Object data, response status code and response headers - def get_inventory_in_object_with_http_info(opts = {}) - if @api_client.config.debugging - @api_client.config.logger.debug "Calling API: StoreApi#get_inventory_in_object ..." - end - - # resource path - local_var_path = "/store/inventory?response=arbitrary_object".sub('{format}','json') - - # query parameters - query_params = {} - - # header parameters - header_params = {} - - # HTTP header 'Accept' (if needed) - _header_accept = ['application/json', 'application/xml'] - _header_accept_result = @api_client.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result - - # HTTP header 'Content-Type' - _header_content_type = [] - header_params['Content-Type'] = @api_client.select_header_content_type(_header_content_type) - - # form parameters - form_params = {} - - # http body (model) - post_body = nil - - auth_names = ['api_key'] - data, status_code, headers = @api_client.call_api(:GET, local_var_path, - :header_params => header_params, - :query_params => query_params, - :form_params => form_params, - :body => post_body, - :auth_names => auth_names, - :return_type => 'Object') - if @api_client.config.debugging - @api_client.config.logger.debug "API called: StoreApi#get_inventory_in_object\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" - end - return data, status_code, headers - end - - # Place an order for a pet - # - # @param [Hash] opts the optional parameters - # @option opts [Order] :body order placed for purchasing the pet - # @return [Order] - def place_order(opts = {}) - data, status_code, headers = place_order_with_http_info(opts) - return data - end - - # Place an order for a pet - # - # @param [Hash] opts the optional parameters - # @option opts [Order] :body order placed for purchasing the pet - # @return [Array<(Order, Fixnum, Hash)>] Order data, response status code and response headers - def place_order_with_http_info(opts = {}) - if @api_client.config.debugging - @api_client.config.logger.debug "Calling API: StoreApi#place_order ..." - end - - # resource path - local_var_path = "/store/order".sub('{format}','json') - - # query parameters - query_params = {} - - # header parameters - header_params = {} - - # HTTP header 'Accept' (if needed) - _header_accept = ['application/json', 'application/xml'] - _header_accept_result = @api_client.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result - - # HTTP header 'Content-Type' - _header_content_type = [] - header_params['Content-Type'] = @api_client.select_header_content_type(_header_content_type) - - # form parameters - form_params = {} - - # http body (model) - post_body = @api_client.object_to_http_body(opts[:'body']) - - auth_names = ['test_api_client_id', 'test_api_client_secret'] - data, status_code, headers = @api_client.call_api(:POST, local_var_path, - :header_params => header_params, - :query_params => query_params, - :form_params => form_params, - :body => post_body, - :auth_names => auth_names, - :return_type => 'Order') - if @api_client.config.debugging - @api_client.config.logger.debug "API called: StoreApi#place_order\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" - end - return data, status_code, headers - end - - # Find purchase order by ID - # For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - # @param order_id ID of pet that needs to be fetched - # @param [Hash] opts the optional parameters - # @return [Order] - def get_order_by_id(order_id, opts = {}) - data, status_code, headers = get_order_by_id_with_http_info(order_id, opts) - return data - end - - # Find purchase order by ID - # For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - # @param order_id ID of pet that needs to be fetched - # @param [Hash] opts the optional parameters - # @return [Array<(Order, Fixnum, Hash)>] Order data, response status code and response headers - def get_order_by_id_with_http_info(order_id, opts = {}) - if @api_client.config.debugging - @api_client.config.logger.debug "Calling API: StoreApi#get_order_by_id ..." - end - - # verify the required parameter 'order_id' is set - fail "Missing the required parameter 'order_id' when calling get_order_by_id" if order_id.nil? - - # resource path - local_var_path = "/store/order/{orderId}".sub('{format}','json').sub('{' + 'orderId' + '}', order_id.to_s) - - # query parameters - query_params = {} - - # header parameters - header_params = {} - - # HTTP header 'Accept' (if needed) - _header_accept = ['application/json', 'application/xml'] - _header_accept_result = @api_client.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result - - # HTTP header 'Content-Type' - _header_content_type = [] - header_params['Content-Type'] = @api_client.select_header_content_type(_header_content_type) - - # form parameters - form_params = {} - - # http body (model) - post_body = nil - - auth_names = ['test_api_key_query', 'test_api_key_header'] - data, status_code, headers = @api_client.call_api(:GET, local_var_path, - :header_params => header_params, - :query_params => query_params, - :form_params => form_params, - :body => post_body, - :auth_names => auth_names, - :return_type => 'Order') - if @api_client.config.debugging - @api_client.config.logger.debug "API called: StoreApi#get_order_by_id\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" - end - return data, status_code, headers - end - # Delete purchase order by ID - # For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + # For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors # @param order_id ID of the order that needs to be deleted # @param [Hash] opts the optional parameters # @return [nil] @@ -346,20 +57,19 @@ module Petstore header_params = {} # HTTP header 'Accept' (if needed) - _header_accept = ['application/json', 'application/xml'] - _header_accept_result = @api_client.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + local_header_accept = ['application/json', 'application/xml'] + local_header_accept_result = @api_client.select_header_accept(local_header_accept) and header_params['Accept'] = local_header_accept_result # HTTP header 'Content-Type' - _header_content_type = [] - header_params['Content-Type'] = @api_client.select_header_content_type(_header_content_type) + local_header_content_type = [] + header_params['Content-Type'] = @api_client.select_header_content_type(local_header_content_type) # form parameters form_params = {} # http body (model) post_body = nil - - auth_names = [] + auth_names = [] data, status_code, headers = @api_client.call_api(:DELETE, local_var_path, :header_params => header_params, :query_params => query_params, @@ -371,5 +81,289 @@ module Petstore end return data, status_code, headers end + + # Finds orders by status + # A single status value can be provided as a string + # @param [Hash] opts the optional parameters + # @option opts [String] :status Status value that needs to be considered for query (default to placed) + # @return [Array] + def find_orders_by_status(opts = {}) + data, _status_code, _headers = find_orders_by_status_with_http_info(opts) + return data + end + + # Finds orders by status + # A single status value can be provided as a string + # @param [Hash] opts the optional parameters + # @option opts [String] :status Status value that needs to be considered for query + # @return [Array<(Array, Fixnum, Hash)>] Array data, response status code and response headers + def find_orders_by_status_with_http_info(opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug "Calling API: StoreApi#find_orders_by_status ..." + end + + if opts[:'status'] && !['placed', 'approved', 'delivered'].include?(opts[:'status']) + fail 'invalid value for "status", must be one of placed, approved, delivered' + end + + # resource path + local_var_path = "/store/findByStatus".sub('{format}','json') + + # query parameters + query_params = {} + query_params[:'status'] = opts[:'status'] if opts[:'status'] + + # header parameters + header_params = {} + + # HTTP header 'Accept' (if needed) + local_header_accept = ['application/json', 'application/xml'] + 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 = [] + header_params['Content-Type'] = @api_client.select_header_content_type(local_header_content_type) + + # form parameters + form_params = {} + + # http body (model) + post_body = nil + auth_names = ['test_api_client_id', 'test_api_client_secret'] + data, status_code, headers = @api_client.call_api(:GET, local_var_path, + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => 'Array') + if @api_client.config.debugging + @api_client.config.logger.debug "API called: StoreApi#find_orders_by_status\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + + # Returns pet inventories by status + # Returns a map of status codes to quantities + # @param [Hash] opts the optional parameters + # @return [Hash] + def get_inventory(opts = {}) + data, _status_code, _headers = get_inventory_with_http_info(opts) + return data + end + + # Returns pet inventories by status + # Returns a map of status codes to quantities + # @param [Hash] opts the optional parameters + # @return [Array<(Hash, Fixnum, Hash)>] Hash data, response status code and response headers + def get_inventory_with_http_info(opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug "Calling API: StoreApi#get_inventory ..." + end + + # resource path + local_var_path = "/store/inventory".sub('{format}','json') + + # query parameters + query_params = {} + + # header parameters + header_params = {} + + # HTTP header 'Accept' (if needed) + local_header_accept = ['application/json', 'application/xml'] + 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 = [] + header_params['Content-Type'] = @api_client.select_header_content_type(local_header_content_type) + + # form parameters + form_params = {} + + # http body (model) + post_body = nil + auth_names = ['api_key'] + data, status_code, headers = @api_client.call_api(:GET, local_var_path, + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => 'Hash') + if @api_client.config.debugging + @api_client.config.logger.debug "API called: StoreApi#get_inventory\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + + # Fake endpoint to test arbitrary object return by 'Get inventory' + # Returns an arbitrary object which is actually a map of status codes to quantities + # @param [Hash] opts the optional parameters + # @return [Object] + def get_inventory_in_object(opts = {}) + data, _status_code, _headers = get_inventory_in_object_with_http_info(opts) + return data + end + + # Fake endpoint to test arbitrary object return by 'Get inventory' + # Returns an arbitrary object which is actually a map of status codes to quantities + # @param [Hash] opts the optional parameters + # @return [Array<(Object, Fixnum, Hash)>] Object data, response status code and response headers + def get_inventory_in_object_with_http_info(opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug "Calling API: StoreApi#get_inventory_in_object ..." + end + + # resource path + local_var_path = "/store/inventory?response=arbitrary_object".sub('{format}','json') + + # query parameters + query_params = {} + + # header parameters + header_params = {} + + # HTTP header 'Accept' (if needed) + local_header_accept = ['application/json', 'application/xml'] + 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 = [] + header_params['Content-Type'] = @api_client.select_header_content_type(local_header_content_type) + + # form parameters + form_params = {} + + # http body (model) + post_body = nil + auth_names = ['api_key'] + data, status_code, headers = @api_client.call_api(:GET, local_var_path, + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => 'Object') + if @api_client.config.debugging + @api_client.config.logger.debug "API called: StoreApi#get_inventory_in_object\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + + # Find purchase order by ID + # For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + # @param order_id ID of pet that needs to be fetched + # @param [Hash] opts the optional parameters + # @return [Order] + def get_order_by_id(order_id, opts = {}) + data, _status_code, _headers = get_order_by_id_with_http_info(order_id, opts) + return data + end + + # Find purchase order by ID + # For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + # @param order_id ID of pet that needs to be fetched + # @param [Hash] opts the optional parameters + # @return [Array<(Order, Fixnum, Hash)>] Order data, response status code and response headers + def get_order_by_id_with_http_info(order_id, opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug "Calling API: StoreApi#get_order_by_id ..." + end + + # verify the required parameter 'order_id' is set + fail "Missing the required parameter 'order_id' when calling get_order_by_id" if order_id.nil? + + # resource path + local_var_path = "/store/order/{orderId}".sub('{format}','json').sub('{' + 'orderId' + '}', order_id.to_s) + + # query parameters + query_params = {} + + # header parameters + header_params = {} + + # HTTP header 'Accept' (if needed) + local_header_accept = ['application/json', 'application/xml'] + 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 = [] + header_params['Content-Type'] = @api_client.select_header_content_type(local_header_content_type) + + # form parameters + form_params = {} + + # http body (model) + post_body = nil + auth_names = ['test_api_key_header', 'test_api_key_query'] + data, status_code, headers = @api_client.call_api(:GET, local_var_path, + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => 'Order') + if @api_client.config.debugging + @api_client.config.logger.debug "API called: StoreApi#get_order_by_id\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + + # Place an order for a pet + # + # @param [Hash] opts the optional parameters + # @option opts [Order] :body order placed for purchasing the pet + # @return [Order] + def place_order(opts = {}) + data, _status_code, _headers = place_order_with_http_info(opts) + return data + end + + # Place an order for a pet + # + # @param [Hash] opts the optional parameters + # @option opts [Order] :body order placed for purchasing the pet + # @return [Array<(Order, Fixnum, Hash)>] Order data, response status code and response headers + def place_order_with_http_info(opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug "Calling API: StoreApi#place_order ..." + end + + # resource path + local_var_path = "/store/order".sub('{format}','json') + + # query parameters + query_params = {} + + # header parameters + header_params = {} + + # HTTP header 'Accept' (if needed) + local_header_accept = ['application/json', 'application/xml'] + 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 = [] + header_params['Content-Type'] = @api_client.select_header_content_type(local_header_content_type) + + # form parameters + form_params = {} + + # http body (model) + post_body = @api_client.object_to_http_body(opts[:'body']) + auth_names = ['test_api_client_id', 'test_api_client_secret'] + data, status_code, headers = @api_client.call_api(:POST, local_var_path, + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => 'Order') + if @api_client.config.debugging + @api_client.config.logger.debug "API called: StoreApi#place_order\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end end end diff --git a/samples/client/petstore/ruby/lib/petstore/api/user_api.rb b/samples/client/petstore/ruby/lib/petstore/api/user_api.rb index 9b883755347..0f9af5bb7f0 100644 --- a/samples/client/petstore/ruby/lib/petstore/api/user_api.rb +++ b/samples/client/petstore/ruby/lib/petstore/api/user_api.rb @@ -54,19 +54,18 @@ module Petstore header_params = {} # HTTP header 'Accept' (if needed) - _header_accept = ['application/json', 'application/xml'] - _header_accept_result = @api_client.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + local_header_accept = ['application/json', 'application/xml'] + local_header_accept_result = @api_client.select_header_accept(local_header_accept) and header_params['Accept'] = local_header_accept_result # HTTP header 'Content-Type' - _header_content_type = [] - header_params['Content-Type'] = @api_client.select_header_content_type(_header_content_type) + local_header_content_type = [] + header_params['Content-Type'] = @api_client.select_header_content_type(local_header_content_type) # form parameters form_params = {} # http body (model) post_body = @api_client.object_to_http_body(opts[:'body']) - auth_names = [] data, status_code, headers = @api_client.call_api(:POST, local_var_path, :header_params => header_params, @@ -110,19 +109,18 @@ module Petstore header_params = {} # HTTP header 'Accept' (if needed) - _header_accept = ['application/json', 'application/xml'] - _header_accept_result = @api_client.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + local_header_accept = ['application/json', 'application/xml'] + local_header_accept_result = @api_client.select_header_accept(local_header_accept) and header_params['Accept'] = local_header_accept_result # HTTP header 'Content-Type' - _header_content_type = [] - header_params['Content-Type'] = @api_client.select_header_content_type(_header_content_type) + local_header_content_type = [] + header_params['Content-Type'] = @api_client.select_header_content_type(local_header_content_type) # form parameters form_params = {} # http body (model) post_body = @api_client.object_to_http_body(opts[:'body']) - auth_names = [] data, status_code, headers = @api_client.call_api(:POST, local_var_path, :header_params => header_params, @@ -166,19 +164,18 @@ module Petstore header_params = {} # HTTP header 'Accept' (if needed) - _header_accept = ['application/json', 'application/xml'] - _header_accept_result = @api_client.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + local_header_accept = ['application/json', 'application/xml'] + local_header_accept_result = @api_client.select_header_accept(local_header_accept) and header_params['Accept'] = local_header_accept_result # HTTP header 'Content-Type' - _header_content_type = [] - header_params['Content-Type'] = @api_client.select_header_content_type(_header_content_type) + local_header_content_type = [] + header_params['Content-Type'] = @api_client.select_header_content_type(local_header_content_type) # form parameters form_params = {} # http body (model) post_body = @api_client.object_to_http_body(opts[:'body']) - auth_names = [] data, status_code, headers = @api_client.call_api(:POST, local_var_path, :header_params => header_params, @@ -192,6 +189,123 @@ module Petstore return data, status_code, headers end + # Delete user + # This can only be done by the logged in user. + # @param username The name that needs to be deleted + # @param [Hash] opts the optional parameters + # @return [nil] + def delete_user(username, opts = {}) + delete_user_with_http_info(username, opts) + return nil + end + + # Delete user + # This can only be done by the logged in user. + # @param username The name that needs to be deleted + # @param [Hash] opts the optional parameters + # @return [Array<(nil, Fixnum, Hash)>] nil, response status code and response headers + def delete_user_with_http_info(username, opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug "Calling API: UserApi#delete_user ..." + end + + # verify the required parameter 'username' is set + fail "Missing the required parameter 'username' when calling delete_user" if username.nil? + + # resource path + local_var_path = "/user/{username}".sub('{format}','json').sub('{' + 'username' + '}', username.to_s) + + # query parameters + query_params = {} + + # header parameters + header_params = {} + + # HTTP header 'Accept' (if needed) + local_header_accept = ['application/json', 'application/xml'] + 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 = [] + header_params['Content-Type'] = @api_client.select_header_content_type(local_header_content_type) + + # form parameters + form_params = {} + + # http body (model) + post_body = nil + auth_names = ['test_http_basic'] + data, status_code, headers = @api_client.call_api(:DELETE, local_var_path, + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names) + if @api_client.config.debugging + @api_client.config.logger.debug "API called: UserApi#delete_user\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + + # Get user by user name + # + # @param username The name that needs to be fetched. Use user1 for testing. + # @param [Hash] opts the optional parameters + # @return [User] + def get_user_by_name(username, opts = {}) + data, _status_code, _headers = get_user_by_name_with_http_info(username, opts) + return data + end + + # Get user by user name + # + # @param username The name that needs to be fetched. Use user1 for testing. + # @param [Hash] opts the optional parameters + # @return [Array<(User, Fixnum, Hash)>] User data, response status code and response headers + def get_user_by_name_with_http_info(username, opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug "Calling API: UserApi#get_user_by_name ..." + end + + # verify the required parameter 'username' is set + fail "Missing the required parameter 'username' when calling get_user_by_name" if username.nil? + + # resource path + local_var_path = "/user/{username}".sub('{format}','json').sub('{' + 'username' + '}', username.to_s) + + # query parameters + query_params = {} + + # header parameters + header_params = {} + + # HTTP header 'Accept' (if needed) + local_header_accept = ['application/json', 'application/xml'] + 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 = [] + header_params['Content-Type'] = @api_client.select_header_content_type(local_header_content_type) + + # form parameters + form_params = {} + + # http body (model) + post_body = nil + auth_names = [] + data, status_code, headers = @api_client.call_api(:GET, local_var_path, + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => 'User') + if @api_client.config.debugging + @api_client.config.logger.debug "API called: UserApi#get_user_by_name\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + # Logs user into the system # # @param [Hash] opts the optional parameters @@ -199,7 +313,7 @@ module Petstore # @option opts [String] :password The password for login in clear text # @return [String] def login_user(opts = {}) - data, status_code, headers = login_user_with_http_info(opts) + data, _status_code, _headers = login_user_with_http_info(opts) return data end @@ -226,20 +340,19 @@ module Petstore header_params = {} # HTTP header 'Accept' (if needed) - _header_accept = ['application/json', 'application/xml'] - _header_accept_result = @api_client.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + local_header_accept = ['application/json', 'application/xml'] + local_header_accept_result = @api_client.select_header_accept(local_header_accept) and header_params['Accept'] = local_header_accept_result # HTTP header 'Content-Type' - _header_content_type = [] - header_params['Content-Type'] = @api_client.select_header_content_type(_header_content_type) + local_header_content_type = [] + header_params['Content-Type'] = @api_client.select_header_content_type(local_header_content_type) # form parameters form_params = {} # http body (model) post_body = nil - - auth_names = [] + auth_names = [] data, status_code, headers = @api_client.call_api(:GET, local_var_path, :header_params => header_params, :query_params => query_params, @@ -281,20 +394,19 @@ module Petstore header_params = {} # HTTP header 'Accept' (if needed) - _header_accept = ['application/json', 'application/xml'] - _header_accept_result = @api_client.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + local_header_accept = ['application/json', 'application/xml'] + local_header_accept_result = @api_client.select_header_accept(local_header_accept) and header_params['Accept'] = local_header_accept_result # HTTP header 'Content-Type' - _header_content_type = [] - header_params['Content-Type'] = @api_client.select_header_content_type(_header_content_type) + local_header_content_type = [] + header_params['Content-Type'] = @api_client.select_header_content_type(local_header_content_type) # form parameters form_params = {} # http body (model) post_body = nil - - auth_names = [] + auth_names = [] data, status_code, headers = @api_client.call_api(:GET, local_var_path, :header_params => header_params, :query_params => query_params, @@ -307,66 +419,6 @@ module Petstore return data, status_code, headers end - # Get user by user name - # - # @param username The name that needs to be fetched. Use user1 for testing. - # @param [Hash] opts the optional parameters - # @return [User] - def get_user_by_name(username, opts = {}) - data, status_code, headers = get_user_by_name_with_http_info(username, opts) - return data - end - - # Get user by user name - # - # @param username The name that needs to be fetched. Use user1 for testing. - # @param [Hash] opts the optional parameters - # @return [Array<(User, Fixnum, Hash)>] User data, response status code and response headers - def get_user_by_name_with_http_info(username, opts = {}) - if @api_client.config.debugging - @api_client.config.logger.debug "Calling API: UserApi#get_user_by_name ..." - end - - # verify the required parameter 'username' is set - fail "Missing the required parameter 'username' when calling get_user_by_name" if username.nil? - - # resource path - local_var_path = "/user/{username}".sub('{format}','json').sub('{' + 'username' + '}', username.to_s) - - # query parameters - query_params = {} - - # header parameters - header_params = {} - - # HTTP header 'Accept' (if needed) - _header_accept = ['application/json', 'application/xml'] - _header_accept_result = @api_client.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result - - # HTTP header 'Content-Type' - _header_content_type = [] - header_params['Content-Type'] = @api_client.select_header_content_type(_header_content_type) - - # form parameters - form_params = {} - - # http body (model) - post_body = nil - - auth_names = [] - data, status_code, headers = @api_client.call_api(:GET, local_var_path, - :header_params => header_params, - :query_params => query_params, - :form_params => form_params, - :body => post_body, - :auth_names => auth_names, - :return_type => 'User') - if @api_client.config.debugging - @api_client.config.logger.debug "API called: UserApi#get_user_by_name\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" - end - return data, status_code, headers - end - # Updated user # This can only be done by the logged in user. # @param username name that need to be deleted @@ -402,19 +454,18 @@ module Petstore header_params = {} # HTTP header 'Accept' (if needed) - _header_accept = ['application/json', 'application/xml'] - _header_accept_result = @api_client.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + local_header_accept = ['application/json', 'application/xml'] + local_header_accept_result = @api_client.select_header_accept(local_header_accept) and header_params['Accept'] = local_header_accept_result # HTTP header 'Content-Type' - _header_content_type = [] - header_params['Content-Type'] = @api_client.select_header_content_type(_header_content_type) + local_header_content_type = [] + header_params['Content-Type'] = @api_client.select_header_content_type(local_header_content_type) # form parameters form_params = {} # http body (model) post_body = @api_client.object_to_http_body(opts[:'body']) - auth_names = [] data, status_code, headers = @api_client.call_api(:PUT, local_var_path, :header_params => header_params, @@ -427,64 +478,5 @@ module Petstore end return data, status_code, headers end - - # Delete user - # This can only be done by the logged in user. - # @param username The name that needs to be deleted - # @param [Hash] opts the optional parameters - # @return [nil] - def delete_user(username, opts = {}) - delete_user_with_http_info(username, opts) - return nil - end - - # Delete user - # This can only be done by the logged in user. - # @param username The name that needs to be deleted - # @param [Hash] opts the optional parameters - # @return [Array<(nil, Fixnum, Hash)>] nil, response status code and response headers - def delete_user_with_http_info(username, opts = {}) - if @api_client.config.debugging - @api_client.config.logger.debug "Calling API: UserApi#delete_user ..." - end - - # verify the required parameter 'username' is set - fail "Missing the required parameter 'username' when calling delete_user" if username.nil? - - # resource path - local_var_path = "/user/{username}".sub('{format}','json').sub('{' + 'username' + '}', username.to_s) - - # query parameters - query_params = {} - - # header parameters - header_params = {} - - # HTTP header 'Accept' (if needed) - _header_accept = ['application/json', 'application/xml'] - _header_accept_result = @api_client.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result - - # HTTP header 'Content-Type' - _header_content_type = [] - header_params['Content-Type'] = @api_client.select_header_content_type(_header_content_type) - - # form parameters - form_params = {} - - # http body (model) - post_body = nil - - auth_names = [] - data, status_code, headers = @api_client.call_api(:DELETE, local_var_path, - :header_params => header_params, - :query_params => query_params, - :form_params => form_params, - :body => post_body, - :auth_names => auth_names) - if @api_client.config.debugging - @api_client.config.logger.debug "API called: UserApi#delete_user\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" - end - return data, status_code, headers - end end end diff --git a/samples/client/petstore/ruby/lib/petstore/api_client.rb b/samples/client/petstore/ruby/lib/petstore/api_client.rb index bb99e08be70..70111d07438 100644 --- a/samples/client/petstore/ruby/lib/petstore/api_client.rb +++ b/samples/client/petstore/ruby/lib/petstore/api_client.rb @@ -31,9 +31,11 @@ module Petstore # @return [Hash] attr_accessor :default_headers + # Initializes the ApiClient + # @option config [Configuration] Configuraiton for initializing the object, default to Configuration.default def initialize(config = Configuration.default) @config = config - @user_agent = "ruby-swagger-#{VERSION}" + @user_agent = "Swagger-Codegen/#{VERSION}/ruby" @default_headers = { 'Content-Type' => "application/json", 'User-Agent' => @user_agent @@ -71,6 +73,15 @@ module Petstore return data, response.code, response.headers end + # Builds the HTTP request + # + # @param [String] http_method HTTP method/verb (e.g. POST) + # @param [String] path URL path (e.g. /account/new) + # @option opts [Hash] :header_params Header parameters + # @option opts [Hash] :query_params Query parameters + # @option opts [Hash] :form_params Query parameters + # @option opts [Object] :body HTTP body (JSON/XML) + # @return [Typhoeus::Request] A Typhoeus Request def build_request(http_method, path, opts = {}) url = build_request_url(path) http_method = http_method.to_sym.downcase @@ -79,9 +90,7 @@ module Petstore query_params = opts[:query_params] || {} form_params = opts[:form_params] || {} - update_params_for_auth! header_params, query_params, opts[:auth_names] - req_opts = { :method => http_method, @@ -112,12 +121,15 @@ module Petstore # application/json # application/json; charset=UTF8 # APPLICATION/JSON + # @param [String] mime MIME + # @return [Boolean] True if the MIME is applicaton/json def json_mime?(mime) - !!(mime =~ /\Aapplication\/json(;.*)?\z/i) + !(mime =~ /\Aapplication\/json(;.*)?\z/i).nil? end # Deserialize the response to the given return type. # + # @param [Response] response HTTP response # @param [String] return_type some examples: "User", "Array[User]", "Hash[String,Integer]" def deserialize(response, return_type) body = response.body @@ -148,6 +160,9 @@ module Petstore end # Convert data to the given return type. + # @param [Object] data Data to be converted + # @param [String] return_type Return type + # @return [Mixed] Data in a particular type def convert_to_type(data, return_type) return nil if data.nil? case return_type @@ -220,7 +235,7 @@ module Petstore # @param [String] filename the filename to be sanitized # @return [String] the sanitized filename def sanitize_filename(filename) - filename.gsub /.*[\/\\]/, '' + filename.gsub(/.*[\/\\]/, '') end def build_request_url(path) @@ -229,6 +244,12 @@ module Petstore URI.encode(@config.base_url + path) end + # Builds the HTTP request body + # + # @param [Hash] header_params Header parameters + # @param [Hash] form_params Query parameters + # @param [Object] body HTTP body (JSON/XML) + # @return [String] HTTP body data in the form of string def build_request_body(header_params, form_params, body) # http form if header_params['Content-Type'] == 'application/x-www-form-urlencoded' || @@ -252,6 +273,10 @@ module Petstore end # Update hearder and query params based on authentication settings. + # + # @param [Hash] header_params Header parameters + # @param [Hash] form_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| auth_setting = @config.auth_settings[auth_name] @@ -264,6 +289,9 @@ module Petstore end end + # Sets user agent in HTTP header + # + # @param [String] user_agent User agent (e.g. swagger-codegen/ruby/1.0.0) def user_agent=(user_agent) @user_agent = user_agent @default_headers['User-Agent'] = @user_agent @@ -295,13 +323,13 @@ module Petstore # @return [String] JSON string representation of the object def object_to_http_body(model) return model if model.nil? || model.is_a?(String) - _body = nil + local_body = nil if model.is_a?(Array) - _body = model.map{|m| object_to_hash(m) } + local_body = model.map{|m| object_to_hash(m) } else - _body = object_to_hash(model) + local_body = object_to_hash(model) end - _body.to_json + local_body.to_json end # Convert object(non-array) to hash. diff --git a/samples/client/petstore/ruby/lib/petstore/configuration.rb b/samples/client/petstore/ruby/lib/petstore/configuration.rb index 60f689cda6d..5125ebe5960 100644 --- a/samples/client/petstore/ruby/lib/petstore/configuration.rb +++ b/samples/client/petstore/ruby/lib/petstore/configuration.rb @@ -157,26 +157,12 @@ module Petstore # Returns Auth Settings hash for api client. def auth_settings { - 'petstore_auth' => - { - type: 'oauth2', - in: 'header', - key: 'Authorization', - value: "Bearer #{access_token}" - }, - 'test_api_client_id' => + 'test_api_key_header' => { type: 'api_key', in: 'header', - key: 'x-test_api_client_id', - value: api_key_with_prefix('x-test_api_client_id') - }, - 'test_api_client_secret' => - { - type: 'api_key', - in: 'header', - key: 'x-test_api_client_secret', - value: api_key_with_prefix('x-test_api_client_secret') + key: 'test_api_key_header', + value: api_key_with_prefix('test_api_key_header') }, 'api_key' => { @@ -185,6 +171,27 @@ module Petstore key: 'api_key', value: api_key_with_prefix('api_key') }, + 'test_http_basic' => + { + type: 'basic', + in: 'header', + key: 'Authorization', + value: basic_auth_token + }, + 'test_api_client_secret' => + { + type: 'api_key', + in: 'header', + key: 'x-test_api_client_secret', + value: api_key_with_prefix('x-test_api_client_secret') + }, + 'test_api_client_id' => + { + type: 'api_key', + in: 'header', + key: 'x-test_api_client_id', + value: api_key_with_prefix('x-test_api_client_id') + }, 'test_api_key_query' => { type: 'api_key', @@ -192,12 +199,12 @@ module Petstore key: 'test_api_key_query', value: api_key_with_prefix('test_api_key_query') }, - 'test_api_key_header' => + 'petstore_auth' => { - type: 'api_key', + type: 'oauth2', in: 'header', - key: 'test_api_key_header', - value: api_key_with_prefix('test_api_key_header') + key: 'Authorization', + value: "Bearer #{access_token}" }, } end diff --git a/samples/client/petstore/ruby/lib/petstore/models/animal.rb b/samples/client/petstore/ruby/lib/petstore/models/animal.rb new file mode 100644 index 00000000000..325898c5676 --- /dev/null +++ b/samples/client/petstore/ruby/lib/petstore/models/animal.rb @@ -0,0 +1,175 @@ +=begin +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@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +License: Apache 2.0 +http://www.apache.org/licenses/LICENSE-2.0.html + +Terms of Service: http://swagger.io/terms/ + +=end + +require 'date' + +module Petstore + class Animal + attr_accessor :class_name + + # Attribute mapping from ruby-style variable name to JSON key. + def self.attribute_map + { + :'class_name' => :'className' + } + end + + # Attribute type mapping. + def self.swagger_types + { + :'class_name' => :'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[:'className'] + self.class_name = attributes[:'className'] + end + 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 && + class_name == o.class_name + 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 + [class_name].hash + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def build_from_hash(attributes) + return nil unless attributes.is_a?(Hash) + self.class.swagger_types.each_pair do |key, type| + if type =~ /^Array<(.*)>/i + # check to ensure the input is an array given that the the attribute + # is documented as an array but the input is not + if attributes[self.class.attribute_map[key]].is_a?(Array) + self.send("#{key}=", attributes[self.class.attribute_map[key]].map{ |v| _deserialize($1, v) } ) + end + elsif !attributes[self.class.attribute_map[key]].nil? + self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) + end # or else data not found in attributes(hash), not an issue as the data can be optional + end + + self + end + + # Deserializes the data based on type + # @param string type Data type + # @param string value Value to be deserialized + # @return [Object] Deserialized data + def _deserialize(type, value) + case type.to_sym + when :DateTime + DateTime.parse(value) + when :Date + Date.parse(value) + when :String + value.to_s + when :Integer + value.to_i + when :Float + value.to_f + when :BOOLEAN + if value.to_s =~ /^(true|t|yes|y|1)$/i + true + else + false + end + when :Object + # generic object (usually a Hash), return directly + value + when /\AArray<(?.+)>\z/ + inner_type = Regexp.last_match[:inner_type] + value.map { |v| _deserialize(inner_type, v) } + when /\AHash<(?.+), (?.+)>\z/ + k_type = Regexp.last_match[:k_type] + v_type = Regexp.last_match[:v_type] + {}.tap do |hash| + value.each do |k, v| + hash[_deserialize(k_type, k)] = _deserialize(v_type, v) + end + end + else # model + temp_model = Petstore.const_get(type).new + temp_model.build_from_hash(value) + end + end + + # Returns the string representation of the object + # @return [String] String presentation of the object + def to_s + to_hash.to_s + end + + # to_body is an alias to to_hash (backward compatibility) + # @return [Hash] Returns the object in the form of hash + def to_body + to_hash + end + + # Returns the object in the form of hash + # @return [Hash] Returns the object in the form of hash + def to_hash + hash = {} + self.class.attribute_map.each_pair do |attr, param| + value = self.send(attr) + next if value.nil? + hash[param] = _to_hash(value) + end + hash + end + + # Outputs non-array value in the form of hash + # For object, use to_hash. Otherwise, just return the value + # @param [Object] value Any valid value + # @return [Hash] Returns the value in the form of hash + def _to_hash(value) + if value.is_a?(Array) + value.compact.map{ |v| _to_hash(v) } + elsif value.is_a?(Hash) + {}.tap do |hash| + value.each { |k, v| hash[k] = _to_hash(v) } + end + elsif value.respond_to? :to_hash + value.to_hash + else + value + end + end + + end +end diff --git a/samples/client/petstore/ruby/lib/petstore/models/cat.rb b/samples/client/petstore/ruby/lib/petstore/models/cat.rb new file mode 100644 index 00000000000..1de8e299b37 --- /dev/null +++ b/samples/client/petstore/ruby/lib/petstore/models/cat.rb @@ -0,0 +1,183 @@ +=begin +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@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +License: Apache 2.0 +http://www.apache.org/licenses/LICENSE-2.0.html + +Terms of Service: http://swagger.io/terms/ + +=end + +require 'date' + +module Petstore + class Cat + attr_accessor :class_name + + attr_accessor :declawed + + # Attribute mapping from ruby-style variable name to JSON key. + def self.attribute_map + { + :'class_name' => :'className', + :'declawed' => :'declawed' + } + end + + # Attribute type mapping. + def self.swagger_types + { + :'class_name' => :'String', +:'declawed' => :'BOOLEAN' + } + 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[:'className'] + self.class_name = attributes[:'className'] + end + if attributes[:'declawed'] + self.declawed = attributes[:'declawed'] + end + 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 && + class_name == o.class_name && + declawed == o.declawed + 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 + [class_name, declawed].hash + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def build_from_hash(attributes) + return nil unless attributes.is_a?(Hash) + self.class.swagger_types.each_pair do |key, type| + if type =~ /^Array<(.*)>/i + # check to ensure the input is an array given that the the attribute + # is documented as an array but the input is not + if attributes[self.class.attribute_map[key]].is_a?(Array) + self.send("#{key}=", attributes[self.class.attribute_map[key]].map{ |v| _deserialize($1, v) } ) + end + elsif !attributes[self.class.attribute_map[key]].nil? + self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) + end # or else data not found in attributes(hash), not an issue as the data can be optional + end + + self + end + + # Deserializes the data based on type + # @param string type Data type + # @param string value Value to be deserialized + # @return [Object] Deserialized data + def _deserialize(type, value) + case type.to_sym + when :DateTime + DateTime.parse(value) + when :Date + Date.parse(value) + when :String + value.to_s + when :Integer + value.to_i + when :Float + value.to_f + when :BOOLEAN + if value.to_s =~ /^(true|t|yes|y|1)$/i + true + else + false + end + when :Object + # generic object (usually a Hash), return directly + value + when /\AArray<(?.+)>\z/ + inner_type = Regexp.last_match[:inner_type] + value.map { |v| _deserialize(inner_type, v) } + when /\AHash<(?.+), (?.+)>\z/ + k_type = Regexp.last_match[:k_type] + v_type = Regexp.last_match[:v_type] + {}.tap do |hash| + value.each do |k, v| + hash[_deserialize(k_type, k)] = _deserialize(v_type, v) + end + end + else # model + temp_model = Petstore.const_get(type).new + temp_model.build_from_hash(value) + end + end + + # Returns the string representation of the object + # @return [String] String presentation of the object + def to_s + to_hash.to_s + end + + # to_body is an alias to to_hash (backward compatibility) + # @return [Hash] Returns the object in the form of hash + def to_body + to_hash + end + + # Returns the object in the form of hash + # @return [Hash] Returns the object in the form of hash + def to_hash + hash = {} + self.class.attribute_map.each_pair do |attr, param| + value = self.send(attr) + next if value.nil? + hash[param] = _to_hash(value) + end + hash + end + + # Outputs non-array value in the form of hash + # For object, use to_hash. Otherwise, just return the value + # @param [Object] value Any valid value + # @return [Hash] Returns the value in the form of hash + def _to_hash(value) + if value.is_a?(Array) + value.compact.map{ |v| _to_hash(v) } + elsif value.is_a?(Hash) + {}.tap do |hash| + value.each { |k, v| hash[k] = _to_hash(v) } + end + elsif value.respond_to? :to_hash + value.to_hash + else + value + end + end + + end +end diff --git a/samples/client/petstore/ruby/lib/petstore/models/category.rb b/samples/client/petstore/ruby/lib/petstore/models/category.rb index 3defc6193d1..cb7091dc788 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/category.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/category.rb @@ -25,11 +25,8 @@ module Petstore # Attribute mapping from ruby-style variable name to JSON key. def self.attribute_map { - :'id' => :'id', - :'name' => :'name' - } end @@ -37,29 +34,28 @@ module Petstore def self.swagger_types { :'id' => :'Integer', - :'name' => :'String' - +:'name' => :'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.inject({}){|memo,(k,v)| memo[k.to_sym] = v; memo} + attributes = attributes.each_with_object({}){|(k,v), h| h[k.to_sym] = v} - if attributes[:'id'] self.id = attributes[:'id'] end - if attributes[:'name'] self.name = attributes[:'name'] end - end - # Check equality by comparing each attribute. + # Checks equality by comparing each attribute. + # @param [Object] Object to be compared def ==(o) return true if self.equal?(o) self.class == o.class && @@ -68,35 +64,41 @@ module Petstore end # @see the `==` method + # @param [Object] Object to be compared def eql?(o) self == o end - # Calculate hash code according to all attributes. + # Calculates hash code according to all attributes. + # @return [Fixnum] Hash code def hash [id, name].hash end - # build the object from hash + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself def build_from_hash(attributes) return nil unless attributes.is_a?(Hash) self.class.swagger_types.each_pair do |key, type| if type =~ /^Array<(.*)>/i + # check to ensure the input is an array given that the the attribute + # is documented as an array but the input is not if attributes[self.class.attribute_map[key]].is_a?(Array) self.send("#{key}=", attributes[self.class.attribute_map[key]].map{ |v| _deserialize($1, v) } ) - else - #TODO show warning in debug mode end elsif !attributes[self.class.attribute_map[key]].nil? self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) - else - # data not found in attributes(hash), not an issue as the data can be optional - end + 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 @@ -130,21 +132,25 @@ module Petstore end end else # model - _model = Petstore.const_get(type).new - _model.build_from_hash(value) + 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_body (backward compatibility)) + # 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 - # return the object in the form of hash + # 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| @@ -155,8 +161,10 @@ module Petstore hash end - # Method to output non-array value in the form of hash + # 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) } diff --git a/samples/client/petstore/ruby/lib/petstore/models/dog.rb b/samples/client/petstore/ruby/lib/petstore/models/dog.rb new file mode 100644 index 00000000000..b0efe164eb7 --- /dev/null +++ b/samples/client/petstore/ruby/lib/petstore/models/dog.rb @@ -0,0 +1,183 @@ +=begin +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@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +License: Apache 2.0 +http://www.apache.org/licenses/LICENSE-2.0.html + +Terms of Service: http://swagger.io/terms/ + +=end + +require 'date' + +module Petstore + class Dog + attr_accessor :class_name + + attr_accessor :breed + + # Attribute mapping from ruby-style variable name to JSON key. + def self.attribute_map + { + :'class_name' => :'className', + :'breed' => :'breed' + } + end + + # Attribute type mapping. + def self.swagger_types + { + :'class_name' => :'String', +:'breed' => :'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[:'className'] + self.class_name = attributes[:'className'] + end + if attributes[:'breed'] + self.breed = attributes[:'breed'] + end + 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 && + class_name == o.class_name && + breed == o.breed + 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 + [class_name, breed].hash + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def build_from_hash(attributes) + return nil unless attributes.is_a?(Hash) + self.class.swagger_types.each_pair do |key, type| + if type =~ /^Array<(.*)>/i + # check to ensure the input is an array given that the the attribute + # is documented as an array but the input is not + if attributes[self.class.attribute_map[key]].is_a?(Array) + self.send("#{key}=", attributes[self.class.attribute_map[key]].map{ |v| _deserialize($1, v) } ) + end + elsif !attributes[self.class.attribute_map[key]].nil? + self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) + end # or else data not found in attributes(hash), not an issue as the data can be optional + end + + self + end + + # Deserializes the data based on type + # @param string type Data type + # @param string value Value to be deserialized + # @return [Object] Deserialized data + def _deserialize(type, value) + case type.to_sym + when :DateTime + DateTime.parse(value) + when :Date + Date.parse(value) + when :String + value.to_s + when :Integer + value.to_i + when :Float + value.to_f + when :BOOLEAN + if value.to_s =~ /^(true|t|yes|y|1)$/i + true + else + false + end + when :Object + # generic object (usually a Hash), return directly + value + when /\AArray<(?.+)>\z/ + inner_type = Regexp.last_match[:inner_type] + value.map { |v| _deserialize(inner_type, v) } + when /\AHash<(?.+), (?.+)>\z/ + k_type = Regexp.last_match[:k_type] + v_type = Regexp.last_match[:v_type] + {}.tap do |hash| + value.each do |k, v| + hash[_deserialize(k_type, k)] = _deserialize(v_type, v) + end + end + else # model + temp_model = Petstore.const_get(type).new + temp_model.build_from_hash(value) + end + end + + # Returns the string representation of the object + # @return [String] String presentation of the object + def to_s + to_hash.to_s + end + + # to_body is an alias to to_hash (backward compatibility) + # @return [Hash] Returns the object in the form of hash + def to_body + to_hash + end + + # Returns the object in the form of hash + # @return [Hash] Returns the object in the form of hash + def to_hash + hash = {} + self.class.attribute_map.each_pair do |attr, param| + value = self.send(attr) + next if value.nil? + hash[param] = _to_hash(value) + end + hash + end + + # Outputs non-array value in the form of hash + # For object, use to_hash. Otherwise, just return the value + # @param [Object] value Any valid value + # @return [Hash] Returns the value in the form of hash + def _to_hash(value) + if value.is_a?(Array) + value.compact.map{ |v| _to_hash(v) } + elsif value.is_a?(Hash) + {}.tap do |hash| + value.each { |k, v| hash[k] = _to_hash(v) } + end + elsif value.respond_to? :to_hash + value.to_hash + else + value + end + end + + end +end diff --git a/samples/client/petstore/ruby/lib/petstore/models/inline_response_200.rb b/samples/client/petstore/ruby/lib/petstore/models/inline_response_200.rb index 4f45295d374..3b75ff5e41e 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 @@ -18,95 +18,134 @@ require 'date' module Petstore class InlineResponse200 - attr_accessor :name + attr_accessor :tags attr_accessor :id attr_accessor :category + # pet status in the store + attr_accessor :status + + attr_accessor :name + + attr_accessor :photo_urls + # Attribute mapping from ruby-style variable name to JSON key. def self.attribute_map { - - :'name' => :'name', - + :'tags' => :'tags', :'id' => :'id', - - :'category' => :'category' - + :'category' => :'category', + :'status' => :'status', + :'name' => :'name', + :'photo_urls' => :'photoUrls' } end # Attribute type mapping. def self.swagger_types { - :'name' => :'String', - :'id' => :'Integer', - :'category' => :'Object' - + :'tags' => :'Array', +:'id' => :'Integer', +:'category' => :'Object', +:'status' => :'String', +:'name' => :'String', +:'photo_urls' => :'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.inject({}){|memo,(k,v)| memo[k.to_sym] = v; memo} + attributes = attributes.each_with_object({}){|(k,v), h| h[k.to_sym] = v} - - if attributes[:'name'] - self.name = attributes[:'name'] + if attributes[:'tags'] + if (value = attributes[:'tags']).is_a?(Array) + self.tags = value + end end - if attributes[:'id'] self.id = attributes[:'id'] end - if attributes[:'category'] self.category = attributes[:'category'] end - + if attributes[:'status'] + self.status = attributes[:'status'] + end + if attributes[:'name'] + self.name = attributes[:'name'] + end + if attributes[:'photoUrls'] + if (value = attributes[:'photoUrls']).is_a?(Array) + self.photo_urls = value + end + end end - # Check equality by comparing each attribute. + # Custom attribute writer method checking allowed values (enum). + # @param [Object] status Object to be assigned + def status=(status) + allowed_values = ["available", "pending", "sold"] + if status && !allowed_values.include?(status) + fail "invalid value for 'status', must be one of #{allowed_values}" + end + @status = status + 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 && - name == o.name && + tags == o.tags && id == o.id && - category == o.category + category == o.category && + status == o.status && + name == o.name && + photo_urls == o.photo_urls end # @see the `==` method + # @param [Object] Object to be compared def eql?(o) self == o end - # Calculate hash code according to all attributes. + # Calculates hash code according to all attributes. + # @return [Fixnum] Hash code def hash - [name, id, category].hash + [tags, id, category, status, name, photo_urls].hash end - # build the object from hash + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself def build_from_hash(attributes) return nil unless attributes.is_a?(Hash) self.class.swagger_types.each_pair do |key, type| if type =~ /^Array<(.*)>/i + # check to ensure the input is an array given that the the attribute + # is documented as an array but the input is not if attributes[self.class.attribute_map[key]].is_a?(Array) self.send("#{key}=", attributes[self.class.attribute_map[key]].map{ |v| _deserialize($1, v) } ) - else - #TODO show warning in debug mode end elsif !attributes[self.class.attribute_map[key]].nil? self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) - else - # data not found in attributes(hash), not an issue as the data can be optional - end + 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 @@ -140,21 +179,25 @@ module Petstore end end else # model - _model = Petstore.const_get(type).new - _model.build_from_hash(value) + 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_body (backward compatibility)) + # 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 - # return the object in the form of hash + # 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| @@ -165,8 +208,10 @@ module Petstore hash end - # Method to output non-array value in the form of hash + # 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) } 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 new file mode 100644 index 00000000000..4e198a489b3 --- /dev/null +++ b/samples/client/petstore/ruby/lib/petstore/models/model_200_response.rb @@ -0,0 +1,176 @@ +=begin +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@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +License: Apache 2.0 +http://www.apache.org/licenses/LICENSE-2.0.html + +Terms of Service: http://swagger.io/terms/ + +=end + +require 'date' + +module Petstore + # Model for testing model name starting with number + class Model200Response + attr_accessor :name + + # Attribute mapping from ruby-style variable name to JSON key. + def self.attribute_map + { + :'name' => :'name' + } + end + + # Attribute type mapping. + def self.swagger_types + { + :'name' => :'Integer' + } + 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[:'name'] + self.name = attributes[:'name'] + end + 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 && + name == o.name + 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 + [name].hash + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def build_from_hash(attributes) + return nil unless attributes.is_a?(Hash) + self.class.swagger_types.each_pair do |key, type| + if type =~ /^Array<(.*)>/i + # check to ensure the input is an array given that the the attribute + # is documented as an array but the input is not + if attributes[self.class.attribute_map[key]].is_a?(Array) + self.send("#{key}=", attributes[self.class.attribute_map[key]].map{ |v| _deserialize($1, v) } ) + end + elsif !attributes[self.class.attribute_map[key]].nil? + self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) + end # or else data not found in attributes(hash), not an issue as the data can be optional + end + + self + end + + # Deserializes the data based on type + # @param string type Data type + # @param string value Value to be deserialized + # @return [Object] Deserialized data + def _deserialize(type, value) + case type.to_sym + when :DateTime + DateTime.parse(value) + when :Date + Date.parse(value) + when :String + value.to_s + when :Integer + value.to_i + when :Float + value.to_f + when :BOOLEAN + if value.to_s =~ /^(true|t|yes|y|1)$/i + true + else + false + end + when :Object + # generic object (usually a Hash), return directly + value + when /\AArray<(?.+)>\z/ + inner_type = Regexp.last_match[:inner_type] + value.map { |v| _deserialize(inner_type, v) } + when /\AHash<(?.+), (?.+)>\z/ + k_type = Regexp.last_match[:k_type] + v_type = Regexp.last_match[:v_type] + {}.tap do |hash| + value.each do |k, v| + hash[_deserialize(k_type, k)] = _deserialize(v_type, v) + end + end + else # model + temp_model = Petstore.const_get(type).new + temp_model.build_from_hash(value) + end + end + + # Returns the string representation of the object + # @return [String] String presentation of the object + def to_s + to_hash.to_s + end + + # to_body is an alias to to_hash (backward compatibility) + # @return [Hash] Returns the object in the form of hash + def to_body + to_hash + end + + # Returns the object in the form of hash + # @return [Hash] Returns the object in the form of hash + def to_hash + hash = {} + self.class.attribute_map.each_pair do |attr, param| + value = self.send(attr) + next if value.nil? + hash[param] = _to_hash(value) + end + hash + end + + # Outputs non-array value in the form of hash + # For object, use to_hash. Otherwise, just return the value + # @param [Object] value Any valid value + # @return [Hash] Returns the value in the form of hash + def _to_hash(value) + if value.is_a?(Array) + value.compact.map{ |v| _to_hash(v) } + elsif value.is_a?(Hash) + {}.tap do |hash| + value.each { |k, v| hash[k] = _to_hash(v) } + end + elsif value.respond_to? :to_hash + value.to_hash + else + value + end + end + + end +end diff --git a/samples/client/petstore/ruby/lib/petstore/models/object_return.rb b/samples/client/petstore/ruby/lib/petstore/models/model_return.rb similarity index 68% rename from samples/client/petstore/ruby/lib/petstore/models/object_return.rb rename to samples/client/petstore/ruby/lib/petstore/models/model_return.rb index 06c9d99fccc..f016ff32fe9 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/object_return.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/model_return.rb @@ -17,15 +17,14 @@ Terms of Service: http://swagger.io/terms/ require 'date' module Petstore - class ObjectReturn + # Model for testing reserved words + class ModelReturn attr_accessor :_return # Attribute mapping from ruby-style variable name to JSON key. def self.attribute_map { - :'_return' => :'return' - } end @@ -33,24 +32,24 @@ module Petstore def self.swagger_types { :'_return' => :'Integer' - } 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.inject({}){|memo,(k,v)| memo[k.to_sym] = v; memo} + attributes = attributes.each_with_object({}){|(k,v), h| h[k.to_sym] = v} - if attributes[:'return'] self._return = attributes[:'return'] end - end - # Check equality by comparing each attribute. + # Checks equality by comparing each attribute. + # @param [Object] Object to be compared def ==(o) return true if self.equal?(o) self.class == o.class && @@ -58,35 +57,41 @@ module Petstore end # @see the `==` method + # @param [Object] Object to be compared def eql?(o) self == o end - # Calculate hash code according to all attributes. + # Calculates hash code according to all attributes. + # @return [Fixnum] Hash code def hash [_return].hash end - # build the object from hash + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself def build_from_hash(attributes) return nil unless attributes.is_a?(Hash) self.class.swagger_types.each_pair do |key, type| if type =~ /^Array<(.*)>/i + # check to ensure the input is an array given that the the attribute + # is documented as an array but the input is not if attributes[self.class.attribute_map[key]].is_a?(Array) self.send("#{key}=", attributes[self.class.attribute_map[key]].map{ |v| _deserialize($1, v) } ) - else - #TODO show warning in debug mode end elsif !attributes[self.class.attribute_map[key]].nil? self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) - else - # data not found in attributes(hash), not an issue as the data can be optional - end + 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 @@ -120,21 +125,25 @@ module Petstore end end else # model - _model = Petstore.const_get(type).new - _model.build_from_hash(value) + 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_body (backward compatibility)) + # 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 - # return the object in the form of hash + # 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| @@ -145,8 +154,10 @@ module Petstore hash end - # Method to output non-array value in the form of hash + # 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) } diff --git a/samples/client/petstore/ruby/lib/petstore/models/name.rb b/samples/client/petstore/ruby/lib/petstore/models/name.rb new file mode 100644 index 00000000000..35ed30e193c --- /dev/null +++ b/samples/client/petstore/ruby/lib/petstore/models/name.rb @@ -0,0 +1,184 @@ +=begin +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@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +License: Apache 2.0 +http://www.apache.org/licenses/LICENSE-2.0.html + +Terms of Service: http://swagger.io/terms/ + +=end + +require 'date' + +module Petstore + # Model for testing model name same as property name + class Name + attr_accessor :name + + attr_accessor :snake_case + + # Attribute mapping from ruby-style variable name to JSON key. + def self.attribute_map + { + :'name' => :'name', + :'snake_case' => :'snake_case' + } + end + + # Attribute type mapping. + def self.swagger_types + { + :'name' => :'Integer', +:'snake_case' => :'Integer' + } + 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[:'name'] + self.name = attributes[:'name'] + end + if attributes[:'snake_case'] + self.snake_case = attributes[:'snake_case'] + end + 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 && + name == o.name && + snake_case == o.snake_case + 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 + [name, snake_case].hash + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def build_from_hash(attributes) + return nil unless attributes.is_a?(Hash) + self.class.swagger_types.each_pair do |key, type| + if type =~ /^Array<(.*)>/i + # check to ensure the input is an array given that the the attribute + # is documented as an array but the input is not + if attributes[self.class.attribute_map[key]].is_a?(Array) + self.send("#{key}=", attributes[self.class.attribute_map[key]].map{ |v| _deserialize($1, v) } ) + end + elsif !attributes[self.class.attribute_map[key]].nil? + self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) + end # or else data not found in attributes(hash), not an issue as the data can be optional + end + + self + end + + # Deserializes the data based on type + # @param string type Data type + # @param string value Value to be deserialized + # @return [Object] Deserialized data + def _deserialize(type, value) + case type.to_sym + when :DateTime + DateTime.parse(value) + when :Date + Date.parse(value) + when :String + value.to_s + when :Integer + value.to_i + when :Float + value.to_f + when :BOOLEAN + if value.to_s =~ /^(true|t|yes|y|1)$/i + true + else + false + end + when :Object + # generic object (usually a Hash), return directly + value + when /\AArray<(?.+)>\z/ + inner_type = Regexp.last_match[:inner_type] + value.map { |v| _deserialize(inner_type, v) } + when /\AHash<(?.+), (?.+)>\z/ + k_type = Regexp.last_match[:k_type] + v_type = Regexp.last_match[:v_type] + {}.tap do |hash| + value.each do |k, v| + hash[_deserialize(k_type, k)] = _deserialize(v_type, v) + end + end + else # model + temp_model = Petstore.const_get(type).new + temp_model.build_from_hash(value) + end + end + + # Returns the string representation of the object + # @return [String] String presentation of the object + def to_s + to_hash.to_s + end + + # to_body is an alias to to_hash (backward compatibility) + # @return [Hash] Returns the object in the form of hash + def to_body + to_hash + end + + # Returns the object in the form of hash + # @return [Hash] Returns the object in the form of hash + def to_hash + hash = {} + self.class.attribute_map.each_pair do |attr, param| + value = self.send(attr) + next if value.nil? + hash[param] = _to_hash(value) + end + hash + end + + # Outputs non-array value in the form of hash + # For object, use to_hash. Otherwise, just return the value + # @param [Object] value Any valid value + # @return [Hash] Returns the value in the form of hash + def _to_hash(value) + if value.is_a?(Array) + value.compact.map{ |v| _to_hash(v) } + elsif value.is_a?(Hash) + {}.tap do |hash| + value.each { |k, v| hash[k] = _to_hash(v) } + end + elsif value.respond_to? :to_hash + value.to_hash + else + value + end + end + + end +end diff --git a/samples/client/petstore/ruby/lib/petstore/models/order.rb b/samples/client/petstore/ruby/lib/petstore/models/order.rb index c7a6076a269..223d748e990 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/order.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/order.rb @@ -34,19 +34,12 @@ module Petstore # Attribute mapping from ruby-style variable name to JSON key. def self.attribute_map { - :'id' => :'id', - :'pet_id' => :'petId', - :'quantity' => :'quantity', - :'ship_date' => :'shipDate', - :'status' => :'status', - :'complete' => :'complete' - } end @@ -54,49 +47,44 @@ module Petstore def self.swagger_types { :'id' => :'Integer', - :'pet_id' => :'Integer', - :'quantity' => :'Integer', - :'ship_date' => :'DateTime', - :'status' => :'String', - :'complete' => :'BOOLEAN' - +:'pet_id' => :'Integer', +:'quantity' => :'Integer', +:'ship_date' => :'DateTime', +:'status' => :'String', +:'complete' => :'BOOLEAN' } 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.inject({}){|memo,(k,v)| memo[k.to_sym] = v; memo} + attributes = attributes.each_with_object({}){|(k,v), h| h[k.to_sym] = v} - if attributes[:'id'] self.id = attributes[:'id'] end - if attributes[:'petId'] self.pet_id = attributes[:'petId'] end - if attributes[:'quantity'] self.quantity = attributes[:'quantity'] end - if attributes[:'shipDate'] self.ship_date = attributes[:'shipDate'] end - if attributes[:'status'] self.status = attributes[:'status'] end - if attributes[:'complete'] self.complete = attributes[:'complete'] end - end # Custom attribute writer method checking allowed values (enum). + # @param [Object] status Object to be assigned def status=(status) allowed_values = ["placed", "approved", "delivered"] if status && !allowed_values.include?(status) @@ -105,7 +93,8 @@ module Petstore @status = status end - # Check equality by comparing each attribute. + # Checks equality by comparing each attribute. + # @param [Object] Object to be compared def ==(o) return true if self.equal?(o) self.class == o.class && @@ -118,35 +107,41 @@ module Petstore end # @see the `==` method + # @param [Object] Object to be compared def eql?(o) self == o end - # Calculate hash code according to all attributes. + # Calculates hash code according to all attributes. + # @return [Fixnum] Hash code def hash [id, pet_id, quantity, ship_date, status, complete].hash end - # build the object from hash + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself def build_from_hash(attributes) return nil unless attributes.is_a?(Hash) self.class.swagger_types.each_pair do |key, type| if type =~ /^Array<(.*)>/i + # check to ensure the input is an array given that the the attribute + # is documented as an array but the input is not if attributes[self.class.attribute_map[key]].is_a?(Array) self.send("#{key}=", attributes[self.class.attribute_map[key]].map{ |v| _deserialize($1, v) } ) - else - #TODO show warning in debug mode end elsif !attributes[self.class.attribute_map[key]].nil? self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) - else - # data not found in attributes(hash), not an issue as the data can be optional - end + 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 @@ -180,21 +175,25 @@ module Petstore end end else # model - _model = Petstore.const_get(type).new - _model.build_from_hash(value) + 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_body (backward compatibility)) + # 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 - # return the object in the form of hash + # 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| @@ -205,8 +204,10 @@ module Petstore hash end - # Method to output non-array value in the form of hash + # 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) } diff --git a/samples/client/petstore/ruby/lib/petstore/models/pet.rb b/samples/client/petstore/ruby/lib/petstore/models/pet.rb index fb0eaa05a72..07c5ee9d75b 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/pet.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/pet.rb @@ -34,19 +34,12 @@ module Petstore # Attribute mapping from ruby-style variable name to JSON key. def self.attribute_map { - :'id' => :'id', - :'category' => :'category', - :'name' => :'name', - :'photo_urls' => :'photoUrls', - :'tags' => :'tags', - :'status' => :'status' - } end @@ -54,53 +47,48 @@ module Petstore def self.swagger_types { :'id' => :'Integer', - :'category' => :'Category', - :'name' => :'String', - :'photo_urls' => :'Array', - :'tags' => :'Array', - :'status' => :'String' - +:'category' => :'Category', +:'name' => :'String', +:'photo_urls' => :'Array', +:'tags' => :'Array', +:'status' => :'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.inject({}){|memo,(k,v)| memo[k.to_sym] = v; memo} + attributes = attributes.each_with_object({}){|(k,v), h| h[k.to_sym] = v} - if attributes[:'id'] self.id = attributes[:'id'] end - if attributes[:'category'] self.category = attributes[:'category'] end - if attributes[:'name'] self.name = attributes[:'name'] end - if attributes[:'photoUrls'] if (value = attributes[:'photoUrls']).is_a?(Array) self.photo_urls = value end end - if attributes[:'tags'] if (value = attributes[:'tags']).is_a?(Array) self.tags = value end end - if attributes[:'status'] self.status = attributes[:'status'] end - end # Custom attribute writer method checking allowed values (enum). + # @param [Object] status Object to be assigned def status=(status) allowed_values = ["available", "pending", "sold"] if status && !allowed_values.include?(status) @@ -109,7 +97,8 @@ module Petstore @status = status end - # Check equality by comparing each attribute. + # Checks equality by comparing each attribute. + # @param [Object] Object to be compared def ==(o) return true if self.equal?(o) self.class == o.class && @@ -122,35 +111,41 @@ module Petstore end # @see the `==` method + # @param [Object] Object to be compared def eql?(o) self == o end - # Calculate hash code according to all attributes. + # Calculates hash code according to all attributes. + # @return [Fixnum] Hash code def hash [id, category, name, photo_urls, tags, status].hash end - # build the object from hash + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself def build_from_hash(attributes) return nil unless attributes.is_a?(Hash) self.class.swagger_types.each_pair do |key, type| if type =~ /^Array<(.*)>/i + # check to ensure the input is an array given that the the attribute + # is documented as an array but the input is not if attributes[self.class.attribute_map[key]].is_a?(Array) self.send("#{key}=", attributes[self.class.attribute_map[key]].map{ |v| _deserialize($1, v) } ) - else - #TODO show warning in debug mode end elsif !attributes[self.class.attribute_map[key]].nil? self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) - else - # data not found in attributes(hash), not an issue as the data can be optional - end + 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 @@ -184,21 +179,25 @@ module Petstore end end else # model - _model = Petstore.const_get(type).new - _model.build_from_hash(value) + 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_body (backward compatibility)) + # 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 - # return the object in the form of hash + # 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| @@ -209,8 +208,10 @@ module Petstore hash end - # Method to output non-array value in the form of hash + # 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) } 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 b8e97d55940..b0509903ef2 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 @@ -23,9 +23,7 @@ module Petstore # Attribute mapping from ruby-style variable name to JSON key. def self.attribute_map { - :'special_property_name' => :'$special[property.name]' - } end @@ -33,24 +31,24 @@ module Petstore def self.swagger_types { :'special_property_name' => :'Integer' - } 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.inject({}){|memo,(k,v)| memo[k.to_sym] = v; memo} + attributes = attributes.each_with_object({}){|(k,v), h| h[k.to_sym] = v} - if attributes[:'$special[property.name]'] self.special_property_name = attributes[:'$special[property.name]'] end - end - # Check equality by comparing each attribute. + # Checks equality by comparing each attribute. + # @param [Object] Object to be compared def ==(o) return true if self.equal?(o) self.class == o.class && @@ -58,35 +56,41 @@ module Petstore end # @see the `==` method + # @param [Object] Object to be compared def eql?(o) self == o end - # Calculate hash code according to all attributes. + # Calculates hash code according to all attributes. + # @return [Fixnum] Hash code def hash [special_property_name].hash end - # build the object from hash + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself def build_from_hash(attributes) return nil unless attributes.is_a?(Hash) self.class.swagger_types.each_pair do |key, type| if type =~ /^Array<(.*)>/i + # check to ensure the input is an array given that the the attribute + # is documented as an array but the input is not if attributes[self.class.attribute_map[key]].is_a?(Array) self.send("#{key}=", attributes[self.class.attribute_map[key]].map{ |v| _deserialize($1, v) } ) - else - #TODO show warning in debug mode end elsif !attributes[self.class.attribute_map[key]].nil? self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) - else - # data not found in attributes(hash), not an issue as the data can be optional - end + 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 @@ -120,21 +124,25 @@ module Petstore end end else # model - _model = Petstore.const_get(type).new - _model.build_from_hash(value) + 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_body (backward compatibility)) + # 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 - # return the object in the form of hash + # 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| @@ -145,8 +153,10 @@ module Petstore hash end - # Method to output non-array value in the form of hash + # 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) } diff --git a/samples/client/petstore/ruby/lib/petstore/models/tag.rb b/samples/client/petstore/ruby/lib/petstore/models/tag.rb index 8c4bb743bf3..c1a07d1b5e6 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/tag.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/tag.rb @@ -25,11 +25,8 @@ module Petstore # Attribute mapping from ruby-style variable name to JSON key. def self.attribute_map { - :'id' => :'id', - :'name' => :'name' - } end @@ -37,29 +34,28 @@ module Petstore def self.swagger_types { :'id' => :'Integer', - :'name' => :'String' - +:'name' => :'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.inject({}){|memo,(k,v)| memo[k.to_sym] = v; memo} + attributes = attributes.each_with_object({}){|(k,v), h| h[k.to_sym] = v} - if attributes[:'id'] self.id = attributes[:'id'] end - if attributes[:'name'] self.name = attributes[:'name'] end - end - # Check equality by comparing each attribute. + # Checks equality by comparing each attribute. + # @param [Object] Object to be compared def ==(o) return true if self.equal?(o) self.class == o.class && @@ -68,35 +64,41 @@ module Petstore end # @see the `==` method + # @param [Object] Object to be compared def eql?(o) self == o end - # Calculate hash code according to all attributes. + # Calculates hash code according to all attributes. + # @return [Fixnum] Hash code def hash [id, name].hash end - # build the object from hash + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself def build_from_hash(attributes) return nil unless attributes.is_a?(Hash) self.class.swagger_types.each_pair do |key, type| if type =~ /^Array<(.*)>/i + # check to ensure the input is an array given that the the attribute + # is documented as an array but the input is not if attributes[self.class.attribute_map[key]].is_a?(Array) self.send("#{key}=", attributes[self.class.attribute_map[key]].map{ |v| _deserialize($1, v) } ) - else - #TODO show warning in debug mode end elsif !attributes[self.class.attribute_map[key]].nil? self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) - else - # data not found in attributes(hash), not an issue as the data can be optional - end + 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 @@ -130,21 +132,25 @@ module Petstore end end else # model - _model = Petstore.const_get(type).new - _model.build_from_hash(value) + 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_body (backward compatibility)) + # 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 - # return the object in the form of hash + # 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| @@ -155,8 +161,10 @@ module Petstore hash end - # Method to output non-array value in the form of hash + # 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) } diff --git a/samples/client/petstore/ruby/lib/petstore/models/user.rb b/samples/client/petstore/ruby/lib/petstore/models/user.rb index dd37878bdc1..8e0c4fc99db 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/user.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/user.rb @@ -38,23 +38,14 @@ module Petstore # Attribute mapping from ruby-style variable name to JSON key. def self.attribute_map { - :'id' => :'id', - :'username' => :'username', - :'first_name' => :'firstName', - :'last_name' => :'lastName', - :'email' => :'email', - :'password' => :'password', - :'phone' => :'phone', - :'user_status' => :'userStatus' - } end @@ -62,59 +53,52 @@ module Petstore def self.swagger_types { :'id' => :'Integer', - :'username' => :'String', - :'first_name' => :'String', - :'last_name' => :'String', - :'email' => :'String', - :'password' => :'String', - :'phone' => :'String', - :'user_status' => :'Integer' - +:'username' => :'String', +:'first_name' => :'String', +:'last_name' => :'String', +:'email' => :'String', +:'password' => :'String', +:'phone' => :'String', +:'user_status' => :'Integer' } 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.inject({}){|memo,(k,v)| memo[k.to_sym] = v; memo} + attributes = attributes.each_with_object({}){|(k,v), h| h[k.to_sym] = v} - if attributes[:'id'] self.id = attributes[:'id'] end - if attributes[:'username'] self.username = attributes[:'username'] end - if attributes[:'firstName'] self.first_name = attributes[:'firstName'] end - if attributes[:'lastName'] self.last_name = attributes[:'lastName'] end - if attributes[:'email'] self.email = attributes[:'email'] end - if attributes[:'password'] self.password = attributes[:'password'] end - if attributes[:'phone'] self.phone = attributes[:'phone'] end - if attributes[:'userStatus'] self.user_status = attributes[:'userStatus'] end - end - # Check equality by comparing each attribute. + # Checks equality by comparing each attribute. + # @param [Object] Object to be compared def ==(o) return true if self.equal?(o) self.class == o.class && @@ -129,35 +113,41 @@ module Petstore end # @see the `==` method + # @param [Object] Object to be compared def eql?(o) self == o end - # Calculate hash code according to all attributes. + # Calculates hash code according to all attributes. + # @return [Fixnum] Hash code def hash [id, username, first_name, last_name, email, password, phone, user_status].hash end - # build the object from hash + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself def build_from_hash(attributes) return nil unless attributes.is_a?(Hash) self.class.swagger_types.each_pair do |key, type| if type =~ /^Array<(.*)>/i + # check to ensure the input is an array given that the the attribute + # is documented as an array but the input is not if attributes[self.class.attribute_map[key]].is_a?(Array) self.send("#{key}=", attributes[self.class.attribute_map[key]].map{ |v| _deserialize($1, v) } ) - else - #TODO show warning in debug mode end elsif !attributes[self.class.attribute_map[key]].nil? self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) - else - # data not found in attributes(hash), not an issue as the data can be optional - end + 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 @@ -191,21 +181,25 @@ module Petstore end end else # model - _model = Petstore.const_get(type).new - _model.build_from_hash(value) + 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_body (backward compatibility)) + # 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 - # return the object in the form of hash + # 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| @@ -216,8 +210,10 @@ module Petstore hash end - # Method to output non-array value in the form of hash + # 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) } diff --git a/samples/client/petstore/ruby/spec/api/PetApi_spec.rb b/samples/client/petstore/ruby/spec/api/PetApi_spec.rb deleted file mode 100644 index 0d4b6ac3519..00000000000 --- a/samples/client/petstore/ruby/spec/api/PetApi_spec.rb +++ /dev/null @@ -1,204 +0,0 @@ -=begin -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@swagger.io -Generated by: https://github.com/swagger-api/swagger-codegen.git - -License: Apache 2.0 -http://www.apache.org/licenses/LICENSE-2.0.html - -Terms of Service: http://swagger.io/terms/ - -=end - -require 'spec_helper' -require 'json' - -# Unit tests for Petstore::PetApi -# Automatically generated by swagger-codegen (github.com/swagger-api/swagger-codegen) -# Please update as you see appropriate -describe 'PetApi' do - before do - # run before each test - @instance = Petstore::PetApi.new - end - - after do - # run after each test - end - - describe 'test an instance of PetApi' do - it 'should create an instact of PetApi' do - @instance.should be_a(Petstore::PetApi) - end - end - - # unit tests for update_pet - # Update an existing pet - # - # @param [Hash] opts the optional parameters - # @option opts [Pet] :body Pet object that needs to be added to the store - # @return [nil] - describe 'update_pet test' do - it "should work" do - # assertion here - # should be_a() - # should be_nil - # should == - # should_not == - end - end - - # unit tests for add_pet - # Add a new pet to the store - # - # @param [Hash] opts the optional parameters - # @option opts [Pet] :body Pet object that needs to be added to the store - # @return [nil] - describe 'add_pet test' do - it "should work" do - # assertion here - # should be_a() - # should be_nil - # should == - # should_not == - end - end - - # unit tests for find_pets_by_status - # Finds Pets by status - # Multiple status values can be provided with comma separated strings - # @param [Hash] opts the optional parameters - # @option opts [Array] :status Status values that need to be considered for query - # @return [Array] - describe 'find_pets_by_status test' do - it "should work" do - # assertion here - # should be_a() - # should be_nil - # should == - # should_not == - end - end - - # unit tests for find_pets_by_tags - # Finds Pets by tags - # Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. - # @param [Hash] opts the optional parameters - # @option opts [Array] :tags Tags to filter by - # @return [Array] - describe 'find_pets_by_tags test' do - it "should work" do - # assertion here - # should be_a() - # should be_nil - # should == - # should_not == - end - end - - # unit tests for get_pet_by_id - # Find pet by ID - # Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions - # @param pet_id ID of pet that needs to be fetched - # @param [Hash] opts the optional parameters - # @return [Pet] - describe 'get_pet_by_id test' do - it "should work" do - # assertion here - # should be_a() - # should be_nil - # should == - # should_not == - end - end - - # unit tests for update_pet_with_form - # Updates a pet in the store with form data - # - # @param pet_id ID of pet that needs to be updated - # @param [Hash] opts the optional parameters - # @option opts [String] :name Updated name of the pet - # @option opts [String] :status Updated status of the pet - # @return [nil] - describe 'update_pet_with_form test' do - it "should work" do - # assertion here - # should be_a() - # should be_nil - # should == - # should_not == - end - end - - # unit tests for delete_pet - # Deletes a pet - # - # @param pet_id Pet id to delete - # @param [Hash] opts the optional parameters - # @option opts [String] :api_key - # @return [nil] - describe 'delete_pet test' do - it "should work" do - # assertion here - # should be_a() - # should be_nil - # should == - # should_not == - end - end - - # unit tests for upload_file - # uploads an image - # - # @param pet_id ID of pet to update - # @param [Hash] opts the optional parameters - # @option opts [String] :additional_metadata Additional data to pass to server - # @option opts [File] :file file to upload - # @return [nil] - describe 'upload_file test' do - it "should work" do - # assertion here - # should be_a() - # should be_nil - # should == - # should_not == - end - end - - # unit tests for pet_pet_idtesting_byte_arraytrue_get - # Fake endpoint to test byte array return by 'Find pet by ID' - # Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions - # @param pet_id ID of pet that needs to be fetched - # @param [Hash] opts the optional parameters - # @return [String] - describe 'pet_pet_idtesting_byte_arraytrue_get test' do - it "should work" do - # assertion here - # should be_a() - # should be_nil - # should == - # should_not == - end - end - - # unit tests for add_pet_using_byte_array - # Fake endpoint to test byte array in body parameter for adding a new pet to the store - # - # @param [Hash] opts the optional parameters - # @option opts [String] :body Pet object in the form of byte array - # @return [nil] - describe 'add_pet_using_byte_array test' do - it "should work" do - # assertion here - # should be_a() - # should be_nil - # should == - # should_not == - end - end - -end diff --git a/samples/client/petstore/ruby/spec/api/StoreApi_spec.rb b/samples/client/petstore/ruby/spec/api/StoreApi_spec.rb deleted file mode 100644 index a64b24ebca6..00000000000 --- a/samples/client/petstore/ruby/spec/api/StoreApi_spec.rb +++ /dev/null @@ -1,118 +0,0 @@ -=begin -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@swagger.io -Generated by: https://github.com/swagger-api/swagger-codegen.git - -License: Apache 2.0 -http://www.apache.org/licenses/LICENSE-2.0.html - -Terms of Service: http://swagger.io/terms/ - -=end - -require 'spec_helper' -require 'json' - -# Unit tests for Petstore::StoreApi -# Automatically generated by swagger-codegen (github.com/swagger-api/swagger-codegen) -# Please update as you see appropriate -describe 'StoreApi' do - before do - # run before each test - @instance = Petstore::StoreApi.new - end - - after do - # run after each test - end - - describe 'test an instance of StoreApi' do - it 'should create an instact of StoreApi' do - @instance.should be_a(Petstore::StoreApi) - end - end - - # unit tests for find_orders_by_status - # Finds orders by status - # A single status value can be provided as a string - # @param [Hash] opts the optional parameters - # @option opts [String] :status Status value that needs to be considered for query - # @return [Array] - describe 'find_orders_by_status test' do - it "should work" do - # assertion here - # should be_a() - # should be_nil - # should == - # should_not == - end - end - - # unit tests for get_inventory - # Returns pet inventories by status - # Returns a map of status codes to quantities - # @param [Hash] opts the optional parameters - # @return [Hash] - describe 'get_inventory test' do - it "should work" do - # assertion here - # should be_a() - # should be_nil - # should == - # should_not == - end - end - - # unit tests for place_order - # Place an order for a pet - # - # @param [Hash] opts the optional parameters - # @option opts [Order] :body order placed for purchasing the pet - # @return [Order] - describe 'place_order test' do - it "should work" do - # assertion here - # should be_a() - # should be_nil - # should == - # should_not == - end - end - - # unit tests for get_order_by_id - # Find purchase order by ID - # For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - # @param order_id ID of pet that needs to be fetched - # @param [Hash] opts the optional parameters - # @return [Order] - describe 'get_order_by_id test' do - it "should work" do - # assertion here - # should be_a() - # should be_nil - # should == - # should_not == - end - end - - # unit tests for delete_order - # Delete purchase order by ID - # For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors - # @param order_id ID of the order that needs to be deleted - # @param [Hash] opts the optional parameters - # @return [nil] - describe 'delete_order test' do - it "should work" do - # assertion here - # should be_a() - # should be_nil - # should == - # should_not == - end - end - -end diff --git a/samples/client/petstore/ruby/spec/api/UserApi_spec.rb b/samples/client/petstore/ruby/spec/api/UserApi_spec.rb deleted file mode 100644 index 894a62f6cc0..00000000000 --- a/samples/client/petstore/ruby/spec/api/UserApi_spec.rb +++ /dev/null @@ -1,168 +0,0 @@ -=begin -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@swagger.io -Generated by: https://github.com/swagger-api/swagger-codegen.git - -License: Apache 2.0 -http://www.apache.org/licenses/LICENSE-2.0.html - -Terms of Service: http://swagger.io/terms/ - -=end - -require 'spec_helper' -require 'json' - -# Unit tests for Petstore::UserApi -# Automatically generated by swagger-codegen (github.com/swagger-api/swagger-codegen) -# Please update as you see appropriate -describe 'UserApi' do - before do - # run before each test - @instance = Petstore::UserApi.new - end - - after do - # run after each test - end - - describe 'test an instance of UserApi' do - it 'should create an instact of UserApi' do - @instance.should be_a(Petstore::UserApi) - end - end - - # unit tests for create_user - # Create user - # This can only be done by the logged in user. - # @param [Hash] opts the optional parameters - # @option opts [User] :body Created user object - # @return [nil] - describe 'create_user test' do - it "should work" do - # assertion here - # should be_a() - # should be_nil - # should == - # should_not == - end - end - - # unit tests for create_users_with_array_input - # Creates list of users with given input array - # - # @param [Hash] opts the optional parameters - # @option opts [Array] :body List of user object - # @return [nil] - describe 'create_users_with_array_input test' do - it "should work" do - # assertion here - # should be_a() - # should be_nil - # should == - # should_not == - end - end - - # unit tests for create_users_with_list_input - # Creates list of users with given input array - # - # @param [Hash] opts the optional parameters - # @option opts [Array] :body List of user object - # @return [nil] - describe 'create_users_with_list_input test' do - it "should work" do - # assertion here - # should be_a() - # should be_nil - # should == - # should_not == - end - end - - # unit tests for login_user - # Logs user into the system - # - # @param [Hash] opts the optional parameters - # @option opts [String] :username The user name for login - # @option opts [String] :password The password for login in clear text - # @return [String] - describe 'login_user test' do - it "should work" do - # assertion here - # should be_a() - # should be_nil - # should == - # should_not == - end - end - - # unit tests for logout_user - # Logs out current logged in user session - # - # @param [Hash] opts the optional parameters - # @return [nil] - describe 'logout_user test' do - it "should work" do - # assertion here - # should be_a() - # should be_nil - # should == - # should_not == - end - end - - # unit tests for get_user_by_name - # Get user by user name - # - # @param username The name that needs to be fetched. Use user1 for testing. - # @param [Hash] opts the optional parameters - # @return [User] - describe 'get_user_by_name test' do - it "should work" do - # assertion here - # should be_a() - # should be_nil - # should == - # should_not == - end - end - - # unit tests for update_user - # Updated user - # This can only be done by the logged in user. - # @param username name that need to be deleted - # @param [Hash] opts the optional parameters - # @option opts [User] :body Updated user object - # @return [nil] - describe 'update_user test' do - it "should work" do - # assertion here - # should be_a() - # should be_nil - # should == - # should_not == - end - end - - # unit tests for delete_user - # Delete user - # This can only be done by the logged in user. - # @param username The name that needs to be deleted - # @param [Hash] opts the optional parameters - # @return [nil] - describe 'delete_user test' do - it "should work" do - # assertion here - # should be_a() - # should be_nil - # should == - # should_not == - end - end - -end diff --git a/samples/client/petstore/ruby/spec/api/pet_api_spec.rb b/samples/client/petstore/ruby/spec/api/pet_api_spec.rb index bf2f747cbdc..12cdc70dc57 100644 --- a/samples/client/petstore/ruby/spec/api/pet_api_spec.rb +++ b/samples/client/petstore/ruby/spec/api/pet_api_spec.rb @@ -36,13 +36,13 @@ describe 'PetApi' do end end - # unit tests for update_pet - # Update an existing pet + # unit tests for add_pet + # Add a new pet to the store # # @param [Hash] opts the optional parameters # @option opts [Pet] :body Pet object that needs to be added to the store # @return [nil] - describe 'update_pet test' do + describe 'add_pet test' do it "should work" do # assertion here # should be_a() @@ -52,13 +52,30 @@ describe 'PetApi' do end end - # unit tests for add_pet - # Add a new pet to the store + # unit tests for add_pet_using_byte_array + # Fake endpoint to test byte array in body parameter for adding a new pet to the store # # @param [Hash] opts the optional parameters - # @option opts [Pet] :body Pet object that needs to be added to the store + # @option opts [String] :body Pet object in the form of byte array # @return [nil] - describe 'add_pet test' do + describe 'add_pet_using_byte_array test' do + it "should work" do + # assertion here + # should be_a() + # should be_nil + # should == + # should_not == + end + end + + # unit tests for delete_pet + # Deletes a pet + # + # @param pet_id Pet id to delete + # @param [Hash] opts the optional parameters + # @option opts [String] :api_key + # @return [nil] + describe 'delete_pet test' do it "should work" do # assertion here # should be_a() @@ -116,59 +133,6 @@ describe 'PetApi' do end end - # unit tests for update_pet_with_form - # Updates a pet in the store with form data - # - # @param pet_id ID of pet that needs to be updated - # @param [Hash] opts the optional parameters - # @option opts [String] :name Updated name of the pet - # @option opts [String] :status Updated status of the pet - # @return [nil] - describe 'update_pet_with_form test' do - it "should work" do - # assertion here - # should be_a() - # should be_nil - # should == - # should_not == - end - end - - # unit tests for delete_pet - # Deletes a pet - # - # @param pet_id Pet id to delete - # @param [Hash] opts the optional parameters - # @option opts [String] :api_key - # @return [nil] - describe 'delete_pet test' do - it "should work" do - # assertion here - # should be_a() - # should be_nil - # should == - # should_not == - end - end - - # unit tests for upload_file - # uploads an image - # - # @param pet_id ID of pet to update - # @param [Hash] opts the optional parameters - # @option opts [String] :additional_metadata Additional data to pass to server - # @option opts [File] :file file to upload - # @return [nil] - describe 'upload_file test' do - it "should work" do - # assertion here - # should be_a() - # should be_nil - # should == - # should_not == - end - end - # unit tests for get_pet_by_id_in_object # Fake endpoint to test inline arbitrary object return by 'Find pet by ID' # Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions @@ -201,13 +165,49 @@ describe 'PetApi' do end end - # unit tests for add_pet_using_byte_array - # Fake endpoint to test byte array in body parameter for adding a new pet to the store + # unit tests for update_pet + # Update an existing pet # # @param [Hash] opts the optional parameters - # @option opts [String] :body Pet object in the form of byte array + # @option opts [Pet] :body Pet object that needs to be added to the store # @return [nil] - describe 'add_pet_using_byte_array test' do + describe 'update_pet test' do + it "should work" do + # assertion here + # should be_a() + # should be_nil + # should == + # should_not == + end + end + + # unit tests for update_pet_with_form + # Updates a pet in the store with form data + # + # @param pet_id ID of pet that needs to be updated + # @param [Hash] opts the optional parameters + # @option opts [String] :name Updated name of the pet + # @option opts [String] :status Updated status of the pet + # @return [nil] + describe 'update_pet_with_form test' do + it "should work" do + # assertion here + # should be_a() + # should be_nil + # should == + # should_not == + end + end + + # unit tests for upload_file + # uploads an image + # + # @param pet_id ID of pet to update + # @param [Hash] opts the optional parameters + # @option opts [String] :additional_metadata Additional data to pass to server + # @option opts [File] :file file to upload + # @return [nil] + describe 'upload_file test' do it "should work" do # assertion here # should be_a() diff --git a/samples/client/petstore/ruby/spec/api/store_api_spec.rb b/samples/client/petstore/ruby/spec/api/store_api_spec.rb index bd388e1a32b..0952b075bf4 100644 --- a/samples/client/petstore/ruby/spec/api/store_api_spec.rb +++ b/samples/client/petstore/ruby/spec/api/store_api_spec.rb @@ -36,6 +36,22 @@ describe 'StoreApi' do end end + # unit tests for delete_order + # Delete purchase order by ID + # For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + # @param order_id ID of the order that needs to be deleted + # @param [Hash] opts the optional parameters + # @return [nil] + describe 'delete_order test' do + it "should work" do + # assertion here + # should be_a() + # should be_nil + # should == + # should_not == + end + end + # unit tests for find_orders_by_status # Finds orders by status # A single status value can be provided as a string @@ -82,6 +98,22 @@ describe 'StoreApi' do end end + # unit tests for get_order_by_id + # Find purchase order by ID + # For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + # @param order_id ID of pet that needs to be fetched + # @param [Hash] opts the optional parameters + # @return [Order] + describe 'get_order_by_id test' do + it "should work" do + # assertion here + # should be_a() + # should be_nil + # should == + # should_not == + end + end + # unit tests for place_order # Place an order for a pet # @@ -98,36 +130,4 @@ describe 'StoreApi' do end end - # unit tests for get_order_by_id - # Find purchase order by ID - # For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - # @param order_id ID of pet that needs to be fetched - # @param [Hash] opts the optional parameters - # @return [Order] - describe 'get_order_by_id test' do - it "should work" do - # assertion here - # should be_a() - # should be_nil - # should == - # should_not == - end - end - - # unit tests for delete_order - # Delete purchase order by ID - # For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors - # @param order_id ID of the order that needs to be deleted - # @param [Hash] opts the optional parameters - # @return [nil] - describe 'delete_order test' do - it "should work" do - # assertion here - # should be_a() - # should be_nil - # should == - # should_not == - end - end - end diff --git a/samples/client/petstore/ruby/spec/api/user_api_spec.rb b/samples/client/petstore/ruby/spec/api/user_api_spec.rb index 894a62f6cc0..60f1dcda16f 100644 --- a/samples/client/petstore/ruby/spec/api/user_api_spec.rb +++ b/samples/client/petstore/ruby/spec/api/user_api_spec.rb @@ -84,6 +84,38 @@ describe 'UserApi' do end end + # unit tests for delete_user + # Delete user + # This can only be done by the logged in user. + # @param username The name that needs to be deleted + # @param [Hash] opts the optional parameters + # @return [nil] + describe 'delete_user test' do + it "should work" do + # assertion here + # should be_a() + # should be_nil + # should == + # should_not == + end + end + + # unit tests for get_user_by_name + # Get user by user name + # + # @param username The name that needs to be fetched. Use user1 for testing. + # @param [Hash] opts the optional parameters + # @return [User] + describe 'get_user_by_name test' do + it "should work" do + # assertion here + # should be_a() + # should be_nil + # should == + # should_not == + end + end + # unit tests for login_user # Logs user into the system # @@ -116,22 +148,6 @@ describe 'UserApi' do end end - # unit tests for get_user_by_name - # Get user by user name - # - # @param username The name that needs to be fetched. Use user1 for testing. - # @param [Hash] opts the optional parameters - # @return [User] - describe 'get_user_by_name test' do - it "should work" do - # assertion here - # should be_a() - # should be_nil - # should == - # should_not == - end - end - # unit tests for update_user # Updated user # This can only be done by the logged in user. @@ -149,20 +165,4 @@ describe 'UserApi' do end end - # unit tests for delete_user - # Delete user - # This can only be done by the logged in user. - # @param username The name that needs to be deleted - # @param [Hash] opts the optional parameters - # @return [nil] - describe 'delete_user test' do - it "should work" do - # assertion here - # should be_a() - # should be_nil - # should == - # should_not == - end - end - end diff --git a/samples/client/petstore/ruby/spec/models/animal_spec.rb b/samples/client/petstore/ruby/spec/models/animal_spec.rb new file mode 100644 index 00000000000..ddbfeca85f9 --- /dev/null +++ b/samples/client/petstore/ruby/spec/models/animal_spec.rb @@ -0,0 +1,50 @@ +=begin +Swagger Petstore + +This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io 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 +Generated by: https://github.com/swagger-api/swagger-codegen.git + +License: Apache 2.0 +http://www.apache.org/licenses/LICENSE-2.0.html + +Terms of Service: http://swagger.io/terms/ + +=end + +require 'spec_helper' +require 'json' +require 'date' + +# Unit tests for Petstore::Animal +# Automatically generated by swagger-codegen (github.com/swagger-api/swagger-codegen) +# Please update as you see appropriate +describe 'Animal' do + before do + # run before each test + @instance = Petstore::Animal.new + end + + after do + # run after each test + end + + describe 'test an instance of Animal' do + it 'should create an instact of Animal' do + @instance.should be_a(Petstore::Animal) + end + end + describe 'test attribute "class_name"' do + it 'should work' do + # assertion here + # should be_a() + # should be_nil + # should == + # should_not == + end + end + +end + diff --git a/samples/client/petstore/ruby/spec/models/cat_spec.rb b/samples/client/petstore/ruby/spec/models/cat_spec.rb new file mode 100644 index 00000000000..220a37dfebe --- /dev/null +++ b/samples/client/petstore/ruby/spec/models/cat_spec.rb @@ -0,0 +1,60 @@ +=begin +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@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +License: Apache 2.0 +http://www.apache.org/licenses/LICENSE-2.0.html + +Terms of Service: http://swagger.io/terms/ + +=end + +require 'spec_helper' +require 'json' +require 'date' + +# Unit tests for Petstore::Cat +# Automatically generated by swagger-codegen (github.com/swagger-api/swagger-codegen) +# Please update as you see appropriate +describe 'Cat' do + before do + # run before each test + @instance = Petstore::Cat.new + end + + after do + # run after each test + end + + describe 'test an instance of Cat' do + it 'should create an instact of Cat' do + @instance.should be_a(Petstore::Cat) + end + end + describe 'test attribute "class_name"' do + it 'should work' do + # assertion here + # should be_a() + # should be_nil + # should == + # should_not == + end + end + + describe 'test attribute "declawed"' do + it 'should work' do + # assertion here + # should be_a() + # should be_nil + # should == + # should_not == + end + end + +end + diff --git a/samples/client/petstore/ruby/spec/models/Category_spec.rb b/samples/client/petstore/ruby/spec/models/category_spec.rb similarity index 97% rename from samples/client/petstore/ruby/spec/models/Category_spec.rb rename to samples/client/petstore/ruby/spec/models/category_spec.rb index 5c99a87bf86..745974cbabd 100644 --- a/samples/client/petstore/ruby/spec/models/Category_spec.rb +++ b/samples/client/petstore/ruby/spec/models/category_spec.rb @@ -18,7 +18,7 @@ require 'spec_helper' require 'json' require 'date' -# Unit tests for Petstore:: +# Unit tests for Petstore::Category # Automatically generated by swagger-codegen (github.com/swagger-api/swagger-codegen) # Please update as you see appropriate describe 'Category' do diff --git a/samples/client/petstore/ruby/spec/models/dog_spec.rb b/samples/client/petstore/ruby/spec/models/dog_spec.rb new file mode 100644 index 00000000000..23b1b9a83f7 --- /dev/null +++ b/samples/client/petstore/ruby/spec/models/dog_spec.rb @@ -0,0 +1,60 @@ +=begin +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@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +License: Apache 2.0 +http://www.apache.org/licenses/LICENSE-2.0.html + +Terms of Service: http://swagger.io/terms/ + +=end + +require 'spec_helper' +require 'json' +require 'date' + +# Unit tests for Petstore::Dog +# Automatically generated by swagger-codegen (github.com/swagger-api/swagger-codegen) +# Please update as you see appropriate +describe 'Dog' do + before do + # run before each test + @instance = Petstore::Dog.new + end + + after do + # run after each test + end + + describe 'test an instance of Dog' do + it 'should create an instact of Dog' do + @instance.should be_a(Petstore::Dog) + end + end + describe 'test attribute "class_name"' do + it 'should work' do + # assertion here + # should be_a() + # should be_nil + # should == + # should_not == + end + end + + describe 'test attribute "breed"' do + it 'should work' do + # assertion here + # should be_a() + # should be_nil + # should == + # should_not == + end + end + +end + diff --git a/samples/client/petstore/ruby/spec/models/inline_response_200_spec.rb b/samples/client/petstore/ruby/spec/models/inline_response_200_spec.rb index 503b1a528ff..858b6504908 100644 --- a/samples/client/petstore/ruby/spec/models/inline_response_200_spec.rb +++ b/samples/client/petstore/ruby/spec/models/inline_response_200_spec.rb @@ -18,7 +18,7 @@ require 'spec_helper' require 'json' require 'date' -# Unit tests for Petstore:: +# Unit tests for Petstore::InlineResponse200 # Automatically generated by swagger-codegen (github.com/swagger-api/swagger-codegen) # Please update as you see appropriate describe 'InlineResponse200' do @@ -36,7 +36,7 @@ describe 'InlineResponse200' do @instance.should be_a(Petstore::InlineResponse200) end end - describe 'test attribute "name"' do + describe 'test attribute "tags"' do it 'should work' do # assertion here # should be_a() @@ -66,5 +66,35 @@ describe 'InlineResponse200' do end end + describe 'test attribute "status"' do + it 'should work' do + # assertion here + # should be_a() + # should be_nil + # should == + # should_not == + end + end + + describe 'test attribute "name"' do + it 'should work' do + # assertion here + # should be_a() + # should be_nil + # should == + # should_not == + end + end + + describe 'test attribute "photo_urls"' do + it 'should work' do + # assertion here + # should be_a() + # should be_nil + # should == + # should_not == + end + end + end diff --git a/samples/client/petstore/ruby/spec/models/model_200_response_spec.rb b/samples/client/petstore/ruby/spec/models/model_200_response_spec.rb new file mode 100644 index 00000000000..4e2f92c5212 --- /dev/null +++ b/samples/client/petstore/ruby/spec/models/model_200_response_spec.rb @@ -0,0 +1,50 @@ +=begin +Swagger Petstore + +This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io 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 +Generated by: https://github.com/swagger-api/swagger-codegen.git + +License: Apache 2.0 +http://www.apache.org/licenses/LICENSE-2.0.html + +Terms of Service: http://swagger.io/terms/ + +=end + +require 'spec_helper' +require 'json' +require 'date' + +# Unit tests for Petstore::Model200Response +# Automatically generated by swagger-codegen (github.com/swagger-api/swagger-codegen) +# Please update as you see appropriate +describe 'Model200Response' do + before do + # run before each test + @instance = Petstore::Model200Response.new + end + + after do + # run after each test + end + + describe 'test an instance of Model200Response' do + it 'should create an instact of Model200Response' do + @instance.should be_a(Petstore::Model200Response) + end + end + describe 'test attribute "name"' do + it 'should work' do + # assertion here + # should be_a() + # should be_nil + # should == + # should_not == + end + end + +end + diff --git a/samples/client/petstore/ruby/spec/models/object_return_spec.rb b/samples/client/petstore/ruby/spec/models/model_return_spec.rb similarity index 79% rename from samples/client/petstore/ruby/spec/models/object_return_spec.rb rename to samples/client/petstore/ruby/spec/models/model_return_spec.rb index c63169bd410..018798b47e3 100644 --- a/samples/client/petstore/ruby/spec/models/object_return_spec.rb +++ b/samples/client/petstore/ruby/spec/models/model_return_spec.rb @@ -18,22 +18,22 @@ require 'spec_helper' require 'json' require 'date' -# Unit tests for Petstore:: +# Unit tests for Petstore::ModelReturn # Automatically generated by swagger-codegen (github.com/swagger-api/swagger-codegen) # Please update as you see appropriate -describe 'ObjectReturn' do +describe 'ModelReturn' do before do # run before each test - @instance = Petstore::ObjectReturn.new + @instance = Petstore::ModelReturn.new end after do # run after each test end - describe 'test an instance of ObjectReturn' do - it 'should create an instact of ObjectReturn' do - @instance.should be_a(Petstore::ObjectReturn) + describe 'test an instance of ModelReturn' do + it 'should create an instact of ModelReturn' do + @instance.should be_a(Petstore::ModelReturn) end end describe 'test attribute "_return"' do diff --git a/samples/client/petstore/ruby/spec/models/name_spec.rb b/samples/client/petstore/ruby/spec/models/name_spec.rb new file mode 100644 index 00000000000..5d66fd078f3 --- /dev/null +++ b/samples/client/petstore/ruby/spec/models/name_spec.rb @@ -0,0 +1,60 @@ +=begin +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@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +License: Apache 2.0 +http://www.apache.org/licenses/LICENSE-2.0.html + +Terms of Service: http://swagger.io/terms/ + +=end + +require 'spec_helper' +require 'json' +require 'date' + +# Unit tests for Petstore::Name +# Automatically generated by swagger-codegen (github.com/swagger-api/swagger-codegen) +# Please update as you see appropriate +describe 'Name' do + before do + # run before each test + @instance = Petstore::Name.new + end + + after do + # run after each test + end + + describe 'test an instance of Name' do + it 'should create an instact of Name' do + @instance.should be_a(Petstore::Name) + end + end + describe 'test attribute "name"' do + it 'should work' do + # assertion here + # should be_a() + # should be_nil + # should == + # should_not == + end + end + + describe 'test attribute "snake_case"' do + it 'should work' do + # assertion here + # should be_a() + # should be_nil + # should == + # should_not == + end + end + +end + diff --git a/samples/client/petstore/ruby/spec/models/Order_spec.rb b/samples/client/petstore/ruby/spec/models/order_spec.rb similarity index 98% rename from samples/client/petstore/ruby/spec/models/Order_spec.rb rename to samples/client/petstore/ruby/spec/models/order_spec.rb index a78677410ef..698f3af9268 100644 --- a/samples/client/petstore/ruby/spec/models/Order_spec.rb +++ b/samples/client/petstore/ruby/spec/models/order_spec.rb @@ -18,7 +18,7 @@ require 'spec_helper' require 'json' require 'date' -# Unit tests for Petstore:: +# Unit tests for Petstore::Order # Automatically generated by swagger-codegen (github.com/swagger-api/swagger-codegen) # Please update as you see appropriate describe 'Order' do diff --git a/samples/client/petstore/ruby/spec/models/Pet_spec.rb b/samples/client/petstore/ruby/spec/models/pet_spec.rb similarity index 98% rename from samples/client/petstore/ruby/spec/models/Pet_spec.rb rename to samples/client/petstore/ruby/spec/models/pet_spec.rb index f78259b5910..cf18e1a5f3a 100644 --- a/samples/client/petstore/ruby/spec/models/Pet_spec.rb +++ b/samples/client/petstore/ruby/spec/models/pet_spec.rb @@ -18,7 +18,7 @@ require 'spec_helper' require 'json' require 'date' -# Unit tests for Petstore:: +# Unit tests for Petstore::Pet # Automatically generated by swagger-codegen (github.com/swagger-api/swagger-codegen) # Please update as you see appropriate describe 'Pet' do diff --git a/samples/client/petstore/ruby/spec/models/special_model_name_spec.rb b/samples/client/petstore/ruby/spec/models/special_model_name_spec.rb index c42e6229085..e3201cb2e31 100644 --- a/samples/client/petstore/ruby/spec/models/special_model_name_spec.rb +++ b/samples/client/petstore/ruby/spec/models/special_model_name_spec.rb @@ -18,7 +18,7 @@ require 'spec_helper' require 'json' require 'date' -# Unit tests for Petstore:: +# Unit tests for Petstore::SpecialModelName # Automatically generated by swagger-codegen (github.com/swagger-api/swagger-codegen) # Please update as you see appropriate describe 'SpecialModelName' do diff --git a/samples/client/petstore/ruby/spec/models/Tag_spec.rb b/samples/client/petstore/ruby/spec/models/tag_spec.rb similarity index 97% rename from samples/client/petstore/ruby/spec/models/Tag_spec.rb rename to samples/client/petstore/ruby/spec/models/tag_spec.rb index e13c9169b8f..4b3ff7ac611 100644 --- a/samples/client/petstore/ruby/spec/models/Tag_spec.rb +++ b/samples/client/petstore/ruby/spec/models/tag_spec.rb @@ -18,7 +18,7 @@ require 'spec_helper' require 'json' require 'date' -# Unit tests for Petstore:: +# Unit tests for Petstore::Tag # Automatically generated by swagger-codegen (github.com/swagger-api/swagger-codegen) # Please update as you see appropriate describe 'Tag' do diff --git a/samples/client/petstore/ruby/spec/models/User_spec.rb b/samples/client/petstore/ruby/spec/models/user_spec.rb similarity index 98% rename from samples/client/petstore/ruby/spec/models/User_spec.rb rename to samples/client/petstore/ruby/spec/models/user_spec.rb index 1d02e14e03a..2c289705417 100644 --- a/samples/client/petstore/ruby/spec/models/User_spec.rb +++ b/samples/client/petstore/ruby/spec/models/user_spec.rb @@ -18,7 +18,7 @@ require 'spec_helper' require 'json' require 'date' -# Unit tests for Petstore:: +# Unit tests for Petstore::User # Automatically generated by swagger-codegen (github.com/swagger-api/swagger-codegen) # Please update as you see appropriate describe 'User' do diff --git a/samples/client/petstore/scala/.gitignore b/samples/client/petstore/scala/.gitignore new file mode 100644 index 00000000000..c58d83b3189 --- /dev/null +++ b/samples/client/petstore/scala/.gitignore @@ -0,0 +1,17 @@ +*.class +*.log + +# sbt specific +.cache +.history +.lib/ +dist/* +target/ +lib_managed/ +src_managed/ +project/boot/ +project/plugins/project/ + +# Scala-IDE specific +.scala_dependencies +.worksheet diff --git a/samples/client/petstore/scala/git_push.sh b/samples/client/petstore/scala/git_push.sh new file mode 100644 index 00000000000..1a36388db02 --- /dev/null +++ b/samples/client/petstore/scala/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="YOUR_GIT_USR_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="YOUR_GIT_REPO_ID" + 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/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 a11cab9211b..c52f7159e4c 100644 --- a/samples/client/petstore/scala/src/main/scala/io/swagger/client/api/PetApi.scala +++ b/samples/client/petstore/scala/src/main/scala/io/swagger/client/api/PetApi.scala @@ -1,6 +1,7 @@ package io.swagger.client.api import io.swagger.client.model.Pet +import io.swagger.client.model.InlineResponse200 import java.io.File import io.swagger.client.ApiInvoker import io.swagger.client.ApiException @@ -23,57 +24,10 @@ class PetApi(val defBasePath: String = "http://petstore.swagger.io/v2", def addHeader(key: String, value: String) = apiInvoker.defaultHeaders += key -> value - /** - * Update an existing pet - * - * @param body Pet object that needs to be added to the store - * @return void - */ - 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 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 = body - - if(contentType.startsWith("multipart/form-data")) { - val mp = new FormDataMultiPart() - - postBody = mp - } - else { - - } - - 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 - } - } - /** * Add a new pet to the store * - * @param body Pet object that needs to be added to the store + * @param body Pet object that needs to be added to the store (optional) * @return void */ def addPet (body: Pet) = { @@ -117,10 +71,108 @@ class PetApi(val defBasePath: String = "http://petstore.swagger.io/v2", } } + /** + * Fake endpoint to test byte array in body parameter for adding a new pet to the store + * + * @param body Pet object in the form of byte array (optional) + * @return void + */ + def addPetUsingByteArray (body: String) = { + // create path and map variables + val path = "/pet?testing_byte_array=true".replaceAll("\\{format\\}","json") + + val contentTypes = List("application/json", "application/xml", "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 = body + + if(contentType.startsWith("multipart/form-data")) { + val mp = new FormDataMultiPart() + + postBody = mp + } + else { + + } + + try { + apiInvoker.invokeApi(basePath, path, "POST", 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 + } + } + + /** + * Deletes a pet + * + * @param petId Pet id to delete + * @param apiKey (optional) + * @return void + */ + def deletePet (petId: Long, apiKey: String) = { + // create path and map variables + 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 + + + var postBody: AnyRef = null + + if(contentType.startsWith("multipart/form-data")) { + val mp = new FormDataMultiPart() + + postBody = mp + } + else { + + } + + try { + apiInvoker.invokeApi(basePath, path, "DELETE", 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 + } + } + /** * Finds Pets by status - * Multiple status values can be provided with comma seperated strings - * @param status Status values that need to be considered for filter + * Multiple status values can be provided with comma separated strings + * @param status Status values that need to be considered for query (optional, default to available) * @return List[Pet] */ def findPetsByStatus (status: List[String] /* = available */) : Option[List[Pet]] = { @@ -169,7 +221,7 @@ class PetApi(val defBasePath: String = "http://petstore.swagger.io/v2", /** * Finds Pets by tags * Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. - * @param tags Tags to filter by + * @param tags Tags to filter by (optional) * @return List[Pet] */ def findPetsByTags (tags: List[String]) : Option[List[Pet]] = { @@ -218,7 +270,7 @@ class PetApi(val defBasePath: String = "http://petstore.swagger.io/v2", /** * Find pet by ID * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions - * @param petId ID of pet that needs to be fetched + * @param petId ID of pet that needs to be fetched * @return Pet */ def getPetById (petId: Long) : Option[Pet] = { @@ -265,12 +317,159 @@ class PetApi(val defBasePath: String = "http://petstore.swagger.io/v2", } } + /** + * Fake endpoint to test inline arbitrary object return by 'Find pet by ID' + * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + * @param petId ID of pet that needs to be fetched + * @return InlineResponse200 + */ + def getPetByIdInObject (petId: Long) : Option[InlineResponse200] = { + // create path and map variables + val path = "/pet/{petId}?response=inline_arbitrary_object".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() + + postBody = mp + } + else { + + } + + try { + apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, formParams.toMap, postBody, headerParams.toMap, contentType) match { + case s: String => + Some(ApiInvoker.deserialize(s, "", classOf[InlineResponse200]).asInstanceOf[InlineResponse200]) + + case _ => None + } + } catch { + case ex: ApiException if ex.code == 404 => None + case ex: ApiException => throw ex + } + } + + /** + * Fake endpoint to test byte array return by 'Find pet by ID' + * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + * @param petId ID of pet that needs to be fetched + * @return String + */ + def petPetIdtestingByteArraytrueGet (petId: Long) : Option[String] = { + // create path and map variables + val path = "/pet/{petId}?testing_byte_array=true".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() + + postBody = mp + } + else { + + } + + try { + apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, formParams.toMap, postBody, headerParams.toMap, contentType) match { + case s: String => + Some(ApiInvoker.deserialize(s, "", classOf[String]).asInstanceOf[String]) + + case _ => None + } + } catch { + case ex: ApiException if ex.code == 404 => None + case ex: ApiException => throw ex + } + } + + /** + * Update an existing pet + * + * @param body Pet object that needs to be added to the store (optional) + * @return void + */ + 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 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 = body + + if(contentType.startsWith("multipart/form-data")) { + val mp = new FormDataMultiPart() + + postBody = mp + } + else { + + } + + 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 + } + } + /** * Updates a pet in the store with form data * - * @param petId ID of pet that needs to be updated - * @param name Updated name of the pet - * @param status Updated status of the pet + * @param petId ID of pet that needs to be updated + * @param name Updated name of the pet (optional) + * @param status Updated status of the pet (optional) * @return void */ def updatePetWithForm (petId: String, name: String, status: String) = { @@ -322,63 +521,12 @@ class PetApi(val defBasePath: String = "http://petstore.swagger.io/v2", } } - /** - * Deletes a pet - * - * @param petId Pet id to delete - * @param apiKey - * @return void - */ - def deletePet (petId: Long, apiKey: String) = { - // create path and map variables - 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 - - - var postBody: AnyRef = null - - if(contentType.startsWith("multipart/form-data")) { - val mp = new FormDataMultiPart() - - postBody = mp - } - else { - - } - - try { - apiInvoker.invokeApi(basePath, path, "DELETE", 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 - } - } - /** * uploads an image * - * @param petId ID of pet to update - * @param additionalMetadata Additional data to pass to server - * @param file file to upload + * @param petId ID of pet to update + * @param additionalMetadata Additional data to pass to server (optional) + * @param file file to upload (optional) * @return void */ def uploadFile (petId: Long, additionalMetadata: String, file: File) = { 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 9b3cc91d788..388c612976f 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 @@ -22,6 +22,104 @@ class StoreApi(val defBasePath: String = "http://petstore.swagger.io/v2", def addHeader(key: String, value: String) = apiInvoker.defaultHeaders += 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 + * @param orderId ID of the order that needs to be deleted + * @return void + */ + def deleteOrder (orderId: String) = { + // create path and map variables + 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() + + postBody = mp + } + else { + + } + + try { + apiInvoker.invokeApi(basePath, path, "DELETE", 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 + } + } + + /** + * Finds orders by status + * A single status value can be provided as a string + * @param status Status value that needs to be considered for query (optional, default to placed) + * @return List[Order] + */ + def findOrdersByStatus (status: String /* = placed */) : Option[List[Order]] = { + // create path and map variables + val path = "/store/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(String.valueOf(status) != "null") queryParams += "status" -> status.toString + + + + + var postBody: AnyRef = null + + if(contentType.startsWith("multipart/form-data")) { + val mp = new FormDataMultiPart() + + postBody = mp + } + else { + + } + + try { + apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, formParams.toMap, postBody, headerParams.toMap, contentType) match { + case s: String => + Some(ApiInvoker.deserialize(s, "array", classOf[Order]).asInstanceOf[List[Order]]) + + case _ => None + } + } catch { + case ex: ApiException if ex.code == 404 => None + case ex: ApiException => throw ex + } + } + /** * Returns pet inventories by status * Returns a map of status codes to quantities @@ -70,14 +168,13 @@ class StoreApi(val defBasePath: String = "http://petstore.swagger.io/v2", } /** - * Place an order for a pet - * - * @param body order placed for purchasing the pet - * @return Order + * Fake endpoint to test arbitrary object return by 'Get inventory' + * Returns an arbitrary object which is actually a map of status codes to quantities + * @return Any */ - def placeOrder (body: Order) : Option[Order] = { + def getInventoryInObject () : Option[Any] = { // create path and map variables - val path = "/store/order".replaceAll("\\{format\\}","json") + val path = "/store/inventory?response=arbitrary_object".replaceAll("\\{format\\}","json") val contentTypes = List("application/json") val contentType = contentTypes(0) @@ -93,7 +190,7 @@ class StoreApi(val defBasePath: String = "http://petstore.swagger.io/v2", - var postBody: AnyRef = body + var postBody: AnyRef = null if(contentType.startsWith("multipart/form-data")) { val mp = new FormDataMultiPart() @@ -105,9 +202,9 @@ class StoreApi(val defBasePath: String = "http://petstore.swagger.io/v2", } try { - apiInvoker.invokeApi(basePath, path, "POST", queryParams.toMap, formParams.toMap, postBody, headerParams.toMap, contentType) match { + apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, formParams.toMap, postBody, headerParams.toMap, contentType) match { case s: String => - Some(ApiInvoker.deserialize(s, "", classOf[Order]).asInstanceOf[Order]) + Some(ApiInvoker.deserialize(s, "", classOf[Any]).asInstanceOf[Any]) case _ => None } @@ -120,7 +217,7 @@ class StoreApi(val defBasePath: String = "http://petstore.swagger.io/v2", /** * 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 + * @param orderId ID of pet that needs to be fetched * @return Order */ def getOrderById (orderId: String) : Option[Order] = { @@ -168,16 +265,14 @@ class StoreApi(val defBasePath: String = "http://petstore.swagger.io/v2", } /** - * Delete purchase order by ID - * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors - * @param orderId ID of the order that needs to be deleted - * @return void + * Place an order for a pet + * + * @param body order placed for purchasing the pet (optional) + * @return Order */ - def deleteOrder (orderId: String) = { + def placeOrder (body: Order) : Option[Order] = { // create path and map variables - val path = "/store/order/{orderId}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "orderId" + "\\}",apiInvoker.escape(orderId)) - - + val path = "/store/order".replaceAll("\\{format\\}","json") val contentTypes = List("application/json") val contentType = contentTypes(0) @@ -193,7 +288,7 @@ class StoreApi(val defBasePath: String = "http://petstore.swagger.io/v2", - var postBody: AnyRef = null + var postBody: AnyRef = body if(contentType.startsWith("multipart/form-data")) { val mp = new FormDataMultiPart() @@ -205,9 +300,10 @@ class StoreApi(val defBasePath: String = "http://petstore.swagger.io/v2", } try { - apiInvoker.invokeApi(basePath, path, "DELETE", queryParams.toMap, formParams.toMap, postBody, headerParams.toMap, contentType) match { + apiInvoker.invokeApi(basePath, path, "POST", queryParams.toMap, formParams.toMap, postBody, headerParams.toMap, contentType) match { case s: String => - + Some(ApiInvoker.deserialize(s, "", classOf[Order]).asInstanceOf[Order]) + case _ => None } } catch { 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 802cf01c25b..e68922f3cce 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 @@ -25,7 +25,7 @@ class UserApi(val defBasePath: String = "http://petstore.swagger.io/v2", /** * Create user * This can only be done by the logged in user. - * @param body Created user object + * @param body Created user object (optional) * @return void */ def createUser (body: User) = { @@ -72,7 +72,7 @@ class UserApi(val defBasePath: String = "http://petstore.swagger.io/v2", /** * Creates list of users with given input array * - * @param body List of user object + * @param body List of user object (optional) * @return void */ def createUsersWithArrayInput (body: List[User]) = { @@ -119,7 +119,7 @@ class UserApi(val defBasePath: String = "http://petstore.swagger.io/v2", /** * Creates list of users with given input array * - * @param body List of user object + * @param body List of user object (optional) * @return void */ def createUsersWithListInput (body: List[User]) = { @@ -163,11 +163,110 @@ class UserApi(val defBasePath: String = "http://petstore.swagger.io/v2", } } + /** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted + * @return void + */ + def deleteUser (username: String) = { + // create path and map variables + 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] + + + + + + + + var postBody: AnyRef = null + + if(contentType.startsWith("multipart/form-data")) { + val mp = new FormDataMultiPart() + + postBody = mp + } + else { + + } + + try { + apiInvoker.invokeApi(basePath, path, "DELETE", 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 + } + } + + /** + * Get user by user name + * + * @param username The name that needs to be fetched. Use user1 for testing. + * @return 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 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() + + postBody = mp + } + else { + + } + + try { + apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, formParams.toMap, postBody, headerParams.toMap, contentType) match { + case s: String => + Some(ApiInvoker.deserialize(s, "", classOf[User]).asInstanceOf[User]) + + case _ => None + } + } catch { + case ex: ApiException if ex.code == 404 => None + case ex: ApiException => throw ex + } + } + /** * Logs user into the system * - * @param username The user name for login - * @param password The password for login in clear text + * @param username The user name for login (optional) + * @param password The password for login in clear text (optional) * @return String */ def loginUser (username: String, password: String) : Option[String] = { @@ -260,61 +359,11 @@ class UserApi(val defBasePath: String = "http://petstore.swagger.io/v2", } } - /** - * Get user by user name - * - * @param username The name that needs to be fetched. Use user1 for testing. - * @return 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 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() - - postBody = mp - } - else { - - } - - try { - apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, formParams.toMap, postBody, headerParams.toMap, contentType) match { - case s: String => - Some(ApiInvoker.deserialize(s, "", classOf[User]).asInstanceOf[User]) - - case _ => None - } - } catch { - case ex: ApiException if ex.code == 404 => None - case ex: ApiException => throw ex - } - } - /** * Updated user * This can only be done by the logged in user. - * @param username name that need to be deleted - * @param body Updated user object + * @param username name that need to be deleted + * @param body Updated user object (optional) * @return void */ def updateUser (username: String, body: User) = { @@ -360,53 +409,4 @@ class UserApi(val defBasePath: String = "http://petstore.swagger.io/v2", } } - /** - * Delete user - * This can only be done by the logged in user. - * @param username The name that needs to be deleted - * @return void - */ - def deleteUser (username: String) = { - // create path and map variables - 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] - - - - - - - - var postBody: AnyRef = null - - if(contentType.startsWith("multipart/form-data")) { - val mp = new FormDataMultiPart() - - postBody = mp - } - else { - - } - - try { - apiInvoker.invokeApi(basePath, path, "DELETE", 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/scala/src/main/scala/io/swagger/client/model/InlineResponse200.scala b/samples/client/petstore/scala/src/main/scala/io/swagger/client/model/InlineResponse200.scala new file mode 100644 index 00000000000..e13f63eeefb --- /dev/null +++ b/samples/client/petstore/scala/src/main/scala/io/swagger/client/model/InlineResponse200.scala @@ -0,0 +1,14 @@ +package io.swagger.client.model + + + + +case class InlineResponse200 ( + tags: List[Tag], + id: Long, + category: Any, + /* pet status in the store */ + status: String, + name: String, + photoUrls: List[String]) + diff --git a/samples/client/petstore/scala/src/main/scala/io/swagger/client/model/Model200Response.scala b/samples/client/petstore/scala/src/main/scala/io/swagger/client/model/Model200Response.scala new file mode 100644 index 00000000000..68601a84e1a --- /dev/null +++ b/samples/client/petstore/scala/src/main/scala/io/swagger/client/model/Model200Response.scala @@ -0,0 +1,8 @@ +package io.swagger.client.model + + + + +case class Model200Response ( + name: Integer) + diff --git a/samples/client/petstore/scala/src/main/scala/io/swagger/client/model/ModelReturn.scala b/samples/client/petstore/scala/src/main/scala/io/swagger/client/model/ModelReturn.scala new file mode 100644 index 00000000000..e4ac8eb1ea7 --- /dev/null +++ b/samples/client/petstore/scala/src/main/scala/io/swagger/client/model/ModelReturn.scala @@ -0,0 +1,8 @@ +package io.swagger.client.model + + + + +case class ModelReturn ( + _return: Integer) + diff --git a/samples/client/petstore/scala/src/main/scala/io/swagger/client/model/Name.scala b/samples/client/petstore/scala/src/main/scala/io/swagger/client/model/Name.scala new file mode 100644 index 00000000000..854a11e6088 --- /dev/null +++ b/samples/client/petstore/scala/src/main/scala/io/swagger/client/model/Name.scala @@ -0,0 +1,8 @@ +package io.swagger.client.model + + + + +case class Name ( + name: Integer) + diff --git a/samples/client/petstore/scala/src/main/scala/io/swagger/client/model/SpecialModelName.scala b/samples/client/petstore/scala/src/main/scala/io/swagger/client/model/SpecialModelName.scala new file mode 100644 index 00000000000..2fee09a7f7c --- /dev/null +++ b/samples/client/petstore/scala/src/main/scala/io/swagger/client/model/SpecialModelName.scala @@ -0,0 +1,8 @@ +package io.swagger.client.model + + + + +case class SpecialModelName ( + specialPropertyName: Long) + diff --git a/samples/client/petstore/swift/.gitignore b/samples/client/petstore/swift/.gitignore new file mode 100644 index 00000000000..5e5d5cebcf4 --- /dev/null +++ b/samples/client/petstore/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/swift/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift index 0b3c5393aa6..a76f0352f52 100644 --- a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift +++ b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift @@ -11,68 +11,11 @@ import PromiseKit public class PetAPI: APIBase { - /** - - Update an existing pet - - - parameter body: (body) Pet object that needs to be added to the store - - parameter completion: completion handler to receive the data and the error objects - */ - public class func updatePet(body body: Pet?, 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 - - returns: Promise - */ - public class func updatePet(body body: Pet?) -> Promise { - let deferred = Promise.pendingPromise() - updatePet(body: body) { error in - if let error = error { - deferred.reject(error) - } else { - deferred.fulfill() - } - } - return deferred.promise - } - - /** - - Update an existing pet - - - PUT /pet - - - - OAuth: - - type: oauth2 - - name: petstore_auth - - - parameter body: (body) Pet object that needs to be added to the store - - - returns: RequestBuilder - */ - public class func updatePetWithRequestBuilder(body body: Pet?) -> RequestBuilder { - let path = "/pet" - let URLString = PetstoreClientAPI.basePath + path - - let parameters = body?.encodeToJSON() as? [String:AnyObject] - - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - - return requestBuilder.init(method: "PUT", URLString: URLString, parameters: parameters, isBody: true) - } - /** Add a new pet to the store - - parameter body: (body) Pet object that needs to be added 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?, completion: ((error: ErrorType?) -> Void)) { @@ -85,7 +28,7 @@ public class PetAPI: APIBase { Add a new pet to the store - - parameter body: (body) Pet object that needs to be added to the store + - parameter body: (body) Pet object that needs to be added to the store (optional) - returns: Promise */ public class func addPet(body body: Pet?) -> Promise { @@ -110,7 +53,7 @@ public class PetAPI: APIBase { - type: oauth2 - name: petstore_auth - - parameter body: (body) Pet object that needs to be added to the store + - parameter body: (body) Pet object that needs to be added to the store (optional) - returns: RequestBuilder */ @@ -125,670 +68,11 @@ public class PetAPI: APIBase { return requestBuilder.init(method: "POST", URLString: URLString, parameters: parameters, isBody: true) } - /** - - Finds Pets by status - - - parameter status: (query) Status values that need to be considered for query - - parameter completion: completion handler to receive the data and the error objects - */ - public class func findPetsByStatus(status status: [String]?, 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 query - - returns: Promise<[Pet]> - */ - public class func findPetsByStatus(status status: [String]?) -> Promise<[Pet]> { - let deferred = Promise<[Pet]>.pendingPromise() - findPetsByStatus(status: status) { data, error in - if let error = error { - deferred.reject(error) - } else { - deferred.fulfill(data!) - } - } - return deferred.promise - } - - /** - - Finds Pets by status - - - GET /pet/findByStatus - - Multiple status values can be provided with comma separated strings - - OAuth: - - type: oauth2 - - name: petstore_auth - - examples: [{example=[ { - "tags" : [ { - "id" : 123456789, - "name" : "aeiou" - } ], - "id" : 123456789, - "category" : { - "id" : 123456789, - "name" : "aeiou" - }, - "status" : "aeiou", - "name" : "doggie", - "photoUrls" : [ "aeiou" ] -} ], contentType=application/json}, {example= - 123456 - doggie - - string - - - - string -, contentType=application/xml}] - - examples: [{example=[ { - "tags" : [ { - "id" : 123456789, - "name" : "aeiou" - } ], - "id" : 123456789, - "category" : { - "id" : 123456789, - "name" : "aeiou" - }, - "status" : "aeiou", - "name" : "doggie", - "photoUrls" : [ "aeiou" ] -} ], contentType=application/json}, {example= - 123456 - doggie - - string - - - - string -, contentType=application/xml}] - - - parameter status: (query) Status values that need to be considered for query - - - returns: RequestBuilder<[Pet]> - */ - public class func findPetsByStatusWithRequestBuilder(status status: [String]?) -> RequestBuilder<[Pet]> { - let path = "/pet/findByStatus" - let URLString = PetstoreClientAPI.basePath + path - - let nillableParameters: [String:AnyObject?] = [ - "status": status - ] - let parameters = APIHelper.rejectNil(nillableParameters) - - let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - - return requestBuilder.init(method: "GET", URLString: URLString, parameters: parameters, isBody: false) - } - - /** - - Finds Pets by tags - - - parameter tags: (query) Tags to filter by - - parameter completion: completion handler to receive the data and the error objects - */ - public class func findPetsByTags(tags tags: [String]?, 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 - - returns: Promise<[Pet]> - */ - public class func findPetsByTags(tags tags: [String]?) -> Promise<[Pet]> { - let deferred = Promise<[Pet]>.pendingPromise() - findPetsByTags(tags: tags) { data, error in - if let error = error { - deferred.reject(error) - } else { - deferred.fulfill(data!) - } - } - return deferred.promise - } - - /** - - Finds Pets by tags - - - GET /pet/findByTags - - Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. - - OAuth: - - type: oauth2 - - name: petstore_auth - - examples: [{example=[ { - "tags" : [ { - "id" : 123456789, - "name" : "aeiou" - } ], - "id" : 123456789, - "category" : { - "id" : 123456789, - "name" : "aeiou" - }, - "status" : "aeiou", - "name" : "doggie", - "photoUrls" : [ "aeiou" ] -} ], contentType=application/json}, {example= - 123456 - doggie - - string - - - - string -, contentType=application/xml}] - - examples: [{example=[ { - "tags" : [ { - "id" : 123456789, - "name" : "aeiou" - } ], - "id" : 123456789, - "category" : { - "id" : 123456789, - "name" : "aeiou" - }, - "status" : "aeiou", - "name" : "doggie", - "photoUrls" : [ "aeiou" ] -} ], contentType=application/json}, {example= - 123456 - doggie - - string - - - - string -, contentType=application/xml}] - - - parameter tags: (query) Tags to filter by - - - returns: RequestBuilder<[Pet]> - */ - public class func findPetsByTagsWithRequestBuilder(tags tags: [String]?) -> RequestBuilder<[Pet]> { - let path = "/pet/findByTags" - let URLString = PetstoreClientAPI.basePath + path - - let nillableParameters: [String:AnyObject?] = [ - "tags": tags - ] - let parameters = APIHelper.rejectNil(nillableParameters) - - let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - - return requestBuilder.init(method: "GET", URLString: URLString, parameters: parameters, 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: Int, 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: Promise - */ - public class func getPetById(petId petId: Int) -> Promise { - let deferred = Promise.pendingPromise() - getPetById(petId: petId) { data, error in - if let error = error { - deferred.reject(error) - } else { - deferred.fulfill(data!) - } - } - return deferred.promise - } - - /** - - 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" - } ], - "id" : 123456789, - "category" : { - "id" : 123456789, - "name" : "aeiou" - }, - "status" : "aeiou", - "name" : "doggie", - "photoUrls" : [ "aeiou" ] -}, contentType=application/json}, {example= - 123456 - doggie - - string - - - - string -, contentType=application/xml}] - - examples: [{example={ - "tags" : [ { - "id" : 123456789, - "name" : "aeiou" - } ], - "id" : 123456789, - "category" : { - "id" : 123456789, - "name" : "aeiou" - }, - "status" : "aeiou", - "name" : "doggie", - "photoUrls" : [ "aeiou" ] -}, contentType=application/json}, {example= - 123456 - doggie - - string - - - - string -, contentType=application/xml}] - - - parameter petId: (path) ID of pet that needs to be fetched - - - returns: RequestBuilder - */ - public class func getPetByIdWithRequestBuilder(petId petId: Int) -> 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 requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - - return requestBuilder.init(method: "GET", URLString: URLString, parameters: parameters, isBody: true) - } - - /** - - Updates a pet in the store with form data - - - parameter petId: (path) ID of pet that needs to be updated - - parameter name: (form) Updated name of the pet - - parameter status: (form) Updated status of the pet - - parameter completion: completion handler to receive the data and the error objects - */ - public class func updatePetWithForm(petId petId: String, name: String?, status: String?, 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 - - parameter status: (form) Updated status of the pet - - returns: Promise - */ - public class func updatePetWithForm(petId petId: String, name: String?, status: String?) -> Promise { - let deferred = Promise.pendingPromise() - updatePetWithForm(petId: petId, name: name, status: status) { error in - if let error = error { - deferred.reject(error) - } else { - deferred.fulfill() - } - } - return deferred.promise - } - - /** - - 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 - - parameter status: (form) Updated status of the pet - - - returns: RequestBuilder - */ - public class func updatePetWithFormWithRequestBuilder(petId petId: String, name: String?, status: String?) -> 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 requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - - return requestBuilder.init(method: "POST", URLString: URLString, parameters: parameters, isBody: false) - } - - /** - - 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: Int, 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: Promise - */ - public class func deletePet(petId petId: Int) -> Promise { - let deferred = Promise.pendingPromise() - deletePet(petId: petId) { error in - if let error = error { - deferred.reject(error) - } else { - deferred.fulfill() - } - } - return deferred.promise - } - - /** - - 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: Int) -> 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 requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - - return requestBuilder.init(method: "DELETE", URLString: URLString, parameters: parameters, isBody: true) - } - - /** - - uploads an image - - - parameter petId: (path) ID of pet to update - - parameter additionalMetadata: (form) Additional data to pass to server - - parameter _file: (form) file to upload - - parameter completion: completion handler to receive the data and the error objects - */ - public class func uploadFile(petId petId: Int, additionalMetadata: String?, _file: NSURL?, 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 - - parameter _file: (form) file to upload - - returns: Promise - */ - public class func uploadFile(petId petId: Int, additionalMetadata: String?, _file: NSURL?) -> Promise { - let deferred = Promise.pendingPromise() - uploadFile(petId: petId, additionalMetadata: additionalMetadata, _file: _file) { error in - if let error = error { - deferred.reject(error) - } else { - deferred.fulfill() - } - } - return deferred.promise - } - - /** - - 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 - - parameter _file: (form) file to upload - - - returns: RequestBuilder - */ - public class func uploadFileWithRequestBuilder(petId petId: Int, additionalMetadata: String?, _file: NSURL?) -> 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 requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - - return requestBuilder.init(method: "POST", URLString: URLString, parameters: parameters, isBody: false) - } - - /** - - Fake endpoint to test inline arbitrary object return by '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 getPetByIdInObject(petId petId: Int, completion: ((data: InlineResponse200?, error: ErrorType?) -> Void)) { - getPetByIdInObjectWithRequestBuilder(petId: petId).execute { (response, error) -> Void in - completion(data: response?.body, error: error); - } - } - - /** - - Fake endpoint to test inline arbitrary object return by 'Find pet by ID' - - - parameter petId: (path) ID of pet that needs to be fetched - - returns: Promise - */ - public class func getPetByIdInObject(petId petId: Int) -> Promise { - let deferred = Promise.pendingPromise() - getPetByIdInObject(petId: petId) { data, error in - if let error = error { - deferred.reject(error) - } else { - deferred.fulfill(data!) - } - } - return deferred.promise - } - - /** - - Fake endpoint to test inline arbitrary object return by 'Find pet by ID' - - - GET /pet/{petId}?response=inline_arbitrary_object - - 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={ - "id" : 123456789, - "category" : "{}", - "name" : "doggie" -}, contentType=application/json}, {example= - 123456 - not implemented io.swagger.models.properties.ObjectProperty@37ff6855 - doggie -, contentType=application/xml}] - - examples: [{example={ - "id" : 123456789, - "category" : "{}", - "name" : "doggie" -}, contentType=application/json}, {example= - 123456 - not implemented io.swagger.models.properties.ObjectProperty@37ff6855 - doggie -, contentType=application/xml}] - - - parameter petId: (path) ID of pet that needs to be fetched - - - returns: RequestBuilder - */ - public class func getPetByIdInObjectWithRequestBuilder(petId petId: Int) -> RequestBuilder { - var path = "/pet/{petId}?response=inline_arbitrary_object" - 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 requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - - return requestBuilder.init(method: "GET", URLString: URLString, parameters: parameters, isBody: true) - } - - /** - - Fake endpoint to test byte array return by '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 petPetIdtestingByteArraytrueGet(petId petId: Int, completion: ((data: String?, error: ErrorType?) -> Void)) { - petPetIdtestingByteArraytrueGetWithRequestBuilder(petId: petId).execute { (response, error) -> Void in - completion(data: response?.body, error: error); - } - } - - /** - - Fake endpoint to test byte array return by 'Find pet by ID' - - - parameter petId: (path) ID of pet that needs to be fetched - - returns: Promise - */ - public class func petPetIdtestingByteArraytrueGet(petId petId: Int) -> Promise { - let deferred = Promise.pendingPromise() - petPetIdtestingByteArraytrueGet(petId: petId) { data, error in - if let error = error { - deferred.reject(error) - } else { - deferred.fulfill(data!) - } - } - return deferred.promise - } - - /** - - Fake endpoint to test byte array return by 'Find pet by ID' - - - GET /pet/{petId}?testing_byte_array=true - - 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="", contentType=application/json}, {example=not implemented io.swagger.models.properties.BinaryProperty@55e6ae9e, contentType=application/xml}] - - examples: [{example="", contentType=application/json}, {example=not implemented io.swagger.models.properties.BinaryProperty@55e6ae9e, contentType=application/xml}] - - - parameter petId: (path) ID of pet that needs to be fetched - - - returns: RequestBuilder - */ - public class func petPetIdtestingByteArraytrueGetWithRequestBuilder(petId petId: Int) -> RequestBuilder { - var path = "/pet/{petId}?testing_byte_array=true" - 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 requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - - return requestBuilder.init(method: "GET", URLString: URLString, parameters: parameters, isBody: true) - } - /** Fake endpoint to test byte array in body parameter for adding a new pet to the store - - parameter body: (body) Pet object in the form of byte array + - parameter body: (body) Pet object in the form of byte array (optional) - parameter completion: completion handler to receive the data and the error objects */ public class func addPetUsingByteArray(body body: String?, completion: ((error: ErrorType?) -> Void)) { @@ -801,7 +85,7 @@ public class PetAPI: APIBase { Fake endpoint to test byte array in body parameter for adding a new pet to the store - - parameter body: (body) Pet object in the form of byte array + - parameter body: (body) Pet object in the form of byte array (optional) - returns: Promise */ public class func addPetUsingByteArray(body body: String?) -> Promise { @@ -826,7 +110,7 @@ public class PetAPI: APIBase { - type: oauth2 - name: petstore_auth - - parameter body: (body) Pet object in the form of byte array + - parameter body: (body) Pet object in the form of byte array (optional) - returns: RequestBuilder */ @@ -841,4 +125,736 @@ public class PetAPI: APIBase { return requestBuilder.init(method: "POST", URLString: URLString, parameters: parameters, 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: Promise + */ + public class func deletePet(petId petId: Int64) -> Promise { + let deferred = Promise.pendingPromise() + deletePet(petId: petId) { error in + if let error = error { + deferred.reject(error) + } else { + deferred.fulfill() + } + } + return deferred.promise + } + + /** + + 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 requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "DELETE", URLString: URLString, parameters: parameters, isBody: true) + } + + /** + + Finds Pets by status + + - parameter status: (query) Status values that need to be considered for query (optional, default to available) + - parameter completion: completion handler to receive the data and the error objects + */ + public class func findPetsByStatus(status status: [String]?, 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 query (optional, default to available) + - returns: Promise<[Pet]> + */ + public class func findPetsByStatus(status status: [String]?) -> Promise<[Pet]> { + let deferred = Promise<[Pet]>.pendingPromise() + findPetsByStatus(status: status) { data, error in + if let error = error { + deferred.reject(error) + } else { + deferred.fulfill(data!) + } + } + return deferred.promise + } + + /** + + 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=[ { + "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 status: (query) Status values that need to be considered for query (optional, default to available) + + - returns: RequestBuilder<[Pet]> + */ + public class func findPetsByStatusWithRequestBuilder(status status: [String]?) -> RequestBuilder<[Pet]> { + let path = "/pet/findByStatus" + let URLString = PetstoreClientAPI.basePath + path + + let nillableParameters: [String:AnyObject?] = [ + "status": status + ] + let parameters = APIHelper.rejectNil(nillableParameters) + + let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "GET", URLString: URLString, parameters: parameters, 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]?, 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: Promise<[Pet]> + */ + public class func findPetsByTags(tags tags: [String]?) -> Promise<[Pet]> { + let deferred = Promise<[Pet]>.pendingPromise() + findPetsByTags(tags: tags) { data, error in + if let error = error { + deferred.reject(error) + } else { + deferred.fulfill(data!) + } + } + return deferred.promise + } + + /** + + Finds Pets by tags + + - GET /pet/findByTags + - Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + - OAuth: + - type: oauth2 + - name: petstore_auth + - examples: [{contentType=application/json, example=[ { + "photoUrls" : [ "aeiou" ], + "name" : "doggie", + "id" : 123456789, + "category" : { + "name" : "aeiou", + "id" : 123456789 + }, + "tags" : [ { + "name" : "aeiou", + "id" : 123456789 + } ], + "status" : "aeiou" +} ]}, {contentType=application/xml, example= + 123456 + doggie + + string + + + + string +}] + - examples: [{contentType=application/json, example=[ { + "photoUrls" : [ "aeiou" ], + "name" : "doggie", + "id" : 123456789, + "category" : { + "name" : "aeiou", + "id" : 123456789 + }, + "tags" : [ { + "name" : "aeiou", + "id" : 123456789 + } ], + "status" : "aeiou" +} ]}, {contentType=application/xml, example= + 123456 + doggie + + string + + + + string +}] + + - parameter tags: (query) Tags to filter by (optional) + + - returns: RequestBuilder<[Pet]> + */ + public class func findPetsByTagsWithRequestBuilder(tags tags: [String]?) -> RequestBuilder<[Pet]> { + let path = "/pet/findByTags" + let URLString = PetstoreClientAPI.basePath + path + + let nillableParameters: [String:AnyObject?] = [ + "tags": tags + ] + let parameters = APIHelper.rejectNil(nillableParameters) + + let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "GET", URLString: URLString, parameters: parameters, 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: Promise + */ + public class func getPetById(petId petId: Int64) -> Promise { + let deferred = Promise.pendingPromise() + getPetById(petId: petId) { data, error in + if let error = error { + deferred.reject(error) + } else { + deferred.fulfill(data!) + } + } + return deferred.promise + } + + /** + + 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 requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "GET", URLString: URLString, parameters: parameters, isBody: true) + } + + /** + + Fake endpoint to test inline arbitrary object return by '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 getPetByIdInObject(petId petId: Int64, completion: ((data: InlineResponse200?, error: ErrorType?) -> Void)) { + getPetByIdInObjectWithRequestBuilder(petId: petId).execute { (response, error) -> Void in + completion(data: response?.body, error: error); + } + } + + /** + + Fake endpoint to test inline arbitrary object return by 'Find pet by ID' + + - parameter petId: (path) ID of pet that needs to be fetched + - returns: Promise + */ + public class func getPetByIdInObject(petId petId: Int64) -> Promise { + let deferred = Promise.pendingPromise() + getPetByIdInObject(petId: petId) { data, error in + if let error = error { + deferred.reject(error) + } else { + deferred.fulfill(data!) + } + } + return deferred.promise + } + + /** + + Fake endpoint to test inline arbitrary object return by 'Find pet by ID' + + - GET /pet/{petId}?response=inline_arbitrary_object + - 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" : "{}", + "tags" : [ { + "name" : "aeiou", + "id" : 123456789 + } ], + "status" : "aeiou" +}}, {contentType=application/xml, example= + string + doggie + 123456 + not implemented io.swagger.models.properties.ObjectProperty@37ff6855 + string +}] + - examples: [{contentType=application/json, example={ + "photoUrls" : [ "aeiou" ], + "name" : "doggie", + "id" : 123456789, + "category" : "{}", + "tags" : [ { + "name" : "aeiou", + "id" : 123456789 + } ], + "status" : "aeiou" +}}, {contentType=application/xml, example= + string + doggie + 123456 + not implemented io.swagger.models.properties.ObjectProperty@37ff6855 + string +}] + + - parameter petId: (path) ID of pet that needs to be fetched + + - returns: RequestBuilder + */ + public class func getPetByIdInObjectWithRequestBuilder(petId petId: Int64) -> RequestBuilder { + var path = "/pet/{petId}?response=inline_arbitrary_object" + 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 requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "GET", URLString: URLString, parameters: parameters, isBody: true) + } + + /** + + Fake endpoint to test byte array return by '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 petPetIdtestingByteArraytrueGet(petId petId: Int64, completion: ((data: String?, error: ErrorType?) -> Void)) { + petPetIdtestingByteArraytrueGetWithRequestBuilder(petId: petId).execute { (response, error) -> Void in + completion(data: response?.body, error: error); + } + } + + /** + + Fake endpoint to test byte array return by 'Find pet by ID' + + - parameter petId: (path) ID of pet that needs to be fetched + - returns: Promise + */ + public class func petPetIdtestingByteArraytrueGet(petId petId: Int64) -> Promise { + let deferred = Promise.pendingPromise() + petPetIdtestingByteArraytrueGet(petId: petId) { data, error in + if let error = error { + deferred.reject(error) + } else { + deferred.fulfill(data!) + } + } + return deferred.promise + } + + /** + + Fake endpoint to test byte array return by 'Find pet by ID' + + - GET /pet/{petId}?testing_byte_array=true + - 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=""}, {contentType=application/xml, example=not implemented io.swagger.models.properties.BinaryProperty@55e6ae9e}] + - examples: [{contentType=application/json, example=""}, {contentType=application/xml, example=not implemented io.swagger.models.properties.BinaryProperty@55e6ae9e}] + + - parameter petId: (path) ID of pet that needs to be fetched + + - returns: RequestBuilder + */ + public class func petPetIdtestingByteArraytrueGetWithRequestBuilder(petId petId: Int64) -> RequestBuilder { + var path = "/pet/{petId}?testing_byte_array=true" + 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 requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "GET", URLString: URLString, parameters: parameters, 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?, 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: Promise + */ + public class func updatePet(body body: Pet?) -> Promise { + let deferred = Promise.pendingPromise() + updatePet(body: body) { error in + if let error = error { + deferred.reject(error) + } else { + deferred.fulfill() + } + } + return deferred.promise + } + + /** + + 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?) -> RequestBuilder { + let path = "/pet" + let URLString = PetstoreClientAPI.basePath + path + + let parameters = body?.encodeToJSON() as? [String:AnyObject] + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "PUT", URLString: URLString, parameters: parameters, isBody: true) + } + + /** + + Updates a pet in the store with form data + + - parameter petId: (path) ID of pet that needs to be updated + - parameter name: (form) Updated name of the pet (optional) + - parameter status: (form) Updated status of the pet (optional) + - parameter completion: completion handler to receive the data and the error objects + */ + public class func updatePetWithForm(petId petId: String, name: String?, status: String?, 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: Promise + */ + public class func updatePetWithForm(petId petId: String, name: String?, status: String?) -> Promise { + let deferred = Promise.pendingPromise() + updatePetWithForm(petId: petId, name: name, status: status) { error in + if let error = error { + deferred.reject(error) + } else { + deferred.fulfill() + } + } + return deferred.promise + } + + /** + + 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?, status: String?) -> 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 requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "POST", URLString: URLString, parameters: parameters, isBody: false) + } + + /** + + uploads an image + + - parameter petId: (path) ID of pet to update + - parameter additionalMetadata: (form) Additional data to pass to server (optional) + - parameter _file: (form) file to upload (optional) + - parameter completion: completion handler to receive the data and the error objects + */ + public class func uploadFile(petId petId: Int64, additionalMetadata: String?, _file: NSURL?, 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: Promise + */ + public class func uploadFile(petId petId: Int64, additionalMetadata: String?, _file: NSURL?) -> Promise { + let deferred = Promise.pendingPromise() + uploadFile(petId: petId, additionalMetadata: additionalMetadata, _file: _file) { error in + if let error = error { + deferred.reject(error) + } else { + deferred.fulfill() + } + } + return deferred.promise + } + + /** + + 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?, _file: NSURL?) -> 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 requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "POST", URLString: URLString, parameters: parameters, isBody: false) + } + } diff --git a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift index 2874b7c05ba..82d8ff179e5 100644 --- a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift +++ b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift @@ -11,11 +11,67 @@ import PromiseKit 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: Promise + */ + public class func deleteOrder(orderId orderId: String) -> Promise { + let deferred = Promise.pendingPromise() + deleteOrder(orderId: orderId) { error in + if let error = error { + deferred.reject(error) + } else { + deferred.fulfill() + } + } + return deferred.promise + } + + /** + + 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 requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "DELETE", URLString: URLString, parameters: parameters, isBody: true) + } + /** Finds orders by status - - parameter status: (query) Status value that needs to be considered for query + - parameter status: (query) Status value that needs to be considered for query (optional, default to placed) - parameter completion: completion handler to receive the data and the error objects */ public class func findOrdersByStatus(status status: String?, completion: ((data: [Order]?, error: ErrorType?) -> Void)) { @@ -28,7 +84,7 @@ public class StoreAPI: APIBase { Finds orders by status - - parameter status: (query) Status value that needs to be considered for query + - parameter status: (query) Status value that needs to be considered for query (optional, default to placed) - returns: Promise<[Order]> */ public class func findOrdersByStatus(status status: String?) -> Promise<[Order]> { @@ -55,38 +111,38 @@ public class StoreAPI: APIBase { - API Key: - type: apiKey x-test_api_client_secret - name: test_api_client_secret - - examples: [{example=[ { - "id" : 123456789, + - examples: [{contentType=application/json, example=[ { "petId" : 123456789, - "complete" : true, - "status" : "aeiou", "quantity" : 123, - "shipDate" : "2000-01-23T04:56:07.000+0000" -} ], contentType=application/json}, {example= + "id" : 123456789, + "shipDate" : "2000-01-23T04:56:07.000+0000", + "complete" : true, + "status" : "aeiou" +} ]}, {contentType=application/xml, example= 123456 123456 0 2000-01-23T04:56:07.000Z string true -, 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+0000" -} ], contentType=application/json}, {example= + "id" : 123456789, + "shipDate" : "2000-01-23T04:56:07.000+0000", + "complete" : true, + "status" : "aeiou" +} ]}, {contentType=application/xml, example= 123456 123456 0 2000-01-23T04:56:07.000Z string true -, contentType=application/xml}] +}] - - parameter status: (query) Status value that needs to be considered for query + - parameter status: (query) Status value that needs to be considered for query (optional, default to placed) - returns: RequestBuilder<[Order]> */ @@ -110,7 +166,7 @@ public class StoreAPI: APIBase { - parameter completion: completion handler to receive the data and the error objects */ - public class func getInventory(completion: ((data: [String:Int]?, error: ErrorType?) -> Void)) { + public class func getInventory(completion: ((data: [String:Int32]?, error: ErrorType?) -> Void)) { getInventoryWithRequestBuilder().execute { (response, error) -> Void in completion(data: response?.body, error: error); } @@ -120,10 +176,10 @@ public class StoreAPI: APIBase { Returns pet inventories by status - - returns: Promise<[String:Int]> + - returns: Promise<[String:Int32]> */ - public class func getInventory() -> Promise<[String:Int]> { - let deferred = Promise<[String:Int]>.pendingPromise() + public class func getInventory() -> Promise<[String:Int32]> { + let deferred = Promise<[String:Int32]>.pendingPromise() getInventory() { data, error in if let error = error { deferred.reject(error) @@ -143,23 +199,23 @@ 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:Int]> + - returns: RequestBuilder<[String:Int32]> */ - public class func getInventoryWithRequestBuilder() -> RequestBuilder<[String:Int]> { + 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 requestBuilder: RequestBuilder<[String:Int]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder<[String:Int32]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() return requestBuilder.init(method: "GET", URLString: URLString, parameters: parameters, isBody: true) } @@ -203,8 +259,8 @@ public class StoreAPI: APIBase { - API Key: - type: apiKey api_key - name: api_key - - examples: [{example="{}", contentType=application/json}, {example=not implemented io.swagger.models.properties.ObjectProperty@37aadb4f, contentType=application/xml}] - - examples: [{example="{}", contentType=application/json}, {example=not implemented io.swagger.models.properties.ObjectProperty@37aadb4f, contentType=application/xml}] + - examples: [{contentType=application/json, example="{}"}, {contentType=application/xml, example=not implemented io.swagger.models.properties.ObjectProperty@37aadb4f}] + - examples: [{contentType=application/json, example="{}"}, {contentType=application/xml, example=not implemented io.swagger.models.properties.ObjectProperty@37aadb4f}] - returns: RequestBuilder */ @@ -220,11 +276,103 @@ public class StoreAPI: APIBase { return requestBuilder.init(method: "GET", URLString: URLString, parameters: parameters, 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: Promise + */ + public class func getOrderById(orderId orderId: String) -> Promise { + let deferred = Promise.pendingPromise() + getOrderById(orderId: orderId) { data, error in + if let error = error { + deferred.reject(error) + } else { + deferred.fulfill(data!) + } + } + return deferred.promise + } + + /** + + 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 + - API Key: + - type: apiKey test_api_key_query (QUERY) + - name: test_api_key_query + - API Key: + - type: apiKey test_api_key_header + - name: test_api_key_header + - examples: [{contentType=application/json, example={ + "petId" : 123456789, + "quantity" : 123, + "id" : 123456789, + "shipDate" : "2000-01-23T04:56:07.000+0000", + "complete" : true, + "status" : "aeiou" +}}, {contentType=application/xml, example= + 123456 + 123456 + 0 + 2000-01-23T04:56:07.000Z + string + true +}] + - examples: [{contentType=application/json, example={ + "petId" : 123456789, + "quantity" : 123, + "id" : 123456789, + "shipDate" : "2000-01-23T04:56:07.000+0000", + "complete" : true, + "status" : "aeiou" +}}, {contentType=application/xml, example= + 123456 + 123456 + 0 + 2000-01-23T04:56:07.000Z + string + true +}] + + - parameter orderId: (path) ID of pet that needs to be fetched + + - returns: RequestBuilder + */ + public class func getOrderByIdWithRequestBuilder(orderId orderId: String) -> RequestBuilder { + var path = "/store/order/{orderId}" + path = path.stringByReplacingOccurrencesOfString("{orderId}", withString: "\(orderId)", options: .LiteralSearch, range: nil) + let URLString = PetstoreClientAPI.basePath + path + + let nillableParameters: [String:AnyObject?] = [:] + let parameters = APIHelper.rejectNil(nillableParameters) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "GET", URLString: URLString, parameters: parameters, isBody: true) + } + /** Place an order for a pet - - parameter body: (body) order placed for purchasing the 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?, completion: ((data: Order?, error: ErrorType?) -> Void)) { @@ -237,7 +385,7 @@ public class StoreAPI: APIBase { Place an order for a pet - - parameter body: (body) order placed for purchasing the pet + - parameter body: (body) order placed for purchasing the pet (optional) - returns: Promise */ public class func placeOrder(body body: Order?) -> Promise { @@ -264,38 +412,38 @@ public class StoreAPI: APIBase { - API Key: - type: apiKey x-test_api_client_secret - name: test_api_client_secret - - examples: [{example={ - "id" : 123456789, + - examples: [{contentType=application/json, example={ "petId" : 123456789, - "complete" : true, - "status" : "aeiou", "quantity" : 123, - "shipDate" : "2000-01-23T04:56:07.000+0000" -}, contentType=application/json}, {example= + "id" : 123456789, + "shipDate" : "2000-01-23T04:56:07.000+0000", + "complete" : true, + "status" : "aeiou" +}}, {contentType=application/xml, example= 123456 123456 0 2000-01-23T04:56:07.000Z string true -, 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+0000" -}, contentType=application/json}, {example= + "id" : 123456789, + "shipDate" : "2000-01-23T04:56:07.000+0000", + "complete" : true, + "status" : "aeiou" +}}, {contentType=application/xml, example= 123456 123456 0 2000-01-23T04:56:07.000Z string true -, contentType=application/xml}] +}] - - parameter body: (body) order placed for purchasing the pet + - parameter body: (body) order placed for purchasing the pet (optional) - returns: RequestBuilder */ @@ -310,152 +458,4 @@ public class StoreAPI: APIBase { return requestBuilder.init(method: "POST", URLString: URLString, parameters: parameters, 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: Promise - */ - public class func getOrderById(orderId orderId: String) -> Promise { - let deferred = Promise.pendingPromise() - getOrderById(orderId: orderId) { data, error in - if let error = error { - deferred.reject(error) - } else { - deferred.fulfill(data!) - } - } - return deferred.promise - } - - /** - - 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 - - API Key: - - type: apiKey test_api_key_header - - name: test_api_key_header - - API Key: - - type: apiKey test_api_key_query (QUERY) - - name: test_api_key_query - - examples: [{example={ - "id" : 123456789, - "petId" : 123456789, - "complete" : true, - "status" : "aeiou", - "quantity" : 123, - "shipDate" : "2000-01-23T04:56:07.000+0000" -}, contentType=application/json}, {example= - 123456 - 123456 - 0 - 2000-01-23T04:56:07.000Z - string - true -, contentType=application/xml}] - - examples: [{example={ - "id" : 123456789, - "petId" : 123456789, - "complete" : true, - "status" : "aeiou", - "quantity" : 123, - "shipDate" : "2000-01-23T04:56:07.000+0000" -}, contentType=application/json}, {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 - - - 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 requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - - return requestBuilder.init(method: "GET", URLString: URLString, parameters: parameters, isBody: true) - } - - /** - - 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: Promise - */ - public class func deleteOrder(orderId orderId: String) -> Promise { - let deferred = Promise.pendingPromise() - deleteOrder(orderId: orderId) { error in - if let error = error { - deferred.reject(error) - } else { - deferred.fulfill() - } - } - return deferred.promise - } - - /** - - 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 requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - - return requestBuilder.init(method: "DELETE", URLString: URLString, parameters: parameters, isBody: true) - } - } diff --git a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift index 7d304039bb0..ec73c765ac1 100644 --- a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift +++ b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift @@ -15,7 +15,7 @@ public class UserAPI: APIBase { Create user - - parameter body: (body) Created user object + - 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?, completion: ((error: ErrorType?) -> Void)) { @@ -28,7 +28,7 @@ public class UserAPI: APIBase { Create user - - parameter body: (body) Created user object + - parameter body: (body) Created user object (optional) - returns: Promise */ public class func createUser(body body: User?) -> Promise { @@ -50,7 +50,7 @@ public class UserAPI: APIBase { - POST /user - This can only be done by the logged in user. - - parameter body: (body) Created user object + - parameter body: (body) Created user object (optional) - returns: RequestBuilder */ @@ -69,7 +69,7 @@ public class UserAPI: APIBase { Creates list of users with given input array - - parameter body: (body) List of user object + - 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]?, completion: ((error: ErrorType?) -> Void)) { @@ -82,7 +82,7 @@ public class UserAPI: APIBase { Creates list of users with given input array - - parameter body: (body) List of user object + - parameter body: (body) List of user object (optional) - returns: Promise */ public class func createUsersWithArrayInput(body body: [User]?) -> Promise { @@ -104,7 +104,7 @@ public class UserAPI: APIBase { - POST /user/createWithArray - - - parameter body: (body) List of user object + - parameter body: (body) List of user object (optional) - returns: RequestBuilder */ @@ -123,7 +123,7 @@ public class UserAPI: APIBase { Creates list of users with given input array - - parameter body: (body) List of user object + - 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]?, completion: ((error: ErrorType?) -> Void)) { @@ -136,7 +136,7 @@ public class UserAPI: APIBase { Creates list of users with given input array - - parameter body: (body) List of user object + - parameter body: (body) List of user object (optional) - returns: Promise */ public class func createUsersWithListInput(body body: [User]?) -> Promise { @@ -158,7 +158,7 @@ public class UserAPI: APIBase { - POST /user/createWithList - - - parameter body: (body) List of user object + - parameter body: (body) List of user object (optional) - returns: RequestBuilder */ @@ -173,12 +173,137 @@ public class UserAPI: APIBase { return requestBuilder.init(method: "POST", URLString: URLString, parameters: parameters, isBody: true) } + /** + + Delete user + + - parameter username: (path) The name that needs to be deleted + - parameter completion: completion handler to receive the data and the error objects + */ + 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: Promise + */ + public class func deleteUser(username username: String) -> Promise { + let deferred = Promise.pendingPromise() + deleteUser(username: username) { error in + if let error = error { + deferred.reject(error) + } else { + deferred.fulfill() + } + } + return deferred.promise + } + + /** + + Delete user + + - DELETE /user/{username} + - This can only be done by the logged in user. + - BASIC: + - type: basic + - name: test_http_basic + + - 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 requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "DELETE", URLString: URLString, parameters: parameters, 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: Promise + */ + public class func getUserByName(username username: String) -> Promise { + let deferred = Promise.pendingPromise() + getUserByName(username: username) { data, error in + if let error = error { + deferred.reject(error) + } else { + deferred.fulfill(data!) + } + } + return deferred.promise + } + + /** + + Get user by user name + + - GET /user/{username} + - + - examples: [{contentType=application/json, example={ + "id" : 1, + "username" : "johnp", + "firstName" : "John", + "lastName" : "Public", + "email" : "johnp@swagger.io", + "password" : "-secret-", + "phone" : "0123456789", + "userStatus" : 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 requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "GET", URLString: URLString, parameters: parameters, isBody: true) + } + /** Logs user into the system - - parameter username: (query) The user name for login - - parameter password: (query) The password for login in clear text + - 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?, password: String?, completion: ((data: String?, error: ErrorType?) -> Void)) { @@ -191,8 +316,8 @@ public class UserAPI: APIBase { Logs user into the system - - parameter username: (query) The user name for login - - parameter password: (query) The password for login in clear text + - parameter username: (query) The user name for login (optional) + - parameter password: (query) The password for login in clear text (optional) - returns: Promise */ public class func loginUser(username username: String?, password: String?) -> Promise { @@ -213,11 +338,11 @@ public class UserAPI: APIBase { - 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 - - parameter password: (query) The password for login in clear text + - parameter username: (query) The user name for login (optional) + - parameter password: (query) The password for login in clear text (optional) - returns: RequestBuilder */ @@ -287,78 +412,12 @@ public class UserAPI: APIBase { return requestBuilder.init(method: "GET", URLString: URLString, parameters: parameters, 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: Promise - */ - public class func getUserByName(username username: String) -> Promise { - let deferred = Promise.pendingPromise() - getUserByName(username: username) { data, error in - if let error = error { - deferred.reject(error) - } else { - deferred.fulfill(data!) - } - } - return deferred.promise - } - - /** - - Get user by user name - - - GET /user/{username} - - - - examples: [{example={ - "id" : 1, - "username" : "johnp", - "firstName" : "John", - "lastName" : "Public", - "email" : "johnp@swagger.io", - "password" : "-secret-", - "phone" : "0123456789", - "userStatus" : 0 -}, contentType=application/json}] - - - 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 requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - - return requestBuilder.init(method: "GET", URLString: URLString, parameters: parameters, isBody: true) - } - /** Updated user - - parameter username: (path) name that need to be deleted - - parameter body: (body) Updated user object + - 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?, completion: ((error: ErrorType?) -> Void)) { @@ -371,8 +430,8 @@ public class UserAPI: APIBase { Updated user - - parameter username: (path) name that need to be deleted - - parameter body: (body) Updated user object + - parameter username: (path) name that need to be deleted + - parameter body: (body) Updated user object (optional) - returns: Promise */ public class func updateUser(username username: String, body: User?) -> Promise { @@ -394,8 +453,8 @@ public class UserAPI: APIBase { - 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 + - parameter username: (path) name that need to be deleted + - parameter body: (body) Updated user object (optional) - returns: RequestBuilder */ @@ -411,60 +470,4 @@ public class UserAPI: APIBase { return requestBuilder.init(method: "PUT", URLString: URLString, parameters: parameters, isBody: true) } - /** - - Delete user - - - parameter username: (path) The name that needs to be deleted - - parameter completion: completion handler to receive the data and the error objects - */ - 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: Promise - */ - public class func deleteUser(username username: String) -> Promise { - let deferred = Promise.pendingPromise() - deleteUser(username: username) { error in - if let error = error { - deferred.reject(error) - } else { - deferred.fulfill() - } - } - return deferred.promise - } - - /** - - 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 requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - - return requestBuilder.init(method: "DELETE", URLString: URLString, parameters: parameters, isBody: true) - } - } diff --git a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Extensions.swift b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Extensions.swift index 8015d1bd3a2..62d374eed05 100644 --- a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Extensions.swift +++ b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Extensions.swift @@ -19,6 +19,14 @@ 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 } } diff --git a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models.swift b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models.swift index 46ebae1e2ba..329eb295157 100644 --- a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models.swift +++ b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models.swift @@ -56,6 +56,12 @@ class Decoders { 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 } @@ -124,26 +130,6 @@ class Decoders { fatalError("formatter failed to parse \(source)") } - // 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: Int.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: Int.self, source: sourceDictionary["userStatus"]) - return instance - } - - // Decoder for [Category] Decoders.addDecoder(clazz: [Category].self) { (source: AnyObject) -> [Category] in return Decoders.decode(clazz: [Category].self, source: source) @@ -152,88 +138,12 @@ class Decoders { Decoders.addDecoder(clazz: Category.self) { (source: AnyObject) -> Category in let sourceDictionary = source as! [NSObject:AnyObject] let instance = Category() - instance.id = Decoders.decodeOptional(clazz: Int.self, source: sourceDictionary["id"]) + instance.id = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["id"]) instance.name = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["name"]) 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: Int.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: Int.self, source: sourceDictionary["id"]) - instance.name = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["name"]) - return instance - } - - - // Decoder for [ObjectReturn] - Decoders.addDecoder(clazz: [ObjectReturn].self) { (source: AnyObject) -> [ObjectReturn] in - return Decoders.decode(clazz: [ObjectReturn].self, source: source) - } - // Decoder for ObjectReturn - Decoders.addDecoder(clazz: ObjectReturn.self) { (source: AnyObject) -> ObjectReturn in - let sourceDictionary = source as! [NSObject:AnyObject] - let instance = ObjectReturn() - instance._return = Decoders.decodeOptional(clazz: Int.self, source: sourceDictionary["_return"]) - 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: Int.self, source: sourceDictionary["id"]) - instance.petId = Decoders.decodeOptional(clazz: Int.self, source: sourceDictionary["petId"]) - instance.quantity = Decoders.decodeOptional(clazz: Int.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 [SpecialModelName] - Decoders.addDecoder(clazz: [SpecialModelName].self) { (source: AnyObject) -> [SpecialModelName] in - return Decoders.decode(clazz: [SpecialModelName].self, source: source) - } - // Decoder for SpecialModelName - Decoders.addDecoder(clazz: SpecialModelName.self) { (source: AnyObject) -> SpecialModelName in - let sourceDictionary = source as! [NSObject:AnyObject] - let instance = SpecialModelName() - instance.specialPropertyName = Decoders.decodeOptional(clazz: Int.self, source: sourceDictionary["specialPropertyName"]) - return instance - } - - // Decoder for [InlineResponse200] Decoders.addDecoder(clazz: [InlineResponse200].self) { (source: AnyObject) -> [InlineResponse200] in return Decoders.decode(clazz: [InlineResponse200].self, source: source) @@ -242,9 +152,135 @@ class Decoders { Decoders.addDecoder(clazz: InlineResponse200.self) { (source: AnyObject) -> InlineResponse200 in let sourceDictionary = source as! [NSObject:AnyObject] let instance = InlineResponse200() - instance.id = Decoders.decodeOptional(clazz: Int.self, source: sourceDictionary["id"]) - instance.category = Decoders.decodeOptional(clazz: AnyObject.self, source: sourceDictionary["category"]) + instance.photoUrls = Decoders.decodeOptional(clazz: Array.self, source: sourceDictionary["photoUrls"]) instance.name = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["name"]) + instance.id = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["id"]) + instance.category = Decoders.decodeOptional(clazz: AnyObject.self, source: sourceDictionary["category"]) + instance.tags = Decoders.decodeOptional(clazz: Array.self, source: sourceDictionary["tags"]) + instance.status = InlineResponse200.Status(rawValue: (sourceDictionary["status"] as? String) ?? "") + return instance + } + + + // Decoder for [Model200Response] + Decoders.addDecoder(clazz: [Model200Response].self) { (source: AnyObject) -> [Model200Response] in + return Decoders.decode(clazz: [Model200Response].self, source: source) + } + // Decoder for Model200Response + Decoders.addDecoder(clazz: Model200Response.self) { (source: AnyObject) -> Model200Response in + let sourceDictionary = source as! [NSObject:AnyObject] + let instance = Model200Response() + instance.name = Decoders.decodeOptional(clazz: Int32.self, source: sourceDictionary["name"]) + return instance + } + + + // Decoder for [ModelReturn] + Decoders.addDecoder(clazz: [ModelReturn].self) { (source: AnyObject) -> [ModelReturn] in + return Decoders.decode(clazz: [ModelReturn].self, source: source) + } + // Decoder for ModelReturn + Decoders.addDecoder(clazz: ModelReturn.self) { (source: AnyObject) -> ModelReturn in + let sourceDictionary = source as! [NSObject:AnyObject] + let instance = ModelReturn() + instance._return = Decoders.decodeOptional(clazz: Int32.self, source: sourceDictionary["return"]) + return instance + } + + + // Decoder for [Name] + Decoders.addDecoder(clazz: [Name].self) { (source: AnyObject) -> [Name] in + return Decoders.decode(clazz: [Name].self, source: source) + } + // Decoder for Name + Decoders.addDecoder(clazz: Name.self) { (source: AnyObject) -> Name in + let sourceDictionary = source as! [NSObject:AnyObject] + let instance = Name() + instance.name = Decoders.decodeOptional(clazz: Int32.self, source: sourceDictionary["name"]) + instance.snakeCase = Decoders.decodeOptional(clazz: Int32.self, source: sourceDictionary["snake_case"]) + 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 [SpecialModelName] + Decoders.addDecoder(clazz: [SpecialModelName].self) { (source: AnyObject) -> [SpecialModelName] in + return Decoders.decode(clazz: [SpecialModelName].self, source: source) + } + // Decoder for SpecialModelName + Decoders.addDecoder(clazz: SpecialModelName.self) { (source: AnyObject) -> SpecialModelName in + let sourceDictionary = source as! [NSObject:AnyObject] + let instance = SpecialModelName() + instance.specialPropertyName = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["$special[property.name]"]) + 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/PetstoreClient/Classes/Swaggers/Models/Category.swift b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/Category.swift index f542ea676f8..2f0ab835e8f 100644 --- a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/Category.swift +++ b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/Category.swift @@ -10,7 +10,7 @@ import Foundation public class Category: JSONEncodable { - public var id: Int? + public var id: Int64? public var name: String? @@ -19,7 +19,7 @@ public class Category: JSONEncodable { // MARK: JSONEncodable func encodeToJSON() -> AnyObject { var nillableDictionary = [String:AnyObject?]() - nillableDictionary["id"] = self.id + 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/PetstoreClient/Classes/Swaggers/Models/InlineResponse200.swift b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/InlineResponse200.swift index 6ef68d3309d..fcf0679aea2 100644 --- a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/InlineResponse200.swift +++ b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/InlineResponse200.swift @@ -10,9 +10,19 @@ import Foundation public class InlineResponse200: JSONEncodable { - public var id: Int? - public var category: AnyObject? + public enum Status: String { + case Available = "available" + case Pending = "pending" + case Sold = "sold" + } + + public var photoUrls: [String]? public var name: String? + public var id: Int64? + public var category: AnyObject? + public var tags: [Tag]? + /** pet status in the store */ + public var status: Status? public init() {} @@ -20,9 +30,12 @@ public class InlineResponse200: JSONEncodable { // MARK: JSONEncodable func encodeToJSON() -> AnyObject { var nillableDictionary = [String:AnyObject?]() - nillableDictionary["id"] = self.id - nillableDictionary["category"] = self.category + nillableDictionary["photoUrls"] = self.photoUrls?.encodeToJSON() nillableDictionary["name"] = self.name + nillableDictionary["id"] = self.id?.encodeToJSON() + nillableDictionary["category"] = self.category + 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/PetstoreClient/Classes/Swaggers/Models/Model200Response.swift b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/Model200Response.swift new file mode 100644 index 00000000000..f929d282358 --- /dev/null +++ b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/Model200Response.swift @@ -0,0 +1,25 @@ +// +// Model200Response.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +public class Model200Response: JSONEncodable { + + public var name: Int32? + + + public init() {} + + // MARK: JSONEncodable + func encodeToJSON() -> AnyObject { + var nillableDictionary = [String:AnyObject?]() + nillableDictionary["name"] = self.name?.encodeToJSON() + let dictionary: [String:AnyObject] = APIHelper.rejectNil(nillableDictionary) ?? [:] + return dictionary + } +} diff --git a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/ModelReturn.swift b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/ModelReturn.swift new file mode 100644 index 00000000000..f3f16f2c13e --- /dev/null +++ b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/ModelReturn.swift @@ -0,0 +1,25 @@ +// +// ModelReturn.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +public class ModelReturn: JSONEncodable { + + 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/swift/PetstoreClient/Classes/Swaggers/Models/Name.swift b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/Name.swift new file mode 100644 index 00000000000..4b49c8325d5 --- /dev/null +++ b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/Name.swift @@ -0,0 +1,27 @@ +// +// Name.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +public class Name: JSONEncodable { + + public var name: Int32? + public var snakeCase: Int32? + + + public init() {} + + // MARK: JSONEncodable + func encodeToJSON() -> AnyObject { + var nillableDictionary = [String:AnyObject?]() + nillableDictionary["name"] = self.name?.encodeToJSON() + nillableDictionary["snake_case"] = self.snakeCase?.encodeToJSON() + let dictionary: [String:AnyObject] = APIHelper.rejectNil(nillableDictionary) ?? [:] + return dictionary + } +} diff --git a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/Order.swift b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/Order.swift index f309744da99..03b977c88f7 100644 --- a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/Order.swift +++ b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/Order.swift @@ -16,9 +16,9 @@ public class Order: JSONEncodable { case Delivered = "delivered" } - public var id: Int? - public var petId: Int? - public var quantity: Int? + public var id: Int64? + public var petId: Int64? + public var quantity: Int32? public var shipDate: NSDate? /** Order Status */ public var status: Status? @@ -30,9 +30,9 @@ public class Order: JSONEncodable { // MARK: JSONEncodable func encodeToJSON() -> AnyObject { var nillableDictionary = [String:AnyObject?]() - nillableDictionary["id"] = self.id - nillableDictionary["petId"] = self.petId - nillableDictionary["quantity"] = self.quantity + 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 diff --git a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/Pet.swift b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/Pet.swift index b1491df2516..5df44cfca96 100644 --- a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/Pet.swift +++ b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/Pet.swift @@ -16,7 +16,7 @@ public class Pet: JSONEncodable { case Sold = "sold" } - public var id: Int? + public var id: Int64? public var category: Category? public var name: String? public var photoUrls: [String]? @@ -30,7 +30,7 @@ public class Pet: JSONEncodable { // MARK: JSONEncodable func encodeToJSON() -> AnyObject { var nillableDictionary = [String:AnyObject?]() - nillableDictionary["id"] = self.id + nillableDictionary["id"] = self.id?.encodeToJSON() nillableDictionary["category"] = self.category?.encodeToJSON() nillableDictionary["name"] = self.name nillableDictionary["photoUrls"] = self.photoUrls?.encodeToJSON() diff --git a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/SpecialModelName.swift b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/SpecialModelName.swift index 8d17d893295..907be7f934a 100644 --- a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/SpecialModelName.swift +++ b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/SpecialModelName.swift @@ -10,7 +10,7 @@ import Foundation public class SpecialModelName: JSONEncodable { - public var specialPropertyName: Int? + public var specialPropertyName: Int64? public init() {} @@ -18,7 +18,7 @@ public class SpecialModelName: JSONEncodable { // MARK: JSONEncodable func encodeToJSON() -> AnyObject { var nillableDictionary = [String:AnyObject?]() - nillableDictionary["specialPropertyName"] = self.specialPropertyName + nillableDictionary["$special[property.name]"] = self.specialPropertyName?.encodeToJSON() let dictionary: [String:AnyObject] = APIHelper.rejectNil(nillableDictionary) ?? [:] return dictionary } diff --git a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/Tag.swift b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/Tag.swift index edcd73a7a0c..ecff268828f 100644 --- a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/Tag.swift +++ b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/Tag.swift @@ -10,7 +10,7 @@ import Foundation public class Tag: JSONEncodable { - public var id: Int? + public var id: Int64? public var name: String? @@ -19,7 +19,7 @@ public class Tag: JSONEncodable { // MARK: JSONEncodable func encodeToJSON() -> AnyObject { var nillableDictionary = [String:AnyObject?]() - nillableDictionary["id"] = self.id + 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/PetstoreClient/Classes/Swaggers/Models/User.swift b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/User.swift index fa0ad3f5019..70fee87f4d5 100644 --- a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/User.swift +++ b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/User.swift @@ -10,7 +10,7 @@ import Foundation public class User: JSONEncodable { - public var id: Int? + public var id: Int64? public var username: String? public var firstName: String? public var lastName: String? @@ -18,7 +18,7 @@ public class User: JSONEncodable { public var password: String? public var phone: String? /** User Status */ - public var userStatus: Int? + public var userStatus: Int32? public init() {} @@ -26,14 +26,14 @@ public class User: JSONEncodable { // MARK: JSONEncodable func encodeToJSON() -> AnyObject { var nillableDictionary = [String:AnyObject?]() - nillableDictionary["id"] = self.id + 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 + nillableDictionary["userStatus"] = self.userStatus?.encodeToJSON() let dictionary: [String:AnyObject] = APIHelper.rejectNil(nillableDictionary) ?? [:] return dictionary } diff --git a/samples/client/petstore/swift/SwaggerClientTests/Pods/Pods.xcodeproj/project.pbxproj b/samples/client/petstore/swift/SwaggerClientTests/Pods/Pods.xcodeproj/project.pbxproj index 0b725804d26..0e841d33df3 100644 --- a/samples/client/petstore/swift/SwaggerClientTests/Pods/Pods.xcodeproj/project.pbxproj +++ b/samples/client/petstore/swift/SwaggerClientTests/Pods/Pods.xcodeproj/project.pbxproj @@ -7,105 +7,108 @@ objects = { /* Begin PBXBuildFile section */ + 0290D4A3795396ABBB81E632E5AADE3A /* UIActionSheet+Promise.swift in Sources */ = {isa = PBXBuildFile; fileRef = FD570E28B63274E742E7D1FBBD55BB41 /* UIActionSheet+Promise.swift */; }; + 02D0672068E53F2D98CC67FBA5278022 /* UIView+AnyPromise.h in Headers */ = {isa = PBXBuildFile; fileRef = BCDD82DB3E6D43BA9769FCA9B744CB5E /* UIView+AnyPromise.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 03790817CF6E76959C0F7E2D0734E9F6 /* after.swift in Sources */ = {isa = PBXBuildFile; fileRef = 275DA9A664C70DD40A4059090D1A00D4 /* after.swift */; }; 03F494989CC1A8857B68A317D5D6860F /* Response.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5DF5FC3AF99846209C5FCE55A2E12D9A /* Response.swift */; }; - 043AACBEFC1A58B79AF6B81C8E7E117E /* Alamofire.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = A1D1571AB15108DF6F9C4FE2064E3C43 /* Alamofire.framework */; }; 0681ADC8BAE2C3185F13487BAAB4D9DD /* Upload.swift in Sources */ = {isa = PBXBuildFile; fileRef = CCE38472832BBCC541E646DA6C18EF9C /* Upload.swift */; }; - 06FD19EDA263742E49199D15FF81FFAA /* dispatch_promise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 392FA21A33296B88F790D62A4FAA4E4E /* dispatch_promise.swift */; }; - 07AA794848F8E6615B1DFD30673CE4EE /* Order.swift in Sources */ = {isa = PBXBuildFile; fileRef = 511325F77CCC682529E5D61A5AA0B381 /* Order.swift */; }; - 0AC8F78F69436E83746D56B1963C7321 /* PMKAlertController.swift in Sources */ = {isa = PBXBuildFile; fileRef = C731FBFCC690050C6C08E5AC9D9DC724 /* PMKAlertController.swift */; }; + 08B247165C2A091EE24F79D73F8ABEC9 /* UIAlertView+Promise.swift in Sources */ = {isa = PBXBuildFile; fileRef = CA854180C132DB5511D64C82535C5FDE /* UIAlertView+Promise.swift */; }; + 09C9710BEE85A253331C8E0994FBB2BF /* QuartzCore.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = FC4BF94DC4B3D8B88FC160B00931B0EC /* QuartzCore.framework */; }; 0B34EB4425C08BB021C2D09F75C9C146 /* OMGHTTPURLRQ.h in Headers */ = {isa = PBXBuildFile; fileRef = 450166FEA2155A5821D97744A0127DF8 /* OMGHTTPURLRQ.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 0B94E66F8539BBA52E693DAE322DCBAA /* APIHelper.swift in Sources */ = {isa = PBXBuildFile; fileRef = 28A3BBCDB687E9609F39F4EFC404B045 /* APIHelper.swift */; }; - 0DB1CFFE7FEC5667D7CD14C580D8AB8F /* UIView+AnyPromise.m in Sources */ = {isa = PBXBuildFile; fileRef = 2F0F4EDC2236E1C270DC2014181D6506 /* UIView+AnyPromise.m */; }; - 0E84511CF3F1E8C48CCC75BA66EBE0BA /* UIViewController+AnyPromise.h in Headers */ = {isa = PBXBuildFile; fileRef = 0BA017E288BB42E06EBEE9C6E6993EAF /* UIViewController+AnyPromise.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 11E1A6059DD32FBA0734660403713531 /* UIAlertView+AnyPromise.m in Sources */ = {isa = PBXBuildFile; fileRef = F075F63EFE77F7B59FF77CBA95B9AADF /* UIAlertView+AnyPromise.m */; }; - 1478812AA43E16777600753CDF6ACE1F /* dispatch_promise.m in Sources */ = {isa = PBXBuildFile; fileRef = A92242715FB4C0608F8DCEBF8F3791E2 /* dispatch_promise.m */; }; - 1C8D5A3F181EE2797475BF8CD3D17FAB /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = FB15A61DB7ABCB74565286162157C5A0 /* Foundation.framework */; }; - 21FB1E69B7CC6FCCA95B3B7531378D84 /* NSNotificationCenter+Promise.swift in Sources */ = {isa = PBXBuildFile; fileRef = B93FB4BB16CFB41DCA35A8CFAD7A7FEF /* NSNotificationCenter+Promise.swift */; }; - 21FE4548D5605FFE12EFA269102C88E1 /* Promise+Properties.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7E0DBDE561A6C2E7AC7A24160F8A5F28 /* Promise+Properties.swift */; }; - 23B39958BB2757E02093BEEFD900A50D /* Models.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1FE322C982813B48FD220881237FD90F /* Models.swift */; }; - 24D2C12AA4466F61F04FB7136AF497CA /* CALayer+AnyPromise.m in Sources */ = {isa = PBXBuildFile; fileRef = 04A22F2595054D39018E03961CA7283A /* CALayer+AnyPromise.m */; }; - 287EC582989EE65F605374D6908AA35C /* UIActionSheet+Promise.swift in Sources */ = {isa = PBXBuildFile; fileRef = FD570E28B63274E742E7D1FBBD55BB41 /* UIActionSheet+Promise.swift */; }; - 293859B4A8F6053D41FC5A50FF268CFA /* UserAPI.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6E25EC84C24B3AB284A71E47CB032082 /* UserAPI.swift */; }; - 2B1CB7AD3BF6CCE951E9CA7080097081 /* PetAPI.swift in Sources */ = {isa = PBXBuildFile; fileRef = D04911F3B72D4F18187122A620682A84 /* PetAPI.swift */; }; + 0BA72DC6AB26C72EE080F8A08CE41643 /* NSNotificationCenter+Promise.swift in Sources */ = {isa = PBXBuildFile; fileRef = B93FB4BB16CFB41DCA35A8CFAD7A7FEF /* NSNotificationCenter+Promise.swift */; }; + 0D6DCC756D1B0B68ADB5F805D575BAB6 /* NSError+Cancellation.h in Headers */ = {isa = PBXBuildFile; fileRef = 045C1F608ADE57757E6732D721779F22 /* NSError+Cancellation.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 0F816E94051557A7BA9BFA5B6B4A32A5 /* Order.swift in Sources */ = {isa = PBXBuildFile; fileRef = EE5E0F8BA6AB1430D31588F5EB170889 /* Order.swift */; }; + 0FFA3D017278D8EB24A9AC4780E3AFEC /* OMGHTTPURLRQ.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 3530BF15E14D1F6D7134EE67377D5C8C /* OMGHTTPURLRQ.framework */; }; + 1372840E154B63D17AACD1257C3E0520 /* NSNotificationCenter+AnyPromise.h in Headers */ = {isa = PBXBuildFile; fileRef = 3616971BAEF40302B7F2F8B1007C0B2B /* NSNotificationCenter+AnyPromise.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 167B939D70FE9AADBA03ABBBBA588B4B /* SpecialModelName.swift in Sources */ = {isa = PBXBuildFile; fileRef = F7F371E5E2A26613C4DE253F4D7A3F56 /* SpecialModelName.swift */; }; + 19DAC977B6B3CBDC69EE2150BD0C1EF6 /* UIView+AnyPromise.m in Sources */ = {isa = PBXBuildFile; fileRef = 2F0F4EDC2236E1C270DC2014181D6506 /* UIView+AnyPromise.m */; }; + 1B099FB3AA9A6794A3039899A6734205 /* Name.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F98C30F79A0AB5920FB4CDBB7413E5C /* Name.swift */; }; + 222C92305B7AC5BB8E2ABAD182F50026 /* Promise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3D23C407A7CDBFD244D6115899F9D45D /* Promise.swift */; }; + 2676E85B9644D55E25A31D3CE61A5726 /* CALayer+AnyPromise.h in Headers */ = {isa = PBXBuildFile; fileRef = 27E0FE41D771BE8BE3F0D4F1DAD0B179 /* CALayer+AnyPromise.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 291E2518A9E470C2E9CE1B69C088C16F /* State.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8DC63EB77B3791891517B98CAA115DE8 /* State.swift */; }; 2C5450AC69398958CF6F7539EF7D99E5 /* Alamofire-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 30CE7341A995EF6812D71771E74CF7F7 /* Alamofire-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 2D5C3B34453DDCB27D66B3D5BF82E831 /* URLDataPromise.swift in Sources */ = {isa = PBXBuildFile; fileRef = E7CE161ED0CF68954A63F30528ACAD9B /* URLDataPromise.swift */; }; - 2D9C89E698B7962248B91C84556B8521 /* AnyPromise.m in Sources */ = {isa = PBXBuildFile; fileRef = 1B7E90A568681E000EF3CB0917584F3C /* AnyPromise.m */; }; - 3365F629B3DD2CC5092161DADB5B24BA /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = FB15A61DB7ABCB74565286162157C5A0 /* Foundation.framework */; }; + 335F10113F178E8D2984BE0602A0DEED /* Tag.swift in Sources */ = {isa = PBXBuildFile; fileRef = 780827122613E6D246695ADFAA7B28B6 /* Tag.swift */; }; 35F6B35131F89EA23246C6508199FB05 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = FB15A61DB7ABCB74565286162157C5A0 /* Foundation.framework */; }; - 36BC51A48A364E9D70DD4A12F1BFDC24 /* NSURLSession+Promise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 535DF88FC12304114DEF55E4003421B2 /* NSURLSession+Promise.swift */; }; + 36CDD7A6638E10B9107C74D9B75079F1 /* NSURLConnection+Promise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 412985229DA7A4DF9E129B7E8F0C09BB /* NSURLConnection+Promise.swift */; }; + 37027676CEABF1BF753684A06C2DCDDB /* URLDataPromise.swift in Sources */ = {isa = PBXBuildFile; fileRef = E7CE161ED0CF68954A63F30528ACAD9B /* URLDataPromise.swift */; }; 3A8D316D4266A3309D0A98ED74F8A13A /* OMGUserAgent.h in Headers */ = {isa = PBXBuildFile; fileRef = 87BC7910B8D7D31310A07C32438A8C67 /* OMGUserAgent.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 3BEC62AF9DDCF822F1865057CF1D50A2 /* AnyPromise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5973BC143AE488C12FFB1E83E71F0C45 /* AnyPromise.swift */; }; - 3FC49DA692C9A42F947C9F561D3CAF1D /* after.swift in Sources */ = {isa = PBXBuildFile; fileRef = 275DA9A664C70DD40A4059090D1A00D4 /* after.swift */; }; - 422EB81C476A49349CBD929094E659BE /* Pet.swift in Sources */ = {isa = PBXBuildFile; fileRef = 54C7F7995EC233B46050D81ABA34442C /* Pet.swift */; }; + 3D2B170AA3737444F26B0E07E1F5FEF1 /* Category.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6D0925CA00A7877078F60FAD44E2DD0F /* Category.swift */; }; + 405F6EBE4BBAAC270AF1B97AFC5B0C16 /* NSURLConnection+AnyPromise.m in Sources */ = {isa = PBXBuildFile; fileRef = A7F0DAACAC89A93B940BBE54E6A87E9F /* NSURLConnection+AnyPromise.m */; }; + 42A66FBE567A7F5B2136FC56BFF4874A /* UIAlertView+AnyPromise.m in Sources */ = {isa = PBXBuildFile; fileRef = F075F63EFE77F7B59FF77CBA95B9AADF /* UIAlertView+AnyPromise.m */; }; + 435BD7136E0E174C6A8811D6C88DEAF2 /* NSObject+Promise.swift in Sources */ = {isa = PBXBuildFile; fileRef = D6EB54C331FED437583A5F01EB2757D1 /* NSObject+Promise.swift */; }; 48CB8E7E16443CA771E4DCFB3E0709A2 /* OMGHTTPURLRQ.m in Sources */ = {isa = PBXBuildFile; fileRef = 9D579267FC1F163C8F04B444DAEFED0D /* OMGHTTPURLRQ.m */; settings = {COMPILER_FLAGS = "-DOS_OBJECT_USE_OBJC=0"; }; }; + 4CE2B026C746F263F6B95534A35E76C0 /* afterlife.swift in Sources */ = {isa = PBXBuildFile; fileRef = C476B916B763E55E4161F0B30760C4E8 /* afterlife.swift */; }; 4DE5FCC41D100B113B6645EA64410F16 /* ParameterEncoding.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1FBD351D007CF4095C98C9DFD9D83D61 /* ParameterEncoding.swift */; }; - 4FBA897D5492D0DD3CB07502E2596F6A /* PetstoreClient-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 46A8E0328DC896E0893B565FE8742167 /* PetstoreClient-dummy.m */; }; + 4EAB3713B40959FB2E0CDEAC8BDE1116 /* when.swift in Sources */ = {isa = PBXBuildFile; fileRef = 16730DAF3E51C161D8247E473F069E71 /* when.swift */; }; 5192A7466019F9B3D7F1E987124E96BC /* OMGHTTPURLRQ-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = F7EBDD2EEED520E06ACB3538B3832049 /* OMGHTTPURLRQ-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 524CC219844C01E75355CACC63869C0D /* join.m in Sources */ = {isa = PBXBuildFile; fileRef = 6AD59903FAA8315AD0036AC459FFB97F /* join.m */; }; + 53FBECFDFCA1B755F2754C4DBC65E3D5 /* UIKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 5A1DC80A0773C5A569348DC442EAFD1D /* UIKit.framework */; }; 5480169E42C456C49BE59E273D7E0115 /* OMGFormURLEncode.h in Headers */ = {isa = PBXBuildFile; fileRef = 51ADA0B6B6B00CB0E818AA8CBC311677 /* OMGFormURLEncode.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 56E4DB673DB3EAE8F31C5854581C9239 /* UIKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 5A1DC80A0773C5A569348DC442EAFD1D /* UIKit.framework */; }; - 61BB171AC3499F5339DEFFBB37E15E84 /* UIViewController+Promise.swift in Sources */ = {isa = PBXBuildFile; fileRef = D6D459D0AB2361B48F81C4D14C6D0DAA /* UIViewController+Promise.swift */; }; - 62F41914F8A9F9740EBBC8E412761EDB /* when.swift in Sources */ = {isa = PBXBuildFile; fileRef = 16730DAF3E51C161D8247E473F069E71 /* when.swift */; }; - 6756077354E35F7C661D714587C52F6B /* QuartzCore.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = FC4BF94DC4B3D8B88FC160B00931B0EC /* QuartzCore.framework */; }; - 6C0758FA1866AFC3B001BCCE294DF971 /* UIViewController+AnyPromise.m in Sources */ = {isa = PBXBuildFile; fileRef = AA24C5EC82CF437D8D1FFFAB68975408 /* UIViewController+AnyPromise.m */; }; - 6C835D49402A31D15D3D53439F607525 /* AnyPromise.h in Headers */ = {isa = PBXBuildFile; fileRef = 1F19945EE403F7B29D8B1939EA6D579A /* AnyPromise.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 57FB6BF21435F091D48B97DBD36E8C7B /* InlineResponse200.swift in Sources */ = {isa = PBXBuildFile; fileRef = 94FB3F3CEFBA56B306D034B69144C68E /* InlineResponse200.swift */; }; + 5849F4EAAAD24A116F0E0E948623AEC0 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = FB15A61DB7ABCB74565286162157C5A0 /* Foundation.framework */; }; + 5EADA3CE22BF3B74E759F948DE7A66F1 /* UIViewController+AnyPromise.m in Sources */ = {isa = PBXBuildFile; fileRef = AA24C5EC82CF437D8D1FFFAB68975408 /* UIViewController+AnyPromise.m */; }; + 63F6FFAB2BCCD07FD3DF44086E11C8B0 /* ObjectReturn.swift in Sources */ = {isa = PBXBuildFile; fileRef = A58E34C4DDB909B2CA900747C6691A5A /* ObjectReturn.swift */; }; + 64739E341A52DFA48F4169E4322E7486 /* PetstoreClient-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 9F681D2C508D1BA8F62893120D9343A4 /* PetstoreClient-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; 6CB84A616D7B4D189A4E94BD37621575 /* OMGUserAgent.m in Sources */ = {isa = PBXBuildFile; fileRef = E11BFB27B43B742CB5D6086C4233A909 /* OMGUserAgent.m */; settings = {COMPILER_FLAGS = "-DOS_OBJECT_USE_OBJC=0"; }; }; 6D264CCBD7DAC0A530076FB1A847EEC7 /* Pods-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 894E5DA93A9F359521A89826BE6DA777 /* Pods-dummy.m */; }; + 6EA827E0ECB8F7CC49F8B4C92A1D93FA /* CALayer+AnyPromise.m in Sources */ = {isa = PBXBuildFile; fileRef = 04A22F2595054D39018E03961CA7283A /* CALayer+AnyPromise.m */; }; 6F63943B0E954F701F32BC7A1F4C2FEC /* OMGFormURLEncode.m in Sources */ = {isa = PBXBuildFile; fileRef = 25614E715DDC170DAFB0DF50C5503E33 /* OMGFormURLEncode.m */; settings = {COMPILER_FLAGS = "-DOS_OBJECT_USE_OBJC=0"; }; }; - 6F676A66D92467D28EA52325927C5BC5 /* AlamofireImplementations.swift in Sources */ = {isa = PBXBuildFile; fileRef = BE4F0EE7E4E76A7AC6932305A9A0A35A /* AlamofireImplementations.swift */; }; - 732A5A91563E46475A3FBE7D28C942E3 /* UIAlertView+Promise.swift in Sources */ = {isa = PBXBuildFile; fileRef = CA854180C132DB5511D64C82535C5FDE /* UIAlertView+Promise.swift */; }; - 74E7435F4420251677F0494908757D56 /* UIActionSheet+AnyPromise.h in Headers */ = {isa = PBXBuildFile; fileRef = 6846D22C9F0CCBC48DF833E309A8E84F /* UIActionSheet+AnyPromise.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 774EB2064BFD3266EEF2B07905D9B0CF /* NSNotificationCenter+AnyPromise.h in Headers */ = {isa = PBXBuildFile; fileRef = 3616971BAEF40302B7F2F8B1007C0B2B /* NSNotificationCenter+AnyPromise.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 76171B607A443BE97E1DBBF6575CD558 /* after.m in Sources */ = {isa = PBXBuildFile; fileRef = B868468092D7B2489B889A50981C9247 /* after.m */; }; + 76FAA23C0A28ECF0BBF6A5C14203F414 /* Models.swift in Sources */ = {isa = PBXBuildFile; fileRef = A360D2EE0575D36C8C8459BCB8325D9A /* Models.swift */; }; + 77F020B749274FC61FD1D5EA3FBBBE18 /* PromiseKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = A112EF8BB3933C1C1E42F11B3DD3B02A /* PromiseKit.framework */; }; 80F496237530D382A045A29654D8C11C /* ServerTrustPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 400A6910E83F606BCD67DC11FA706697 /* ServerTrustPolicy.swift */; }; 82971968CBDAB224212EEB4607C9FB8D /* Result.swift in Sources */ = {isa = PBXBuildFile; fileRef = 53F8B2513042BD6DB957E8063EF895BD /* Result.swift */; }; + 82B5B0FF21A9A28284AE7F1124199D3F /* UIActionSheet+AnyPromise.m in Sources */ = {isa = PBXBuildFile; fileRef = 9774D31336C85248A115B569E7D95283 /* UIActionSheet+AnyPromise.m */; }; 8399DBEE3E2D98EB1F466132E476F4D9 /* MultipartFormData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5F14E17B4D6BDF8BD3E384BE6528F744 /* MultipartFormData.swift */; }; - 874DC0CE734CE6E3F54200621F9BECE5 /* UIActionSheet+AnyPromise.m in Sources */ = {isa = PBXBuildFile; fileRef = 9774D31336C85248A115B569E7D95283 /* UIActionSheet+AnyPromise.m */; }; - 90E44B5F3E21A2420F481DB132E52684 /* PetstoreClient-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 9F681D2C508D1BA8F62893120D9343A4 /* PetstoreClient-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 920AD5E4875F89BE0B3413FA0946ACB4 /* PromiseKit.h in Headers */ = {isa = PBXBuildFile; fileRef = 3BFFA6FD621E9ED341AA89AEAC1604D7 /* PromiseKit.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 92D9F79E690C48BC3A1BE0C4D861E4B7 /* afterlife.swift in Sources */ = {isa = PBXBuildFile; fileRef = C476B916B763E55E4161F0B30760C4E8 /* afterlife.swift */; }; - 92DB5CB64170AA4B906B58018ADC9419 /* Promise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3D23C407A7CDBFD244D6115899F9D45D /* Promise.swift */; }; - 94E9D5A7158985FA79136143BCA8E66E /* join.swift in Sources */ = {isa = PBXBuildFile; fileRef = 84319E048FE6DD89B905FA3A81005C5F /* join.swift */; }; - 95DFE0BD617B4C9A707D8D55CD2F6858 /* hang.m in Sources */ = {isa = PBXBuildFile; fileRef = F4B6A98D6DAF474045210F5A74FF1C3C /* hang.m */; }; + 886AC602EE7FCFDCD2DCD470CCB41721 /* PetstoreClient-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 46A8E0328DC896E0893B565FE8742167 /* PetstoreClient-dummy.m */; }; + 8ABFD5E4F7621D554DBB12C6472A8313 /* PetAPI.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1A44CBCE721F71F03C7758DB3F36CDFF /* PetAPI.swift */; }; + 91DF85663A3771DCD35D0FF07135959B /* Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 84A386C655413763AEE8133A102DF2C8 /* Extensions.swift */; }; + 9254814FE352958B5270E874E5CCD394 /* NSURLSession+Promise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 535DF88FC12304114DEF55E4003421B2 /* NSURLSession+Promise.swift */; }; + 964EA2E9AA68D7D587ED15143FEC4BE5 /* Promise+Properties.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7E0DBDE561A6C2E7AC7A24160F8A5F28 /* Promise+Properties.swift */; }; 96D99D0C2472535A169DED65CB231CD7 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = FB15A61DB7ABCB74565286162157C5A0 /* Foundation.framework */; }; - 9D70DDC375D7119F81D3B5FA30F17D38 /* PromiseKit-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 9042667D08D783E45394FE8B97EE6468 /* PromiseKit-dummy.m */; }; - 9E339448B1EFC5B2112D847A766F844A /* PromiseKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = A112EF8BB3933C1C1E42F11B3DD3B02A /* PromiseKit.framework */; }; - 9FB7204EEC7DA5E6E0BB5826DAE8FA6F /* Error.swift in Sources */ = {isa = PBXBuildFile; fileRef = 558DFECE2C740177CA6357DA71A1DFBB /* Error.swift */; }; + 97A9635E99E7EB0F33260600E1AC82F6 /* StoreAPI.swift in Sources */ = {isa = PBXBuildFile; fileRef = A27DF5A602B1BB474A141C895934F712 /* StoreAPI.swift */; }; + 99710CDCDDFF9ED74B8E01EB8E4BF563 /* UIView+Promise.swift in Sources */ = {isa = PBXBuildFile; fileRef = E3CDA0958D6247505ECD9098D662EA74 /* UIView+Promise.swift */; }; + 9DA852770BE32039F2C21096F27872A0 /* ModelReturn.swift in Sources */ = {isa = PBXBuildFile; fileRef = BEA71A34D3031D95E61F1082A5BEEB7A /* ModelReturn.swift */; }; + A2A8512E15D1A4B6DBD515D6144EC083 /* Error.swift in Sources */ = {isa = PBXBuildFile; fileRef = 558DFECE2C740177CA6357DA71A1DFBB /* Error.swift */; }; A2C172FE407C0BC3478ADCA91A6C9CEC /* Manager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2D51C929AC51E34493AA757180C09C3B /* Manager.swift */; }; A3505FA2FB3067D53847AD288AC04F03 /* Download.swift in Sources */ = {isa = PBXBuildFile; fileRef = A04177B09D9596450D827FE49A36C4C4 /* Download.swift */; }; - A4AE8E155661325CF82446A0FF242B07 /* Umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 0A8906F6D6920DF197965D1740A7E283 /* Umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; - A9DF4EE19A7494F3A91CE23C261FDE13 /* NSError+Cancellation.h in Headers */ = {isa = PBXBuildFile; fileRef = 045C1F608ADE57757E6732D721779F22 /* NSError+Cancellation.h */; settings = {ATTRIBUTES = (Public, ); }; }; - AF3198275DBC570992BA895FB8FAF293 /* Tag.swift in Sources */ = {isa = PBXBuildFile; fileRef = A60C1B336FDA263A9AB0025BF89FF7D6 /* Tag.swift */; }; + AB06DA1AC0FA3BDF50BAAEBBD06AB46E /* Model200Response.swift in Sources */ = {isa = PBXBuildFile; fileRef = A02D16E80C10DF32F2A88A66B83D7DD9 /* Model200Response.swift */; }; + AC30241BA84931703B312A09DD64C648 /* Umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 0A8906F6D6920DF197965D1740A7E283 /* Umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; B0FB4B01682814B9E3D32F9DC4A5E762 /* Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8B476A57549D7994745E17A6DE5BE745 /* Alamofire.swift */; }; - B1931E222F0FF379FE4B14FC99171BF9 /* Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 40980C10A3E4CD8F73FEF4585BC9B273 /* Extensions.swift */; }; - B68C4829A81227CAC51BC61F43D91445 /* APIs.swift in Sources */ = {isa = PBXBuildFile; fileRef = B0C04A06028D1D93105B1F69EE2C7311 /* APIs.swift */; }; + B0FB5055748E072728CA7129C3CAA3C6 /* APIs.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7220AB25575F15EB89521DFE33F4B764 /* APIs.swift */; }; + B4FAA3F0ED04F0506E66FCD7141AD989 /* APIHelper.swift in Sources */ = {isa = PBXBuildFile; fileRef = A4B4E403BC5209472D6DA0EEF82A8BD9 /* APIHelper.swift */; }; B6D2DC3E3DA44CD382B9B425F40E11C1 /* Alamofire-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 139346EB669CBE2DE8FE506E14A2BA9C /* Alamofire-dummy.m */; }; - BC5E262FDC0CD0C1803EB715E2C48F52 /* User.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2001DB27FE23C000ACF411B329BC099F /* User.swift */; }; - C0FBBB8365C842ACBC9181264649DCC1 /* State.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8DC63EB77B3791891517B98CAA115DE8 /* State.swift */; }; - C1AC5BBB1762E93B083317C5E8A939DE /* OMGHTTPURLRQ.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 3530BF15E14D1F6D7134EE67377D5C8C /* OMGHTTPURLRQ.framework */; }; - C320DDEFFEED8D4BB9EF3954D6FC8DE2 /* NSObject+Promise.swift in Sources */ = {isa = PBXBuildFile; fileRef = D6EB54C331FED437583A5F01EB2757D1 /* NSObject+Promise.swift */; }; + B72EE02E33CE31F594630D54EEEF9A15 /* hang.m in Sources */ = {isa = PBXBuildFile; fileRef = F4B6A98D6DAF474045210F5A74FF1C3C /* hang.m */; }; + B908D3F77F293FC72B20EEB48208F5C6 /* race.swift in Sources */ = {isa = PBXBuildFile; fileRef = 980FD13F87B44BFD90F8AC129BEB2E61 /* race.swift */; }; + BF2A197091B6FC0646CFA61A5FBE66AF /* when.m in Sources */ = {isa = PBXBuildFile; fileRef = 143BC30E5DDAF52A3D9578F507EC6A41 /* when.m */; }; + BFA18BBF784D749FE8BFA654088F3630 /* join.swift in Sources */ = {isa = PBXBuildFile; fileRef = 84319E048FE6DD89B905FA3A81005C5F /* join.swift */; }; + C04283A3B7479C8EDE2B95F4DDEE2C2C /* UIViewController+AnyPromise.h in Headers */ = {isa = PBXBuildFile; fileRef = 0BA017E288BB42E06EBEE9C6E6993EAF /* UIViewController+AnyPromise.h */; settings = {ATTRIBUTES = (Public, ); }; }; + C4688FFE2C4E161516878B521EF54FBE /* AlamofireImplementations.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2B25BD9A4F08A3124D223BDB55576886 /* AlamofireImplementations.swift */; }; C75519F0450166A6F28126ECC7664E9C /* Validation.swift in Sources */ = {isa = PBXBuildFile; fileRef = CA1AD92813B887E2D017D051B8C0E3D2 /* Validation.swift */; }; - C7F1A5669CE3AAA90BF2B5CCA70F90F6 /* SpecialModelName.swift in Sources */ = {isa = PBXBuildFile; fileRef = B043AFA6B4E018E9989ED2EBED883492 /* SpecialModelName.swift */; }; - C8F3620654924A2D88756CDCC5CCFB11 /* StoreAPI.swift in Sources */ = {isa = PBXBuildFile; fileRef = 75A581DA18EB8A9137C3A6FCB144D6EA /* StoreAPI.swift */; }; - CDFEEA22781236F07F32D6B739517178 /* CALayer+AnyPromise.h in Headers */ = {isa = PBXBuildFile; fileRef = 27E0FE41D771BE8BE3F0D4F1DAD0B179 /* CALayer+AnyPromise.h */; settings = {ATTRIBUTES = (Public, ); }; }; + C95D8B9276E75DA8F6DECCDCE147C781 /* join.m in Sources */ = {isa = PBXBuildFile; fileRef = 6AD59903FAA8315AD0036AC459FFB97F /* join.m */; }; + C96CB79BD56A7931541FC22617A2D613 /* UIAlertView+AnyPromise.h in Headers */ = {isa = PBXBuildFile; fileRef = 92D340D66F03F31237B70F23FE9B00D0 /* UIAlertView+AnyPromise.h */; settings = {ATTRIBUTES = (Public, ); }; }; + CCA3921F36A6B36DC1F993112BEF0602 /* NSURLConnection+AnyPromise.h in Headers */ = {isa = PBXBuildFile; fileRef = BAE48ACA10E8895BB8BF5CE8C0846B4B /* NSURLConnection+AnyPromise.h */; settings = {ATTRIBUTES = (Public, ); }; }; D1E8B31EFCBDE00F108E739AD69425C0 /* Pods-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 2BCC458FDD5F692BBB2BFC64BB5701FC /* Pods-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; D21B7325B3642887BFBE977E021F2D26 /* ResponseSerialization.swift in Sources */ = {isa = PBXBuildFile; fileRef = FD558DDCDDA1B46951548B02C34277EF /* ResponseSerialization.swift */; }; - D21F8EFE0A5E06F45D8C203FE583EF77 /* race.swift in Sources */ = {isa = PBXBuildFile; fileRef = 980FD13F87B44BFD90F8AC129BEB2E61 /* race.swift */; }; D358A828E68E152D06FC8E35533BF00B /* OMGHTTPURLRQ-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 0F36B65CF990C57DC527824ED0BA1915 /* OMGHTTPURLRQ-dummy.m */; }; + D46A1F4211ACD4C9EF7726AFAD2609EA /* User.swift in Sources */ = {isa = PBXBuildFile; fileRef = 71972929AF72164C887BB8F5F1059089 /* User.swift */; }; + D55A97CF31106A21298F731FC890BCA1 /* UIActionSheet+AnyPromise.h in Headers */ = {isa = PBXBuildFile; fileRef = 6846D22C9F0CCBC48DF833E309A8E84F /* UIActionSheet+AnyPromise.h */; settings = {ATTRIBUTES = (Public, ); }; }; D75CA395D510E08C404E55F5BDAE55CE /* Error.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8A9CB35983E4859DFFBAD8840196A094 /* Error.swift */; }; - DC5EC2239846C76B4CCC3EAD4B022B8D /* NSNotificationCenter+AnyPromise.m in Sources */ = {isa = PBXBuildFile; fileRef = 4798BAC01B0E3F07E3BBBB07BA57F2D7 /* NSNotificationCenter+AnyPromise.m */; }; - DD324C55ECC625F8893C07BD52B67E99 /* UIView+AnyPromise.h in Headers */ = {isa = PBXBuildFile; fileRef = BCDD82DB3E6D43BA9769FCA9B744CB5E /* UIView+AnyPromise.h */; settings = {ATTRIBUTES = (Public, ); }; }; + D78AD94D0DBA6A1CC4E6673D2F14C832 /* NSNotificationCenter+AnyPromise.m in Sources */ = {isa = PBXBuildFile; fileRef = 4798BAC01B0E3F07E3BBBB07BA57F2D7 /* NSNotificationCenter+AnyPromise.m */; }; + D854F67FD7486C6D25CA841C7D2D5030 /* AnyPromise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5973BC143AE488C12FFB1E83E71F0C45 /* AnyPromise.swift */; }; DD8D067A7F742F39B87FA04CE12DD118 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = FB15A61DB7ABCB74565286162157C5A0 /* Foundation.framework */; }; - E29B659D873F03F056C25D9B139CE225 /* NSURLConnection+AnyPromise.h in Headers */ = {isa = PBXBuildFile; fileRef = BAE48ACA10E8895BB8BF5CE8C0846B4B /* NSURLConnection+AnyPromise.h */; settings = {ATTRIBUTES = (Public, ); }; }; - E3A8BAEE55DCBC8D16D9210A78D5A200 /* ObjectReturn.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0A6DD0A2A0094280A4A78C9B772E3BAF /* ObjectReturn.swift */; }; - EE2920251312E2F32C421CD05ACF4DA4 /* when.m in Sources */ = {isa = PBXBuildFile; fileRef = 143BC30E5DDAF52A3D9578F507EC6A41 /* when.m */; }; - F0322283A43A3230AF9E1A363F5682AF /* InlineResponse200.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5559FBE62F3407535CE97AD320341ACC /* InlineResponse200.swift */; }; - F2F841536DFF2E08BA87B09E1A62A15C /* Category.swift in Sources */ = {isa = PBXBuildFile; fileRef = 876669E4CF92F0757A01F74D0325057C /* Category.swift */; }; - F300CE6E3C784F5DEB89BC29C4895DBE /* NSURLConnection+AnyPromise.m in Sources */ = {isa = PBXBuildFile; fileRef = A7F0DAACAC89A93B940BBE54E6A87E9F /* NSURLConnection+AnyPromise.m */; }; - F4FE9A55D8791B871926069F21DCF818 /* after.m in Sources */ = {isa = PBXBuildFile; fileRef = B868468092D7B2489B889A50981C9247 /* after.m */; }; - F79E72246A63190A6B5E70F348E6670F /* UIAlertView+AnyPromise.h in Headers */ = {isa = PBXBuildFile; fileRef = 92D340D66F03F31237B70F23FE9B00D0 /* UIAlertView+AnyPromise.h */; settings = {ATTRIBUTES = (Public, ); }; }; + DF8DB782B7C2F5EEC7F29E2E2A5F8154 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = FB15A61DB7ABCB74565286162157C5A0 /* Foundation.framework */; }; + E6810077387057466534FD27AA294211 /* UIViewController+Promise.swift in Sources */ = {isa = PBXBuildFile; fileRef = D6D459D0AB2361B48F81C4D14C6D0DAA /* UIViewController+Promise.swift */; }; + E6B182F5E233FB9F529BEFEAD3D02ACF /* AnyPromise.h in Headers */ = {isa = PBXBuildFile; fileRef = 1F19945EE403F7B29D8B1939EA6D579A /* AnyPromise.h */; settings = {ATTRIBUTES = (Public, ); }; }; + E6FDE3505ED7CEF6B87500A5C52B7938 /* Alamofire.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = A1D1571AB15108DF6F9C4FE2064E3C43 /* Alamofire.framework */; }; + E8DDC87F287107068FF40443CF059433 /* dispatch_promise.m in Sources */ = {isa = PBXBuildFile; fileRef = A92242715FB4C0608F8DCEBF8F3791E2 /* dispatch_promise.m */; }; + E93C3C3AABF32094F0D673E3EC3B2C20 /* dispatch_promise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 392FA21A33296B88F790D62A4FAA4E4E /* dispatch_promise.swift */; }; + EC5B36837863572EC400633CD2FFAF94 /* PromiseKit-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 9042667D08D783E45394FE8B97EE6468 /* PromiseKit-dummy.m */; }; + F049FFBDC929BB045C2AEDF0ECABE513 /* AnyPromise.m in Sources */ = {isa = PBXBuildFile; fileRef = 1B7E90A568681E000EF3CB0917584F3C /* AnyPromise.m */; }; + F70B5EF0A4B94F8FF906073882DCDB78 /* UserAPI.swift in Sources */ = {isa = PBXBuildFile; fileRef = 094C870CE73CCEC940F4DA86D7FE0C30 /* UserAPI.swift */; }; + F8C6EBC22D97E301AA4EA4D04B3FC860 /* Pet.swift in Sources */ = {isa = PBXBuildFile; fileRef = C909E10C22B35220020268EF2BF27E18 /* Pet.swift */; }; + F8DAC10D25E6E36B83261AC032A77F1A /* PromiseKit.h in Headers */ = {isa = PBXBuildFile; fileRef = 3BFFA6FD621E9ED341AA89AEAC1604D7 /* PromiseKit.h */; settings = {ATTRIBUTES = (Public, ); }; }; + FA78EA5177275F71FD7F2C52F6B7518D /* PMKAlertController.swift in Sources */ = {isa = PBXBuildFile; fileRef = C731FBFCC690050C6C08E5AC9D9DC724 /* PMKAlertController.swift */; }; FC14480CECE872865A9C6E584F886DA3 /* Request.swift in Sources */ = {isa = PBXBuildFile; fileRef = 133C5287CFDCB3B67578A7B1221E132C /* Request.swift */; }; - FC574F2027A58666D90BE40CF7716309 /* NSURLConnection+Promise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 412985229DA7A4DF9E129B7E8F0C09BB /* NSURLConnection+Promise.swift */; }; - FD9BA35E0547A375AE7FCA49432C9C54 /* UIView+Promise.swift in Sources */ = {isa = PBXBuildFile; fileRef = E3CDA0958D6247505ECD9098D662EA74 /* UIView+Promise.swift */; }; FEF0D7653948988B804226129471C1EC /* Stream.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8A8F373B23E0F7FB68B0BA71D92D1C60 /* Stream.swift */; }; /* End PBXBuildFile section */ @@ -114,31 +117,24 @@ isa = PBXContainerItemProxy; containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; proxyType = 1; - remoteGlobalIDString = 9A0F758601B5E1ACBCB2624392B58BD1; + remoteGlobalIDString = E1B34E9A45508C6EDDA7F25D88C85434; remoteInfo = PetstoreClient; }; - 085169F5A412617F5AA660FCA8662D05 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; - proxyType = 1; - remoteGlobalIDString = 190ACD3A51BC90B85EADB13E9CDD207B; - remoteInfo = OMGHTTPURLRQ; - }; - 3C56ED43C177CB987DA7685FD87B4736 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; - proxyType = 1; - remoteGlobalIDString = FB594EEBD21FB1EF5B7508805A6F5D02; - remoteInfo = PromiseKit; - }; - 769630CDAAA8C24AA5B4C81A85C45AC8 /* PBXContainerItemProxy */ = { + 098BDC6B6850C9E726FB5016BB254FC7 /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; proxyType = 1; remoteGlobalIDString = 432ECC54282C84882B482CCB4CF227FC; remoteInfo = Alamofire; }; - 94CC4862E0BF723067DDE7ABACFC5AF0 /* PBXContainerItemProxy */ = { + 11BAC0C3DDD46F7C7EA2DE10681BBE09 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; + proxyType = 1; + remoteGlobalIDString = A348BE32D0894EA7204BDCB3F0DF636F; + remoteInfo = PromiseKit; + }; + 769630CDAAA8C24AA5B4C81A85C45AC8 /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; proxyType = 1; @@ -156,15 +152,22 @@ isa = PBXContainerItemProxy; containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; proxyType = 1; - remoteGlobalIDString = FB594EEBD21FB1EF5B7508805A6F5D02; + remoteGlobalIDString = A348BE32D0894EA7204BDCB3F0DF636F; remoteInfo = PromiseKit; }; + BAB3DC0D4AB6EA5B20F7BA63A3F779EC /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; + proxyType = 1; + remoteGlobalIDString = 190ACD3A51BC90B85EADB13E9CDD207B; + remoteInfo = OMGHTTPURLRQ; + }; /* End PBXContainerItemProxy section */ /* Begin PBXFileReference section */ 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 = ""; }; - 0A6DD0A2A0094280A4A78C9B772E3BAF /* ObjectReturn.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = ObjectReturn.swift; sourceTree = ""; }; + 094C870CE73CCEC940F4DA86D7FE0C30 /* UserAPI.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = UserAPI.swift; sourceTree = ""; }; 0A8906F6D6920DF197965D1740A7E283 /* Umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = Umbrella.h; path = Sources/Umbrella.h; sourceTree = ""; }; 0BA017E288BB42E06EBEE9C6E6993EAF /* UIViewController+AnyPromise.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "UIViewController+AnyPromise.h"; path = "Categories/UIKit/UIViewController+AnyPromise.h"; sourceTree = ""; }; 0F36B65CF990C57DC527824ED0BA1915 /* OMGHTTPURLRQ-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "OMGHTTPURLRQ-dummy.m"; sourceTree = ""; }; @@ -175,19 +178,19 @@ 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 = ""; }; + 1A44CBCE721F71F03C7758DB3F36CDFF /* PetAPI.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = PetAPI.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 = ""; }; - 1FE322C982813B48FD220881237FD90F /* Models.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Models.swift; sourceTree = ""; }; - 2001DB27FE23C000ACF411B329BC099F /* User.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = User.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 = ""; }; 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 = ""; }; - 28A3BBCDB687E9609F39F4EFC404B045 /* APIHelper.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = APIHelper.swift; sourceTree = ""; }; + 2B25BD9A4F08A3124D223BDB55576886 /* AlamofireImplementations.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = AlamofireImplementations.swift; sourceTree = ""; }; 2BCC458FDD5F692BBB2BFC64BB5701FC /* Pods-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Pods-umbrella.h"; 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 = ""; }; + 2F98C30F79A0AB5920FB4CDBB7413E5C /* Name.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Name.swift; sourceTree = ""; }; 30CE7341A995EF6812D71771E74CF7F7 /* Alamofire-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Alamofire-umbrella.h"; sourceTree = ""; }; 3530BF15E14D1F6D7134EE67377D5C8C /* OMGHTTPURLRQ.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = OMGHTTPURLRQ.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 3616971BAEF40302B7F2F8B1007C0B2B /* NSNotificationCenter+AnyPromise.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "NSNotificationCenter+AnyPromise.h"; path = "Categories/Foundation/NSNotificationCenter+AnyPromise.h"; sourceTree = ""; }; @@ -197,17 +200,13 @@ 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 = ""; }; 400A6910E83F606BCD67DC11FA706697 /* ServerTrustPolicy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ServerTrustPolicy.swift; path = Source/ServerTrustPolicy.swift; sourceTree = ""; }; - 40980C10A3E4CD8F73FEF4585BC9B273 /* Extensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Extensions.swift; sourceTree = ""; }; 412985229DA7A4DF9E129B7E8F0C09BB /* NSURLConnection+Promise.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "NSURLConnection+Promise.swift"; path = "Categories/Foundation/NSURLConnection+Promise.swift"; sourceTree = ""; }; 450166FEA2155A5821D97744A0127DF8 /* OMGHTTPURLRQ.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = OMGHTTPURLRQ.h; path = Sources/OMGHTTPURLRQ.h; sourceTree = ""; }; 46A8E0328DC896E0893B565FE8742167 /* PetstoreClient-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "PetstoreClient-dummy.m"; sourceTree = ""; }; 4798BAC01B0E3F07E3BBBB07BA57F2D7 /* NSNotificationCenter+AnyPromise.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "NSNotificationCenter+AnyPromise.m"; path = "Categories/Foundation/NSNotificationCenter+AnyPromise.m"; sourceTree = ""; }; - 511325F77CCC682529E5D61A5AA0B381 /* Order.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Order.swift; 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 = ""; }; - 54C7F7995EC233B46050D81ABA34442C /* Pet.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Pet.swift; sourceTree = ""; }; - 5559FBE62F3407535CE97AD320341ACC /* InlineResponse200.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = InlineResponse200.swift; sourceTree = ""; }; 558DFECE2C740177CA6357DA71A1DFBB /* Error.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Error.swift; path = Sources/Error.swift; sourceTree = ""; }; 5973BC143AE488C12FFB1E83E71F0C45 /* AnyPromise.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AnyPromise.swift; path = Sources/AnyPromise.swift; sourceTree = ""; }; 5A1DC80A0773C5A569348DC442EAFD1D /* UIKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = UIKit.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS9.0.sdk/System/Library/Frameworks/UIKit.framework; sourceTree = DEVELOPER_DIR; }; @@ -216,14 +215,16 @@ 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 = ""; }; 6AD59903FAA8315AD0036AC459FFB97F /* join.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = join.m; path = Sources/join.m; sourceTree = ""; }; - 6E25EC84C24B3AB284A71E47CB032082 /* UserAPI.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = UserAPI.swift; sourceTree = ""; }; - 75A581DA18EB8A9137C3A6FCB144D6EA /* StoreAPI.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = StoreAPI.swift; sourceTree = ""; }; + 6D0925CA00A7877078F60FAD44E2DD0F /* Category.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Category.swift; sourceTree = ""; }; + 71972929AF72164C887BB8F5F1059089 /* User.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = User.swift; sourceTree = ""; }; + 7220AB25575F15EB89521DFE33F4B764 /* APIs.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = APIs.swift; sourceTree = ""; }; + 780827122613E6D246695ADFAA7B28B6 /* Tag.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Tag.swift; sourceTree = ""; }; 792D14AC86CD98AA9C31373287E0F353 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; 79A9DEDC89FE8336BF5FEDAAF75BF7FC /* Pods.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = "sourcecode.module-map"; path = Pods.modulemap; sourceTree = ""; }; 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 = ""; }; + 84A386C655413763AEE8133A102DF2C8 /* Extensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Extensions.swift; sourceTree = ""; }; 8749F40CC17CE0C26C36B0F431A9C8F0 /* Alamofire.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = "sourcecode.module-map"; path = Alamofire.modulemap; sourceTree = ""; }; - 876669E4CF92F0757A01F74D0325057C /* Category.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Category.swift; sourceTree = ""; }; 87B213035BAC5F75386F62D3C75D2342 /* Pods-acknowledgements.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-acknowledgements.plist"; sourceTree = ""; }; 87BC7910B8D7D31310A07C32438A8C67 /* OMGUserAgent.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = OMGUserAgent.h; path = Sources/OMGUserAgent.h; sourceTree = ""; }; 894E5DA93A9F359521A89826BE6DA777 /* Pods-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Pods-dummy.m"; sourceTree = ""; }; @@ -233,21 +234,24 @@ 8DC63EB77B3791891517B98CAA115DE8 /* State.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = State.swift; path = Sources/State.swift; sourceTree = ""; }; 9042667D08D783E45394FE8B97EE6468 /* PromiseKit-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "PromiseKit-dummy.m"; sourceTree = ""; }; 92D340D66F03F31237B70F23FE9B00D0 /* UIAlertView+AnyPromise.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "UIAlertView+AnyPromise.h"; path = "Categories/UIKit/UIAlertView+AnyPromise.h"; sourceTree = ""; }; + 94FB3F3CEFBA56B306D034B69144C68E /* InlineResponse200.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = InlineResponse200.swift; sourceTree = ""; }; 9774D31336C85248A115B569E7D95283 /* UIActionSheet+AnyPromise.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "UIActionSheet+AnyPromise.m"; path = "Categories/UIKit/UIActionSheet+AnyPromise.m"; sourceTree = ""; }; 977577C045EDA9D9D1F46E2598D19FC7 /* Pods.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = Pods.debug.xcconfig; sourceTree = ""; }; 980FD13F87B44BFD90F8AC129BEB2E61 /* race.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = race.swift; path = Sources/race.swift; sourceTree = ""; }; 9D579267FC1F163C8F04B444DAEFED0D /* OMGHTTPURLRQ.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = OMGHTTPURLRQ.m; path = Sources/OMGHTTPURLRQ.m; sourceTree = ""; }; 9F681D2C508D1BA8F62893120D9343A4 /* PetstoreClient-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "PetstoreClient-umbrella.h"; sourceTree = ""; }; + A02D16E80C10DF32F2A88A66B83D7DD9 /* Model200Response.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Model200Response.swift; sourceTree = ""; }; A04177B09D9596450D827FE49A36C4C4 /* Download.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Download.swift; path = Source/Download.swift; 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; }; - A60C1B336FDA263A9AB0025BF89FF7D6 /* Tag.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Tag.swift; sourceTree = ""; }; + A27DF5A602B1BB474A141C895934F712 /* StoreAPI.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = StoreAPI.swift; sourceTree = ""; }; + A360D2EE0575D36C8C8459BCB8325D9A /* Models.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Models.swift; sourceTree = ""; }; + A4B4E403BC5209472D6DA0EEF82A8BD9 /* APIHelper.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = APIHelper.swift; sourceTree = ""; }; + A58E34C4DDB909B2CA900747C6691A5A /* ObjectReturn.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = ObjectReturn.swift; sourceTree = ""; }; 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 = ""; }; - B043AFA6B4E018E9989ED2EBED883492 /* SpecialModelName.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = SpecialModelName.swift; sourceTree = ""; }; - B0C04A06028D1D93105B1F69EE2C7311 /* APIs.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = APIs.swift; 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 = ""; }; @@ -255,9 +259,10 @@ BA6428E9F66FD5A23C0A2E06ED26CD2F /* Podfile */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; name = Podfile; path = ../Podfile; sourceTree = SOURCE_ROOT; xcLanguageSpecificationIdentifier = xcode.lang.ruby; }; BAE48ACA10E8895BB8BF5CE8C0846B4B /* NSURLConnection+AnyPromise.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "NSURLConnection+AnyPromise.h"; path = "Categories/Foundation/NSURLConnection+AnyPromise.h"; sourceTree = ""; }; BCDD82DB3E6D43BA9769FCA9B744CB5E /* UIView+AnyPromise.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "UIView+AnyPromise.h"; path = "Categories/UIKit/UIView+AnyPromise.h"; sourceTree = ""; }; - BE4F0EE7E4E76A7AC6932305A9A0A35A /* AlamofireImplementations.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = AlamofireImplementations.swift; sourceTree = ""; }; + BEA71A34D3031D95E61F1082A5BEEB7A /* ModelReturn.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = ModelReturn.swift; 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 = ""; }; + C909E10C22B35220020268EF2BF27E18 /* Pet.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Pet.swift; sourceTree = ""; }; CA1AD92813B887E2D017D051B8C0E3D2 /* Validation.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Validation.swift; path = Source/Validation.swift; sourceTree = ""; }; CA854180C132DB5511D64C82535C5FDE /* UIAlertView+Promise.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UIAlertView+Promise.swift"; path = "Categories/UIKit/UIAlertView+Promise.swift"; sourceTree = ""; }; CBC0F7C552B739C909B650A0F42F7F38 /* Pods-resources.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-resources.sh"; sourceTree = ""; }; @@ -265,7 +270,6 @@ CCE38472832BBCC541E646DA6C18EF9C /* Upload.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Upload.swift; path = Source/Upload.swift; sourceTree = ""; }; CDC4DD7DB9F4C34A288BECA73BC13B57 /* PromiseKit.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = "sourcecode.module-map"; path = PromiseKit.modulemap; sourceTree = ""; }; D0405803033A2A777B8E4DFA0C1800ED /* Pods-acknowledgements.markdown */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; path = "Pods-acknowledgements.markdown"; sourceTree = ""; }; - D04911F3B72D4F18187122A620682A84 /* PetAPI.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = PetAPI.swift; sourceTree = ""; }; D4248CF20178C57CEFEFAAF453C0DC75 /* PromiseKit.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = PromiseKit.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 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 = ""; }; @@ -280,10 +284,12 @@ E7F21354943D9F42A70697D5A5EF72E9 /* Pods-frameworks.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-frameworks.sh"; sourceTree = ""; }; E8446514FBAD26C0E18F24A5715AEF67 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; EBC4140FCBB5B4D3A955B1608C165C04 /* Alamofire.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Alamofire.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + EE5E0F8BA6AB1430D31588F5EB170889 /* Order.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Order.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 = ""; }; F0D4E00A8974E74325E9E53D456F9AD4 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; 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 = ""; }; + F7F371E5E2A26613C4DE253F4D7A3F56 /* SpecialModelName.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = SpecialModelName.swift; sourceTree = ""; }; FB15A61DB7ABCB74565286162157C5A0 /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS9.0.sdk/System/Library/Frameworks/Foundation.framework; sourceTree = DEVELOPER_DIR; }; FC4BF94DC4B3D8B88FC160B00931B0EC /* QuartzCore.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = QuartzCore.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS9.0.sdk/System/Library/Frameworks/QuartzCore.framework; sourceTree = DEVELOPER_DIR; }; FD558DDCDDA1B46951548B02C34277EF /* ResponseSerialization.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ResponseSerialization.swift; path = Source/ResponseSerialization.swift; sourceTree = ""; }; @@ -291,24 +297,13 @@ /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ - 38849761E5F4A894893A402F6D564927 /* Frameworks */ = { + 4B81AD7DF193F182592D3F3510F50796 /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - 1C8D5A3F181EE2797475BF8CD3D17FAB /* Foundation.framework in Frameworks */, - C1AC5BBB1762E93B083317C5E8A939DE /* OMGHTTPURLRQ.framework in Frameworks */, - 6756077354E35F7C661D714587C52F6B /* QuartzCore.framework in Frameworks */, - 56E4DB673DB3EAE8F31C5854581C9239 /* UIKit.framework in Frameworks */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - 7404DE837DAB14F44B0D18F88690804A /* Frameworks */ = { - isa = PBXFrameworksBuildPhase; - buildActionMask = 2147483647; - files = ( - 043AACBEFC1A58B79AF6B81C8E7E117E /* Alamofire.framework in Frameworks */, - 3365F629B3DD2CC5092161DADB5B24BA /* Foundation.framework in Frameworks */, - 9E339448B1EFC5B2112D847A766F844A /* PromiseKit.framework in Frameworks */, + E6FDE3505ED7CEF6B87500A5C52B7938 /* Alamofire.framework in Frameworks */, + DF8DB782B7C2F5EEC7F29E2E2A5F8154 /* Foundation.framework in Frameworks */, + 77F020B749274FC61FD1D5EA3FBBBE18 /* PromiseKit.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -328,6 +323,17 @@ ); runOnlyForDeploymentPostprocessing = 0; }; + C5452032741F5F809522C754A4393C4A /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 5849F4EAAAD24A116F0E0E948623AEC0 /* Foundation.framework in Frameworks */, + 0FFA3D017278D8EB24A9AC4780E3AFEC /* OMGHTTPURLRQ.framework in Frameworks */, + 09C9710BEE85A253331C8E0994FBB2BF /* QuartzCore.framework in Frameworks */, + 53FBECFDFCA1B755F2754C4DBC65E3D5 /* UIKit.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; FA26D2C7E461A1BBD50054579AFE2F7C /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; @@ -370,6 +376,20 @@ name = "Development Pods"; sourceTree = ""; }; + 2B28CE488E7531BE86FAB354C15AD30E /* Swaggers */ = { + isa = PBXGroup; + children = ( + 2B25BD9A4F08A3124D223BDB55576886 /* AlamofireImplementations.swift */, + A4B4E403BC5209472D6DA0EEF82A8BD9 /* APIHelper.swift */, + 7220AB25575F15EB89521DFE33F4B764 /* APIs.swift */, + 84A386C655413763AEE8133A102DF2C8 /* Extensions.swift */, + A360D2EE0575D36C8C8459BCB8325D9A /* Models.swift */, + ADCA66FBD4BDE0A0E2B51D3E13DCA949 /* APIs */, + 8781DE8648430F3693508310D0B40CA0 /* Models */, + ); + path = Swaggers; + sourceTree = ""; + }; 75D98FF52E597A11900E131B6C4E1ADA /* Pods */ = { isa = PBXGroup; children = ( @@ -404,21 +424,6 @@ name = Foundation; sourceTree = ""; }; - 788DC9779BF60419FE26A13FA7F62348 /* Models */ = { - isa = PBXGroup; - children = ( - 876669E4CF92F0757A01F74D0325057C /* Category.swift */, - 5559FBE62F3407535CE97AD320341ACC /* InlineResponse200.swift */, - 0A6DD0A2A0094280A4A78C9B772E3BAF /* ObjectReturn.swift */, - 511325F77CCC682529E5D61A5AA0B381 /* Order.swift */, - 54C7F7995EC233B46050D81ABA34442C /* Pet.swift */, - B043AFA6B4E018E9989ED2EBED883492 /* SpecialModelName.swift */, - A60C1B336FDA263A9AB0025BF89FF7D6 /* Tag.swift */, - 2001DB27FE23C000ACF411B329BC099F /* User.swift */, - ); - path = Models; - sourceTree = ""; - }; 7DB346D0F39D3F0E887471402A8071AB = { isa = PBXGroup; children = ( @@ -464,28 +469,22 @@ name = QuartzCore; sourceTree = ""; }; - 8598DF5E36C16045F5598501B66C2CCB /* APIs */ = { + 8781DE8648430F3693508310D0B40CA0 /* Models */ = { isa = PBXGroup; children = ( - D04911F3B72D4F18187122A620682A84 /* PetAPI.swift */, - 75A581DA18EB8A9137C3A6FCB144D6EA /* StoreAPI.swift */, - 6E25EC84C24B3AB284A71E47CB032082 /* UserAPI.swift */, + 6D0925CA00A7877078F60FAD44E2DD0F /* Category.swift */, + 94FB3F3CEFBA56B306D034B69144C68E /* InlineResponse200.swift */, + A02D16E80C10DF32F2A88A66B83D7DD9 /* Model200Response.swift */, + BEA71A34D3031D95E61F1082A5BEEB7A /* ModelReturn.swift */, + 2F98C30F79A0AB5920FB4CDBB7413E5C /* Name.swift */, + A58E34C4DDB909B2CA900747C6691A5A /* ObjectReturn.swift */, + EE5E0F8BA6AB1430D31588F5EB170889 /* Order.swift */, + C909E10C22B35220020268EF2BF27E18 /* Pet.swift */, + F7F371E5E2A26613C4DE253F4D7A3F56 /* SpecialModelName.swift */, + 780827122613E6D246695ADFAA7B28B6 /* Tag.swift */, + 71972929AF72164C887BB8F5F1059089 /* User.swift */, ); - path = APIs; - sourceTree = ""; - }; - 86A31D6593E5DF6FFDE3D3802AAAA862 /* Swaggers */ = { - isa = PBXGroup; - children = ( - BE4F0EE7E4E76A7AC6932305A9A0A35A /* AlamofireImplementations.swift */, - 28A3BBCDB687E9609F39F4EFC404B045 /* APIHelper.swift */, - B0C04A06028D1D93105B1F69EE2C7311 /* APIs.swift */, - 40980C10A3E4CD8F73FEF4585BC9B273 /* Extensions.swift */, - 1FE322C982813B48FD220881237FD90F /* Models.swift */, - 8598DF5E36C16045F5598501B66C2CCB /* APIs */, - 788DC9779BF60419FE26A13FA7F62348 /* Models */, - ); - path = Swaggers; + path = Models; sourceTree = ""; }; 8EA2A359F1831ACBB15BAAEA04D6FB95 /* UIKit */ = { @@ -579,11 +578,21 @@ AD94092456F8ABCB18F74CAC75AD85DE /* Classes */ = { isa = PBXGroup; children = ( - 86A31D6593E5DF6FFDE3D3802AAAA862 /* Swaggers */, + 2B28CE488E7531BE86FAB354C15AD30E /* Swaggers */, ); path = Classes; sourceTree = ""; }; + ADCA66FBD4BDE0A0E2B51D3E13DCA949 /* APIs */ = { + isa = PBXGroup; + children = ( + 1A44CBCE721F71F03C7758DB3F36CDFF /* PetAPI.swift */, + A27DF5A602B1BB474A141C895934F712 /* StoreAPI.swift */, + 094C870CE73CCEC940F4DA86D7FE0C30 /* UserAPI.swift */, + ); + path = APIs; + sourceTree = ""; + }; B7B80995527643776607AFFA75B91E24 /* Targets Support Files */ = { isa = PBXGroup; children = ( @@ -712,24 +721,6 @@ ); runOnlyForDeploymentPostprocessing = 0; }; - 8D247574BE8EE44D7F586F5EE3E64A71 /* Headers */ = { - isa = PBXHeadersBuildPhase; - buildActionMask = 2147483647; - files = ( - 6C835D49402A31D15D3D53439F607525 /* AnyPromise.h in Headers */, - CDFEEA22781236F07F32D6B739517178 /* CALayer+AnyPromise.h in Headers */, - A9DF4EE19A7494F3A91CE23C261FDE13 /* NSError+Cancellation.h in Headers */, - 774EB2064BFD3266EEF2B07905D9B0CF /* NSNotificationCenter+AnyPromise.h in Headers */, - E29B659D873F03F056C25D9B139CE225 /* NSURLConnection+AnyPromise.h in Headers */, - 920AD5E4875F89BE0B3413FA0946ACB4 /* PromiseKit.h in Headers */, - 74E7435F4420251677F0494908757D56 /* UIActionSheet+AnyPromise.h in Headers */, - F79E72246A63190A6B5E70F348E6670F /* UIAlertView+AnyPromise.h in Headers */, - DD324C55ECC625F8893C07BD52B67E99 /* UIView+AnyPromise.h in Headers */, - 0E84511CF3F1E8C48CCC75BA66EBE0BA /* UIViewController+AnyPromise.h in Headers */, - A4AE8E155661325CF82446A0FF242B07 /* Umbrella.h in Headers */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; 8EC2461DE4442A7991319873E6012164 /* Headers */ = { isa = PBXHeadersBuildPhase; buildActionMask = 2147483647; @@ -741,11 +732,29 @@ ); runOnlyForDeploymentPostprocessing = 0; }; - DB92AC3A884C820A686DDA31CFC1C325 /* Headers */ = { + A11C62D33B885E6DA9FECD0493A47746 /* Headers */ = { isa = PBXHeadersBuildPhase; buildActionMask = 2147483647; files = ( - 90E44B5F3E21A2420F481DB132E52684 /* PetstoreClient-umbrella.h in Headers */, + E6B182F5E233FB9F529BEFEAD3D02ACF /* AnyPromise.h in Headers */, + 2676E85B9644D55E25A31D3CE61A5726 /* CALayer+AnyPromise.h in Headers */, + 0D6DCC756D1B0B68ADB5F805D575BAB6 /* NSError+Cancellation.h in Headers */, + 1372840E154B63D17AACD1257C3E0520 /* NSNotificationCenter+AnyPromise.h in Headers */, + CCA3921F36A6B36DC1F993112BEF0602 /* NSURLConnection+AnyPromise.h in Headers */, + F8DAC10D25E6E36B83261AC032A77F1A /* PromiseKit.h in Headers */, + D55A97CF31106A21298F731FC890BCA1 /* UIActionSheet+AnyPromise.h in Headers */, + C96CB79BD56A7931541FC22617A2D613 /* UIAlertView+AnyPromise.h in Headers */, + 02D0672068E53F2D98CC67FBA5278022 /* UIView+AnyPromise.h in Headers */, + C04283A3B7479C8EDE2B95F4DDEE2C2C /* UIViewController+AnyPromise.h in Headers */, + AC30241BA84931703B312A09DD64C648 /* Umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + BE7D2FA2E9F1656CC6B0266B63C0D938 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 64739E341A52DFA48F4169E4322E7486 /* PetstoreClient-umbrella.h in Headers */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -807,43 +816,43 @@ productReference = D931A99C6B5A8E0F69C818C6ECC3C44F /* Pods.framework */; productType = "com.apple.product-type.framework"; }; - 9A0F758601B5E1ACBCB2624392B58BD1 /* PetstoreClient */ = { + A348BE32D0894EA7204BDCB3F0DF636F /* PromiseKit */ = { isa = PBXNativeTarget; - buildConfigurationList = 0481A4393EA0CC504EB6542154C8F7AE /* Build configuration list for PBXNativeTarget "PetstoreClient" */; + buildConfigurationList = 8567709BC3BD98E81A0E9B5AD85D011F /* Build configuration list for PBXNativeTarget "PromiseKit" */; buildPhases = ( - 44D324C6406A51269508FD8F254CF846 /* Sources */, - 7404DE837DAB14F44B0D18F88690804A /* Frameworks */, - DB92AC3A884C820A686DDA31CFC1C325 /* Headers */, + FCE6B9AB03DB341C5159F1510AAA9722 /* Sources */, + C5452032741F5F809522C754A4393C4A /* Frameworks */, + A11C62D33B885E6DA9FECD0493A47746 /* Headers */, ); buildRules = ( ); dependencies = ( - 0791AE80538B89D74023D1648662A746 /* PBXTargetDependency */, - 6D5049EB7DC059D4D2A0236320915EE8 /* PBXTargetDependency */, - ); - name = PetstoreClient; - productName = PetstoreClient; - productReference = E160B50E4D11692AA38E74C897D69C61 /* PetstoreClient.framework */; - productType = "com.apple.product-type.framework"; - }; - FB594EEBD21FB1EF5B7508805A6F5D02 /* PromiseKit */ = { - isa = PBXNativeTarget; - buildConfigurationList = F48703966D7224FCD529288B421CB38B /* Build configuration list for PBXNativeTarget "PromiseKit" */; - buildPhases = ( - 3F8ED5287F9952B5D94F0569303CB691 /* Sources */, - 38849761E5F4A894893A402F6D564927 /* Frameworks */, - 8D247574BE8EE44D7F586F5EE3E64A71 /* Headers */, - ); - buildRules = ( - ); - dependencies = ( - BBE09C7A178207CA23DF95EC1E858E78 /* PBXTargetDependency */, + DDA10AB05EE4CD847D1133226B79818E /* PBXTargetDependency */, ); name = PromiseKit; productName = PromiseKit; productReference = D4248CF20178C57CEFEFAAF453C0DC75 /* PromiseKit.framework */; productType = "com.apple.product-type.framework"; }; + E1B34E9A45508C6EDDA7F25D88C85434 /* PetstoreClient */ = { + isa = PBXNativeTarget; + buildConfigurationList = 715B91C131A5E33AED9768BD75742013 /* Build configuration list for PBXNativeTarget "PetstoreClient" */; + buildPhases = ( + A6723A33627D0A815D42193CACD7E74A /* Sources */, + 4B81AD7DF193F182592D3F3510F50796 /* Frameworks */, + BE7D2FA2E9F1656CC6B0266B63C0D938 /* Headers */, + ); + buildRules = ( + ); + dependencies = ( + 0D6B2D0CAE4FAFE97E7D7D0EC2C6DCE0 /* PBXTargetDependency */, + A102D2D546E8C75239F44407687481EE /* PBXTargetDependency */, + ); + name = PetstoreClient; + productName = PetstoreClient; + productReference = E160B50E4D11692AA38E74C897D69C61 /* PetstoreClient.framework */; + productType = "com.apple.product-type.framework"; + }; /* End PBXNativeTarget section */ /* Begin PBXProject section */ @@ -867,56 +876,14 @@ targets = ( 432ECC54282C84882B482CCB4CF227FC /* Alamofire */, 190ACD3A51BC90B85EADB13E9CDD207B /* OMGHTTPURLRQ */, - 9A0F758601B5E1ACBCB2624392B58BD1 /* PetstoreClient */, + E1B34E9A45508C6EDDA7F25D88C85434 /* PetstoreClient */, 7A5DBD588D2CC1C0CB1C42D4ED613FE4 /* Pods */, - FB594EEBD21FB1EF5B7508805A6F5D02 /* PromiseKit */, + A348BE32D0894EA7204BDCB3F0DF636F /* PromiseKit */, ); }; /* End PBXProject section */ /* Begin PBXSourcesBuildPhase section */ - 3F8ED5287F9952B5D94F0569303CB691 /* Sources */ = { - isa = PBXSourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - F4FE9A55D8791B871926069F21DCF818 /* after.m in Sources */, - 3FC49DA692C9A42F947C9F561D3CAF1D /* after.swift in Sources */, - 92D9F79E690C48BC3A1BE0C4D861E4B7 /* afterlife.swift in Sources */, - 2D9C89E698B7962248B91C84556B8521 /* AnyPromise.m in Sources */, - 3BEC62AF9DDCF822F1865057CF1D50A2 /* AnyPromise.swift in Sources */, - 24D2C12AA4466F61F04FB7136AF497CA /* CALayer+AnyPromise.m in Sources */, - 1478812AA43E16777600753CDF6ACE1F /* dispatch_promise.m in Sources */, - 06FD19EDA263742E49199D15FF81FFAA /* dispatch_promise.swift in Sources */, - 9FB7204EEC7DA5E6E0BB5826DAE8FA6F /* Error.swift in Sources */, - 95DFE0BD617B4C9A707D8D55CD2F6858 /* hang.m in Sources */, - 524CC219844C01E75355CACC63869C0D /* join.m in Sources */, - 94E9D5A7158985FA79136143BCA8E66E /* join.swift in Sources */, - DC5EC2239846C76B4CCC3EAD4B022B8D /* NSNotificationCenter+AnyPromise.m in Sources */, - 21FB1E69B7CC6FCCA95B3B7531378D84 /* NSNotificationCenter+Promise.swift in Sources */, - C320DDEFFEED8D4BB9EF3954D6FC8DE2 /* NSObject+Promise.swift in Sources */, - F300CE6E3C784F5DEB89BC29C4895DBE /* NSURLConnection+AnyPromise.m in Sources */, - FC574F2027A58666D90BE40CF7716309 /* NSURLConnection+Promise.swift in Sources */, - 36BC51A48A364E9D70DD4A12F1BFDC24 /* NSURLSession+Promise.swift in Sources */, - 0AC8F78F69436E83746D56B1963C7321 /* PMKAlertController.swift in Sources */, - 21FE4548D5605FFE12EFA269102C88E1 /* Promise+Properties.swift in Sources */, - 92DB5CB64170AA4B906B58018ADC9419 /* Promise.swift in Sources */, - 9D70DDC375D7119F81D3B5FA30F17D38 /* PromiseKit-dummy.m in Sources */, - D21F8EFE0A5E06F45D8C203FE583EF77 /* race.swift in Sources */, - C0FBBB8365C842ACBC9181264649DCC1 /* State.swift in Sources */, - 874DC0CE734CE6E3F54200621F9BECE5 /* UIActionSheet+AnyPromise.m in Sources */, - 287EC582989EE65F605374D6908AA35C /* UIActionSheet+Promise.swift in Sources */, - 11E1A6059DD32FBA0734660403713531 /* UIAlertView+AnyPromise.m in Sources */, - 732A5A91563E46475A3FBE7D28C942E3 /* UIAlertView+Promise.swift in Sources */, - 0DB1CFFE7FEC5667D7CD14C580D8AB8F /* UIView+AnyPromise.m in Sources */, - FD9BA35E0547A375AE7FCA49432C9C54 /* UIView+Promise.swift in Sources */, - 6C0758FA1866AFC3B001BCCE294DF971 /* UIViewController+AnyPromise.m in Sources */, - 61BB171AC3499F5339DEFFBB37E15E84 /* UIViewController+Promise.swift in Sources */, - 2D5C3B34453DDCB27D66B3D5BF82E831 /* URLDataPromise.swift in Sources */, - EE2920251312E2F32C421CD05ACF4DA4 /* when.m in Sources */, - 62F41914F8A9F9740EBBC8E412761EDB /* when.swift in Sources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; 44321F32F148EB47FF23494889576DF5 /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; @@ -928,30 +895,6 @@ ); runOnlyForDeploymentPostprocessing = 0; }; - 44D324C6406A51269508FD8F254CF846 /* Sources */ = { - isa = PBXSourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 6F676A66D92467D28EA52325927C5BC5 /* AlamofireImplementations.swift in Sources */, - 0B94E66F8539BBA52E693DAE322DCBAA /* APIHelper.swift in Sources */, - B68C4829A81227CAC51BC61F43D91445 /* APIs.swift in Sources */, - F2F841536DFF2E08BA87B09E1A62A15C /* Category.swift in Sources */, - B1931E222F0FF379FE4B14FC99171BF9 /* Extensions.swift in Sources */, - F0322283A43A3230AF9E1A363F5682AF /* InlineResponse200.swift in Sources */, - 23B39958BB2757E02093BEEFD900A50D /* Models.swift in Sources */, - E3A8BAEE55DCBC8D16D9210A78D5A200 /* ObjectReturn.swift in Sources */, - 07AA794848F8E6615B1DFD30673CE4EE /* Order.swift in Sources */, - 422EB81C476A49349CBD929094E659BE /* Pet.swift in Sources */, - 2B1CB7AD3BF6CCE951E9CA7080097081 /* PetAPI.swift in Sources */, - 4FBA897D5492D0DD3CB07502E2596F6A /* PetstoreClient-dummy.m in Sources */, - C7F1A5669CE3AAA90BF2B5CCA70F90F6 /* SpecialModelName.swift in Sources */, - C8F3620654924A2D88756CDCC5CCFB11 /* StoreAPI.swift in Sources */, - AF3198275DBC570992BA895FB8FAF293 /* Tag.swift in Sources */, - BC5E262FDC0CD0C1803EB715E2C48F52 /* User.swift in Sources */, - 293859B4A8F6053D41FC5A50FF268CFA /* UserAPI.swift in Sources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; 91F4D6732A1613C9660866E34445A67B /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; @@ -960,6 +903,33 @@ ); runOnlyForDeploymentPostprocessing = 0; }; + A6723A33627D0A815D42193CACD7E74A /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + C4688FFE2C4E161516878B521EF54FBE /* AlamofireImplementations.swift in Sources */, + B4FAA3F0ED04F0506E66FCD7141AD989 /* APIHelper.swift in Sources */, + B0FB5055748E072728CA7129C3CAA3C6 /* APIs.swift in Sources */, + 3D2B170AA3737444F26B0E07E1F5FEF1 /* Category.swift in Sources */, + 91DF85663A3771DCD35D0FF07135959B /* Extensions.swift in Sources */, + 57FB6BF21435F091D48B97DBD36E8C7B /* InlineResponse200.swift in Sources */, + AB06DA1AC0FA3BDF50BAAEBBD06AB46E /* Model200Response.swift in Sources */, + 9DA852770BE32039F2C21096F27872A0 /* ModelReturn.swift in Sources */, + 76FAA23C0A28ECF0BBF6A5C14203F414 /* Models.swift in Sources */, + 1B099FB3AA9A6794A3039899A6734205 /* Name.swift in Sources */, + 63F6FFAB2BCCD07FD3DF44086E11C8B0 /* ObjectReturn.swift in Sources */, + 0F816E94051557A7BA9BFA5B6B4A32A5 /* Order.swift in Sources */, + F8C6EBC22D97E301AA4EA4D04B3FC860 /* Pet.swift in Sources */, + 8ABFD5E4F7621D554DBB12C6472A8313 /* PetAPI.swift in Sources */, + 886AC602EE7FCFDCD2DCD470CCB41721 /* PetstoreClient-dummy.m in Sources */, + 167B939D70FE9AADBA03ABBBBA588B4B /* SpecialModelName.swift in Sources */, + 97A9635E99E7EB0F33260600E1AC82F6 /* StoreAPI.swift in Sources */, + 335F10113F178E8D2984BE0602A0DEED /* Tag.swift in Sources */, + D46A1F4211ACD4C9EF7726AFAD2609EA /* User.swift in Sources */, + F70B5EF0A4B94F8FF906073882DCDB78 /* UserAPI.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; EF659EFF40D426A3A32A82CDB98CC6EE /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; @@ -982,25 +952,67 @@ ); runOnlyForDeploymentPostprocessing = 0; }; + FCE6B9AB03DB341C5159F1510AAA9722 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 76171B607A443BE97E1DBBF6575CD558 /* after.m in Sources */, + 03790817CF6E76959C0F7E2D0734E9F6 /* after.swift in Sources */, + 4CE2B026C746F263F6B95534A35E76C0 /* afterlife.swift in Sources */, + F049FFBDC929BB045C2AEDF0ECABE513 /* AnyPromise.m in Sources */, + D854F67FD7486C6D25CA841C7D2D5030 /* AnyPromise.swift in Sources */, + 6EA827E0ECB8F7CC49F8B4C92A1D93FA /* CALayer+AnyPromise.m in Sources */, + E8DDC87F287107068FF40443CF059433 /* dispatch_promise.m in Sources */, + E93C3C3AABF32094F0D673E3EC3B2C20 /* dispatch_promise.swift in Sources */, + A2A8512E15D1A4B6DBD515D6144EC083 /* Error.swift in Sources */, + B72EE02E33CE31F594630D54EEEF9A15 /* hang.m in Sources */, + C95D8B9276E75DA8F6DECCDCE147C781 /* join.m in Sources */, + BFA18BBF784D749FE8BFA654088F3630 /* join.swift in Sources */, + D78AD94D0DBA6A1CC4E6673D2F14C832 /* NSNotificationCenter+AnyPromise.m in Sources */, + 0BA72DC6AB26C72EE080F8A08CE41643 /* NSNotificationCenter+Promise.swift in Sources */, + 435BD7136E0E174C6A8811D6C88DEAF2 /* NSObject+Promise.swift in Sources */, + 405F6EBE4BBAAC270AF1B97AFC5B0C16 /* NSURLConnection+AnyPromise.m in Sources */, + 36CDD7A6638E10B9107C74D9B75079F1 /* NSURLConnection+Promise.swift in Sources */, + 9254814FE352958B5270E874E5CCD394 /* NSURLSession+Promise.swift in Sources */, + FA78EA5177275F71FD7F2C52F6B7518D /* PMKAlertController.swift in Sources */, + 964EA2E9AA68D7D587ED15143FEC4BE5 /* Promise+Properties.swift in Sources */, + 222C92305B7AC5BB8E2ABAD182F50026 /* Promise.swift in Sources */, + EC5B36837863572EC400633CD2FFAF94 /* PromiseKit-dummy.m in Sources */, + B908D3F77F293FC72B20EEB48208F5C6 /* race.swift in Sources */, + 291E2518A9E470C2E9CE1B69C088C16F /* State.swift in Sources */, + 82B5B0FF21A9A28284AE7F1124199D3F /* UIActionSheet+AnyPromise.m in Sources */, + 0290D4A3795396ABBB81E632E5AADE3A /* UIActionSheet+Promise.swift in Sources */, + 42A66FBE567A7F5B2136FC56BFF4874A /* UIAlertView+AnyPromise.m in Sources */, + 08B247165C2A091EE24F79D73F8ABEC9 /* UIAlertView+Promise.swift in Sources */, + 19DAC977B6B3CBDC69EE2150BD0C1EF6 /* UIView+AnyPromise.m in Sources */, + 99710CDCDDFF9ED74B8E01EB8E4BF563 /* UIView+Promise.swift in Sources */, + 5EADA3CE22BF3B74E759F948DE7A66F1 /* UIViewController+AnyPromise.m in Sources */, + E6810077387057466534FD27AA294211 /* UIViewController+Promise.swift in Sources */, + 37027676CEABF1BF753684A06C2DCDDB /* URLDataPromise.swift in Sources */, + BF2A197091B6FC0646CFA61A5FBE66AF /* when.m in Sources */, + 4EAB3713B40959FB2E0CDEAC8BDE1116 /* when.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; /* End PBXSourcesBuildPhase section */ /* Begin PBXTargetDependency section */ - 0791AE80538B89D74023D1648662A746 /* PBXTargetDependency */ = { + 0D6B2D0CAE4FAFE97E7D7D0EC2C6DCE0 /* PBXTargetDependency */ = { isa = PBXTargetDependency; name = Alamofire; target = 432ECC54282C84882B482CCB4CF227FC /* Alamofire */; - targetProxy = 94CC4862E0BF723067DDE7ABACFC5AF0 /* PBXContainerItemProxy */; + targetProxy = 098BDC6B6850C9E726FB5016BB254FC7 /* PBXContainerItemProxy */; }; 2673248EF608AB8375FABCFDA8141072 /* PBXTargetDependency */ = { isa = PBXTargetDependency; name = PetstoreClient; - target = 9A0F758601B5E1ACBCB2624392B58BD1 /* PetstoreClient */; + target = E1B34E9A45508C6EDDA7F25D88C85434 /* PetstoreClient */; targetProxy = 014385BD85FA83B60A03ADE9E8844F33 /* PBXContainerItemProxy */; }; 5433AD51A3DC696530C96B8A7D78ED7D /* PBXTargetDependency */ = { isa = PBXTargetDependency; name = PromiseKit; - target = FB594EEBD21FB1EF5B7508805A6F5D02 /* PromiseKit */; + target = A348BE32D0894EA7204BDCB3F0DF636F /* PromiseKit */; targetProxy = B5FB8931CDF8801206EDD2FEF94793BF /* PBXContainerItemProxy */; }; 64142DAEC5D96F7E876BBE00917C0E9D /* PBXTargetDependency */ = { @@ -1009,17 +1021,17 @@ target = 432ECC54282C84882B482CCB4CF227FC /* Alamofire */; targetProxy = 769630CDAAA8C24AA5B4C81A85C45AC8 /* PBXContainerItemProxy */; }; - 6D5049EB7DC059D4D2A0236320915EE8 /* PBXTargetDependency */ = { + A102D2D546E8C75239F44407687481EE /* PBXTargetDependency */ = { isa = PBXTargetDependency; name = PromiseKit; - target = FB594EEBD21FB1EF5B7508805A6F5D02 /* PromiseKit */; - targetProxy = 3C56ED43C177CB987DA7685FD87B4736 /* PBXContainerItemProxy */; + target = A348BE32D0894EA7204BDCB3F0DF636F /* PromiseKit */; + targetProxy = 11BAC0C3DDD46F7C7EA2DE10681BBE09 /* PBXContainerItemProxy */; }; - BBE09C7A178207CA23DF95EC1E858E78 /* PBXTargetDependency */ = { + DDA10AB05EE4CD847D1133226B79818E /* PBXTargetDependency */ = { isa = PBXTargetDependency; name = OMGHTTPURLRQ; target = 190ACD3A51BC90B85EADB13E9CDD207B /* OMGHTTPURLRQ */; - targetProxy = 085169F5A412617F5AA660FCA8662D05 /* PBXContainerItemProxy */; + targetProxy = BAB3DC0D4AB6EA5B20F7BA63A3F779EC /* PBXContainerItemProxy */; }; F74DEE1C89F05CC835997330B0E3B7C1 /* PBXTargetDependency */ = { isa = PBXTargetDependency; @@ -1030,33 +1042,6 @@ /* End PBXTargetDependency section */ /* Begin XCBuildConfiguration section */ - 03999803391289FE0834D6CBC3E2921D /* Release */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = CC49FF2A84C0E0E9349747D94036B728 /* PromiseKit.xcconfig */; - buildSettings = { - "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; - CURRENT_PROJECT_VERSION = 1; - DEFINES_MODULE = YES; - DYLIB_COMPATIBILITY_VERSION = 1; - DYLIB_CURRENT_VERSION = 1; - DYLIB_INSTALL_NAME_BASE = "@rpath"; - ENABLE_STRICT_OBJC_MSGSEND = YES; - GCC_PREFIX_HEADER = "Target Support Files/PromiseKit/PromiseKit-prefix.pch"; - INFOPLIST_FILE = "Target Support Files/PromiseKit/Info.plist"; - INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - IPHONEOS_DEPLOYMENT_TARGET = 9.2; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; - MODULEMAP_FILE = "Target Support Files/PromiseKit/PromiseKit.modulemap"; - MTL_ENABLE_DEBUG_INFO = NO; - PRODUCT_NAME = PromiseKit; - SDKROOT = iphoneos; - SKIP_INSTALL = YES; - TARGETED_DEVICE_FAMILY = "1,2"; - VERSIONING_SYSTEM = "apple-generic"; - VERSION_INFO_PREFIX = ""; - }; - name = Release; - }; 0D12EBEB35AC8FA740B275C8105F9152 /* Release */ = { isa = XCBuildConfiguration; baseConfigurationReference = 141F0B43C42CE92856BBA8F8D98481DB /* Alamofire.xcconfig */; @@ -1143,7 +1128,7 @@ }; name = Debug; }; - 331BDA95D137A77409EE2678EFFC5790 /* Release */ = { + 3BDAD538EAD1230A7FDC1A3BD8F3005E /* Release */ = { isa = XCBuildConfiguration; baseConfigurationReference = DADAB10704E49D6B9E18F59F995BB88F /* PetstoreClient.xcconfig */; buildSettings = { @@ -1197,6 +1182,33 @@ }; name = Release; }; + 79AE81D89452EFFAB0143A9C7CD108DC /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = CC49FF2A84C0E0E9349747D94036B728 /* PromiseKit.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_PREFIX_HEADER = "Target Support Files/PromiseKit/PromiseKit-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/PromiseKit/Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 9.2; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + MODULEMAP_FILE = "Target Support Files/PromiseKit/PromiseKit.modulemap"; + MTL_ENABLE_DEBUG_INFO = NO; + PRODUCT_NAME = PromiseKit; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; 819D3D3D508154D9CFF3CE30C13E000E /* Debug */ = { isa = XCBuildConfiguration; baseConfigurationReference = 16D7C901D915C251DEBA27AC1EF57E34 /* OMGHTTPURLRQ.xcconfig */; @@ -1263,7 +1275,7 @@ }; name = Debug; }; - A290B7D0BE49A98C009A6FC59BDF65F1 /* Debug */ = { + B11D8789540F26AC42B990A7825BC01A /* Debug */ = { isa = XCBuildConfiguration; baseConfigurationReference = DADAB10704E49D6B9E18F59F995BB88F /* PetstoreClient.xcconfig */; buildSettings = { @@ -1291,7 +1303,7 @@ }; name = Debug; }; - C47FA3DFC99B853D3A46E60927179D9A /* Debug */ = { + BBB0CFD9A19744A94202BA4ADC92A507 /* Debug */ = { isa = XCBuildConfiguration; baseConfigurationReference = CC49FF2A84C0E0E9349747D94036B728 /* PromiseKit.xcconfig */; buildSettings = { @@ -1386,15 +1398,6 @@ /* End XCBuildConfiguration section */ /* Begin XCConfigurationList section */ - 0481A4393EA0CC504EB6542154C8F7AE /* Build configuration list for PBXNativeTarget "PetstoreClient" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - A290B7D0BE49A98C009A6FC59BDF65F1 /* Debug */, - 331BDA95D137A77409EE2678EFFC5790 /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; 2D8E8EC45A3A1A1D94AE762CB5028504 /* Build configuration list for PBXProject "Pods" */ = { isa = XCConfigurationList; buildConfigurations = ( @@ -1413,6 +1416,24 @@ defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; + 715B91C131A5E33AED9768BD75742013 /* Build configuration list for PBXNativeTarget "PetstoreClient" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + B11D8789540F26AC42B990A7825BC01A /* Debug */, + 3BDAD538EAD1230A7FDC1A3BD8F3005E /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 8567709BC3BD98E81A0E9B5AD85D011F /* Build configuration list for PBXNativeTarget "PromiseKit" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + BBB0CFD9A19744A94202BA4ADC92A507 /* Debug */, + 79AE81D89452EFFAB0143A9C7CD108DC /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; 8B2B2DA2F7F80D41B1FDB5FACFA4B3DE /* Build configuration list for PBXNativeTarget "Alamofire" */ = { isa = XCConfigurationList; buildConfigurations = ( @@ -1431,15 +1452,6 @@ defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; - F48703966D7224FCD529288B421CB38B /* Build configuration list for PBXNativeTarget "PromiseKit" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - C47FA3DFC99B853D3A46E60927179D9A /* Debug */, - 03999803391289FE0834D6CBC3E2921D /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; /* End XCConfigurationList section */ }; rootObject = D41D8CD98F00B204E9800998ECF8427E /* Project object */; diff --git a/samples/client/petstore/swift/SwaggerClientTests/SwaggerClient/Assets.xcassets/AppIcon.appiconset/Contents.json b/samples/client/petstore/swift/SwaggerClientTests/SwaggerClient/Assets.xcassets/AppIcon.appiconset/Contents.json index 36d2c80d889..eeea76c2db5 100644 --- a/samples/client/petstore/swift/SwaggerClientTests/SwaggerClient/Assets.xcassets/AppIcon.appiconset/Contents.json +++ b/samples/client/petstore/swift/SwaggerClientTests/SwaggerClient/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -59,6 +59,11 @@ "idiom" : "ipad", "size" : "76x76", "scale" : "2x" + }, + { + "idiom" : "ipad", + "size" : "83.5x83.5", + "scale" : "2x" } ], "info" : { diff --git a/samples/client/petstore/swift/git_push.sh b/samples/client/petstore/swift/git_push.sh new file mode 100644 index 00000000000..1a36388db02 --- /dev/null +++ b/samples/client/petstore/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="YOUR_GIT_USR_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="YOUR_GIT_REPO_ID" + 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/typescript-angular/API/Client/InlineResponse200.ts b/samples/client/petstore/typescript-angular/API/Client/InlineResponse200.ts new file mode 100644 index 00000000000..079eac61bc6 --- /dev/null +++ b/samples/client/petstore/typescript-angular/API/Client/InlineResponse200.ts @@ -0,0 +1,32 @@ +/// + +namespace API.Client { + 'use strict'; + + export interface InlineResponse200 { + + "tags"?: Array; + + "id": number; + + "category"?: any; + + /** + * pet status in the store + */ + "status"?: InlineResponse200.StatusEnum; + + "name"?: string; + + "photoUrls"?: Array; + } + + export namespace InlineResponse200 { + + export enum StatusEnum { + available = 'available', + pending = 'pending', + sold = 'sold' + } + } +} diff --git a/samples/client/petstore/typescript-angular/API/Client/Model200Response.ts b/samples/client/petstore/typescript-angular/API/Client/Model200Response.ts new file mode 100644 index 00000000000..ef34114f4a3 --- /dev/null +++ b/samples/client/petstore/typescript-angular/API/Client/Model200Response.ts @@ -0,0 +1,11 @@ +/// + +namespace API.Client { + 'use strict'; + + export interface Model200Response { + + "name"?: number; + } + +} diff --git a/samples/client/petstore/typescript-angular/API/Client/ModelReturn.ts b/samples/client/petstore/typescript-angular/API/Client/ModelReturn.ts new file mode 100644 index 00000000000..c147566cf47 --- /dev/null +++ b/samples/client/petstore/typescript-angular/API/Client/ModelReturn.ts @@ -0,0 +1,11 @@ +/// + +namespace API.Client { + 'use strict'; + + export interface ModelReturn { + + "return"?: number; + } + +} diff --git a/samples/client/petstore/typescript-angular/API/Client/Name.ts b/samples/client/petstore/typescript-angular/API/Client/Name.ts new file mode 100644 index 00000000000..9277422d52f --- /dev/null +++ b/samples/client/petstore/typescript-angular/API/Client/Name.ts @@ -0,0 +1,11 @@ +/// + +namespace API.Client { + 'use strict'; + + export interface Name { + + "name"?: number; + } + +} diff --git a/samples/client/petstore/typescript-angular/API/Client/PetApi.ts b/samples/client/petstore/typescript-angular/API/Client/PetApi.ts index 98a18b1124f..d11e0d780ed 100644 --- a/samples/client/petstore/typescript-angular/API/Client/PetApi.ts +++ b/samples/client/petstore/typescript-angular/API/Client/PetApi.ts @@ -27,17 +27,17 @@ namespace API.Client { } /** - * Update an existing pet + * Add a new pet to the store * * @param body Pet object that needs to be added to the store */ - public updatePet (body?: Pet, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { + public addPet (body?: Pet, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { const localVarPath = this.basePath + '/pet'; let queryParameters: any = {}; let headerParams: any = this.extendObj({}, this.defaultHeaders); let httpRequestParams: any = { - method: 'PUT', + method: 'POST', url: localVarPath, json: true, data: body, @@ -54,12 +54,12 @@ namespace API.Client { return this.$http(httpRequestParams); } /** - * Add a new pet to the store + * Fake endpoint to test byte array in body parameter for adding a new pet to the store * - * @param body Pet object that needs to be added to the store + * @param body Pet object in the form of byte array */ - public addPet (body?: Pet, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { - const localVarPath = this.basePath + '/pet'; + public addPetUsingByteArray (body?: string, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { + const localVarPath = this.basePath + '/pet?testing_byte_array=true'; let queryParameters: any = {}; let headerParams: any = this.extendObj({}, this.defaultHeaders); @@ -80,6 +80,40 @@ namespace API.Client { return this.$http(httpRequestParams); } + /** + * Deletes a pet + * + * @param petId Pet id to delete + * @param apiKey + */ + public deletePet (petId: number, apiKey?: string, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { + const localVarPath = this.basePath + '/pet/{petId}' + .replace('{' + 'petId' + '}', String(petId)); + + let queryParameters: any = {}; + let headerParams: any = this.extendObj({}, this.defaultHeaders); + // verify required parameter 'petId' is set + if (!petId) { + throw new Error('Missing required parameter petId when calling deletePet'); + } + headerParams['api_key'] = apiKey; + + let httpRequestParams: any = { + method: 'DELETE', + url: localVarPath, + json: true, + + + params: queryParameters, + headers: headerParams + }; + + if (extraHttpRequestParams) { + httpRequestParams = this.extendObj(httpRequestParams, extraHttpRequestParams); + } + + return this.$http(httpRequestParams); + } /** * Finds Pets by status * Multiple status values can be provided with comma separated strings @@ -171,6 +205,95 @@ namespace API.Client { return this.$http(httpRequestParams); } + /** + * Fake endpoint to test inline arbitrary object return by 'Find pet by ID' + * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + * @param petId ID of pet that needs to be fetched + */ + public getPetByIdInObject (petId: number, extraHttpRequestParams?: any ) : ng.IHttpPromise { + const localVarPath = this.basePath + '/pet/{petId}?response=inline_arbitrary_object' + .replace('{' + 'petId' + '}', String(petId)); + + let queryParameters: any = {}; + let headerParams: any = this.extendObj({}, this.defaultHeaders); + // verify required parameter 'petId' is set + if (!petId) { + throw new Error('Missing required parameter petId when calling getPetByIdInObject'); + } + let httpRequestParams: any = { + method: 'GET', + url: localVarPath, + json: true, + + + params: queryParameters, + headers: headerParams + }; + + if (extraHttpRequestParams) { + httpRequestParams = this.extendObj(httpRequestParams, extraHttpRequestParams); + } + + return this.$http(httpRequestParams); + } + /** + * Fake endpoint to test byte array return by 'Find pet by ID' + * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + * @param petId ID of pet that needs to be fetched + */ + public petPetIdtestingByteArraytrueGet (petId: number, extraHttpRequestParams?: any ) : ng.IHttpPromise { + const localVarPath = this.basePath + '/pet/{petId}?testing_byte_array=true' + .replace('{' + 'petId' + '}', String(petId)); + + let queryParameters: any = {}; + let headerParams: any = this.extendObj({}, this.defaultHeaders); + // verify required parameter 'petId' is set + if (!petId) { + throw new Error('Missing required parameter petId when calling petPetIdtestingByteArraytrueGet'); + } + let httpRequestParams: any = { + method: 'GET', + url: localVarPath, + json: true, + + + params: queryParameters, + headers: headerParams + }; + + if (extraHttpRequestParams) { + httpRequestParams = this.extendObj(httpRequestParams, extraHttpRequestParams); + } + + return this.$http(httpRequestParams); + } + /** + * Update an existing pet + * + * @param body Pet object that needs to be added to the store + */ + public updatePet (body?: Pet, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { + const localVarPath = this.basePath + '/pet'; + + let queryParameters: any = {}; + let headerParams: any = this.extendObj({}, this.defaultHeaders); + let httpRequestParams: any = { + method: 'PUT', + url: localVarPath, + json: true, + data: body, + + + params: queryParameters, + headers: headerParams + }; + + if (extraHttpRequestParams) { + httpRequestParams = this.extendObj(httpRequestParams, extraHttpRequestParams); + } + + return this.$http(httpRequestParams); + } /** * Updates a pet in the store with form data * @@ -213,40 +336,6 @@ namespace API.Client { return this.$http(httpRequestParams); } - /** - * Deletes a pet - * - * @param petId Pet id to delete - * @param apiKey - */ - public deletePet (petId: number, apiKey?: string, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { - const localVarPath = this.basePath + '/pet/{petId}' - .replace('{' + 'petId' + '}', String(petId)); - - let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); - // verify required parameter 'petId' is set - if (!petId) { - throw new Error('Missing required parameter petId when calling deletePet'); - } - headerParams['api_key'] = apiKey; - - let httpRequestParams: any = { - method: 'DELETE', - url: localVarPath, - json: true, - - - params: queryParameters, - headers: headerParams - }; - - if (extraHttpRequestParams) { - httpRequestParams = this.extendObj(httpRequestParams, extraHttpRequestParams); - } - - return this.$http(httpRequestParams); - } /** * uploads an image * @@ -287,64 +376,6 @@ namespace API.Client { httpRequestParams = this.extendObj(httpRequestParams, extraHttpRequestParams); } - return this.$http(httpRequestParams); - } - /** - * Fake endpoint to test byte array return by 'Find pet by ID' - * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions - * @param petId ID of pet that needs to be fetched - */ - public petPetIdtestingByteArraytrueGet (petId: number, extraHttpRequestParams?: any ) : ng.IHttpPromise { - const localVarPath = this.basePath + '/pet/{petId}?testing_byte_array=true' - .replace('{' + 'petId' + '}', String(petId)); - - let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); - // verify required parameter 'petId' is set - if (!petId) { - throw new Error('Missing required parameter petId when calling petPetIdtestingByteArraytrueGet'); - } - let httpRequestParams: any = { - method: 'GET', - url: localVarPath, - json: true, - - - params: queryParameters, - headers: headerParams - }; - - if (extraHttpRequestParams) { - httpRequestParams = this.extendObj(httpRequestParams, extraHttpRequestParams); - } - - return this.$http(httpRequestParams); - } - /** - * Fake endpoint to test byte array in body parameter for adding a new pet to the store - * - * @param body Pet object in the form of byte array - */ - public addPetUsingByteArray (body?: string, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { - const localVarPath = this.basePath + '/pet?testing_byte_array=true'; - - let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); - let httpRequestParams: any = { - method: 'POST', - url: localVarPath, - json: true, - data: body, - - - params: queryParameters, - headers: headerParams - }; - - if (extraHttpRequestParams) { - httpRequestParams = this.extendObj(httpRequestParams, extraHttpRequestParams); - } - return this.$http(httpRequestParams); } } diff --git a/samples/client/petstore/typescript-angular/API/Client/SpecialModelName.ts b/samples/client/petstore/typescript-angular/API/Client/SpecialModelName.ts new file mode 100644 index 00000000000..550ab8cd008 --- /dev/null +++ b/samples/client/petstore/typescript-angular/API/Client/SpecialModelName.ts @@ -0,0 +1,11 @@ +/// + +namespace API.Client { + 'use strict'; + + export interface SpecialModelName { + + "$Special[propertyName]"?: number; + } + +} diff --git a/samples/client/petstore/typescript-angular/API/Client/StoreApi.ts b/samples/client/petstore/typescript-angular/API/Client/StoreApi.ts index 7c9115fbe8f..193e12fe5e5 100644 --- a/samples/client/petstore/typescript-angular/API/Client/StoreApi.ts +++ b/samples/client/petstore/typescript-angular/API/Client/StoreApi.ts @@ -26,6 +26,37 @@ namespace API.Client { return objA; } + /** + * Delete purchase order by ID + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * @param orderId ID of the order that needs to be deleted + */ + public deleteOrder (orderId: string, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { + const localVarPath = this.basePath + '/store/order/{orderId}' + .replace('{' + 'orderId' + '}', String(orderId)); + + let queryParameters: any = {}; + let headerParams: any = this.extendObj({}, this.defaultHeaders); + // verify required parameter 'orderId' is set + if (!orderId) { + throw new Error('Missing required parameter orderId when calling deleteOrder'); + } + let httpRequestParams: any = { + method: 'DELETE', + url: localVarPath, + json: true, + + + params: queryParameters, + headers: headerParams + }; + + if (extraHttpRequestParams) { + httpRequestParams = this.extendObj(httpRequestParams, extraHttpRequestParams); + } + + return this.$http(httpRequestParams); + } /** * Finds orders by status * A single status value can be provided as a string @@ -82,20 +113,18 @@ namespace API.Client { return this.$http(httpRequestParams); } /** - * Place an order for a pet - * - * @param body order placed for purchasing the pet + * Fake endpoint to test arbitrary object return by 'Get inventory' + * Returns an arbitrary object which is actually a map of status codes to quantities */ - public placeOrder (body?: Order, extraHttpRequestParams?: any ) : ng.IHttpPromise { - const localVarPath = this.basePath + '/store/order'; + public getInventoryInObject (extraHttpRequestParams?: any ) : ng.IHttpPromise { + const localVarPath = this.basePath + '/store/inventory?response=arbitrary_object'; let queryParameters: any = {}; let headerParams: any = this.extendObj({}, this.defaultHeaders); let httpRequestParams: any = { - method: 'POST', + method: 'GET', url: localVarPath, json: true, - data: body, params: queryParameters, @@ -140,24 +169,20 @@ namespace API.Client { return this.$http(httpRequestParams); } /** - * 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 + * Place an order for a pet + * + * @param body order placed for purchasing the pet */ - public deleteOrder (orderId: string, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { - const localVarPath = this.basePath + '/store/order/{orderId}' - .replace('{' + 'orderId' + '}', String(orderId)); + public placeOrder (body?: Order, extraHttpRequestParams?: any ) : ng.IHttpPromise { + const localVarPath = this.basePath + '/store/order'; let queryParameters: any = {}; let headerParams: any = this.extendObj({}, this.defaultHeaders); - // verify required parameter 'orderId' is set - if (!orderId) { - throw new Error('Missing required parameter orderId when calling deleteOrder'); - } let httpRequestParams: any = { - method: 'DELETE', + method: 'POST', url: localVarPath, json: true, + data: body, params: queryParameters, diff --git a/samples/client/petstore/typescript-angular/API/Client/UserApi.ts b/samples/client/petstore/typescript-angular/API/Client/UserApi.ts index 719085a63ac..c1111e146ad 100644 --- a/samples/client/petstore/typescript-angular/API/Client/UserApi.ts +++ b/samples/client/petstore/typescript-angular/API/Client/UserApi.ts @@ -107,6 +107,68 @@ namespace API.Client { return this.$http(httpRequestParams); } + /** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted + */ + public deleteUser (username: string, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { + const localVarPath = this.basePath + '/user/{username}' + .replace('{' + 'username' + '}', String(username)); + + let queryParameters: any = {}; + let headerParams: any = this.extendObj({}, this.defaultHeaders); + // verify required parameter 'username' is set + if (!username) { + throw new Error('Missing required parameter username when calling deleteUser'); + } + let httpRequestParams: any = { + method: 'DELETE', + url: localVarPath, + json: true, + + + params: queryParameters, + headers: headerParams + }; + + if (extraHttpRequestParams) { + httpRequestParams = this.extendObj(httpRequestParams, extraHttpRequestParams); + } + + return this.$http(httpRequestParams); + } + /** + * Get user by user name + * + * @param username The name that needs to be fetched. Use user1 for testing. + */ + public getUserByName (username: string, extraHttpRequestParams?: any ) : ng.IHttpPromise { + const localVarPath = this.basePath + '/user/{username}' + .replace('{' + 'username' + '}', String(username)); + + let queryParameters: any = {}; + let headerParams: any = this.extendObj({}, this.defaultHeaders); + // verify required parameter 'username' is set + if (!username) { + throw new Error('Missing required parameter username when calling getUserByName'); + } + let httpRequestParams: any = { + method: 'GET', + url: localVarPath, + json: true, + + + params: queryParameters, + headers: headerParams + }; + + if (extraHttpRequestParams) { + httpRequestParams = this.extendObj(httpRequestParams, extraHttpRequestParams); + } + + return this.$http(httpRequestParams); + } /** * Logs user into the system * @@ -167,37 +229,6 @@ namespace API.Client { return this.$http(httpRequestParams); } - /** - * Get user by user name - * - * @param username The name that needs to be fetched. Use user1 for testing. - */ - public getUserByName (username: string, extraHttpRequestParams?: any ) : ng.IHttpPromise { - const localVarPath = this.basePath + '/user/{username}' - .replace('{' + 'username' + '}', String(username)); - - let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); - // verify required parameter 'username' is set - if (!username) { - throw new Error('Missing required parameter username when calling getUserByName'); - } - let httpRequestParams: any = { - method: 'GET', - url: localVarPath, - json: true, - - - params: queryParameters, - headers: headerParams - }; - - if (extraHttpRequestParams) { - httpRequestParams = this.extendObj(httpRequestParams, extraHttpRequestParams); - } - - return this.$http(httpRequestParams); - } /** * Updated user * This can only be done by the logged in user. @@ -229,37 +260,6 @@ namespace API.Client { httpRequestParams = this.extendObj(httpRequestParams, extraHttpRequestParams); } - return this.$http(httpRequestParams); - } - /** - * Delete user - * This can only be done by the logged in user. - * @param username The name that needs to be deleted - */ - public deleteUser (username: string, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { - const localVarPath = this.basePath + '/user/{username}' - .replace('{' + 'username' + '}', String(username)); - - let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); - // verify required parameter 'username' is set - if (!username) { - throw new Error('Missing required parameter username when calling deleteUser'); - } - let httpRequestParams: any = { - method: 'DELETE', - url: localVarPath, - json: true, - - - params: queryParameters, - headers: headerParams - }; - - if (extraHttpRequestParams) { - httpRequestParams = this.extendObj(httpRequestParams, extraHttpRequestParams); - } - return this.$http(httpRequestParams); } } diff --git a/samples/client/petstore/typescript-angular/API/Client/api.d.ts b/samples/client/petstore/typescript-angular/API/Client/api.d.ts index 19c60623dc9..c9e5e7a2f57 100644 --- a/samples/client/petstore/typescript-angular/API/Client/api.d.ts +++ b/samples/client/petstore/typescript-angular/API/Client/api.d.ts @@ -1,9 +1,14 @@ -/// /// -/// -/// +/// +/// +/// +/// /// +/// +/// +/// +/// -/// /// /// +/// diff --git a/samples/client/petstore/typescript-angular/git_push.sh b/samples/client/petstore/typescript-angular/git_push.sh new file mode 100644 index 00000000000..1a36388db02 --- /dev/null +++ b/samples/client/petstore/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="YOUR_GIT_USR_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="YOUR_GIT_REPO_ID" + 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/typescript-node/api.ts b/samples/client/petstore/typescript-node/api.ts index 8acf6f06000..3020e77491c 100644 --- a/samples/client/petstore/typescript-node/api.ts +++ b/samples/client/petstore/typescript-node/api.ts @@ -8,47 +8,40 @@ import http = require('http'); /* tslint:disable:no-unused-variable */ -export class User { - "id": number; - "username": string; - "firstName": string; - "lastName": string; - "email": string; - "password": string; - "phone": string; - /** - * User Status - */ - "userStatus": number; -} - export class Category { "id": number; "name": string; } -export class Pet { - "id": number; - "category": Category; - "name": string; - "photoUrls": Array; +export class InlineResponse200 { "tags": Array; + "id": number; + "category": any; /** * pet status in the store */ - "status": Pet.StatusEnum; + "status": InlineResponse200.StatusEnum; + "name": string; + "photoUrls": Array; } -export namespace Pet { +export namespace InlineResponse200 { export enum StatusEnum { available = 'available', pending = 'pending', sold = 'sold' } } -export class Tag { - "id": number; - "name": string; +export class Model200Response { + "name": number; +} + +export class ModelReturn { + "return": number; +} + +export class Name { + "name": number; } export class Order { @@ -70,6 +63,48 @@ export namespace Order { delivered = 'delivered' } } +export class Pet { + "id": number; + "category": Category; + "name": string; + "photoUrls": Array; + "tags": Array; + /** + * pet status in the store + */ + "status": Pet.StatusEnum; +} + +export namespace Pet { + export enum StatusEnum { + available = 'available', + pending = 'pending', + sold = 'sold' + } +} +export class SpecialModelName { + "$Special[propertyName]": number; +} + +export class Tag { + "id": number; + "name": string; +} + +export class User { + "id": number; + "username": string; + "firstName": string; + "lastName": string; + "email": string; + "password": string; + "phone": string; + /** + * User Status + */ + "userStatus": number; +} + interface Authentication { /** @@ -119,482 +154,6 @@ class VoidAuth implements Authentication { } } -export class UserApi { - protected basePath = 'http://petstore.swagger.io/v2'; - protected defaultHeaders : any = {}; - - - - public authentications = { - 'default': new VoidAuth(), - 'test_api_key_header': new ApiKeyAuth('header', 'test_api_key_header'), - 'api_key': new ApiKeyAuth('header', 'api_key'), - 'test_api_client_secret': new ApiKeyAuth('header', 'x-test_api_client_secret'), - 'test_api_client_id': new ApiKeyAuth('header', 'x-test_api_client_id'), - 'test_api_key_query': new ApiKeyAuth('query', 'test_api_key_query'), - '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 apiKey(key: string) { - this.authentications.test_api_key_header.apiKey = key; - } - - set apiKey(key: string) { - this.authentications.api_key.apiKey = key; - } - - set apiKey(key: string) { - this.authentications.test_api_client_secret.apiKey = key; - } - - set apiKey(key: string) { - this.authentications.test_api_client_id.apiKey = key; - } - - set apiKey(key: string) { - this.authentications.test_api_key_query.apiKey = key; - } - - 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; - } - /** - * Create user - * This can only be done by the logged in user. - * @param body Created user object - */ - public createUser (body?: User) : Promise<{ response: http.ClientResponse; body?: any; }> { - const localVarPath = this.basePath + '/user'; - let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); - let formParams: any = {}; - - - let useFormData = false; - - let localVarDeferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); - - let requestOptions: request.Options = { - method: 'POST', - qs: queryParameters, - headers: headerParams, - uri: localVarPath, - json: true, - body: body, - } - - this.authentications.default.applyToRequest(requestOptions); - - if (Object.keys(formParams).length) { - if (useFormData) { - (requestOptions).formData = formParams; - } else { - requestOptions.form = formParams; - } - } - - request(requestOptions, (error, response, body) => { - if (error) { - localVarDeferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - localVarDeferred.resolve({ response: response, body: body }); - } else { - localVarDeferred.reject({ response: response, body: body }); - } - } - }); - - return localVarDeferred.promise; - } - /** - * Creates list of users with given input array - * - * @param body List of user object - */ - public createUsersWithArrayInput (body?: Array) : Promise<{ response: http.ClientResponse; body?: any; }> { - const localVarPath = this.basePath + '/user/createWithArray'; - let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); - let formParams: any = {}; - - - let useFormData = false; - - let localVarDeferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); - - let requestOptions: request.Options = { - method: 'POST', - qs: queryParameters, - headers: headerParams, - uri: localVarPath, - json: true, - body: body, - } - - this.authentications.default.applyToRequest(requestOptions); - - if (Object.keys(formParams).length) { - if (useFormData) { - (requestOptions).formData = formParams; - } else { - requestOptions.form = formParams; - } - } - - request(requestOptions, (error, response, body) => { - if (error) { - localVarDeferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - localVarDeferred.resolve({ response: response, body: body }); - } else { - localVarDeferred.reject({ response: response, body: body }); - } - } - }); - - return localVarDeferred.promise; - } - /** - * Creates list of users with given input array - * - * @param body List of user object - */ - public createUsersWithListInput (body?: Array) : Promise<{ response: http.ClientResponse; body?: any; }> { - const localVarPath = this.basePath + '/user/createWithList'; - let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); - let formParams: any = {}; - - - let useFormData = false; - - let localVarDeferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); - - let requestOptions: request.Options = { - method: 'POST', - qs: queryParameters, - headers: headerParams, - uri: localVarPath, - json: true, - body: body, - } - - this.authentications.default.applyToRequest(requestOptions); - - if (Object.keys(formParams).length) { - if (useFormData) { - (requestOptions).formData = formParams; - } else { - requestOptions.form = formParams; - } - } - - request(requestOptions, (error, response, body) => { - if (error) { - localVarDeferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - localVarDeferred.resolve({ response: response, body: body }); - } else { - localVarDeferred.reject({ response: response, body: body }); - } - } - }); - - return localVarDeferred.promise; - } - /** - * Logs user into the system - * - * @param username The user name for login - * @param password The password for login in clear text - */ - public loginUser (username?: string, password?: string) : Promise<{ response: http.ClientResponse; body: string; }> { - const localVarPath = this.basePath + '/user/login'; - let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); - let formParams: any = {}; - - - if (username !== undefined) { - queryParameters['username'] = username; - } - - if (password !== undefined) { - queryParameters['password'] = password; - } - - let useFormData = false; - - let localVarDeferred = promise.defer<{ response: http.ClientResponse; body: string; }>(); - - let requestOptions: request.Options = { - method: 'GET', - qs: queryParameters, - headers: headerParams, - uri: localVarPath, - json: true, - } - - this.authentications.default.applyToRequest(requestOptions); - - if (Object.keys(formParams).length) { - if (useFormData) { - (requestOptions).formData = formParams; - } else { - requestOptions.form = formParams; - } - } - - request(requestOptions, (error, response, body) => { - if (error) { - localVarDeferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - localVarDeferred.resolve({ response: response, body: body }); - } else { - localVarDeferred.reject({ response: response, body: body }); - } - } - }); - - return localVarDeferred.promise; - } - /** - * Logs out current logged in user session - * - */ - public logoutUser () : Promise<{ response: http.ClientResponse; body?: any; }> { - const localVarPath = this.basePath + '/user/logout'; - let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); - let formParams: any = {}; - - - let useFormData = false; - - let localVarDeferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); - - let requestOptions: request.Options = { - method: 'GET', - qs: queryParameters, - headers: headerParams, - uri: localVarPath, - json: true, - } - - this.authentications.default.applyToRequest(requestOptions); - - if (Object.keys(formParams).length) { - if (useFormData) { - (requestOptions).formData = formParams; - } else { - requestOptions.form = formParams; - } - } - - request(requestOptions, (error, response, body) => { - if (error) { - localVarDeferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - localVarDeferred.resolve({ response: response, body: body }); - } else { - localVarDeferred.reject({ response: response, body: body }); - } - } - }); - - return localVarDeferred.promise; - } - /** - * Get user by user name - * - * @param username The name that needs to be fetched. Use user1 for testing. - */ - public getUserByName (username: string) : Promise<{ response: http.ClientResponse; body: User; }> { - const localVarPath = this.basePath + '/user/{username}' - .replace('{' + 'username' + '}', String(username)); - let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); - let formParams: any = {}; - - - // verify required parameter 'username' is set - if (!username) { - throw new Error('Missing required parameter username when calling getUserByName'); - } - - let useFormData = false; - - let localVarDeferred = promise.defer<{ response: http.ClientResponse; body: User; }>(); - - let requestOptions: request.Options = { - method: 'GET', - qs: queryParameters, - headers: headerParams, - uri: localVarPath, - json: true, - } - - this.authentications.default.applyToRequest(requestOptions); - - if (Object.keys(formParams).length) { - if (useFormData) { - (requestOptions).formData = formParams; - } else { - requestOptions.form = formParams; - } - } - - request(requestOptions, (error, response, body) => { - if (error) { - localVarDeferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - localVarDeferred.resolve({ response: response, body: body }); - } else { - localVarDeferred.reject({ response: response, body: body }); - } - } - }); - - return localVarDeferred.promise; - } - /** - * Updated user - * This can only be done by the logged in user. - * @param username name that need to be deleted - * @param body Updated user object - */ - public updateUser (username: string, body?: User) : Promise<{ response: http.ClientResponse; body?: any; }> { - const localVarPath = this.basePath + '/user/{username}' - .replace('{' + 'username' + '}', String(username)); - let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); - let formParams: any = {}; - - - // verify required parameter 'username' is set - if (!username) { - throw new Error('Missing required parameter username when calling updateUser'); - } - - let useFormData = false; - - let localVarDeferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); - - let requestOptions: request.Options = { - method: 'PUT', - qs: queryParameters, - headers: headerParams, - uri: localVarPath, - json: true, - body: body, - } - - this.authentications.default.applyToRequest(requestOptions); - - if (Object.keys(formParams).length) { - if (useFormData) { - (requestOptions).formData = formParams; - } else { - requestOptions.form = formParams; - } - } - - request(requestOptions, (error, response, body) => { - if (error) { - localVarDeferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - localVarDeferred.resolve({ response: response, body: body }); - } else { - localVarDeferred.reject({ response: response, body: body }); - } - } - }); - - return localVarDeferred.promise; - } - /** - * Delete user - * This can only be done by the logged in user. - * @param username The name that needs to be deleted - */ - public deleteUser (username: string) : Promise<{ response: http.ClientResponse; body?: any; }> { - const localVarPath = this.basePath + '/user/{username}' - .replace('{' + 'username' + '}', String(username)); - let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); - let formParams: any = {}; - - - // verify required parameter 'username' is set - if (!username) { - throw new Error('Missing required parameter username when calling deleteUser'); - } - - let useFormData = false; - - let localVarDeferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); - - let requestOptions: request.Options = { - method: 'DELETE', - qs: queryParameters, - headers: headerParams, - uri: localVarPath, - json: true, - } - - this.authentications.default.applyToRequest(requestOptions); - - if (Object.keys(formParams).length) { - if (useFormData) { - (requestOptions).formData = formParams; - } else { - requestOptions.form = formParams; - } - } - - request(requestOptions, (error, response, body) => { - if (error) { - localVarDeferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - localVarDeferred.resolve({ response: response, body: body }); - } else { - localVarDeferred.reject({ response: response, body: body }); - } - } - }); - - return localVarDeferred.promise; - } -} export class PetApi { protected basePath = 'http://petstore.swagger.io/v2'; protected defaultHeaders : any = {}; @@ -605,6 +164,7 @@ export class PetApi { 'default': new VoidAuth(), 'test_api_key_header': new ApiKeyAuth('header', 'test_api_key_header'), 'api_key': new ApiKeyAuth('header', 'api_key'), + 'test_http_basic': new HttpBasicAuth(), 'test_api_client_secret': new ApiKeyAuth('header', 'x-test_api_client_secret'), 'test_api_client_id': new ApiKeyAuth('header', 'x-test_api_client_id'), 'test_api_key_query': new ApiKeyAuth('query', 'test_api_key_query'), @@ -612,8 +172,11 @@ export class PetApi { } constructor(basePath?: string); + constructor(username: string, password: string, basePath?: string); constructor(basePathOrUsername: string, password?: string, basePath?: string) { if (password) { + this.username = basePathOrUsername; + this.password = password if (basePath) { this.basePath = basePath; } @@ -632,6 +195,14 @@ export class PetApi { this.authentications.api_key.apiKey = key; } + set username(username: string) { + this.authentications.test_http_basic.username = username; + } + + set password(password: string) { + this.authentications.test_http_basic.password = password; + } + set apiKey(key: string) { this.authentications.test_api_client_secret.apiKey = key; } @@ -656,11 +227,11 @@ export class PetApi { return objA; } /** - * Update an existing pet + * Add a new pet to the store * * @param body Pet object that needs to be added to the store */ - public updatePet (body?: Pet) : Promise<{ response: http.ClientResponse; body?: any; }> { + public addPet (body?: Pet) : Promise<{ response: http.ClientResponse; body?: any; }> { const localVarPath = this.basePath + '/pet'; let queryParameters: any = {}; let headerParams: any = this.extendObj({}, this.defaultHeaders); @@ -672,7 +243,7 @@ export class PetApi { let localVarDeferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); let requestOptions: request.Options = { - method: 'PUT', + method: 'POST', qs: queryParameters, headers: headerParams, uri: localVarPath, @@ -707,12 +278,12 @@ export class PetApi { return localVarDeferred.promise; } /** - * Add a new pet to the store + * Fake endpoint to test byte array in body parameter for adding a new pet to the store * - * @param body Pet object that needs to be added to the store + * @param body Pet object in the form of byte array */ - public addPet (body?: Pet) : Promise<{ response: http.ClientResponse; body?: any; }> { - const localVarPath = this.basePath + '/pet'; + public addPetUsingByteArray (body?: string) : Promise<{ response: http.ClientResponse; body?: any; }> { + const localVarPath = this.basePath + '/pet?testing_byte_array=true'; let queryParameters: any = {}; let headerParams: any = this.extendObj({}, this.defaultHeaders); let formParams: any = {}; @@ -757,6 +328,65 @@ export class PetApi { return localVarDeferred.promise; } + /** + * Deletes a pet + * + * @param petId Pet id to delete + * @param apiKey + */ + public deletePet (petId: number, apiKey?: string) : Promise<{ response: http.ClientResponse; body?: any; }> { + const localVarPath = this.basePath + '/pet/{petId}' + .replace('{' + 'petId' + '}', String(petId)); + let queryParameters: any = {}; + let headerParams: any = this.extendObj({}, this.defaultHeaders); + let formParams: any = {}; + + + // verify required parameter 'petId' is set + if (!petId) { + throw new Error('Missing required parameter petId when calling deletePet'); + } + + headerParams['api_key'] = apiKey; + + let useFormData = false; + + let localVarDeferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); + + let requestOptions: request.Options = { + method: 'DELETE', + qs: queryParameters, + headers: headerParams, + uri: localVarPath, + json: true, + } + + this.authentications.petstore_auth.applyToRequest(requestOptions); + + this.authentications.default.applyToRequest(requestOptions); + + if (Object.keys(formParams).length) { + if (useFormData) { + (requestOptions).formData = formParams; + } else { + requestOptions.form = formParams; + } + } + + request(requestOptions, (error, response, body) => { + if (error) { + localVarDeferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + localVarDeferred.resolve({ response: response, body: body }); + } else { + localVarDeferred.reject({ response: response, body: body }); + } + } + }); + + return localVarDeferred.promise; + } /** * Finds Pets by status * Multiple status values can be provided with comma separated strings @@ -923,6 +553,173 @@ export class PetApi { return localVarDeferred.promise; } + /** + * Fake endpoint to test inline arbitrary object return by 'Find pet by ID' + * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + * @param petId ID of pet that needs to be fetched + */ + public getPetByIdInObject (petId: number) : Promise<{ response: http.ClientResponse; body: InlineResponse200; }> { + const localVarPath = this.basePath + '/pet/{petId}?response=inline_arbitrary_object' + .replace('{' + 'petId' + '}', String(petId)); + let queryParameters: any = {}; + let headerParams: any = this.extendObj({}, this.defaultHeaders); + let formParams: any = {}; + + + // verify required parameter 'petId' is set + if (!petId) { + throw new Error('Missing required parameter petId when calling getPetByIdInObject'); + } + + let useFormData = false; + + let localVarDeferred = promise.defer<{ response: http.ClientResponse; body: InlineResponse200; }>(); + + let requestOptions: request.Options = { + method: 'GET', + qs: queryParameters, + headers: headerParams, + uri: localVarPath, + json: true, + } + + this.authentications.api_key.applyToRequest(requestOptions); + + this.authentications.petstore_auth.applyToRequest(requestOptions); + + this.authentications.default.applyToRequest(requestOptions); + + if (Object.keys(formParams).length) { + if (useFormData) { + (requestOptions).formData = formParams; + } else { + requestOptions.form = formParams; + } + } + + request(requestOptions, (error, response, body) => { + if (error) { + localVarDeferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + localVarDeferred.resolve({ response: response, body: body }); + } else { + localVarDeferred.reject({ response: response, body: body }); + } + } + }); + + return localVarDeferred.promise; + } + /** + * Fake endpoint to test byte array return by 'Find pet by ID' + * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + * @param petId ID of pet that needs to be fetched + */ + public petPetIdtestingByteArraytrueGet (petId: number) : Promise<{ response: http.ClientResponse; body: string; }> { + const localVarPath = this.basePath + '/pet/{petId}?testing_byte_array=true' + .replace('{' + 'petId' + '}', String(petId)); + let queryParameters: any = {}; + let headerParams: any = this.extendObj({}, this.defaultHeaders); + let formParams: any = {}; + + + // verify required parameter 'petId' is set + if (!petId) { + throw new Error('Missing required parameter petId when calling petPetIdtestingByteArraytrueGet'); + } + + let useFormData = false; + + let localVarDeferred = promise.defer<{ response: http.ClientResponse; body: string; }>(); + + let requestOptions: request.Options = { + method: 'GET', + qs: queryParameters, + headers: headerParams, + uri: localVarPath, + json: true, + } + + this.authentications.api_key.applyToRequest(requestOptions); + + this.authentications.petstore_auth.applyToRequest(requestOptions); + + this.authentications.default.applyToRequest(requestOptions); + + if (Object.keys(formParams).length) { + if (useFormData) { + (requestOptions).formData = formParams; + } else { + requestOptions.form = formParams; + } + } + + request(requestOptions, (error, response, body) => { + if (error) { + localVarDeferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + localVarDeferred.resolve({ response: response, body: body }); + } else { + localVarDeferred.reject({ response: response, body: body }); + } + } + }); + + return localVarDeferred.promise; + } + /** + * Update an existing pet + * + * @param body Pet object that needs to be added to the store + */ + public updatePet (body?: Pet) : Promise<{ response: http.ClientResponse; body?: any; }> { + const localVarPath = this.basePath + '/pet'; + let queryParameters: any = {}; + let headerParams: any = this.extendObj({}, this.defaultHeaders); + let formParams: any = {}; + + + let useFormData = false; + + let localVarDeferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); + + let requestOptions: request.Options = { + method: 'PUT', + qs: queryParameters, + headers: headerParams, + uri: localVarPath, + json: true, + body: body, + } + + this.authentications.petstore_auth.applyToRequest(requestOptions); + + this.authentications.default.applyToRequest(requestOptions); + + if (Object.keys(formParams).length) { + if (useFormData) { + (requestOptions).formData = formParams; + } else { + requestOptions.form = formParams; + } + } + + request(requestOptions, (error, response, body) => { + if (error) { + localVarDeferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + localVarDeferred.resolve({ response: response, body: body }); + } else { + localVarDeferred.reject({ response: response, body: body }); + } + } + }); + + return localVarDeferred.promise; + } /** * Updates a pet in the store with form data * @@ -989,65 +786,6 @@ export class PetApi { return localVarDeferred.promise; } - /** - * Deletes a pet - * - * @param petId Pet id to delete - * @param apiKey - */ - public deletePet (petId: number, apiKey?: string) : Promise<{ response: http.ClientResponse; body?: any; }> { - const localVarPath = this.basePath + '/pet/{petId}' - .replace('{' + 'petId' + '}', String(petId)); - let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); - let formParams: any = {}; - - - // verify required parameter 'petId' is set - if (!petId) { - throw new Error('Missing required parameter petId when calling deletePet'); - } - - headerParams['api_key'] = apiKey; - - let useFormData = false; - - let localVarDeferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); - - let requestOptions: request.Options = { - method: 'DELETE', - qs: queryParameters, - headers: headerParams, - uri: localVarPath, - json: true, - } - - this.authentications.petstore_auth.applyToRequest(requestOptions); - - this.authentications.default.applyToRequest(requestOptions); - - if (Object.keys(formParams).length) { - if (useFormData) { - (requestOptions).formData = formParams; - } else { - requestOptions.form = formParams; - } - } - - request(requestOptions, (error, response, body) => { - if (error) { - localVarDeferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - localVarDeferred.resolve({ response: response, body: body }); - } else { - localVarDeferred.reject({ response: response, body: body }); - } - } - }); - - return localVarDeferred.promise; - } /** * uploads an image * @@ -1113,115 +851,6 @@ export class PetApi { } }); - return localVarDeferred.promise; - } - /** - * Fake endpoint to test byte array return by 'Find pet by ID' - * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions - * @param petId ID of pet that needs to be fetched - */ - public petPetIdtestingByteArraytrueGet (petId: number) : Promise<{ response: http.ClientResponse; body: string; }> { - const localVarPath = this.basePath + '/pet/{petId}?testing_byte_array=true' - .replace('{' + 'petId' + '}', String(petId)); - let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); - let formParams: any = {}; - - - // verify required parameter 'petId' is set - if (!petId) { - throw new Error('Missing required parameter petId when calling petPetIdtestingByteArraytrueGet'); - } - - let useFormData = false; - - let localVarDeferred = promise.defer<{ response: http.ClientResponse; body: string; }>(); - - let requestOptions: request.Options = { - method: 'GET', - qs: queryParameters, - headers: headerParams, - uri: localVarPath, - json: true, - } - - this.authentications.api_key.applyToRequest(requestOptions); - - this.authentications.petstore_auth.applyToRequest(requestOptions); - - this.authentications.default.applyToRequest(requestOptions); - - if (Object.keys(formParams).length) { - if (useFormData) { - (requestOptions).formData = formParams; - } else { - requestOptions.form = formParams; - } - } - - request(requestOptions, (error, response, body) => { - if (error) { - localVarDeferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - localVarDeferred.resolve({ response: response, body: body }); - } else { - localVarDeferred.reject({ response: response, body: body }); - } - } - }); - - return localVarDeferred.promise; - } - /** - * Fake endpoint to test byte array in body parameter for adding a new pet to the store - * - * @param body Pet object in the form of byte array - */ - public addPetUsingByteArray (body?: string) : Promise<{ response: http.ClientResponse; body?: any; }> { - const localVarPath = this.basePath + '/pet?testing_byte_array=true'; - let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); - let formParams: any = {}; - - - let useFormData = false; - - let localVarDeferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); - - let requestOptions: request.Options = { - method: 'POST', - qs: queryParameters, - headers: headerParams, - uri: localVarPath, - json: true, - body: body, - } - - this.authentications.petstore_auth.applyToRequest(requestOptions); - - this.authentications.default.applyToRequest(requestOptions); - - if (Object.keys(formParams).length) { - if (useFormData) { - (requestOptions).formData = formParams; - } else { - requestOptions.form = formParams; - } - } - - request(requestOptions, (error, response, body) => { - if (error) { - localVarDeferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - localVarDeferred.resolve({ response: response, body: body }); - } else { - localVarDeferred.reject({ response: response, body: body }); - } - } - }); - return localVarDeferred.promise; } } @@ -1235,6 +864,7 @@ export class StoreApi { 'default': new VoidAuth(), 'test_api_key_header': new ApiKeyAuth('header', 'test_api_key_header'), 'api_key': new ApiKeyAuth('header', 'api_key'), + 'test_http_basic': new HttpBasicAuth(), 'test_api_client_secret': new ApiKeyAuth('header', 'x-test_api_client_secret'), 'test_api_client_id': new ApiKeyAuth('header', 'x-test_api_client_id'), 'test_api_key_query': new ApiKeyAuth('query', 'test_api_key_query'), @@ -1242,8 +872,11 @@ export class StoreApi { } constructor(basePath?: string); + constructor(username: string, password: string, basePath?: string); constructor(basePathOrUsername: string, password?: string, basePath?: string) { if (password) { + this.username = basePathOrUsername; + this.password = password if (basePath) { this.basePath = basePath; } @@ -1262,6 +895,14 @@ export class StoreApi { this.authentications.api_key.apiKey = key; } + set username(username: string) { + this.authentications.test_http_basic.username = username; + } + + set password(password: string) { + this.authentications.test_http_basic.password = password; + } + set apiKey(key: string) { this.authentications.test_api_client_secret.apiKey = key; } @@ -1285,6 +926,60 @@ export class StoreApi { } return objA; } + /** + * Delete purchase order by ID + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * @param orderId ID of the order that needs to be deleted + */ + public deleteOrder (orderId: string) : Promise<{ response: http.ClientResponse; body?: any; }> { + const localVarPath = this.basePath + '/store/order/{orderId}' + .replace('{' + 'orderId' + '}', String(orderId)); + let queryParameters: any = {}; + let headerParams: any = this.extendObj({}, this.defaultHeaders); + let formParams: any = {}; + + + // verify required parameter 'orderId' is set + if (!orderId) { + throw new Error('Missing required parameter orderId when calling deleteOrder'); + } + + let useFormData = false; + + let localVarDeferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); + + let requestOptions: request.Options = { + method: 'DELETE', + qs: queryParameters, + headers: headerParams, + uri: localVarPath, + json: true, + } + + this.authentications.default.applyToRequest(requestOptions); + + if (Object.keys(formParams).length) { + if (useFormData) { + (requestOptions).formData = formParams; + } else { + requestOptions.form = formParams; + } + } + + request(requestOptions, (error, response, body) => { + if (error) { + localVarDeferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + localVarDeferred.resolve({ response: response, body: body }); + } else { + localVarDeferred.reject({ response: response, body: body }); + } + } + }); + + return localVarDeferred.promise; + } /** * Finds orders by status * A single status value can be provided as a string @@ -1391,12 +1086,11 @@ export class StoreApi { return localVarDeferred.promise; } /** - * Place an order for a pet - * - * @param body order placed for purchasing the pet + * Fake endpoint to test arbitrary object return by 'Get inventory' + * Returns an arbitrary object which is actually a map of status codes to quantities */ - public placeOrder (body?: Order) : Promise<{ response: http.ClientResponse; body: Order; }> { - const localVarPath = this.basePath + '/store/order'; + public getInventoryInObject () : Promise<{ response: http.ClientResponse; body: any; }> { + const localVarPath = this.basePath + '/store/inventory?response=arbitrary_object'; let queryParameters: any = {}; let headerParams: any = this.extendObj({}, this.defaultHeaders); let formParams: any = {}; @@ -1404,20 +1098,17 @@ export class StoreApi { let useFormData = false; - let localVarDeferred = promise.defer<{ response: http.ClientResponse; body: Order; }>(); + let localVarDeferred = promise.defer<{ response: http.ClientResponse; body: any; }>(); let requestOptions: request.Options = { - method: 'POST', + method: 'GET', qs: queryParameters, headers: headerParams, uri: localVarPath, json: true, - body: body, } - this.authentications.test_api_client_id.applyToRequest(requestOptions); - - this.authentications.test_api_client_secret.applyToRequest(requestOptions); + this.authentications.api_key.applyToRequest(requestOptions); this.authentications.default.applyToRequest(requestOptions); @@ -1502,21 +1193,294 @@ export class StoreApi { return localVarDeferred.promise; } /** - * 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 + * Place an order for a pet + * + * @param body order placed for purchasing the pet */ - public deleteOrder (orderId: string) : Promise<{ response: http.ClientResponse; body?: any; }> { - const localVarPath = this.basePath + '/store/order/{orderId}' - .replace('{' + 'orderId' + '}', String(orderId)); + public placeOrder (body?: Order) : Promise<{ response: http.ClientResponse; body: Order; }> { + const localVarPath = this.basePath + '/store/order'; let queryParameters: any = {}; let headerParams: any = this.extendObj({}, this.defaultHeaders); let formParams: any = {}; - // verify required parameter 'orderId' is set - if (!orderId) { - throw new Error('Missing required parameter orderId when calling deleteOrder'); + let useFormData = false; + + let localVarDeferred = promise.defer<{ response: http.ClientResponse; body: Order; }>(); + + let requestOptions: request.Options = { + method: 'POST', + qs: queryParameters, + headers: headerParams, + uri: localVarPath, + json: true, + body: body, + } + + this.authentications.test_api_client_id.applyToRequest(requestOptions); + + this.authentications.test_api_client_secret.applyToRequest(requestOptions); + + this.authentications.default.applyToRequest(requestOptions); + + if (Object.keys(formParams).length) { + if (useFormData) { + (requestOptions).formData = formParams; + } else { + requestOptions.form = formParams; + } + } + + request(requestOptions, (error, response, body) => { + if (error) { + localVarDeferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + localVarDeferred.resolve({ response: response, body: body }); + } else { + localVarDeferred.reject({ response: response, body: body }); + } + } + }); + + return localVarDeferred.promise; + } +} +export class UserApi { + protected basePath = 'http://petstore.swagger.io/v2'; + protected defaultHeaders : any = {}; + + + + public authentications = { + 'default': new VoidAuth(), + 'test_api_key_header': new ApiKeyAuth('header', 'test_api_key_header'), + 'api_key': new ApiKeyAuth('header', 'api_key'), + 'test_http_basic': new HttpBasicAuth(), + 'test_api_client_secret': new ApiKeyAuth('header', 'x-test_api_client_secret'), + 'test_api_client_id': new ApiKeyAuth('header', 'x-test_api_client_id'), + 'test_api_key_query': new ApiKeyAuth('query', 'test_api_key_query'), + 'petstore_auth': new OAuth(), + } + + constructor(basePath?: string); + constructor(username: string, password: string, basePath?: string); + constructor(basePathOrUsername: string, password?: string, basePath?: string) { + if (password) { + this.username = basePathOrUsername; + this.password = password + if (basePath) { + this.basePath = basePath; + } + } else { + if (basePathOrUsername) { + this.basePath = basePathOrUsername + } + } + } + + set apiKey(key: string) { + this.authentications.test_api_key_header.apiKey = key; + } + + set apiKey(key: string) { + this.authentications.api_key.apiKey = key; + } + + set username(username: string) { + this.authentications.test_http_basic.username = username; + } + + set password(password: string) { + this.authentications.test_http_basic.password = password; + } + + set apiKey(key: string) { + this.authentications.test_api_client_secret.apiKey = key; + } + + set apiKey(key: string) { + this.authentications.test_api_client_id.apiKey = key; + } + + set apiKey(key: string) { + this.authentications.test_api_key_query.apiKey = key; + } + + 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; + } + /** + * Create user + * This can only be done by the logged in user. + * @param body Created user object + */ + public createUser (body?: User) : Promise<{ response: http.ClientResponse; body?: any; }> { + const localVarPath = this.basePath + '/user'; + let queryParameters: any = {}; + let headerParams: any = this.extendObj({}, this.defaultHeaders); + let formParams: any = {}; + + + let useFormData = false; + + let localVarDeferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); + + let requestOptions: request.Options = { + method: 'POST', + qs: queryParameters, + headers: headerParams, + uri: localVarPath, + json: true, + body: body, + } + + this.authentications.default.applyToRequest(requestOptions); + + if (Object.keys(formParams).length) { + if (useFormData) { + (requestOptions).formData = formParams; + } else { + requestOptions.form = formParams; + } + } + + request(requestOptions, (error, response, body) => { + if (error) { + localVarDeferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + localVarDeferred.resolve({ response: response, body: body }); + } else { + localVarDeferred.reject({ response: response, body: body }); + } + } + }); + + return localVarDeferred.promise; + } + /** + * Creates list of users with given input array + * + * @param body List of user object + */ + public createUsersWithArrayInput (body?: Array) : Promise<{ response: http.ClientResponse; body?: any; }> { + const localVarPath = this.basePath + '/user/createWithArray'; + let queryParameters: any = {}; + let headerParams: any = this.extendObj({}, this.defaultHeaders); + let formParams: any = {}; + + + let useFormData = false; + + let localVarDeferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); + + let requestOptions: request.Options = { + method: 'POST', + qs: queryParameters, + headers: headerParams, + uri: localVarPath, + json: true, + body: body, + } + + this.authentications.default.applyToRequest(requestOptions); + + if (Object.keys(formParams).length) { + if (useFormData) { + (requestOptions).formData = formParams; + } else { + requestOptions.form = formParams; + } + } + + request(requestOptions, (error, response, body) => { + if (error) { + localVarDeferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + localVarDeferred.resolve({ response: response, body: body }); + } else { + localVarDeferred.reject({ response: response, body: body }); + } + } + }); + + return localVarDeferred.promise; + } + /** + * Creates list of users with given input array + * + * @param body List of user object + */ + public createUsersWithListInput (body?: Array) : Promise<{ response: http.ClientResponse; body?: any; }> { + const localVarPath = this.basePath + '/user/createWithList'; + let queryParameters: any = {}; + let headerParams: any = this.extendObj({}, this.defaultHeaders); + let formParams: any = {}; + + + let useFormData = false; + + let localVarDeferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); + + let requestOptions: request.Options = { + method: 'POST', + qs: queryParameters, + headers: headerParams, + uri: localVarPath, + json: true, + body: body, + } + + this.authentications.default.applyToRequest(requestOptions); + + if (Object.keys(formParams).length) { + if (useFormData) { + (requestOptions).formData = formParams; + } else { + requestOptions.form = formParams; + } + } + + request(requestOptions, (error, response, body) => { + if (error) { + localVarDeferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + localVarDeferred.resolve({ response: response, body: body }); + } else { + localVarDeferred.reject({ response: response, body: body }); + } + } + }); + + return localVarDeferred.promise; + } + /** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted + */ + public deleteUser (username: string) : Promise<{ response: http.ClientResponse; body?: any; }> { + const localVarPath = this.basePath + '/user/{username}' + .replace('{' + 'username' + '}', String(username)); + let queryParameters: any = {}; + let headerParams: any = this.extendObj({}, this.defaultHeaders); + let formParams: any = {}; + + + // verify required parameter 'username' is set + if (!username) { + throw new Error('Missing required parameter username when calling deleteUser'); } let useFormData = false; @@ -1531,6 +1495,222 @@ export class StoreApi { json: true, } + this.authentications.test_http_basic.applyToRequest(requestOptions); + + this.authentications.default.applyToRequest(requestOptions); + + if (Object.keys(formParams).length) { + if (useFormData) { + (requestOptions).formData = formParams; + } else { + requestOptions.form = formParams; + } + } + + request(requestOptions, (error, response, body) => { + if (error) { + localVarDeferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + localVarDeferred.resolve({ response: response, body: body }); + } else { + localVarDeferred.reject({ response: response, body: body }); + } + } + }); + + return localVarDeferred.promise; + } + /** + * Get user by user name + * + * @param username The name that needs to be fetched. Use user1 for testing. + */ + public getUserByName (username: string) : Promise<{ response: http.ClientResponse; body: User; }> { + const localVarPath = this.basePath + '/user/{username}' + .replace('{' + 'username' + '}', String(username)); + let queryParameters: any = {}; + let headerParams: any = this.extendObj({}, this.defaultHeaders); + let formParams: any = {}; + + + // verify required parameter 'username' is set + if (!username) { + throw new Error('Missing required parameter username when calling getUserByName'); + } + + let useFormData = false; + + let localVarDeferred = promise.defer<{ response: http.ClientResponse; body: User; }>(); + + let requestOptions: request.Options = { + method: 'GET', + qs: queryParameters, + headers: headerParams, + uri: localVarPath, + json: true, + } + + this.authentications.default.applyToRequest(requestOptions); + + if (Object.keys(formParams).length) { + if (useFormData) { + (requestOptions).formData = formParams; + } else { + requestOptions.form = formParams; + } + } + + request(requestOptions, (error, response, body) => { + if (error) { + localVarDeferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + localVarDeferred.resolve({ response: response, body: body }); + } else { + localVarDeferred.reject({ response: response, body: body }); + } + } + }); + + return localVarDeferred.promise; + } + /** + * Logs user into the system + * + * @param username The user name for login + * @param password The password for login in clear text + */ + public loginUser (username?: string, password?: string) : Promise<{ response: http.ClientResponse; body: string; }> { + const localVarPath = this.basePath + '/user/login'; + let queryParameters: any = {}; + let headerParams: any = this.extendObj({}, this.defaultHeaders); + let formParams: any = {}; + + + if (username !== undefined) { + queryParameters['username'] = username; + } + + if (password !== undefined) { + queryParameters['password'] = password; + } + + let useFormData = false; + + let localVarDeferred = promise.defer<{ response: http.ClientResponse; body: string; }>(); + + let requestOptions: request.Options = { + method: 'GET', + qs: queryParameters, + headers: headerParams, + uri: localVarPath, + json: true, + } + + this.authentications.default.applyToRequest(requestOptions); + + if (Object.keys(formParams).length) { + if (useFormData) { + (requestOptions).formData = formParams; + } else { + requestOptions.form = formParams; + } + } + + request(requestOptions, (error, response, body) => { + if (error) { + localVarDeferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + localVarDeferred.resolve({ response: response, body: body }); + } else { + localVarDeferred.reject({ response: response, body: body }); + } + } + }); + + return localVarDeferred.promise; + } + /** + * Logs out current logged in user session + * + */ + public logoutUser () : Promise<{ response: http.ClientResponse; body?: any; }> { + const localVarPath = this.basePath + '/user/logout'; + let queryParameters: any = {}; + let headerParams: any = this.extendObj({}, this.defaultHeaders); + let formParams: any = {}; + + + let useFormData = false; + + let localVarDeferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); + + let requestOptions: request.Options = { + method: 'GET', + qs: queryParameters, + headers: headerParams, + uri: localVarPath, + json: true, + } + + this.authentications.default.applyToRequest(requestOptions); + + if (Object.keys(formParams).length) { + if (useFormData) { + (requestOptions).formData = formParams; + } else { + requestOptions.form = formParams; + } + } + + request(requestOptions, (error, response, body) => { + if (error) { + localVarDeferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + localVarDeferred.resolve({ response: response, body: body }); + } else { + localVarDeferred.reject({ response: response, body: body }); + } + } + }); + + return localVarDeferred.promise; + } + /** + * Updated user + * This can only be done by the logged in user. + * @param username name that need to be deleted + * @param body Updated user object + */ + public updateUser (username: string, body?: User) : Promise<{ response: http.ClientResponse; body?: any; }> { + const localVarPath = this.basePath + '/user/{username}' + .replace('{' + 'username' + '}', String(username)); + let queryParameters: any = {}; + let headerParams: any = this.extendObj({}, this.defaultHeaders); + let formParams: any = {}; + + + // verify required parameter 'username' is set + if (!username) { + throw new Error('Missing required parameter username when calling updateUser'); + } + + let useFormData = false; + + let localVarDeferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); + + let requestOptions: request.Options = { + method: 'PUT', + qs: queryParameters, + headers: headerParams, + uri: localVarPath, + json: true, + body: body, + } + this.authentications.default.applyToRequest(requestOptions); if (Object.keys(formParams).length) { diff --git a/samples/client/petstore/typescript-node/git_push.sh b/samples/client/petstore/typescript-node/git_push.sh new file mode 100644 index 00000000000..1a36388db02 --- /dev/null +++ b/samples/client/petstore/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="YOUR_GIT_USR_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="YOUR_GIT_REPO_ID" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="Minor update" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=`git remote` +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git crediential in your environment." + git remote add origin https://github.com/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:${GIT_TOKEN}@github.com/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://github.com/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' + diff --git a/samples/server/petstore/jaxrs-cxf/gen/java/io/swagger/api/PetApi.java b/samples/server/petstore/jaxrs-cxf/gen/java/io/swagger/api/PetApi.java index 9d7192ff535..2e8ef241f49 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,63 +1,56 @@ package io.swagger.api; import io.swagger.model.Pet; +import io.swagger.model.ApiResponse; import java.io.File; import javax.ws.rs.*; import javax.ws.rs.core.Response; +import org.apache.cxf.jaxrs.ext.multipart.*; + @Path("/") public interface PetApi { - @PUT - @Path("/pet") - @Consumes({ "application/json", "application/xml" }) - @Produces({ "application/json", "application/xml" }) - public Response updatePet(Pet body); @POST @Path("/pet") @Consumes({ "application/json", "application/xml" }) - @Produces({ "application/json", "application/xml" }) + @Produces({ "application/xml", "application/json" }) public 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); @GET @Path("/pet/findByStatus") - @Produces({ "application/json", "application/xml" }) + @Produces({ "application/xml", "application/json" }) public Response findPetsByStatus(@QueryParam("status") List status); @GET @Path("/pet/findByTags") - @Produces({ "application/json", "application/xml" }) + @Produces({ "application/xml", "application/json" }) public Response findPetsByTags(@QueryParam("tags") List tags); @GET @Path("/pet/{petId}") - @Produces({ "application/json", "application/xml" }) + @Produces({ "application/xml", "application/json" }) public Response getPetById(@PathParam("petId") Long petId); + @PUT + @Path("/pet") + @Consumes({ "application/json", "application/xml" }) + @Produces({ "application/xml", "application/json" }) + public Response updatePet(Pet body); @POST @Path("/pet/{petId}") @Consumes({ "application/x-www-form-urlencoded" }) - @Produces({ "application/json", "application/xml" }) - public Response updatePetWithForm(@PathParam("petId") String petId,@Multipart(value = "name", required = false) String name,@Multipart(value = "status", required = false) String status); - @DELETE - @Path("/pet/{petId}") - - @Produces({ "application/json", "application/xml" }) - public Response deletePet(@PathParam("petId") Long petId,@HeaderParam("api_key") String apiKey); + @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); @POST @Path("/pet/{petId}/uploadImage") @Consumes({ "multipart/form-data" }) - @Produces({ "application/json", "application/xml" }) + @Produces({ "application/json" }) public 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); - @GET - @Path("/pet/{petId}?testing_byte_array=true") - - @Produces({ "application/json", "application/xml" }) - public Response petPetIdtestingByteArraytrueGet(@PathParam("petId") Long petId); - @POST - @Path("/pet?testing_byte_array=true") - @Consumes({ "application/json", "application/xml" }) - @Produces({ "application/json", "application/xml" }) - public Response addPetUsingByteArray(byte[] body); } 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 f6729e7fafb..7b26e047746 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 @@ -6,27 +6,29 @@ import io.swagger.model.Order; import javax.ws.rs.*; import javax.ws.rs.core.Response; +import org.apache.cxf.jaxrs.ext.multipart.*; + @Path("/") public interface StoreApi { - @GET - @Path("/store/inventory") - - @Produces({ "application/json", "application/xml" }) - public Response getInventory(); - @POST - @Path("/store/order") - - @Produces({ "application/json", "application/xml" }) - public Response placeOrder(Order body); - @GET - @Path("/store/order/{orderId}") - - @Produces({ "application/json", "application/xml" }) - public Response getOrderById(@PathParam("orderId") String orderId); @DELETE @Path("/store/order/{orderId}") - @Produces({ "application/json", "application/xml" }) - public Response deleteOrder(@PathParam("orderId") String orderId); + @Produces({ "application/xml", "application/json" }) + public Response deleteOrder(@PathParam("orderId") Long orderId); + @GET + @Path("/store/inventory") + + @Produces({ "application/json" }) + public Response getInventory(); + @GET + @Path("/store/order/{orderId}") + + @Produces({ "application/xml", "application/json" }) + public Response getOrderById(@PathParam("orderId") Long orderId); + @POST + @Path("/store/order") + + @Produces({ "application/xml", "application/json" }) + public 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 88027929085..19e5ab04f3a 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 @@ -6,47 +6,49 @@ import java.util.List; import javax.ws.rs.*; import javax.ws.rs.core.Response; +import org.apache.cxf.jaxrs.ext.multipart.*; + @Path("/") public interface UserApi { @POST @Path("/user") - @Produces({ "application/json", "application/xml" }) + @Produces({ "application/xml", "application/json" }) public Response createUser(User body); @POST @Path("/user/createWithArray") - @Produces({ "application/json", "application/xml" }) + @Produces({ "application/xml", "application/json" }) public Response createUsersWithArrayInput(List body); @POST @Path("/user/createWithList") - @Produces({ "application/json", "application/xml" }) + @Produces({ "application/xml", "application/json" }) public Response createUsersWithListInput(List body); + @DELETE + @Path("/user/{username}") + + @Produces({ "application/xml", "application/json" }) + public Response deleteUser(@PathParam("username") String username); + @GET + @Path("/user/{username}") + + @Produces({ "application/xml", "application/json" }) + public Response getUserByName(@PathParam("username") String username); @GET @Path("/user/login") - @Produces({ "application/json", "application/xml" }) + @Produces({ "application/xml", "application/json" }) public Response loginUser(@QueryParam("username") String username,@QueryParam("password") String password); @GET @Path("/user/logout") - @Produces({ "application/json", "application/xml" }) + @Produces({ "application/xml", "application/json" }) public Response logoutUser(); - @GET - @Path("/user/{username}") - - @Produces({ "application/json", "application/xml" }) - public Response getUserByName(@PathParam("username") String username); @PUT @Path("/user/{username}") - @Produces({ "application/json", "application/xml" }) + @Produces({ "application/xml", "application/json" }) public Response updateUser(@PathParam("username") String username,User body); - @DELETE - @Path("/user/{username}") - - @Produces({ "application/json", "application/xml" }) - public Response deleteUser(@PathParam("username") String username); } 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 new file mode 100644 index 00000000000..68908204335 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf/gen/java/io/swagger/model/ApiResponse.java @@ -0,0 +1,82 @@ +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/Order.java b/samples/server/petstore/jaxrs-cxf/gen/java/io/swagger/model/Order.java index 60ffccbd8f9..93c120e6c5a 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 @@ -45,7 +45,7 @@ public enum Order { private StatusEnum status = null; - private Boolean complete = null; + private Boolean complete = false; /** diff --git a/samples/server/petstore/jaxrs-resteasy/src/gen/java/io/swagger/api/ApiException.java b/samples/server/petstore/jaxrs-resteasy/src/gen/java/io/swagger/api/ApiException.java index 98c42b54565..bfeaf6571ad 100644 --- a/samples/server/petstore/jaxrs-resteasy/src/gen/java/io/swagger/api/ApiException.java +++ b/samples/server/petstore/jaxrs-resteasy/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-02-04T01:58:20.368+07:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaResteasyServerCodegen", date = "2016-03-16T14:27:58.108+08:00") public class ApiException extends Exception{ private int code; public ApiException (int code, String msg) { diff --git a/samples/server/petstore/jaxrs-resteasy/src/gen/java/io/swagger/api/ApiOriginFilter.java b/samples/server/petstore/jaxrs-resteasy/src/gen/java/io/swagger/api/ApiOriginFilter.java index 80cf57bb0b3..419f9ebab09 100644 --- a/samples/server/petstore/jaxrs-resteasy/src/gen/java/io/swagger/api/ApiOriginFilter.java +++ b/samples/server/petstore/jaxrs-resteasy/src/gen/java/io/swagger/api/ApiOriginFilter.java @@ -5,7 +5,7 @@ import java.io.IOException; import javax.servlet.*; import javax.servlet.http.HttpServletResponse; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaResteasyServerCodegen", date = "2016-02-04T01:58:20.368+07:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaResteasyServerCodegen", date = "2016-03-16T14:27:58.108+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/src/gen/java/io/swagger/api/ApiResponseMessage.java b/samples/server/petstore/jaxrs-resteasy/src/gen/java/io/swagger/api/ApiResponseMessage.java index 06f9706c04b..2e00645c336 100644 --- a/samples/server/petstore/jaxrs-resteasy/src/gen/java/io/swagger/api/ApiResponseMessage.java +++ b/samples/server/petstore/jaxrs-resteasy/src/gen/java/io/swagger/api/ApiResponseMessage.java @@ -3,7 +3,7 @@ package io.swagger.api; import javax.xml.bind.annotation.XmlTransient; @javax.xml.bind.annotation.XmlRootElement -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaResteasyServerCodegen", date = "2016-02-04T01:58:20.368+07:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaResteasyServerCodegen", date = "2016-03-16T14:27:58.108+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/src/gen/java/io/swagger/api/NotFoundException.java b/samples/server/petstore/jaxrs-resteasy/src/gen/java/io/swagger/api/NotFoundException.java index 6b3581fa559..52d5224b7eb 100644 --- a/samples/server/petstore/jaxrs-resteasy/src/gen/java/io/swagger/api/NotFoundException.java +++ b/samples/server/petstore/jaxrs-resteasy/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-02-04T01:58:20.368+07:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaResteasyServerCodegen", date = "2016-03-16T14:27:58.108+08:00") public class NotFoundException extends ApiException { private int code; public NotFoundException (int code, String msg) { diff --git a/samples/server/petstore/jaxrs-resteasy/src/gen/java/io/swagger/api/PetApi.java b/samples/server/petstore/jaxrs-resteasy/src/gen/java/io/swagger/api/PetApi.java index c87f9f8e25f..10d335c19bd 100644 --- a/samples/server/petstore/jaxrs-resteasy/src/gen/java/io/swagger/api/PetApi.java +++ b/samples/server/petstore/jaxrs-resteasy/src/gen/java/io/swagger/api/PetApi.java @@ -5,9 +5,9 @@ import io.swagger.api.PetApiService; import io.swagger.api.factories.PetApiServiceFactory; import io.swagger.model.Pet; +import io.swagger.model.InlineResponse200; import java.io.File; - import java.util.List; import io.swagger.api.NotFoundException; @@ -22,21 +22,10 @@ import org.jboss.resteasy.plugins.providers.multipart.MultipartFormDataInput; @Path("/pet") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaResteasyServerCodegen", date = "2016-02-04T01:58:20.368+07:00") - +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaResteasyServerCodegen", date = "2016-03-16T14:27:58.108+08:00") public class PetApi { private final PetApiService delegate = PetApiServiceFactory.getPetApi(); - - @PUT - - @Consumes({ "application/json", "application/xml" }) - @Produces({ "application/json", "application/xml" }) - public Response updatePet( Pet body,@Context SecurityContext securityContext) - throws NotFoundException { - return delegate.updatePet(body,securityContext); - } - @POST @Consumes({ "application/json", "application/xml" }) @@ -45,43 +34,6 @@ public class PetApi { throws NotFoundException { return delegate.addPet(body,securityContext); } - - @GET - @Path("/findByStatus") - - @Produces({ "application/json", "application/xml" }) - public Response findPetsByStatus( @QueryParam("status") List status,@Context SecurityContext securityContext) - throws NotFoundException { - return delegate.findPetsByStatus(status,securityContext); - } - - @GET - @Path("/findByTags") - - @Produces({ "application/json", "application/xml" }) - public Response findPetsByTags( @QueryParam("tags") List tags,@Context SecurityContext securityContext) - throws NotFoundException { - return delegate.findPetsByTags(tags,securityContext); - } - - @GET - @Path("/{petId}") - - @Produces({ "application/json", "application/xml" }) - public Response getPetById( @PathParam("petId") Long petId,@Context SecurityContext securityContext) - throws NotFoundException { - return delegate.getPetById(petId,securityContext); - } - - @POST - @Path("/{petId}") - @Consumes({ "application/x-www-form-urlencoded" }) - @Produces({ "application/json", "application/xml" }) - public Response updatePetWithForm( @PathParam("petId") String petId,@FormParam("name") String name,@FormParam("status") String status,@Context SecurityContext securityContext) - throws NotFoundException { - return delegate.updatePetWithForm(petId,name,status,securityContext); - } - @DELETE @Path("/{petId}") @@ -90,7 +42,62 @@ public class PetApi { throws NotFoundException { return delegate.deletePet(petId,apiKey,securityContext); } - + @GET + @Path("/findByStatus") + + @Produces({ "application/json", "application/xml" }) + public Response findPetsByStatus( @QueryParam("status") List status,@Context SecurityContext securityContext) + throws NotFoundException { + return delegate.findPetsByStatus(status,securityContext); + } + @GET + @Path("/findByTags") + + @Produces({ "application/json", "application/xml" }) + public Response findPetsByTags( @QueryParam("tags") List tags,@Context SecurityContext securityContext) + throws NotFoundException { + return delegate.findPetsByTags(tags,securityContext); + } + @GET + @Path("/{petId}") + + @Produces({ "application/json", "application/xml" }) + public Response getPetById( @PathParam("petId") Long petId,@Context SecurityContext securityContext) + throws NotFoundException { + return delegate.getPetById(petId,securityContext); + } + @GET + @Path("/{petId}?response=inline_arbitrary_object") + + @Produces({ "application/json", "application/xml" }) + public Response getPetByIdInObject( @PathParam("petId") Long petId,@Context SecurityContext securityContext) + throws NotFoundException { + return delegate.getPetByIdInObject(petId,securityContext); + } + @GET + @Path("/{petId}?testing_byte_array=true") + + @Produces({ "application/json", "application/xml" }) + public Response petPetIdtestingByteArraytrueGet( @PathParam("petId") Long petId,@Context SecurityContext securityContext) + throws NotFoundException { + return delegate.petPetIdtestingByteArraytrueGet(petId,securityContext); + } + @PUT + + @Consumes({ "application/json", "application/xml" }) + @Produces({ "application/json", "application/xml" }) + public Response updatePet( Pet body,@Context SecurityContext securityContext) + throws NotFoundException { + return delegate.updatePet(body,securityContext); + } + @POST + @Path("/{petId}") + @Consumes({ "application/x-www-form-urlencoded" }) + @Produces({ "application/json", "application/xml" }) + public Response updatePetWithForm( @PathParam("petId") String petId,@FormParam("name") String name,@FormParam("status") String status,@Context SecurityContext securityContext) + throws NotFoundException { + return delegate.updatePetWithForm(petId,name,status,securityContext); + } @POST @Path("/{petId}/uploadImage") @Consumes({ "multipart/form-data" }) @@ -99,15 +106,4 @@ public class PetApi { throws NotFoundException { return delegate.uploadFile(input,petId,securityContext); } - - @GET - @Path("/{petId}?testing_byte_array=true") - - @Produces({ "application/json", "application/xml" }) - public Response getPetByIdWithByteArray( @PathParam("petId") Long petId,@Context SecurityContext securityContext) - throws NotFoundException { - return delegate.getPetByIdWithByteArray(petId,securityContext); - } - } - diff --git a/samples/server/petstore/jaxrs-resteasy/src/gen/java/io/swagger/api/PetApiService.java b/samples/server/petstore/jaxrs-resteasy/src/gen/java/io/swagger/api/PetApiService.java index 485ef63212a..47ed65af8ab 100644 --- a/samples/server/petstore/jaxrs-resteasy/src/gen/java/io/swagger/api/PetApiService.java +++ b/samples/server/petstore/jaxrs-resteasy/src/gen/java/io/swagger/api/PetApiService.java @@ -6,9 +6,9 @@ import org.jboss.resteasy.plugins.providers.multipart.MultipartFormDataInput; import io.swagger.model.Pet; +import io.swagger.model.InlineResponse200; import java.io.File; - import java.util.List; import io.swagger.api.NotFoundException; @@ -17,14 +17,13 @@ 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.JavaResteasyServerCodegen", date = "2016-02-04T01:58:20.368+07:00") - +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaResteasyServerCodegen", date = "2016-03-16T14:27:58.108+08:00") public abstract class PetApiService { - public abstract Response updatePet(Pet body,SecurityContext securityContext) + public abstract Response addPet(Pet body,SecurityContext securityContext) throws NotFoundException; - public abstract Response addPet(Pet body,SecurityContext securityContext) + public abstract Response deletePet(Long petId,String apiKey,SecurityContext securityContext) throws NotFoundException; public abstract Response findPetsByStatus(List status,SecurityContext securityContext) @@ -36,17 +35,19 @@ public abstract class PetApiService { public abstract Response getPetById(Long petId,SecurityContext securityContext) throws NotFoundException; - public abstract Response updatePetWithForm(String petId,String name,String status,SecurityContext securityContext) + public abstract Response getPetByIdInObject(Long petId,SecurityContext securityContext) throws NotFoundException; - public abstract Response deletePet(Long petId,String apiKey,SecurityContext securityContext) + public abstract Response petPetIdtestingByteArraytrueGet(Long petId,SecurityContext securityContext) + throws NotFoundException; + + public abstract Response updatePet(Pet body,SecurityContext securityContext) + throws NotFoundException; + + public abstract Response updatePetWithForm(String petId,String name,String status,SecurityContext securityContext) throws NotFoundException; public abstract Response uploadFile(MultipartFormDataInput input,Long petId,SecurityContext securityContext) throws NotFoundException; - public abstract Response getPetByIdWithByteArray(Long petId,SecurityContext securityContext) - throws NotFoundException; - } - diff --git a/samples/server/petstore/jaxrs-resteasy/src/gen/java/io/swagger/api/PettestingByteArraytrueApi.java b/samples/server/petstore/jaxrs-resteasy/src/gen/java/io/swagger/api/PettestingByteArraytrueApi.java index e85fcfbe42c..8c742e89268 100644 --- a/samples/server/petstore/jaxrs-resteasy/src/gen/java/io/swagger/api/PettestingByteArraytrueApi.java +++ b/samples/server/petstore/jaxrs-resteasy/src/gen/java/io/swagger/api/PettestingByteArraytrueApi.java @@ -5,7 +5,6 @@ import io.swagger.api.PettestingByteArraytrueApiService; import io.swagger.api.factories.PettestingByteArraytrueApiServiceFactory; - import java.util.List; import io.swagger.api.NotFoundException; @@ -19,12 +18,10 @@ import javax.ws.rs.*; @Path("/pet?testing_byte_array=true") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaResteasyServerCodegen", date = "2016-02-04T01:58:20.368+07:00") - +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaResteasyServerCodegen", date = "2016-03-16T14:27:58.108+08:00") public class PettestingByteArraytrueApi { private final PettestingByteArraytrueApiService delegate = PettestingByteArraytrueApiServiceFactory.getPettestingByteArraytrueApi(); - @POST @Consumes({ "application/json", "application/xml" }) @@ -33,6 +30,4 @@ public class PettestingByteArraytrueApi { throws NotFoundException { return delegate.addPetUsingByteArray(body,securityContext); } - } - diff --git a/samples/server/petstore/jaxrs-resteasy/src/gen/java/io/swagger/api/PettestingByteArraytrueApiService.java b/samples/server/petstore/jaxrs-resteasy/src/gen/java/io/swagger/api/PettestingByteArraytrueApiService.java index 553cf5743e4..08186045b71 100644 --- a/samples/server/petstore/jaxrs-resteasy/src/gen/java/io/swagger/api/PettestingByteArraytrueApiService.java +++ b/samples/server/petstore/jaxrs-resteasy/src/gen/java/io/swagger/api/PettestingByteArraytrueApiService.java @@ -5,7 +5,6 @@ import io.swagger.model.*; - import java.util.List; import io.swagger.api.NotFoundException; @@ -14,12 +13,10 @@ 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.JavaResteasyServerCodegen", date = "2016-02-04T01:58:20.368+07:00") - +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaResteasyServerCodegen", date = "2016-03-16T14:27:58.108+08:00") public abstract class PettestingByteArraytrueApiService { public abstract Response addPetUsingByteArray(byte[] body,SecurityContext securityContext) throws NotFoundException; } - diff --git a/samples/server/petstore/jaxrs-resteasy/src/gen/java/io/swagger/api/StoreApi.java b/samples/server/petstore/jaxrs-resteasy/src/gen/java/io/swagger/api/StoreApi.java index 52f513318c8..945b73e32f3 100644 --- a/samples/server/petstore/jaxrs-resteasy/src/gen/java/io/swagger/api/StoreApi.java +++ b/samples/server/petstore/jaxrs-resteasy/src/gen/java/io/swagger/api/StoreApi.java @@ -4,9 +4,8 @@ import io.swagger.model.*; import io.swagger.api.StoreApiService; import io.swagger.api.factories.StoreApiServiceFactory; -import java.util.Map; import io.swagger.model.Order; - +import java.util.Map; import java.util.List; import io.swagger.api.NotFoundException; @@ -21,39 +20,10 @@ import javax.ws.rs.*; @Path("/store") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaResteasyServerCodegen", date = "2016-02-04T01:58:20.368+07:00") - +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaResteasyServerCodegen", date = "2016-03-16T14:27:58.108+08:00") public class StoreApi { private final StoreApiService delegate = StoreApiServiceFactory.getStoreApi(); - - @GET - @Path("/inventory") - - @Produces({ "application/json", "application/xml" }) - public Response getInventory(@Context SecurityContext securityContext) - throws NotFoundException { - return delegate.getInventory(securityContext); - } - - @POST - @Path("/order") - - @Produces({ "application/json", "application/xml" }) - public Response placeOrder( Order body,@Context SecurityContext securityContext) - throws NotFoundException { - return delegate.placeOrder(body,securityContext); - } - - @GET - @Path("/order/{orderId}") - - @Produces({ "application/json", "application/xml" }) - public Response getOrderById( @PathParam("orderId") String orderId,@Context SecurityContext securityContext) - throws NotFoundException { - return delegate.getOrderById(orderId,securityContext); - } - @DELETE @Path("/order/{orderId}") @@ -62,6 +32,44 @@ public class StoreApi { throws NotFoundException { return delegate.deleteOrder(orderId,securityContext); } - + @GET + @Path("/findByStatus") + + @Produces({ "application/json", "application/xml" }) + public Response findOrdersByStatus( @QueryParam("status") String status,@Context SecurityContext securityContext) + throws NotFoundException { + return delegate.findOrdersByStatus(status,securityContext); + } + @GET + @Path("/inventory") + + @Produces({ "application/json", "application/xml" }) + public Response getInventory(@Context SecurityContext securityContext) + throws NotFoundException { + return delegate.getInventory(securityContext); + } + @GET + @Path("/inventory?response=arbitrary_object") + + @Produces({ "application/json", "application/xml" }) + public Response getInventoryInObject(@Context SecurityContext securityContext) + throws NotFoundException { + return delegate.getInventoryInObject(securityContext); + } + @GET + @Path("/order/{orderId}") + + @Produces({ "application/json", "application/xml" }) + public Response getOrderById( @PathParam("orderId") String orderId,@Context SecurityContext securityContext) + throws NotFoundException { + return delegate.getOrderById(orderId,securityContext); + } + @POST + @Path("/order") + + @Produces({ "application/json", "application/xml" }) + public Response placeOrder( Order body,@Context SecurityContext securityContext) + throws NotFoundException { + return delegate.placeOrder(body,securityContext); + } } - diff --git a/samples/server/petstore/jaxrs-resteasy/src/gen/java/io/swagger/api/StoreApiService.java b/samples/server/petstore/jaxrs-resteasy/src/gen/java/io/swagger/api/StoreApiService.java index f0857c1cab6..61ad4fd923b 100644 --- a/samples/server/petstore/jaxrs-resteasy/src/gen/java/io/swagger/api/StoreApiService.java +++ b/samples/server/petstore/jaxrs-resteasy/src/gen/java/io/swagger/api/StoreApiService.java @@ -4,9 +4,8 @@ import io.swagger.api.*; import io.swagger.model.*; -import java.util.Map; import io.swagger.model.Order; - +import java.util.Map; import java.util.List; import io.swagger.api.NotFoundException; @@ -16,21 +15,25 @@ 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.JavaResteasyServerCodegen", date = "2016-02-04T01:58:20.368+07:00") - +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaResteasyServerCodegen", date = "2016-03-16T14:27:58.108+08:00") public abstract class StoreApiService { + public abstract Response deleteOrder(String orderId,SecurityContext securityContext) + throws NotFoundException; + + public abstract Response findOrdersByStatus(String status,SecurityContext securityContext) + throws NotFoundException; + public abstract Response getInventory(SecurityContext securityContext) throws NotFoundException; - public abstract Response placeOrder(Order body,SecurityContext securityContext) + public abstract Response getInventoryInObject(SecurityContext securityContext) throws NotFoundException; public abstract Response getOrderById(String orderId,SecurityContext securityContext) throws NotFoundException; - public abstract Response deleteOrder(String orderId,SecurityContext securityContext) + public abstract Response placeOrder(Order body,SecurityContext securityContext) throws NotFoundException; } - diff --git a/samples/server/petstore/jaxrs-resteasy/src/gen/java/io/swagger/api/StringUtil.java b/samples/server/petstore/jaxrs-resteasy/src/gen/java/io/swagger/api/StringUtil.java index 2747ff81082..87d9317396e 100644 --- a/samples/server/petstore/jaxrs-resteasy/src/gen/java/io/swagger/api/StringUtil.java +++ b/samples/server/petstore/jaxrs-resteasy/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-02-04T01:58:20.368+07:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaResteasyServerCodegen", date = "2016-03-16T14:27:58.108+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/src/gen/java/io/swagger/api/UserApi.java b/samples/server/petstore/jaxrs-resteasy/src/gen/java/io/swagger/api/UserApi.java index 2841e06a7d7..be7af49cefa 100644 --- a/samples/server/petstore/jaxrs-resteasy/src/gen/java/io/swagger/api/UserApi.java +++ b/samples/server/petstore/jaxrs-resteasy/src/gen/java/io/swagger/api/UserApi.java @@ -5,8 +5,7 @@ import io.swagger.api.UserApiService; import io.swagger.api.factories.UserApiServiceFactory; import io.swagger.model.User; -import java.util.*; - +import java.util.List; import java.util.List; import io.swagger.api.NotFoundException; @@ -21,12 +20,10 @@ import javax.ws.rs.*; @Path("/user") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaResteasyServerCodegen", date = "2016-02-04T01:58:20.368+07:00") - +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaResteasyServerCodegen", date = "2016-03-16T14:27:58.108+08:00") public class UserApi { private final UserApiService delegate = UserApiServiceFactory.getUserApi(); - @POST @@ -35,7 +32,6 @@ public class UserApi { throws NotFoundException { return delegate.createUser(body,securityContext); } - @POST @Path("/createWithArray") @@ -44,7 +40,6 @@ public class UserApi { throws NotFoundException { return delegate.createUsersWithArrayInput(body,securityContext); } - @POST @Path("/createWithList") @@ -53,43 +48,6 @@ public class UserApi { throws NotFoundException { return delegate.createUsersWithListInput(body,securityContext); } - - @GET - @Path("/login") - - @Produces({ "application/json", "application/xml" }) - public Response loginUser( @QueryParam("username") String username, @QueryParam("password") String password,@Context SecurityContext securityContext) - throws NotFoundException { - return delegate.loginUser(username,password,securityContext); - } - - @GET - @Path("/logout") - - @Produces({ "application/json", "application/xml" }) - public Response logoutUser(@Context SecurityContext securityContext) - throws NotFoundException { - return delegate.logoutUser(securityContext); - } - - @GET - @Path("/{username}") - - @Produces({ "application/json", "application/xml" }) - public Response getUserByName( @PathParam("username") String username,@Context SecurityContext securityContext) - throws NotFoundException { - return delegate.getUserByName(username,securityContext); - } - - @PUT - @Path("/{username}") - - @Produces({ "application/json", "application/xml" }) - public Response updateUser( @PathParam("username") String username, User body,@Context SecurityContext securityContext) - throws NotFoundException { - return delegate.updateUser(username,body,securityContext); - } - @DELETE @Path("/{username}") @@ -98,6 +56,36 @@ public class UserApi { throws NotFoundException { return delegate.deleteUser(username,securityContext); } - + @GET + @Path("/{username}") + + @Produces({ "application/json", "application/xml" }) + public Response getUserByName( @PathParam("username") String username,@Context SecurityContext securityContext) + throws NotFoundException { + return delegate.getUserByName(username,securityContext); + } + @GET + @Path("/login") + + @Produces({ "application/json", "application/xml" }) + public Response loginUser( @QueryParam("username") String username, @QueryParam("password") String password,@Context SecurityContext securityContext) + throws NotFoundException { + return delegate.loginUser(username,password,securityContext); + } + @GET + @Path("/logout") + + @Produces({ "application/json", "application/xml" }) + public Response logoutUser(@Context SecurityContext securityContext) + throws NotFoundException { + return delegate.logoutUser(securityContext); + } + @PUT + @Path("/{username}") + + @Produces({ "application/json", "application/xml" }) + public Response updateUser( @PathParam("username") String username, User body,@Context SecurityContext securityContext) + throws NotFoundException { + return delegate.updateUser(username,body,securityContext); + } } - diff --git a/samples/server/petstore/jaxrs-resteasy/src/gen/java/io/swagger/api/UserApiService.java b/samples/server/petstore/jaxrs-resteasy/src/gen/java/io/swagger/api/UserApiService.java index 09ac506294a..d28f14c07c0 100644 --- a/samples/server/petstore/jaxrs-resteasy/src/gen/java/io/swagger/api/UserApiService.java +++ b/samples/server/petstore/jaxrs-resteasy/src/gen/java/io/swagger/api/UserApiService.java @@ -5,8 +5,7 @@ import io.swagger.model.*; import io.swagger.model.User; -import java.util.*; - +import java.util.List; import java.util.List; import io.swagger.api.NotFoundException; @@ -16,8 +15,7 @@ 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.JavaResteasyServerCodegen", date = "2016-02-04T01:58:20.368+07:00") - +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaResteasyServerCodegen", date = "2016-03-16T14:27:58.108+08:00") public abstract class UserApiService { public abstract Response createUser(User body,SecurityContext securityContext) @@ -29,20 +27,19 @@ public abstract class UserApiService { public abstract Response createUsersWithListInput(List body,SecurityContext securityContext) throws NotFoundException; + public abstract Response deleteUser(String username,SecurityContext securityContext) + throws NotFoundException; + + public abstract Response getUserByName(String username,SecurityContext securityContext) + throws NotFoundException; + public abstract Response loginUser(String username,String password,SecurityContext securityContext) throws NotFoundException; public abstract Response logoutUser(SecurityContext securityContext) throws NotFoundException; - public abstract Response getUserByName(String username,SecurityContext securityContext) - throws NotFoundException; - public abstract Response updateUser(String username,User body,SecurityContext securityContext) throws NotFoundException; - public abstract Response deleteUser(String username,SecurityContext securityContext) - throws NotFoundException; - } - diff --git a/samples/server/petstore/jaxrs-resteasy/src/gen/java/io/swagger/model/Category.java b/samples/server/petstore/jaxrs-resteasy/src/gen/java/io/swagger/model/Category.java index 473b212ab2e..3786c816887 100644 --- a/samples/server/petstore/jaxrs-resteasy/src/gen/java/io/swagger/model/Category.java +++ b/samples/server/petstore/jaxrs-resteasy/src/gen/java/io/swagger/model/Category.java @@ -1,15 +1,14 @@ package io.swagger.model; import java.util.Objects; +import java.util.ArrayList; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonValue; - - -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaResteasyServerCodegen", date = "2016-02-04T01:58:20.368+07:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaResteasyServerCodegen", date = "2016-03-16T14:27:58.108+08:00") public class Category { private Long id = null; @@ -82,5 +81,3 @@ public class Category { } } - - diff --git a/samples/server/petstore/jaxrs-resteasy/src/gen/java/io/swagger/model/InlineResponse200.java b/samples/server/petstore/jaxrs-resteasy/src/gen/java/io/swagger/model/InlineResponse200.java new file mode 100644 index 00000000000..408a4ccdb0e --- /dev/null +++ b/samples/server/petstore/jaxrs-resteasy/src/gen/java/io/swagger/model/InlineResponse200.java @@ -0,0 +1,166 @@ +package io.swagger.model; + +import java.util.Objects; +import java.util.ArrayList; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.model.Tag; +import java.util.List; + + + + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaResteasyServerCodegen", date = "2016-03-16T14:27:58.108+08:00") +public class InlineResponse200 { + + private List tags = new ArrayList(); + private Long id = null; + private Object category = null; + + + 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; + private String name = null; + private List photoUrls = new ArrayList(); + + + /** + **/ + + @JsonProperty("tags") + public List getTags() { + return tags; + } + public void setTags(List tags) { + this.tags = tags; + } + + + /** + **/ + + @JsonProperty("id") + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + + /** + **/ + + @JsonProperty("category") + public Object getCategory() { + return category; + } + public void setCategory(Object category) { + this.category = category; + } + + + /** + * pet status in the store + **/ + + @JsonProperty("status") + public StatusEnum getStatus() { + return status; + } + public void setStatus(StatusEnum status) { + this.status = status; + } + + + /** + **/ + + @JsonProperty("name") + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + + + /** + **/ + + @JsonProperty("photoUrls") + public List getPhotoUrls() { + return photoUrls; + } + public void setPhotoUrls(List photoUrls) { + this.photoUrls = photoUrls; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + InlineResponse200 inlineResponse200 = (InlineResponse200) o; + return Objects.equals(tags, inlineResponse200.tags) && + Objects.equals(id, inlineResponse200.id) && + Objects.equals(category, inlineResponse200.category) && + Objects.equals(status, inlineResponse200.status) && + Objects.equals(name, inlineResponse200.name) && + Objects.equals(photoUrls, inlineResponse200.photoUrls); + } + + @Override + public int hashCode() { + return Objects.hash(tags, id, category, status, name, photoUrls); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class InlineResponse200 {\n"); + + sb.append(" tags: ").append(toIndentedString(tags)).append("\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" category: ").append(toIndentedString(category)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" photoUrls: ").append(toIndentedString(photoUrls)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs-resteasy/src/gen/java/io/swagger/model/ModelReturn.java b/samples/server/petstore/jaxrs-resteasy/src/gen/java/io/swagger/model/ModelReturn.java new file mode 100644 index 00000000000..a7ab3bb3df6 --- /dev/null +++ b/samples/server/petstore/jaxrs-resteasy/src/gen/java/io/swagger/model/ModelReturn.java @@ -0,0 +1,68 @@ +package io.swagger.model; + +import java.util.Objects; +import java.util.ArrayList; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonValue; + + + + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaResteasyServerCodegen", date = "2016-03-16T14:27:58.108+08:00") +public class ModelReturn { + + private Integer _return = null; + + + /** + **/ + + @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/jaxrs-resteasy/src/gen/java/io/swagger/model/Name.java b/samples/server/petstore/jaxrs-resteasy/src/gen/java/io/swagger/model/Name.java new file mode 100644 index 00000000000..ff879eeb209 --- /dev/null +++ b/samples/server/petstore/jaxrs-resteasy/src/gen/java/io/swagger/model/Name.java @@ -0,0 +1,68 @@ +package io.swagger.model; + +import java.util.Objects; +import java.util.ArrayList; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonValue; + + + + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaResteasyServerCodegen", date = "2016-03-16T14:27:58.108+08:00") +public class Name { + + private Integer name = null; + + + /** + **/ + + @JsonProperty("name") + public Integer getName() { + return name; + } + public void setName(Integer name) { + this.name = name; + } + + + + @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); + } + + @Override + public int hashCode() { + return Objects.hash(name); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Name {\n"); + + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs-resteasy/src/gen/java/io/swagger/model/Order.java b/samples/server/petstore/jaxrs-resteasy/src/gen/java/io/swagger/model/Order.java index acd23dfd33c..1d40f9c3359 100644 --- a/samples/server/petstore/jaxrs-resteasy/src/gen/java/io/swagger/model/Order.java +++ b/samples/server/petstore/jaxrs-resteasy/src/gen/java/io/swagger/model/Order.java @@ -1,6 +1,7 @@ package io.swagger.model; import java.util.Objects; +import java.util.ArrayList; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonValue; import java.util.Date; @@ -8,9 +9,7 @@ import java.util.Date; - - -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaResteasyServerCodegen", date = "2016-02-04T01:58:20.368+07:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaResteasyServerCodegen", date = "2016-03-16T14:27:58.108+08:00") public class Order { private Long id = null; @@ -164,5 +163,3 @@ public class Order { } } - - diff --git a/samples/server/petstore/jaxrs-resteasy/src/gen/java/io/swagger/model/Pet.java b/samples/server/petstore/jaxrs-resteasy/src/gen/java/io/swagger/model/Pet.java index efc60c75bbe..51f31e982ef 100644 --- a/samples/server/petstore/jaxrs-resteasy/src/gen/java/io/swagger/model/Pet.java +++ b/samples/server/petstore/jaxrs-resteasy/src/gen/java/io/swagger/model/Pet.java @@ -1,18 +1,17 @@ package io.swagger.model; import java.util.Objects; +import java.util.ArrayList; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonValue; import io.swagger.model.Category; import io.swagger.model.Tag; -import java.util.*; +import java.util.List; - - -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaResteasyServerCodegen", date = "2016-02-04T01:58:20.368+07:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaResteasyServerCodegen", date = "2016-03-16T14:27:58.108+08:00") public class Pet { private Long id = null; @@ -166,5 +165,3 @@ public class Pet { } } - - diff --git a/samples/server/petstore/jaxrs-resteasy/src/gen/java/io/swagger/model/SpecialModelName.java b/samples/server/petstore/jaxrs-resteasy/src/gen/java/io/swagger/model/SpecialModelName.java new file mode 100644 index 00000000000..f5c2edcb253 --- /dev/null +++ b/samples/server/petstore/jaxrs-resteasy/src/gen/java/io/swagger/model/SpecialModelName.java @@ -0,0 +1,68 @@ +package io.swagger.model; + +import java.util.Objects; +import java.util.ArrayList; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonValue; + + + + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaResteasyServerCodegen", date = "2016-03-16T14:27:58.108+08:00") +public class SpecialModelName { + + private Long specialPropertyName = null; + + + /** + **/ + + @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/jaxrs-resteasy/src/gen/java/io/swagger/model/Tag.java b/samples/server/petstore/jaxrs-resteasy/src/gen/java/io/swagger/model/Tag.java index e3756279b4d..9f231bfabcd 100644 --- a/samples/server/petstore/jaxrs-resteasy/src/gen/java/io/swagger/model/Tag.java +++ b/samples/server/petstore/jaxrs-resteasy/src/gen/java/io/swagger/model/Tag.java @@ -1,15 +1,14 @@ package io.swagger.model; import java.util.Objects; +import java.util.ArrayList; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonValue; - - -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaResteasyServerCodegen", date = "2016-02-04T01:58:20.368+07:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaResteasyServerCodegen", date = "2016-03-16T14:27:58.108+08:00") public class Tag { private Long id = null; @@ -82,5 +81,3 @@ public class Tag { } } - - diff --git a/samples/server/petstore/jaxrs-resteasy/src/gen/java/io/swagger/model/User.java b/samples/server/petstore/jaxrs-resteasy/src/gen/java/io/swagger/model/User.java index 1df990a8163..16b2b78a9f3 100644 --- a/samples/server/petstore/jaxrs-resteasy/src/gen/java/io/swagger/model/User.java +++ b/samples/server/petstore/jaxrs-resteasy/src/gen/java/io/swagger/model/User.java @@ -1,15 +1,14 @@ package io.swagger.model; import java.util.Objects; +import java.util.ArrayList; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonValue; - - -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaResteasyServerCodegen", date = "2016-02-04T01:58:20.368+07:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaResteasyServerCodegen", date = "2016-03-16T14:27:58.108+08:00") public class User { private Long id = null; @@ -173,5 +172,3 @@ public class User { } } - - diff --git a/samples/server/petstore/jaxrs-resteasy/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java b/samples/server/petstore/jaxrs-resteasy/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java index 9657e9b17cc..1e4b479b32f 100644 --- a/samples/server/petstore/jaxrs-resteasy/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java +++ b/samples/server/petstore/jaxrs-resteasy/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java @@ -20,69 +20,66 @@ import javax.ws.rs.core.SecurityContext; @javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaResteasyServerCodegen", date = "2016-02-04T01:58:20.368+07:00") public class PetApiServiceImpl extends PetApiService { - - @Override - public Response updatePet(Pet body,SecurityContext securityContext) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - - @Override - public Response addPet(Pet body,SecurityContext securityContext) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - - @Override - public Response findPetsByStatus(List status,SecurityContext securityContext) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - - @Override - public Response findPetsByTags(List tags,SecurityContext securityContext) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - - @Override - public Response getPetById(Long petId,SecurityContext securityContext) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - - @Override - public Response updatePetWithForm(String petId,String name,String status,SecurityContext securityContext) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - - @Override - public Response deletePet(Long petId,String apiKey,SecurityContext securityContext) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - - @Override - public Response uploadFile(MultipartFormDataInput input,Long petId,SecurityContext securityContext) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - - @Override - public Response getPetByIdWithByteArray(Long petId,SecurityContext securityContext) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - + + @Override + public Response updatePet(Pet body,SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + + @Override + public Response addPet(Pet body,SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + + @Override + public Response findPetsByStatus(List status,SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + + @Override + public Response findPetsByTags(List tags,SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + + @Override + public Response getPetById(Long petId,SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + + @Override + public Response getPetByIdInObject(Long petId,SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + + @Override + public Response updatePetWithForm(String petId,String name,String status,SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + + @Override + public Response deletePet(Long petId,String apiKey,SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + + @Override + public Response uploadFile(MultipartFormDataInput input,Long petId,SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + + @Override + public Response petPetIdtestingByteArraytrueGet(Long petId,SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + } diff --git a/samples/server/petstore/jaxrs-resteasy/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java b/samples/server/petstore/jaxrs-resteasy/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java index f8538681c49..0bb503589cb 100644 --- a/samples/server/petstore/jaxrs-resteasy/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java +++ b/samples/server/petstore/jaxrs-resteasy/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java @@ -19,34 +19,42 @@ import javax.ws.rs.core.SecurityContext; @javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaResteasyServerCodegen", date = "2016-02-04T01:58:20.368+07:00") public class StoreApiServiceImpl extends StoreApiService { - - @Override - public Response getInventory(SecurityContext securityContext) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - - @Override - public Response placeOrder(Order body,SecurityContext securityContext) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - - @Override - public Response getOrderById(String orderId,SecurityContext securityContext) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - - @Override - public Response deleteOrder(String orderId,SecurityContext securityContext) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - + + @Override + public Response getInventory(SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + + @Override + public Response getInventoryInObject(SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + + @Override + public Response placeOrder(Order body,SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + + @Override + public Response getOrderById(String orderId,SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + + @Override + public Response deleteOrder(String orderId,SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + + @Override + public Response findOrdersByStatus(String status, SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + } diff --git a/samples/server/petstore/jaxrs-resteasy/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java b/samples/server/petstore/jaxrs-resteasy/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java index 2640ecd3121..e2d9acb67ba 100644 --- a/samples/server/petstore/jaxrs-resteasy/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java +++ b/samples/server/petstore/jaxrs-resteasy/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java @@ -19,62 +19,54 @@ import javax.ws.rs.core.SecurityContext; @javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaResteasyServerCodegen", date = "2016-02-04T01:58:20.368+07:00") public class UserApiServiceImpl extends UserApiService { - - @Override - public Response createUser(User body,SecurityContext securityContext) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - - @Override - public Response createUsersWithArrayInput(List body,SecurityContext securityContext) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - - @Override - public Response createUsersWithListInput(List body,SecurityContext securityContext) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - - @Override - public Response loginUser(String username,String password,SecurityContext securityContext) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - - @Override - public Response logoutUser(SecurityContext securityContext) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - - @Override - public Response getUserByName(String username,SecurityContext securityContext) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - - @Override - public Response updateUser(String username,User body,SecurityContext securityContext) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - - @Override - public Response deleteUser(String username,SecurityContext securityContext) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - + + @Override + public Response createUser(User body,SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + + @Override + public Response createUsersWithArrayInput(List body,SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + + @Override + public Response createUsersWithListInput(List body,SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + + @Override + public Response loginUser(String username,String password,SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + + @Override + public Response logoutUser(SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + + @Override + public Response getUserByName(String username,SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + + @Override + public Response updateUser(String username,User body,SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + + @Override + public Response deleteUser(String username,SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + } diff --git a/samples/server/petstore/jaxrs/pom.xml b/samples/server/petstore/jaxrs/pom.xml index c9c9a8b0ad5..9064489b34d 100644 --- a/samples/server/petstore/jaxrs/pom.xml +++ b/samples/server/petstore/jaxrs/pom.xml @@ -168,7 +168,7 @@ - 1.5.7 + 1.5.8 9.2.9.v20150224 1.18.1 1.6.3 diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/ApiException.java b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/ApiException.java index 05a021fa926..7fa61c50d24 100644 --- a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/ApiException.java +++ b/samples/server/petstore/jaxrs/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.JavaJerseyServerCodegen", date = "2016-01-31T21:10:14.319Z") + public class ApiException extends Exception{ private int code; public ApiException (int code, String msg) { diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/ApiOriginFilter.java b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/ApiOriginFilter.java index 453651a7531..2dc07362c92 100644 --- a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/ApiOriginFilter.java +++ b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/ApiOriginFilter.java @@ -5,7 +5,7 @@ import java.io.IOException; import javax.servlet.*; import javax.servlet.http.HttpServletResponse; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaJerseyServerCodegen", date = "2016-01-31T21:10:14.319Z") + 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/src/gen/java/io/swagger/api/ApiResponseMessage.java b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/ApiResponseMessage.java index cdaec8116e1..33f95878e54 100644 --- a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/ApiResponseMessage.java +++ b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/ApiResponseMessage.java @@ -3,7 +3,7 @@ package io.swagger.api; import javax.xml.bind.annotation.XmlTransient; @javax.xml.bind.annotation.XmlRootElement -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaJerseyServerCodegen", date = "2016-01-31T21:10:14.319Z") + public class ApiResponseMessage { public static final int ERROR = 1; public static final int WARNING = 2; diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/JacksonJsonProvider.java b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/JacksonJsonProvider.java new file mode 100644 index 00000000000..49792814c5e --- /dev/null +++ b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/JacksonJsonProvider.java @@ -0,0 +1,19 @@ +package io.swagger.api; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider; +import io.swagger.util.Json; + +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.ext.Provider; + +@Provider +@Produces({MediaType.APPLICATION_JSON}) +public class JacksonJsonProvider extends JacksonJaxbJsonProvider { + private static ObjectMapper commonMapper = Json.mapper(); + + public JacksonJsonProvider() { + super.setMapper(commonMapper); + } +} \ No newline at end of file diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/NotFoundException.java b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/NotFoundException.java index 09e3cde5a11..295109d7fc4 100644 --- a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/NotFoundException.java +++ b/samples/server/petstore/jaxrs/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.JavaJerseyServerCodegen", date = "2016-01-31T21:10:14.319Z") + public class NotFoundException extends ApiException { private int code; public NotFoundException (int code, String msg) { diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/PetApi.java b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/PetApi.java index 5951ff34fab..500451add3a 100644 --- a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/PetApi.java +++ b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/PetApi.java @@ -9,6 +9,7 @@ import io.swagger.annotations.ApiParam; import com.sun.jersey.multipart.FormDataParam; import io.swagger.model.Pet; +import io.swagger.model.ApiResponse; import java.io.File; import java.util.List; @@ -28,36 +29,14 @@ import javax.ws.rs.*; @io.swagger.annotations.Api(description = "the pet API") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaJerseyServerCodegen", date = "2016-01-31T21:10:14.319Z") + public class PetApi { private final PetApiService delegate = PetApiServiceFactory.getPetApi(); - @PUT - - @Consumes({ "application/json", "application/xml" }) - @Produces({ "application/json", "application/xml" }) - @io.swagger.annotations.ApiOperation(value = "Update an existing pet", notes = "", response = void.class, authorizations = { - @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { - @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), - @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") - }) - }, tags={ "pet", }) - @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid ID supplied", response = void.class), - - @io.swagger.annotations.ApiResponse(code = 404, message = "Pet not found", response = void.class), - - @io.swagger.annotations.ApiResponse(code = 405, message = "Validation exception", response = void.class) }) - - public Response updatePet( -@ApiParam(value = "Pet object that needs to be added to the store" ) Pet body,@Context SecurityContext securityContext) - throws NotFoundException { - return delegate.updatePet(body,securityContext); - } @POST @Consumes({ "application/json", "application/xml" }) - @Produces({ "application/json", "application/xml" }) + @Produces({ "application/xml", "application/json" }) @io.swagger.annotations.ApiOperation(value = "Add a new pet to the store", notes = "", response = void.class, authorizations = { @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), @@ -66,95 +45,16 @@ 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" ) Pet body,@Context SecurityContext securityContext) + @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); } - @GET - @Path("/findByStatus") - - @Produces({ "application/json", "application/xml" }) - @io.swagger.annotations.ApiOperation(value = "Finds Pets by status", notes = "Multiple status values can be provided with comma seperated strings", response = Pet.class, responseContainer = "List", authorizations = { - @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { - @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), - @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") - }) - }, tags={ "pet", }) - @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Pet.class, responseContainer = "List"), - - @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid status value", response = Pet.class, responseContainer = "List") }) - - public Response findPetsByStatus(@ApiParam(value = "Status values that need to be considered for filter", defaultValue="available") @DefaultValue("available") @QueryParam("status") List status -,@Context SecurityContext securityContext) - throws NotFoundException { - return delegate.findPetsByStatus(status,securityContext); - } - @GET - @Path("/findByTags") - - @Produces({ "application/json", "application/xml" }) - @io.swagger.annotations.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 = { - @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { - @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), - @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") - }) - }, tags={ "pet", }) - @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Pet.class, responseContainer = "List"), - - @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid tag value", response = Pet.class, responseContainer = "List") }) - - public Response findPetsByTags(@ApiParam(value = "Tags to filter by") @QueryParam("tags") List tags -,@Context SecurityContext securityContext) - throws NotFoundException { - return delegate.findPetsByTags(tags,securityContext); - } - @GET - @Path("/{petId}") - - @Produces({ "application/json", "application/xml" }) - @io.swagger.annotations.ApiOperation(value = "Find pet by ID", notes = "Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions", response = Pet.class, authorizations = { - @io.swagger.annotations.Authorization(value = "api_key") - }, tags={ "pet", }) - @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Pet.class), - - @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid ID supplied", response = Pet.class), - - @io.swagger.annotations.ApiResponse(code = 404, message = "Pet not found", response = Pet.class) }) - - public Response getPetById( -@ApiParam(value = "ID of pet that needs to be fetched",required=true) @PathParam("petId") Long petId,@Context SecurityContext securityContext) - throws NotFoundException { - return delegate.getPetById(petId,securityContext); - } - @POST - @Path("/{petId}") - @Consumes({ "application/x-www-form-urlencoded" }) - @Produces({ "application/json", "application/xml" }) - @io.swagger.annotations.ApiOperation(value = "Updates a pet in the store with form data", notes = "", response = void.class, authorizations = { - @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { - @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), - @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") - }) - }, tags={ "pet", }) - @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 405, message = "Invalid input", response = void.class) }) - - public Response updatePetWithForm( -@ApiParam(value = "ID of pet that needs to be updated",required=true) @PathParam("petId") String 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); - } @DELETE @Path("/{petId}") - @Produces({ "application/json", "application/xml" }) + @Produces({ "application/xml", "application/json" }) @io.swagger.annotations.ApiOperation(value = "Deletes a pet", notes = "", response = void.class, authorizations = { @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), @@ -162,52 +62,129 @@ public class PetApi { }) }, tags={ "pet", }) @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid pet value", response = void.class) }) - + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid ID supplied", response = void.class), + @io.swagger.annotations.ApiResponse(code = 404, message = "Pet not found", response = void.class) }) 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) + @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); } - @POST - @Path("/{petId}/uploadImage") - @Consumes({ "multipart/form-data" }) - @Produces({ "application/json", "application/xml" }) - @io.swagger.annotations.ApiOperation(value = "uploads an image", notes = "", response = void.class, authorizations = { + @GET + @Path("/findByStatus") + + @Produces({ "application/xml", "application/json" }) + @io.swagger.annotations.ApiOperation(value = "Finds Pets by status", notes = "Multiple status values can be provided with comma separated strings", response = Pet.class, responseContainer = "List", authorizations = { @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") }) }, tags={ "pet", }) @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = void.class) }) - + @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Pet.class, responseContainer = "List"), + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid status value", response = Pet.class, responseContainer = "List") }) + public Response findPetsByStatus( + @ApiParam(value = "Status values that need to be considered for filter",required=true) @QueryParam("status") List status, + @Context SecurityContext securityContext) + throws NotFoundException { + return delegate.findPetsByStatus(status,securityContext); + } + @GET + @Path("/findByTags") + + @Produces({ "application/xml", "application/json" }) + @io.swagger.annotations.ApiOperation(value = "Finds Pets by tags", notes = "Muliple tags can be provided with comma separated strings. Use\ntag1, tag2, tag3 for testing.\n", response = Pet.class, responseContainer = "List", authorizations = { + @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { + @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }, tags={ "pet", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Pet.class, responseContainer = "List"), + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid tag value", response = Pet.class, responseContainer = "List") }) + public Response findPetsByTags( + @ApiParam(value = "Tags to filter by",required=true) @QueryParam("tags") List tags, + @Context SecurityContext securityContext) + throws NotFoundException { + return delegate.findPetsByTags(tags,securityContext); + } + @GET + @Path("/{petId}") + + @Produces({ "application/xml", "application/json" }) + @io.swagger.annotations.ApiOperation(value = "Find pet by ID", notes = "Returns a single pet", response = Pet.class, authorizations = { + @io.swagger.annotations.Authorization(value = "api_key") + }, tags={ "pet", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Pet.class), + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid ID supplied", response = Pet.class), + @io.swagger.annotations.ApiResponse(code = 404, message = "Pet not found", response = Pet.class) }) + public Response getPetById( + @ApiParam(value = "ID of pet to return",required=true) @PathParam("petId") Long petId, + @Context SecurityContext securityContext) + throws NotFoundException { + return delegate.getPetById(petId,securityContext); + } + @PUT + + @Consumes({ "application/json", "application/xml" }) + @Produces({ "application/xml", "application/json" }) + @io.swagger.annotations.ApiOperation(value = "Update an existing pet", notes = "", response = void.class, authorizations = { + @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { + @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }, tags={ "pet", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid ID supplied", response = void.class), + @io.swagger.annotations.ApiResponse(code = 404, message = "Pet not found", response = void.class), + @io.swagger.annotations.ApiResponse(code = 405, message = "Validation exception", response = void.class) }) + public Response updatePet( + @ApiParam(value = "Pet object that needs to be added to the store" ,required=true) Pet body, + @Context SecurityContext securityContext) + throws NotFoundException { + return delegate.updatePet(body,securityContext); + } + @POST + @Path("/{petId}") + @Consumes({ "application/x-www-form-urlencoded" }) + @Produces({ "application/xml", "application/json" }) + @io.swagger.annotations.ApiOperation(value = "Updates a pet in the store with form data", notes = "null", response = void.class, authorizations = { + @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { + @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }, tags={ "pet", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 405, message = "Invalid input", response = void.class) }) + public Response updatePetWithForm( + @ApiParam(value = "ID of pet that needs to be updated",required=true) @PathParam("petId") Long petId, + @ApiParam(value = "Updated name of the pet")@FormParam("name") String name, + @ApiParam(value = "Updated status of the pet")@FormParam("status") String status, + @Context SecurityContext securityContext) + throws NotFoundException { + return delegate.updatePetWithForm(petId,name,status,securityContext); + } + @POST + @Path("/{petId}/uploadImage") + @Consumes({ "multipart/form-data" }) + @Produces({ "application/json" }) + @io.swagger.annotations.ApiOperation(value = "uploads an image", notes = "", response = ApiResponse.class, authorizations = { + @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { + @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }, tags={ "pet" }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = ApiResponse.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")@FormParam("additionalMetadata") String additionalMetadata, - @FormDataParam("file") InputStream inputStream, - @FormDataParam("file") FormDataContentDisposition fileDetail,@Context SecurityContext securityContext) + @ApiParam(value = "ID of pet to update",required=true) @PathParam("petId") Long petId, + @FormDataParam("additionalMetadata") String additionalMetadata, + @FormDataParam("file") InputStream inputStream, + @FormDataParam("file") FormDataContentDisposition fileDetail, + @Context SecurityContext securityContext) throws NotFoundException { return delegate.uploadFile(petId,additionalMetadata,inputStream, fileDetail,securityContext); } - @GET - @Path("/{petId}?testing_byte_array=true") - - @Produces({ "application/json", "application/xml" }) - @io.swagger.annotations.ApiOperation(value = "Fake endpoint to test byte array return by 'Find pet by ID'", notes = "Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions", response = byte[].class, authorizations = { - @io.swagger.annotations.Authorization(value = "api_key") - }, tags={ "pet" }) - @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = byte[].class), - - @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid ID supplied", response = byte[].class), - - @io.swagger.annotations.ApiResponse(code = 404, message = "Pet not found", response = byte[].class) }) - - public Response getPetByIdWithByteArray( -@ApiParam(value = "ID of pet that needs to be fetched",required=true) @PathParam("petId") Long petId,@Context SecurityContext securityContext) - throws NotFoundException { - return delegate.getPetByIdWithByteArray(petId,securityContext); - } } diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/PetApiService.java b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/PetApiService.java index 589ffc75d64..2aa3ab0cd34 100644 --- a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/PetApiService.java +++ b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/PetApiService.java @@ -6,6 +6,7 @@ import io.swagger.model.*; import com.sun.jersey.multipart.FormDataParam; import io.swagger.model.Pet; +import io.swagger.model.ApiResponse; import java.io.File; import java.util.List; @@ -19,13 +20,13 @@ import com.sun.jersey.multipart.FormDataParam; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaJerseyServerCodegen", date = "2016-01-31T21:10:14.319Z") + public abstract class PetApiService { - public abstract Response updatePet(Pet body,SecurityContext securityContext) + public abstract Response addPet(Pet body,SecurityContext securityContext) throws NotFoundException; - public abstract Response addPet(Pet body,SecurityContext securityContext) + public abstract Response deletePet(Long petId,String apiKey,SecurityContext securityContext) throws NotFoundException; public abstract Response findPetsByStatus(List status,SecurityContext securityContext) @@ -37,16 +38,13 @@ public abstract class PetApiService { public abstract Response getPetById(Long petId,SecurityContext securityContext) throws NotFoundException; - public abstract Response updatePetWithForm(String petId,String name,String status,SecurityContext securityContext) + public abstract Response updatePet(Pet body,SecurityContext securityContext) throws NotFoundException; - public abstract Response deletePet(Long petId,String apiKey,SecurityContext securityContext) + 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 getPetByIdWithByteArray(Long petId,SecurityContext securityContext) - throws NotFoundException; - } diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/PettestingByteArraytrueApi.java b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/PettestingByteArraytrueApi.java deleted file mode 100644 index 8bdad3def7f..00000000000 --- a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/PettestingByteArraytrueApi.java +++ /dev/null @@ -1,51 +0,0 @@ -package io.swagger.api; - -import io.swagger.model.*; -import io.swagger.api.PettestingByteArraytrueApiService; -import io.swagger.api.factories.PettestingByteArraytrueApiServiceFactory; - -import io.swagger.annotations.ApiParam; - -import com.sun.jersey.multipart.FormDataParam; - - -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("/pet?testing_byte_array=true") - - -@io.swagger.annotations.Api(description = "the pet?testing_byte_array=true API") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaJerseyServerCodegen", date = "2016-01-31T21:10:14.319Z") -public class PettestingByteArraytrueApi { - private final PettestingByteArraytrueApiService delegate = PettestingByteArraytrueApiServiceFactory.getPettestingByteArraytrueApi(); - - @POST - - @Consumes({ "application/json", "application/xml" }) - @Produces({ "application/json", "application/xml" }) - @io.swagger.annotations.ApiOperation(value = "Fake endpoint to test byte array in body parameter for adding a new pet to the store", notes = "", response = void.class, authorizations = { - @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { - @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), - @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") - }) - }, tags={ "pet" }) - @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 405, message = "Invalid input", response = void.class) }) - - public Response addPetUsingByteArray( -@ApiParam(value = "Pet object in the form of byte array" ) byte[] body,@Context SecurityContext securityContext) - throws NotFoundException { - return delegate.addPetUsingByteArray(body,securityContext); - } -} diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/PettestingByteArraytrueApiService.java b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/PettestingByteArraytrueApiService.java deleted file mode 100644 index 01ca4f1e877..00000000000 --- a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/PettestingByteArraytrueApiService.java +++ /dev/null @@ -1,26 +0,0 @@ -package io.swagger.api; - -import io.swagger.api.*; -import io.swagger.model.*; - -import com.sun.jersey.multipart.FormDataParam; - - -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; - -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaJerseyServerCodegen", date = "2016-01-31T21:10:14.319Z") -public abstract class PettestingByteArraytrueApiService { - - public abstract Response addPetUsingByteArray(byte[] body,SecurityContext securityContext) - throws NotFoundException; - -} diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/StoreApi.java b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/StoreApi.java index 0200a17a256..c9d9a17aec7 100644 --- a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/StoreApi.java +++ b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/StoreApi.java @@ -28,69 +28,65 @@ import javax.ws.rs.*; @io.swagger.annotations.Api(description = "the store API") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaJerseyServerCodegen", date = "2016-01-31T21:10:14.319Z") + public class StoreApi { private final StoreApiService delegate = StoreApiServiceFactory.getStoreApi(); + @DELETE + @Path("/order/{orderId}") + + @Produces({ "application/xml", "application/json" }) + @io.swagger.annotations.ApiOperation(value = "Delete purchase order by ID", notes = "For valid response try integer IDs with positive integer value.\\ \\ Negative or non-integer values will generate API errors", response = void.class, tags={ "store", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid ID supplied", response = void.class), + @io.swagger.annotations.ApiResponse(code = 404, message = "Order not found", response = void.class) }) + public Response deleteOrder( + @ApiParam(value = "ID of the order that needs to be deleted",required=true) @PathParam("orderId") Long orderId, + @Context SecurityContext securityContext) + throws NotFoundException { + return delegate.deleteOrder(orderId,securityContext); + } @GET @Path("/inventory") - @Produces({ "application/json", "application/xml" }) + @Produces({ "application/json" }) @io.swagger.annotations.ApiOperation(value = "Returns pet inventories by status", notes = "Returns a map of status codes to quantities", response = Integer.class, responseContainer = "Map", authorizations = { @io.swagger.annotations.Authorization(value = "api_key") }, tags={ "store", }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Integer.class, responseContainer = "Map") }) - - public Response getInventory(@Context SecurityContext securityContext) + public Response getInventory( + @Context SecurityContext securityContext) throws NotFoundException { return delegate.getInventory(securityContext); } - @POST - @Path("/order") - - @Produces({ "application/json", "application/xml" }) - @io.swagger.annotations.ApiOperation(value = "Place an order for a pet", notes = "", response = Order.class, tags={ "store", }) - @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Order.class), - - @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid Order", response = Order.class) }) - - public Response placeOrder( -@ApiParam(value = "order placed for purchasing the pet" ) Order body,@Context SecurityContext securityContext) - throws NotFoundException { - return delegate.placeOrder(body,securityContext); - } @GET @Path("/order/{orderId}") - @Produces({ "application/json", "application/xml" }) - @io.swagger.annotations.ApiOperation(value = "Find purchase order by ID", notes = "For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions", response = Order.class, tags={ "store", }) + @Produces({ "application/xml", "application/json" }) + @io.swagger.annotations.ApiOperation(value = "Find purchase order by ID", notes = "For valid response try integer IDs with value >= 1 and <= 10.\nOther values will generated exceptions\n", response = Order.class, tags={ "store", }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Order.class), - @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid ID supplied", response = Order.class), - @io.swagger.annotations.ApiResponse(code = 404, message = "Order not found", response = Order.class) }) - public Response getOrderById( -@ApiParam(value = "ID of pet that needs to be fetched",required=true) @PathParam("orderId") String orderId,@Context SecurityContext securityContext) + @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); } - @DELETE - @Path("/order/{orderId}") + @POST + @Path("/order") - @Produces({ "application/json", "application/xml" }) - @io.swagger.annotations.ApiOperation(value = "Delete purchase order by ID", notes = "For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors", response = void.class, tags={ "store" }) + @Produces({ "application/xml", "application/json" }) + @io.swagger.annotations.ApiOperation(value = "Place an order for a pet", notes = "", response = Order.class, tags={ "store" }) @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 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) + @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Order.class), + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid Order", response = Order.class) }) + public Response placeOrder( + @ApiParam(value = "order placed for purchasing the pet" ,required=true) Order body, + @Context SecurityContext securityContext) throws NotFoundException { - return delegate.deleteOrder(orderId,securityContext); + return delegate.placeOrder(body,securityContext); } } diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/StoreApiService.java b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/StoreApiService.java index a332fbd7a4f..643a46d6596 100644 --- a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/StoreApiService.java +++ b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/StoreApiService.java @@ -19,19 +19,19 @@ import com.sun.jersey.multipart.FormDataParam; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaJerseyServerCodegen", date = "2016-01-31T21:10:14.319Z") + public abstract class StoreApiService { + public abstract Response deleteOrder(Long orderId,SecurityContext securityContext) + throws NotFoundException; + public abstract Response getInventory(SecurityContext securityContext) throws NotFoundException; + public abstract Response getOrderById(Long orderId,SecurityContext securityContext) + throws NotFoundException; + public abstract Response placeOrder(Order body,SecurityContext securityContext) throws NotFoundException; - public abstract Response getOrderById(String orderId,SecurityContext securityContext) - throws NotFoundException; - - public abstract Response deleteOrder(String orderId,SecurityContext securityContext) - throws NotFoundException; - } diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/StringUtil.java b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/StringUtil.java index 7b6da6b2c21..6f4a3dadbbf 100644 --- a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/StringUtil.java +++ b/samples/server/petstore/jaxrs/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.JavaJerseyServerCodegen", date = "2016-01-31T21:10:14.319Z") + public class StringUtil { /** * Check if the given array contains the given value (with case-insensitive comparison). diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/UserApi.java b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/UserApi.java index 160019dbe2d..43728481866 100644 --- a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/UserApi.java +++ b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/UserApi.java @@ -9,7 +9,7 @@ import io.swagger.annotations.ApiParam; import com.sun.jersey.multipart.FormDataParam; import io.swagger.model.User; -import java.util.*; +import java.util.List; import java.util.List; import io.swagger.api.NotFoundException; @@ -28,123 +28,118 @@ import javax.ws.rs.*; @io.swagger.annotations.Api(description = "the user API") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaJerseyServerCodegen", date = "2016-01-31T21:10:14.319Z") + public class UserApi { private final UserApiService delegate = UserApiServiceFactory.getUserApi(); @POST - @Produces({ "application/json", "application/xml" }) + @Produces({ "application/xml", "application/json" }) @io.swagger.annotations.ApiOperation(value = "Create user", notes = "This can only be done by the logged in user.", response = void.class, tags={ "user", }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = void.class) }) - public Response createUser( -@ApiParam(value = "Created user object" ) User body,@Context SecurityContext securityContext) + @ApiParam(value = "Created user object" ,required=true) User body, + @Context SecurityContext securityContext) throws NotFoundException { return delegate.createUser(body,securityContext); } @POST @Path("/createWithArray") - @Produces({ "application/json", "application/xml" }) + @Produces({ "application/xml", "application/json" }) @io.swagger.annotations.ApiOperation(value = "Creates list of users with given input array", notes = "", response = void.class, tags={ "user", }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = void.class) }) - public Response createUsersWithArrayInput( -@ApiParam(value = "List of user object" ) List body,@Context SecurityContext securityContext) + @ApiParam(value = "List of user object" ,required=true) List body, + @Context SecurityContext securityContext) throws NotFoundException { return delegate.createUsersWithArrayInput(body,securityContext); } @POST @Path("/createWithList") - @Produces({ "application/json", "application/xml" }) + @Produces({ "application/xml", "application/json" }) @io.swagger.annotations.ApiOperation(value = "Creates list of users with given input array", notes = "", response = void.class, tags={ "user", }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = void.class) }) - public Response createUsersWithListInput( -@ApiParam(value = "List of user object" ) List body,@Context SecurityContext securityContext) + @ApiParam(value = "List of user object" ,required=true) List body, + @Context SecurityContext securityContext) throws NotFoundException { return delegate.createUsersWithListInput(body,securityContext); } + @DELETE + @Path("/{username}") + + @Produces({ "application/xml", "application/json" }) + @io.swagger.annotations.ApiOperation(value = "Delete user", notes = "This can only be done by the logged in user.", response = void.class, tags={ "user", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid username supplied", response = void.class), + @io.swagger.annotations.ApiResponse(code = 404, message = "User not found", response = void.class) }) + public Response deleteUser( + @ApiParam(value = "The name that needs to be deleted",required=true) @PathParam("username") String username, + @Context SecurityContext securityContext) + throws NotFoundException { + return delegate.deleteUser(username,securityContext); + } + @GET + @Path("/{username}") + + @Produces({ "application/xml", "application/json" }) + @io.swagger.annotations.ApiOperation(value = "Get user by user name", notes = "", response = User.class, tags={ "user", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = User.class), + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid username supplied", response = User.class), + @io.swagger.annotations.ApiResponse(code = 404, message = "User not found", response = User.class) }) + public Response getUserByName( + @ApiParam(value = "The name that needs to be fetched. Use user1 for testing.",required=true) @PathParam("username") String username, + @Context SecurityContext securityContext) + throws NotFoundException { + return delegate.getUserByName(username,securityContext); + } @GET @Path("/login") - @Produces({ "application/json", "application/xml" }) + @Produces({ "application/xml", "application/json" }) @io.swagger.annotations.ApiOperation(value = "Logs user into the system", notes = "", response = String.class, tags={ "user", }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = String.class), - @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid username/password supplied", response = String.class) }) - - public Response loginUser(@ApiParam(value = "The user name for login") @QueryParam("username") String username -,@ApiParam(value = "The password for login in clear text") @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); } @GET @Path("/logout") - @Produces({ "application/json", "application/xml" }) - @io.swagger.annotations.ApiOperation(value = "Logs out current logged in user session", notes = "", response = void.class, tags={ "user", }) + @Produces({ "application/xml", "application/json" }) + @io.swagger.annotations.ApiOperation(value = "Logs out current logged in user session", notes = "null", response = void.class, tags={ "user", }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = void.class) }) - - public Response logoutUser(@Context SecurityContext securityContext) + public Response logoutUser( + @Context SecurityContext securityContext) throws NotFoundException { return delegate.logoutUser(securityContext); } - @GET - @Path("/{username}") - - @Produces({ "application/json", "application/xml" }) - @io.swagger.annotations.ApiOperation(value = "Get user by user name", notes = "", response = User.class, tags={ "user", }) - @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = User.class), - - @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid username supplied", response = User.class), - - @io.swagger.annotations.ApiResponse(code = 404, message = "User not found", response = User.class) }) - - public Response getUserByName( -@ApiParam(value = "The name that needs to be fetched. Use user1 for testing.",required=true) @PathParam("username") String username,@Context SecurityContext securityContext) - throws NotFoundException { - return delegate.getUserByName(username,securityContext); - } @PUT @Path("/{username}") - @Produces({ "application/json", "application/xml" }) - @io.swagger.annotations.ApiOperation(value = "Updated user", notes = "This can only be done by the logged in user.", response = void.class, tags={ "user", }) + @Produces({ "application/xml", "application/json" }) + @io.swagger.annotations.ApiOperation(value = "Updated user", notes = "This can only be done by the logged in user.", response = void.class, tags={ "user" }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid user supplied", response = void.class), - @io.swagger.annotations.ApiResponse(code = 404, message = "User not found", response = void.class) }) - public Response updateUser( -@ApiParam(value = "name that need to be deleted",required=true) @PathParam("username") String username, -@ApiParam(value = "Updated user object" ) User body,@Context SecurityContext securityContext) + @ApiParam(value = "name that need to be updated",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); } - @DELETE - @Path("/{username}") - - @Produces({ "application/json", "application/xml" }) - @io.swagger.annotations.ApiOperation(value = "Delete user", notes = "This can only be done by the logged in user.", response = void.class, tags={ "user" }) - @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid username supplied", response = void.class), - - @io.swagger.annotations.ApiResponse(code = 404, message = "User not found", response = void.class) }) - - public Response deleteUser( -@ApiParam(value = "The name that needs to be deleted",required=true) @PathParam("username") String username,@Context SecurityContext securityContext) - throws NotFoundException { - return delegate.deleteUser(username,securityContext); - } } diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/UserApiService.java b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/UserApiService.java index aac73ea0853..334bfa1164b 100644 --- a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/UserApiService.java +++ b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/UserApiService.java @@ -6,7 +6,7 @@ import io.swagger.model.*; import com.sun.jersey.multipart.FormDataParam; import io.swagger.model.User; -import java.util.*; +import java.util.List; import java.util.List; import io.swagger.api.NotFoundException; @@ -19,7 +19,7 @@ import com.sun.jersey.multipart.FormDataParam; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaJerseyServerCodegen", date = "2016-01-31T21:10:14.319Z") + public abstract class UserApiService { public abstract Response createUser(User body,SecurityContext securityContext) @@ -31,19 +31,19 @@ public abstract class UserApiService { public abstract Response createUsersWithListInput(List body,SecurityContext securityContext) throws NotFoundException; + public abstract Response deleteUser(String username,SecurityContext securityContext) + throws NotFoundException; + + public abstract Response getUserByName(String username,SecurityContext securityContext) + throws NotFoundException; + public abstract Response loginUser(String username,String password,SecurityContext securityContext) throws NotFoundException; public abstract Response logoutUser(SecurityContext securityContext) throws NotFoundException; - public abstract Response getUserByName(String username,SecurityContext securityContext) - throws NotFoundException; - public abstract Response updateUser(String username,User body,SecurityContext securityContext) throws NotFoundException; - public abstract Response deleteUser(String username,SecurityContext securityContext) - throws NotFoundException; - } diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/ApiResponse.java b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/ApiResponse.java new file mode 100644 index 00000000000..dd6bcbf2cb1 --- /dev/null +++ b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/ApiResponse.java @@ -0,0 +1,117 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + + + + + + +public class ApiResponse { + + private Integer code = null; + private String type = null; + private String message = null; + + + /** + **/ + public ApiResponse code(Integer code) { + this.code = code; + return this; + } + + + @ApiModelProperty(value = "") + @JsonProperty("code") + public Integer getCode() { + return code; + } + public void setCode(Integer code) { + this.code = code; + } + + + /** + **/ + public ApiResponse type(String type) { + this.type = type; + return this; + } + + + @ApiModelProperty(value = "") + @JsonProperty("type") + public String getType() { + return type; + } + public void setType(String type) { + this.type = type; + } + + + /** + **/ + public ApiResponse message(String message) { + this.message = message; + return this; + } + + + @ApiModelProperty(value = "") + @JsonProperty("message") + public String getMessage() { + return message; + } + public void setMessage(String message) { + this.message = message; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ApiResponse apiResponse = (ApiResponse) 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 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 String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/Category.java b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/Category.java index ae75071b81a..fd27ccac1c4 100644 --- a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/Category.java +++ b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/Category.java @@ -2,7 +2,6 @@ package io.swagger.model; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonValue; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -10,7 +9,7 @@ import io.swagger.annotations.ApiModelProperty; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaJerseyServerCodegen", date = "2016-01-31T21:10:14.319Z") + public class Category { private Long id = null; @@ -19,6 +18,11 @@ public class Category { /** **/ + public Category id(Long id) { + this.id = id; + return this; + } + @ApiModelProperty(value = "") @JsonProperty("id") @@ -32,6 +36,11 @@ public class Category { /** **/ + public Category name(String name) { + this.name = name; + return this; + } + @ApiModelProperty(value = "") @JsonProperty("name") diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/Order.java b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/Order.java index bbbc49454e5..0dd4222776c 100644 --- a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/Order.java +++ b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/Order.java @@ -11,7 +11,7 @@ import java.util.Date; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaJerseyServerCodegen", date = "2016-01-31T21:10:14.319Z") + public class Order { private Long id = null; @@ -39,11 +39,16 @@ public class Order { } private StatusEnum status = null; - private Boolean complete = null; + private Boolean complete = false; /** **/ + public Order id(Long id) { + this.id = id; + return this; + } + @ApiModelProperty(value = "") @JsonProperty("id") @@ -57,6 +62,11 @@ public class Order { /** **/ + public Order petId(Long petId) { + this.petId = petId; + return this; + } + @ApiModelProperty(value = "") @JsonProperty("petId") @@ -70,6 +80,11 @@ public class Order { /** **/ + public Order quantity(Integer quantity) { + this.quantity = quantity; + return this; + } + @ApiModelProperty(value = "") @JsonProperty("quantity") @@ -83,6 +98,11 @@ public class Order { /** **/ + public Order shipDate(Date shipDate) { + this.shipDate = shipDate; + return this; + } + @ApiModelProperty(value = "") @JsonProperty("shipDate") @@ -97,6 +117,11 @@ public class Order { /** * Order Status **/ + public Order status(StatusEnum status) { + this.status = status; + return this; + } + @ApiModelProperty(value = "Order Status") @JsonProperty("status") @@ -110,6 +135,11 @@ public class Order { /** **/ + public Order complete(Boolean complete) { + this.complete = complete; + return this; + } + @ApiModelProperty(value = "") @JsonProperty("complete") diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/Pet.java b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/Pet.java index fab0903ee2a..514bb24508d 100644 --- a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/Pet.java +++ b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/Pet.java @@ -7,13 +7,14 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import io.swagger.model.Category; import io.swagger.model.Tag; -import java.util.*; +import java.util.ArrayList; +import java.util.List; + -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaJerseyServerCodegen", date = "2016-01-31T21:10:14.319Z") public class Pet { private Long id = null; @@ -46,6 +47,11 @@ public class Pet { /** **/ + public Pet id(Long id) { + this.id = id; + return this; + } + @ApiModelProperty(value = "") @JsonProperty("id") @@ -59,6 +65,11 @@ public class Pet { /** **/ + public Pet category(Category category) { + this.category = category; + return this; + } + @ApiModelProperty(value = "") @JsonProperty("category") @@ -72,8 +83,13 @@ public class Pet { /** **/ + public Pet name(String name) { + this.name = name; + return this; + } + - @ApiModelProperty(required = true, value = "") + @ApiModelProperty(example = "doggie", required = true, value = "") @JsonProperty("name") public String getName() { return name; @@ -85,6 +101,11 @@ public class Pet { /** **/ + public Pet photoUrls(List photoUrls) { + this.photoUrls = photoUrls; + return this; + } + @ApiModelProperty(required = true, value = "") @JsonProperty("photoUrls") @@ -98,6 +119,11 @@ public class Pet { /** **/ + public Pet tags(List tags) { + this.tags = tags; + return this; + } + @ApiModelProperty(value = "") @JsonProperty("tags") @@ -112,6 +138,11 @@ public class Pet { /** * pet status in the store **/ + public Pet status(StatusEnum status) { + this.status = status; + return this; + } + @ApiModelProperty(value = "pet status in the store") @JsonProperty("status") diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/Tag.java b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/Tag.java index 9c867802749..b46638ccb69 100644 --- a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/Tag.java +++ b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/Tag.java @@ -2,7 +2,6 @@ package io.swagger.model; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonValue; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -10,7 +9,7 @@ import io.swagger.annotations.ApiModelProperty; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaJerseyServerCodegen", date = "2016-01-31T21:10:14.319Z") + public class Tag { private Long id = null; @@ -19,6 +18,11 @@ public class Tag { /** **/ + public Tag id(Long id) { + this.id = id; + return this; + } + @ApiModelProperty(value = "") @JsonProperty("id") @@ -32,6 +36,11 @@ public class Tag { /** **/ + public Tag name(String name) { + this.name = name; + return this; + } + @ApiModelProperty(value = "") @JsonProperty("name") diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/User.java b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/User.java index 0a18f623d90..7f18c02f599 100644 --- a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/User.java +++ b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/User.java @@ -2,7 +2,6 @@ package io.swagger.model; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonValue; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -10,7 +9,7 @@ import io.swagger.annotations.ApiModelProperty; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaJerseyServerCodegen", date = "2016-01-31T21:10:14.319Z") + public class User { private Long id = null; @@ -25,6 +24,11 @@ public class User { /** **/ + public User id(Long id) { + this.id = id; + return this; + } + @ApiModelProperty(value = "") @JsonProperty("id") @@ -38,6 +42,11 @@ public class User { /** **/ + public User username(String username) { + this.username = username; + return this; + } + @ApiModelProperty(value = "") @JsonProperty("username") @@ -51,6 +60,11 @@ public class User { /** **/ + public User firstName(String firstName) { + this.firstName = firstName; + return this; + } + @ApiModelProperty(value = "") @JsonProperty("firstName") @@ -64,6 +78,11 @@ public class User { /** **/ + public User lastName(String lastName) { + this.lastName = lastName; + return this; + } + @ApiModelProperty(value = "") @JsonProperty("lastName") @@ -77,6 +96,11 @@ public class User { /** **/ + public User email(String email) { + this.email = email; + return this; + } + @ApiModelProperty(value = "") @JsonProperty("email") @@ -90,6 +114,11 @@ public class User { /** **/ + public User password(String password) { + this.password = password; + return this; + } + @ApiModelProperty(value = "") @JsonProperty("password") @@ -103,6 +132,11 @@ public class User { /** **/ + public User phone(String phone) { + this.phone = phone; + return this; + } + @ApiModelProperty(value = "") @JsonProperty("phone") @@ -117,6 +151,11 @@ public class User { /** * User Status **/ + public User userStatus(Integer userStatus) { + this.userStatus = userStatus; + return this; + } + @ApiModelProperty(value = "User Status") @JsonProperty("userStatus") diff --git a/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/Bootstrap.java b/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/Bootstrap.java new file mode 100644 index 00000000000..0651af80f18 --- /dev/null +++ b/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/Bootstrap.java @@ -0,0 +1,31 @@ +package io.swagger.api; + +import io.swagger.jaxrs.config.SwaggerContextService; +import io.swagger.models.*; + +import io.swagger.models.auth.*; + +import javax.servlet.http.HttpServlet; +import javax.servlet.ServletContext; +import javax.servlet.ServletConfig; +import javax.servlet.ServletException; + +public class Bootstrap extends HttpServlet { + @Override + public void init(ServletConfig config) throws ServletException { + Info info = new Info() + .title("Swagger Server") + .description("This is a sample server Petstore server. You can find out more about\nSwagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/).\nFor this sample, you can use the api key `special-key` to test the authorization filters.\n") + .termsOfService("http://swagger.io/terms/") + .contact(new Contact() + .email("apiteam@swagger.io")) + .license(new License() + .name("Apache 2.0") + .url("http://www.apache.org/licenses/LICENSE-2.0.html")); + + ServletContext context = config.getServletContext(); + Swagger swagger = new Swagger().info(info); + + new SwaggerContextService().withServletConfig(config).updateSwagger(swagger); + } +} diff --git a/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/factories/PetApiServiceFactory.java b/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/factories/PetApiServiceFactory.java index 7b353884832..8a15fd9a8ad 100644 --- a/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/factories/PetApiServiceFactory.java +++ b/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/factories/PetApiServiceFactory.java @@ -3,7 +3,7 @@ package io.swagger.api.factories; import io.swagger.api.PetApiService; import io.swagger.api.impl.PetApiServiceImpl; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2016-01-14T21:37:36.074Z") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaJerseyServerCodegen", date = "2016-04-03T13:30:41.715-06:00") public class PetApiServiceFactory { private final static PetApiService service = new PetApiServiceImpl(); diff --git a/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/factories/PettestingByteArraytrueApiServiceFactory.java b/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/factories/PettestingByteArraytrueApiServiceFactory.java deleted file mode 100644 index d92bf7269f5..00000000000 --- a/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/factories/PettestingByteArraytrueApiServiceFactory.java +++ /dev/null @@ -1,15 +0,0 @@ -package io.swagger.api.factories; - -import io.swagger.api.PettestingByteArraytrueApiService; -import io.swagger.api.impl.PettestingByteArraytrueApiServiceImpl; - -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2016-01-14T21:37:36.074Z") -public class PettestingByteArraytrueApiServiceFactory { - - private final static PettestingByteArraytrueApiService service = new PettestingByteArraytrueApiServiceImpl(); - - public static PettestingByteArraytrueApiService getPettestingByteArraytrueApi() - { - return service; - } -} diff --git a/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/factories/StoreApiServiceFactory.java b/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/factories/StoreApiServiceFactory.java index 51871b0d3d2..4f83a413c6f 100644 --- a/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/factories/StoreApiServiceFactory.java +++ b/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/factories/StoreApiServiceFactory.java @@ -3,7 +3,7 @@ package io.swagger.api.factories; import io.swagger.api.StoreApiService; import io.swagger.api.impl.StoreApiServiceImpl; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2016-01-14T21:37:36.074Z") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaJerseyServerCodegen", date = "2016-04-03T13:30:41.715-06:00") public class StoreApiServiceFactory { private final static StoreApiService service = new StoreApiServiceImpl(); diff --git a/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/factories/UserApiServiceFactory.java b/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/factories/UserApiServiceFactory.java index 54e1d5a034a..0ce96e28a30 100644 --- a/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/factories/UserApiServiceFactory.java +++ b/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/factories/UserApiServiceFactory.java @@ -3,7 +3,7 @@ package io.swagger.api.factories; import io.swagger.api.UserApiService; import io.swagger.api.impl.UserApiServiceImpl; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2016-01-14T21:37:36.074Z") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaJerseyServerCodegen", date = "2016-04-03T13:30:41.715-06:00") public class UserApiServiceFactory { private final static UserApiService service = new UserApiServiceImpl(); diff --git a/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java b/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java index f59ede262ce..a6183190212 100644 --- a/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java +++ b/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java @@ -6,6 +6,7 @@ import io.swagger.model.*; import com.sun.jersey.multipart.FormDataParam; import io.swagger.model.Pet; +import io.swagger.model.ApiResponse; import java.io.File; import java.util.List; @@ -19,70 +20,63 @@ import com.sun.jersey.multipart.FormDataParam; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2016-01-14T21:37:36.074Z") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaJerseyServerCodegen", date = "2016-04-03T13:30:41.715-06:00") public class PetApiServiceImpl extends PetApiService { - - @Override - public Response updatePet(Pet body,SecurityContext securityContext) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - - @Override - public Response addPet(Pet body,SecurityContext securityContext) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - - @Override - public Response findPetsByStatus(List status,SecurityContext securityContext) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - - @Override - public Response findPetsByTags(List tags,SecurityContext securityContext) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - - @Override - public Response getPetById(Long petId,SecurityContext securityContext) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - - @Override - public Response updatePetWithForm(String petId,String name,String status,SecurityContext securityContext) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - - @Override - public Response deletePet(Long petId,String apiKey,SecurityContext securityContext) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - - @Override - public Response uploadFile(Long petId,String additionalMetadata,InputStream inputStream, FormDataContentDisposition fileDetail,SecurityContext securityContext) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - - @Override - public Response getPetByIdWithByteArray(Long petId,SecurityContext securityContext) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - + + @Override + public Response addPet(Pet body, SecurityContext securityContext) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + + @Override + public Response deletePet(Long petId, String apiKey, SecurityContext securityContext) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + + @Override + public Response findPetsByStatus(List status, SecurityContext securityContext) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + + @Override + public Response findPetsByTags(List tags, SecurityContext securityContext) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + + @Override + public Response getPetById(Long petId, SecurityContext securityContext) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + + @Override + public Response updatePet(Pet body, SecurityContext securityContext) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + + @Override + public Response updatePetWithForm(Long petId, String name, String status, SecurityContext securityContext) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + + @Override + public Response uploadFile(Long petId, String additionalMetadata, InputStream inputStream, FormDataContentDisposition fileDetail, SecurityContext securityContext) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + } diff --git a/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/impl/PettestingByteArraytrueApiServiceImpl.java b/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/impl/PettestingByteArraytrueApiServiceImpl.java deleted file mode 100644 index e9f77a280d3..00000000000 --- a/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/impl/PettestingByteArraytrueApiServiceImpl.java +++ /dev/null @@ -1,30 +0,0 @@ -package io.swagger.api.impl; - -import io.swagger.api.*; -import io.swagger.model.*; - -import com.sun.jersey.multipart.FormDataParam; - - -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; - -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2016-01-14T21:37:36.074Z") -public class PettestingByteArraytrueApiServiceImpl extends PettestingByteArraytrueApiService { - - @Override - public Response addPetUsingByteArray(byte[] body,SecurityContext securityContext) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - -} diff --git a/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java b/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java index 1f4ae01ab30..e54a128b242 100644 --- a/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java +++ b/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java @@ -19,35 +19,35 @@ import com.sun.jersey.multipart.FormDataParam; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2016-01-14T21:37:36.074Z") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaJerseyServerCodegen", date = "2016-04-03T13:30:41.715-06:00") public class StoreApiServiceImpl extends StoreApiService { - - @Override - public Response getInventory(SecurityContext securityContext) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - - @Override - public Response placeOrder(Order body,SecurityContext securityContext) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - - @Override - public Response getOrderById(String orderId,SecurityContext securityContext) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - - @Override - public Response deleteOrder(String orderId,SecurityContext securityContext) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - + + @Override + public Response deleteOrder(Long orderId, SecurityContext securityContext) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + + @Override + public Response getInventory(SecurityContext securityContext) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + + @Override + public Response getOrderById(Long orderId, SecurityContext securityContext) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + + @Override + public Response placeOrder(Order body, SecurityContext securityContext) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + } diff --git a/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java b/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java index 91a44816244..5a73ac74e73 100644 --- a/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java +++ b/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java @@ -6,7 +6,7 @@ import io.swagger.model.*; import com.sun.jersey.multipart.FormDataParam; import io.swagger.model.User; -import java.util.*; +import java.util.List; import java.util.List; import io.swagger.api.NotFoundException; @@ -19,63 +19,63 @@ import com.sun.jersey.multipart.FormDataParam; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2016-01-14T21:37:36.074Z") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaJerseyServerCodegen", date = "2016-04-03T13:30:41.715-06:00") public class UserApiServiceImpl extends UserApiService { - - @Override - public Response createUser(User body,SecurityContext securityContext) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - - @Override - public Response createUsersWithArrayInput(List body,SecurityContext securityContext) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - - @Override - public Response createUsersWithListInput(List body,SecurityContext securityContext) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - - @Override - public Response loginUser(String username,String password,SecurityContext securityContext) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - - @Override - public Response logoutUser(SecurityContext securityContext) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - - @Override - public Response getUserByName(String username,SecurityContext securityContext) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - - @Override - public Response updateUser(String username,User body,SecurityContext securityContext) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - - @Override - public Response deleteUser(String username,SecurityContext securityContext) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - + + @Override + public Response createUser(User body, SecurityContext securityContext) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + + @Override + public Response createUsersWithArrayInput(List body, SecurityContext securityContext) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + + @Override + public Response createUsersWithListInput(List body, SecurityContext securityContext) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + + @Override + public Response deleteUser(String username, SecurityContext securityContext) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + + @Override + public Response getUserByName(String username, SecurityContext securityContext) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + + @Override + public Response loginUser(String username, String password, SecurityContext securityContext) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + + @Override + public Response logoutUser(SecurityContext securityContext) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + + @Override + public Response updateUser(String username, User body, SecurityContext securityContext) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + } diff --git a/samples/server/petstore/jersey2/README.md b/samples/server/petstore/jersey2/README.md new file mode 100644 index 00000000000..4e7da8b7f63 --- /dev/null +++ b/samples/server/petstore/jersey2/README.md @@ -0,0 +1,23 @@ +# Swagger Jersey 2 generated server + +## Overview +This server was generated by the [swagger-codegen](https://github.com/swagger-api/swagger-codegen) project. By using the +[OpenAPI-Spec](https://github.com/swagger-api/swagger-core/wiki) from a remote server, you can easily generate a server stub. This +is an example of building a swagger-enabled JAX-RS server. + +This example uses the [JAX-RS](https://jax-rs-spec.java.net/) framework. + +To run the server, please execute the following: + +``` +mvn clean package jetty:run +``` + +You can then view the swagger listing here: + +``` +http://localhost:8080/v2/swagger.json +``` + +Note that if you have configured the `host` to be something other than localhost, the calls through +swagger-ui will be directed to that host and not localhost! \ No newline at end of file diff --git a/samples/server/petstore/jersey2/pom.xml b/samples/server/petstore/jersey2/pom.xml new file mode 100644 index 00000000000..4b70918e691 --- /dev/null +++ b/samples/server/petstore/jersey2/pom.xml @@ -0,0 +1,145 @@ + + 4.0.0 + io.swagger + swagger-jaxrs-server + jar + swagger-jaxrs-server + 1.0.0 + + src/main/java + + + org.apache.maven.plugins + maven-war-plugin + 2.1.1 + + + maven-failsafe-plugin + 2.6 + + + + integration-test + verify + + + + + + org.eclipse.jetty + jetty-maven-plugin + ${jetty-version} + + + / + + target/${project.artifactId}-${project.version} + 8079 + stopit + + 8080 + 60000 + + + + + start-jetty + pre-integration-test + + start + + + 0 + true + + + + stop-jetty + post-integration-test + + stop + + + + + + org.codehaus.mojo + build-helper-maven-plugin + 1.9.1 + + + add-source + generate-sources + + add-source + + + + src/gen/java + + + + + + + + + + io.swagger + swagger-jersey2-jaxrs + compile + ${swagger-core-version} + + + ch.qos.logback + logback-classic + ${logback-version} + compile + + + ch.qos.logback + logback-core + ${logback-version} + compile + + + junit + junit + ${junit-version} + test + + + javax.servlet + servlet-api + ${servlet-api-version} + + + org.glassfish.jersey.containers + jersey-container-servlet-core + ${jersey2-version} + + + org.glassfish.jersey.media + jersey-media-multipart + ${jersey2-version} + + + + + sonatype-snapshots + https://oss.sonatype.org/content/repositories/snapshots + + true + + + + + 1.5.8 + 9.2.9.v20150224 + 2.6 + 1.6.3 + 4.8.1 + 1.0.1 + 2.5 + + \ No newline at end of file diff --git a/samples/server/petstore/jersey2/src/gen/java/io/swagger/api/ApiException.java b/samples/server/petstore/jersey2/src/gen/java/io/swagger/api/ApiException.java new file mode 100644 index 00000000000..97e535d3c21 --- /dev/null +++ b/samples/server/petstore/jersey2/src/gen/java/io/swagger/api/ApiException.java @@ -0,0 +1,10 @@ +package io.swagger.api; + + +public class ApiException extends Exception{ + private int code; + public ApiException (int code, String msg) { + super(msg); + this.code = code; + } +} diff --git a/samples/server/petstore/jersey2/src/gen/java/io/swagger/api/ApiOriginFilter.java b/samples/server/petstore/jersey2/src/gen/java/io/swagger/api/ApiOriginFilter.java new file mode 100644 index 00000000000..38791eef046 --- /dev/null +++ b/samples/server/petstore/jersey2/src/gen/java/io/swagger/api/ApiOriginFilter.java @@ -0,0 +1,22 @@ +package io.swagger.api; + +import java.io.IOException; + +import javax.servlet.*; +import javax.servlet.http.HttpServletResponse; + + +public class ApiOriginFilter implements javax.servlet.Filter { + public void doFilter(ServletRequest request, ServletResponse response, + FilterChain chain) throws IOException, ServletException { + HttpServletResponse res = (HttpServletResponse) response; + res.addHeader("Access-Control-Allow-Origin", "*"); + res.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT"); + res.addHeader("Access-Control-Allow-Headers", "Content-Type"); + chain.doFilter(request, response); + } + + public void destroy() {} + + public void init(FilterConfig filterConfig) throws ServletException {} +} \ No newline at end of file diff --git a/samples/server/petstore/jersey2/src/gen/java/io/swagger/api/ApiResponseMessage.java b/samples/server/petstore/jersey2/src/gen/java/io/swagger/api/ApiResponseMessage.java new file mode 100644 index 00000000000..87db95c1009 --- /dev/null +++ b/samples/server/petstore/jersey2/src/gen/java/io/swagger/api/ApiResponseMessage.java @@ -0,0 +1,69 @@ +package io.swagger.api; + +import javax.xml.bind.annotation.XmlTransient; + +@javax.xml.bind.annotation.XmlRootElement + +public class ApiResponseMessage { + public static final int ERROR = 1; + public static final int WARNING = 2; + public static final int INFO = 3; + public static final int OK = 4; + public static final int TOO_BUSY = 5; + + int code; + String type; + String message; + + public ApiResponseMessage(){} + + public ApiResponseMessage(int code, String message){ + this.code = code; + switch(code){ + case ERROR: + setType("error"); + break; + case WARNING: + setType("warning"); + break; + case INFO: + setType("info"); + break; + case OK: + setType("ok"); + break; + case TOO_BUSY: + setType("too busy"); + break; + default: + setType("unknown"); + break; + } + this.message = message; + } + + @XmlTransient + public int getCode() { + return code; + } + + public void setCode(int code) { + this.code = code; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } +} diff --git a/samples/server/petstore/jersey2/src/gen/java/io/swagger/api/Bootstrap.java b/samples/server/petstore/jersey2/src/gen/java/io/swagger/api/Bootstrap.java new file mode 100644 index 00000000000..0651af80f18 --- /dev/null +++ b/samples/server/petstore/jersey2/src/gen/java/io/swagger/api/Bootstrap.java @@ -0,0 +1,31 @@ +package io.swagger.api; + +import io.swagger.jaxrs.config.SwaggerContextService; +import io.swagger.models.*; + +import io.swagger.models.auth.*; + +import javax.servlet.http.HttpServlet; +import javax.servlet.ServletContext; +import javax.servlet.ServletConfig; +import javax.servlet.ServletException; + +public class Bootstrap extends HttpServlet { + @Override + public void init(ServletConfig config) throws ServletException { + Info info = new Info() + .title("Swagger Server") + .description("This is a sample server Petstore server. You can find out more about\nSwagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/).\nFor this sample, you can use the api key `special-key` to test the authorization filters.\n") + .termsOfService("http://swagger.io/terms/") + .contact(new Contact() + .email("apiteam@swagger.io")) + .license(new License() + .name("Apache 2.0") + .url("http://www.apache.org/licenses/LICENSE-2.0.html")); + + ServletContext context = config.getServletContext(); + Swagger swagger = new Swagger().info(info); + + new SwaggerContextService().withServletConfig(config).updateSwagger(swagger); + } +} diff --git a/samples/server/petstore/jersey2/src/gen/java/io/swagger/api/JacksonJsonProvider.java b/samples/server/petstore/jersey2/src/gen/java/io/swagger/api/JacksonJsonProvider.java new file mode 100644 index 00000000000..49792814c5e --- /dev/null +++ b/samples/server/petstore/jersey2/src/gen/java/io/swagger/api/JacksonJsonProvider.java @@ -0,0 +1,19 @@ +package io.swagger.api; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider; +import io.swagger.util.Json; + +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.ext.Provider; + +@Provider +@Produces({MediaType.APPLICATION_JSON}) +public class JacksonJsonProvider extends JacksonJaxbJsonProvider { + private static ObjectMapper commonMapper = Json.mapper(); + + public JacksonJsonProvider() { + super.setMapper(commonMapper); + } +} \ No newline at end of file diff --git a/samples/server/petstore/jersey2/src/gen/java/io/swagger/api/NotFoundException.java b/samples/server/petstore/jersey2/src/gen/java/io/swagger/api/NotFoundException.java new file mode 100644 index 00000000000..b28b67ea4b2 --- /dev/null +++ b/samples/server/petstore/jersey2/src/gen/java/io/swagger/api/NotFoundException.java @@ -0,0 +1,10 @@ +package io.swagger.api; + + +public class NotFoundException extends ApiException { + private int code; + public NotFoundException (int code, String msg) { + super(code, msg); + this.code = code; + } +} diff --git a/samples/server/petstore/jersey2/src/gen/java/io/swagger/api/PetApi.java b/samples/server/petstore/jersey2/src/gen/java/io/swagger/api/PetApi.java new file mode 100644 index 00000000000..1f9043ab85a --- /dev/null +++ b/samples/server/petstore/jersey2/src/gen/java/io/swagger/api/PetApi.java @@ -0,0 +1,175 @@ +package io.swagger.api; + +import io.swagger.model.*; +import io.swagger.api.PetApiService; +import io.swagger.api.factories.PetApiServiceFactory; + +import io.swagger.annotations.ApiParam; + +import io.swagger.model.Pet; +import io.swagger.model.ApiResponse; +import java.io.File; + +import java.util.List; +import io.swagger.api.NotFoundException; + +import java.io.InputStream; + +import org.glassfish.jersey.media.multipart.FormDataContentDisposition; +import org.glassfish.jersey.media.multipart.FormDataParam; + +import javax.ws.rs.core.Context; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; +import javax.ws.rs.*; + +@Path("/pet") + + +@io.swagger.annotations.Api(description = "the pet API") + +public class PetApi { + private final PetApiService delegate = PetApiServiceFactory.getPetApi(); + + @POST + + @Consumes({ "application/json", "application/xml" }) + @Produces({ "application/xml", "application/json" }) + @io.swagger.annotations.ApiOperation(value = "Add a new pet to the store", notes = "", response = void.class, authorizations = { + @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { + @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }, tags={ "pet", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 405, message = "Invalid input", response = void.class) }) + public Response addPet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true) Pet body,@Context SecurityContext securityContext) + throws NotFoundException { + return delegate.addPet(body,securityContext); + } + @DELETE + @Path("/{petId}") + + @Produces({ "application/xml", "application/json" }) + @io.swagger.annotations.ApiOperation(value = "Deletes a pet", notes = "", response = void.class, authorizations = { + @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { + @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }, tags={ "pet", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid ID supplied", response = void.class), + + @io.swagger.annotations.ApiResponse(code = 404, message = "Pet not found", response = void.class) }) + public Response deletePet(@ApiParam(value = "Pet id to delete",required=true) @PathParam("petId") Long petId,@ApiParam(value = "" )@HeaderParam("api_key") String apiKey,@Context SecurityContext securityContext) + throws NotFoundException { + return delegate.deletePet(petId,apiKey,securityContext); + } + @GET + @Path("/findByStatus") + + @Produces({ "application/xml", "application/json" }) + @io.swagger.annotations.ApiOperation(value = "Finds Pets by status", notes = "Multiple status values can be provided with comma separated strings", response = Pet.class, responseContainer = "List", authorizations = { + @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { + @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }, tags={ "pet", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Pet.class, responseContainer = "List"), + + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid status value", response = Pet.class, responseContainer = "List") }) + public Response findPetsByStatus(@ApiParam(value = "Status values that need to be considered for filter",required=true) @QueryParam("status") List status,@Context SecurityContext securityContext) + throws NotFoundException { + return delegate.findPetsByStatus(status,securityContext); + } + @GET + @Path("/findByTags") + + @Produces({ "application/xml", "application/json" }) + @io.swagger.annotations.ApiOperation(value = "Finds Pets by tags", notes = "Muliple tags can be provided with comma separated strings. Use\ntag1, tag2, tag3 for testing.\n", response = Pet.class, responseContainer = "List", authorizations = { + @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { + @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }, tags={ "pet", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Pet.class, responseContainer = "List"), + + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid tag value", response = Pet.class, responseContainer = "List") }) + public Response findPetsByTags(@ApiParam(value = "Tags to filter by",required=true) @QueryParam("tags") List tags,@Context SecurityContext securityContext) + throws NotFoundException { + return delegate.findPetsByTags(tags,securityContext); + } + @GET + @Path("/{petId}") + + @Produces({ "application/xml", "application/json" }) + @io.swagger.annotations.ApiOperation(value = "Find pet by ID", notes = "Returns a single pet", response = Pet.class, authorizations = { + @io.swagger.annotations.Authorization(value = "api_key") + }, tags={ "pet", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Pet.class), + + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid ID supplied", response = Pet.class), + + @io.swagger.annotations.ApiResponse(code = 404, message = "Pet not found", response = Pet.class) }) + public Response getPetById(@ApiParam(value = "ID of pet to return",required=true) @PathParam("petId") Long petId,@Context SecurityContext securityContext) + throws NotFoundException { + return delegate.getPetById(petId,securityContext); + } + @PUT + + @Consumes({ "application/json", "application/xml" }) + @Produces({ "application/xml", "application/json" }) + @io.swagger.annotations.ApiOperation(value = "Update an existing pet", notes = "", response = void.class, authorizations = { + @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { + @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }, tags={ "pet", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid ID supplied", response = void.class), + + @io.swagger.annotations.ApiResponse(code = 404, message = "Pet not found", response = void.class), + + @io.swagger.annotations.ApiResponse(code = 405, message = "Validation exception", response = void.class) }) + public Response updatePet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true) Pet body,@Context SecurityContext securityContext) + throws NotFoundException { + return delegate.updatePet(body,securityContext); + } + @POST + @Path("/{petId}") + @Consumes({ "application/x-www-form-urlencoded" }) + @Produces({ "application/xml", "application/json" }) + @io.swagger.annotations.ApiOperation(value = "Updates a pet in the store with form data", notes = "null", response = void.class, authorizations = { + @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { + @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }, tags={ "pet", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 405, message = "Invalid input", response = void.class) }) + public Response updatePetWithForm(@ApiParam(value = "ID of pet that needs to be updated",required=true) @PathParam("petId") Long petId,@ApiParam(value = "Updated name of the pet")@FormParam("name") String name,@ApiParam(value = "Updated status of the pet")@FormParam("status") String status,@Context SecurityContext securityContext) + throws NotFoundException { + return delegate.updatePetWithForm(petId,name,status,securityContext); + } + @POST + @Path("/{petId}/uploadImage") + @Consumes({ "multipart/form-data" }) + @Produces({ "application/json" }) + @io.swagger.annotations.ApiOperation(value = "uploads an image", notes = "", response = ApiResponse.class, authorizations = { + @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { + @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }, tags={ "pet", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = ApiResponse.class) }) + public Response uploadFile(@ApiParam(value = "ID of pet to update",required=true) @PathParam("petId") Long petId,@ApiParam(value = "Additional data to pass to server")@FormDataParam("additionalMetadata") String additionalMetadata, + @FormDataParam("file") InputStream inputStream, + @FormDataParam("file") FormDataContentDisposition fileDetail,@Context SecurityContext securityContext) + throws NotFoundException { + return delegate.uploadFile(petId,additionalMetadata,inputStream, fileDetail,securityContext); + } +} diff --git a/samples/server/petstore/jersey2/src/gen/java/io/swagger/api/PetApiService.java b/samples/server/petstore/jersey2/src/gen/java/io/swagger/api/PetApiService.java new file mode 100644 index 00000000000..80d5170b242 --- /dev/null +++ b/samples/server/petstore/jersey2/src/gen/java/io/swagger/api/PetApiService.java @@ -0,0 +1,39 @@ +package io.swagger.api; + +import io.swagger.api.*; +import io.swagger.model.*; + +import org.glassfish.jersey.media.multipart.FormDataContentDisposition; + +import io.swagger.model.Pet; +import io.swagger.model.ApiResponse; +import java.io.File; + +import java.util.List; +import io.swagger.api.NotFoundException; + +import java.io.InputStream; + +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; + + +public abstract class PetApiService { + + public abstract Response addPet(Pet body,SecurityContext securityContext) throws NotFoundException; + + public abstract Response deletePet(Long petId,String apiKey,SecurityContext securityContext) throws NotFoundException; + + public abstract Response findPetsByStatus(List status,SecurityContext securityContext) throws NotFoundException; + + public abstract Response findPetsByTags(List tags,SecurityContext securityContext) throws NotFoundException; + + public abstract Response getPetById(Long petId,SecurityContext securityContext) throws NotFoundException; + + public abstract Response updatePet(Pet body,SecurityContext securityContext) throws NotFoundException; + + public abstract Response updatePetWithForm(Long petId,String name,String status,SecurityContext securityContext) throws NotFoundException; + + public abstract Response uploadFile(Long petId,String additionalMetadata,InputStream inputStream, FormDataContentDisposition fileDetail,SecurityContext securityContext) throws NotFoundException; + +} diff --git a/samples/server/petstore/jersey2/src/gen/java/io/swagger/api/StoreApi.java b/samples/server/petstore/jersey2/src/gen/java/io/swagger/api/StoreApi.java new file mode 100644 index 00000000000..2708e4b2cf9 --- /dev/null +++ b/samples/server/petstore/jersey2/src/gen/java/io/swagger/api/StoreApi.java @@ -0,0 +1,87 @@ +package io.swagger.api; + +import io.swagger.model.*; +import io.swagger.api.StoreApiService; +import io.swagger.api.factories.StoreApiServiceFactory; + +import io.swagger.annotations.ApiParam; + +import java.util.Map; +import io.swagger.model.Order; + +import java.util.List; +import io.swagger.api.NotFoundException; + +import java.io.InputStream; + +import org.glassfish.jersey.media.multipart.FormDataContentDisposition; +import org.glassfish.jersey.media.multipart.FormDataParam; + +import javax.ws.rs.core.Context; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; +import javax.ws.rs.*; + +@Path("/store") + + +@io.swagger.annotations.Api(description = "the store API") + +public class StoreApi { + private final StoreApiService delegate = StoreApiServiceFactory.getStoreApi(); + + @DELETE + @Path("/order/{orderId}") + + @Produces({ "application/xml", "application/json" }) + @io.swagger.annotations.ApiOperation(value = "Delete purchase order by ID", notes = "For valid response try integer IDs with positive integer value.\\ \\ Negative or non-integer values will generate API errors", response = void.class, tags={ "store", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid ID supplied", response = void.class), + + @io.swagger.annotations.ApiResponse(code = 404, message = "Order not found", response = void.class) }) + public Response deleteOrder(@ApiParam(value = "ID of the order that needs to be deleted",required=true) @PathParam("orderId") Long orderId,@Context SecurityContext securityContext) + throws NotFoundException { + return delegate.deleteOrder(orderId,securityContext); + } + @GET + @Path("/inventory") + + @Produces({ "application/json" }) + @io.swagger.annotations.ApiOperation(value = "Returns pet inventories by status", notes = "Returns a map of status codes to quantities", response = Integer.class, responseContainer = "Map", authorizations = { + @io.swagger.annotations.Authorization(value = "api_key") + }, tags={ "store", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Integer.class, responseContainer = "Map") }) + public Response getInventory(@Context SecurityContext securityContext) + throws NotFoundException { + return delegate.getInventory(securityContext); + } + @GET + @Path("/order/{orderId}") + + @Produces({ "application/xml", "application/json" }) + @io.swagger.annotations.ApiOperation(value = "Find purchase order by ID", notes = "For valid response try integer IDs with value >= 1 and <= 10.\nOther values will generated exceptions\n", response = Order.class, tags={ "store", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Order.class), + + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid ID supplied", response = Order.class), + + @io.swagger.annotations.ApiResponse(code = 404, message = "Order not found", response = Order.class) }) + public Response getOrderById(@ApiParam(value = "ID of pet that needs to be fetched",required=true) @PathParam("orderId") Long orderId,@Context SecurityContext securityContext) + throws NotFoundException { + return delegate.getOrderById(orderId,securityContext); + } + @POST + @Path("/order") + + @Produces({ "application/xml", "application/json" }) + @io.swagger.annotations.ApiOperation(value = "Place an order for a pet", notes = "", response = Order.class, tags={ "store", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Order.class), + + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid Order", response = Order.class) }) + public Response placeOrder(@ApiParam(value = "order placed for purchasing the pet" ,required=true) Order body,@Context SecurityContext securityContext) + throws NotFoundException { + return delegate.placeOrder(body,securityContext); + } +} diff --git a/samples/server/petstore/jersey2/src/gen/java/io/swagger/api/StoreApiService.java b/samples/server/petstore/jersey2/src/gen/java/io/swagger/api/StoreApiService.java new file mode 100644 index 00000000000..43078d32756 --- /dev/null +++ b/samples/server/petstore/jersey2/src/gen/java/io/swagger/api/StoreApiService.java @@ -0,0 +1,30 @@ +package io.swagger.api; + +import io.swagger.api.*; +import io.swagger.model.*; + +import org.glassfish.jersey.media.multipart.FormDataContentDisposition; + +import java.util.Map; +import io.swagger.model.Order; + +import java.util.List; +import io.swagger.api.NotFoundException; + +import java.io.InputStream; + +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; + + +public abstract class StoreApiService { + + public abstract Response deleteOrder(Long orderId,SecurityContext securityContext) throws NotFoundException; + + public abstract Response getInventory(SecurityContext securityContext) throws NotFoundException; + + public abstract Response getOrderById(Long orderId,SecurityContext securityContext) throws NotFoundException; + + public abstract Response placeOrder(Order body,SecurityContext securityContext) throws NotFoundException; + +} diff --git a/samples/server/petstore/jersey2/src/gen/java/io/swagger/api/StringUtil.java b/samples/server/petstore/jersey2/src/gen/java/io/swagger/api/StringUtil.java new file mode 100644 index 00000000000..6f4a3dadbbf --- /dev/null +++ b/samples/server/petstore/jersey2/src/gen/java/io/swagger/api/StringUtil.java @@ -0,0 +1,42 @@ +package io.swagger.api; + + +public class StringUtil { + /** + * Check if the given array contains the given value (with case-insensitive comparison). + * + * @param array The array + * @param value The value to search + * @return true if the array contains the value + */ + public static boolean containsIgnoreCase(String[] array, String value) { + for (String str : array) { + if (value == null && str == null) return true; + if (value != null && value.equalsIgnoreCase(str)) return true; + } + return false; + } + + /** + * Join an array of strings with the given separator. + *

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

+ * + * @param array The array of strings + * @param separator The separator + * @return the resulting string + */ + public static String join(String[] array, String separator) { + int len = array.length; + if (len == 0) return ""; + + StringBuilder out = new StringBuilder(); + out.append(array[0]); + for (int i = 1; i < len; i++) { + out.append(separator).append(array[i]); + } + return out.toString(); + } +} diff --git a/samples/server/petstore/jersey2/src/gen/java/io/swagger/api/UserApi.java b/samples/server/petstore/jersey2/src/gen/java/io/swagger/api/UserApi.java new file mode 100644 index 00000000000..cf4af7071eb --- /dev/null +++ b/samples/server/petstore/jersey2/src/gen/java/io/swagger/api/UserApi.java @@ -0,0 +1,131 @@ +package io.swagger.api; + +import io.swagger.model.*; +import io.swagger.api.UserApiService; +import io.swagger.api.factories.UserApiServiceFactory; + +import io.swagger.annotations.ApiParam; + +import io.swagger.model.User; +import java.util.List; + +import java.util.List; +import io.swagger.api.NotFoundException; + +import java.io.InputStream; + +import org.glassfish.jersey.media.multipart.FormDataContentDisposition; +import org.glassfish.jersey.media.multipart.FormDataParam; + +import javax.ws.rs.core.Context; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; +import javax.ws.rs.*; + +@Path("/user") + + +@io.swagger.annotations.Api(description = "the user API") + +public class UserApi { + private final UserApiService delegate = UserApiServiceFactory.getUserApi(); + + @POST + + + @Produces({ "application/xml", "application/json" }) + @io.swagger.annotations.ApiOperation(value = "Create user", notes = "This can only be done by the logged in user.", response = void.class, tags={ "user", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = void.class) }) + public Response createUser(@ApiParam(value = "Created user object" ,required=true) User body,@Context SecurityContext securityContext) + throws NotFoundException { + return delegate.createUser(body,securityContext); + } + @POST + @Path("/createWithArray") + + @Produces({ "application/xml", "application/json" }) + @io.swagger.annotations.ApiOperation(value = "Creates list of users with given input array", notes = "", response = void.class, tags={ "user", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = void.class) }) + public Response createUsersWithArrayInput(@ApiParam(value = "List of user object" ,required=true) List body,@Context SecurityContext securityContext) + throws NotFoundException { + return delegate.createUsersWithArrayInput(body,securityContext); + } + @POST + @Path("/createWithList") + + @Produces({ "application/xml", "application/json" }) + @io.swagger.annotations.ApiOperation(value = "Creates list of users with given input array", notes = "", response = void.class, tags={ "user", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = void.class) }) + public Response createUsersWithListInput(@ApiParam(value = "List of user object" ,required=true) List body,@Context SecurityContext securityContext) + throws NotFoundException { + return delegate.createUsersWithListInput(body,securityContext); + } + @DELETE + @Path("/{username}") + + @Produces({ "application/xml", "application/json" }) + @io.swagger.annotations.ApiOperation(value = "Delete user", notes = "This can only be done by the logged in user.", response = void.class, tags={ "user", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid username supplied", response = void.class), + + @io.swagger.annotations.ApiResponse(code = 404, message = "User not found", response = void.class) }) + public Response deleteUser(@ApiParam(value = "The name that needs to be deleted",required=true) @PathParam("username") String username,@Context SecurityContext securityContext) + throws NotFoundException { + return delegate.deleteUser(username,securityContext); + } + @GET + @Path("/{username}") + + @Produces({ "application/xml", "application/json" }) + @io.swagger.annotations.ApiOperation(value = "Get user by user name", notes = "", response = User.class, tags={ "user", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = User.class), + + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid username supplied", response = User.class), + + @io.swagger.annotations.ApiResponse(code = 404, message = "User not found", response = User.class) }) + public Response getUserByName(@ApiParam(value = "The name that needs to be fetched. Use user1 for testing.",required=true) @PathParam("username") String username,@Context SecurityContext securityContext) + throws NotFoundException { + return delegate.getUserByName(username,securityContext); + } + @GET + @Path("/login") + + @Produces({ "application/xml", "application/json" }) + @io.swagger.annotations.ApiOperation(value = "Logs user into the system", notes = "", response = String.class, tags={ "user", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = String.class), + + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid username/password supplied", response = String.class) }) + public Response loginUser(@ApiParam(value = "The user name for login",required=true) @QueryParam("username") String username,@ApiParam(value = "The password for login in clear text",required=true) @QueryParam("password") String password,@Context SecurityContext securityContext) + throws NotFoundException { + return delegate.loginUser(username,password,securityContext); + } + @GET + @Path("/logout") + + @Produces({ "application/xml", "application/json" }) + @io.swagger.annotations.ApiOperation(value = "Logs out current logged in user session", notes = "null", response = void.class, tags={ "user", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = void.class) }) + public Response logoutUser(@Context SecurityContext securityContext) + throws NotFoundException { + return delegate.logoutUser(securityContext); + } + @PUT + @Path("/{username}") + + @Produces({ "application/xml", "application/json" }) + @io.swagger.annotations.ApiOperation(value = "Updated user", notes = "This can only be done by the logged in user.", response = void.class, tags={ "user", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid user supplied", response = void.class), + + @io.swagger.annotations.ApiResponse(code = 404, message = "User not found", response = void.class) }) + public Response updateUser(@ApiParam(value = "name that need to be updated",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/jersey2/src/gen/java/io/swagger/api/UserApiService.java b/samples/server/petstore/jersey2/src/gen/java/io/swagger/api/UserApiService.java new file mode 100644 index 00000000000..0cfc9c1fb35 --- /dev/null +++ b/samples/server/petstore/jersey2/src/gen/java/io/swagger/api/UserApiService.java @@ -0,0 +1,38 @@ +package io.swagger.api; + +import io.swagger.api.*; +import io.swagger.model.*; + +import org.glassfish.jersey.media.multipart.FormDataContentDisposition; + +import io.swagger.model.User; +import java.util.List; + +import java.util.List; +import io.swagger.api.NotFoundException; + +import java.io.InputStream; + +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; + + +public abstract class UserApiService { + + public abstract Response createUser(User body,SecurityContext securityContext) throws NotFoundException; + + public abstract Response createUsersWithArrayInput(List body,SecurityContext securityContext) throws NotFoundException; + + public abstract Response createUsersWithListInput(List body,SecurityContext securityContext) throws NotFoundException; + + public abstract Response deleteUser(String username,SecurityContext securityContext) throws NotFoundException; + + public abstract Response getUserByName(String username,SecurityContext securityContext) throws NotFoundException; + + public abstract Response loginUser(String username,String password,SecurityContext securityContext) throws NotFoundException; + + public abstract Response logoutUser(SecurityContext securityContext) throws NotFoundException; + + public abstract Response updateUser(String username,User body,SecurityContext securityContext) throws NotFoundException; + +} diff --git a/samples/server/petstore/jersey2/src/gen/java/io/swagger/model/ApiResponse.java b/samples/server/petstore/jersey2/src/gen/java/io/swagger/model/ApiResponse.java new file mode 100644 index 00000000000..dd6bcbf2cb1 --- /dev/null +++ b/samples/server/petstore/jersey2/src/gen/java/io/swagger/model/ApiResponse.java @@ -0,0 +1,117 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + + + + + + +public class ApiResponse { + + private Integer code = null; + private String type = null; + private String message = null; + + + /** + **/ + public ApiResponse code(Integer code) { + this.code = code; + return this; + } + + + @ApiModelProperty(value = "") + @JsonProperty("code") + public Integer getCode() { + return code; + } + public void setCode(Integer code) { + this.code = code; + } + + + /** + **/ + public ApiResponse type(String type) { + this.type = type; + return this; + } + + + @ApiModelProperty(value = "") + @JsonProperty("type") + public String getType() { + return type; + } + public void setType(String type) { + this.type = type; + } + + + /** + **/ + public ApiResponse message(String message) { + this.message = message; + return this; + } + + + @ApiModelProperty(value = "") + @JsonProperty("message") + public String getMessage() { + return message; + } + public void setMessage(String message) { + this.message = message; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ApiResponse apiResponse = (ApiResponse) 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 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 String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jersey2/src/gen/java/io/swagger/model/Category.java b/samples/server/petstore/jersey2/src/gen/java/io/swagger/model/Category.java new file mode 100644 index 00000000000..fd27ccac1c4 --- /dev/null +++ b/samples/server/petstore/jersey2/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 io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + + + + + + +public class Category { + + private Long id = null; + private String name = null; + + + /** + **/ + public Category id(Long id) { + this.id = id; + return this; + } + + + @ApiModelProperty(value = "") + @JsonProperty("id") + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + + /** + **/ + public Category name(String name) { + this.name = name; + return this; + } + + + @ApiModelProperty(value = "") + @JsonProperty("name") + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Category category = (Category) o; + return Objects.equals(id, category.id) && + Objects.equals(name, category.name); + } + + @Override + public int hashCode() { + return Objects.hash(id, name); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Category {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jersey2/src/gen/java/io/swagger/model/Order.java b/samples/server/petstore/jersey2/src/gen/java/io/swagger/model/Order.java new file mode 100644 index 00000000000..0dd4222776c --- /dev/null +++ b/samples/server/petstore/jersey2/src/gen/java/io/swagger/model/Order.java @@ -0,0 +1,203 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.util.Date; + + + + + + +public class Order { + + private Long id = null; + private Long petId = null; + private Integer quantity = null; + private Date shipDate = null; + + + public enum StatusEnum { + PLACED("placed"), + APPROVED("approved"), + DELIVERED("delivered"); + + private String value; + + StatusEnum(String value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return value; + } + } + + private StatusEnum status = null; + private Boolean complete = false; + + + /** + **/ + public Order id(Long id) { + this.id = id; + return this; + } + + + @ApiModelProperty(value = "") + @JsonProperty("id") + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + + /** + **/ + public Order petId(Long petId) { + this.petId = petId; + return this; + } + + + @ApiModelProperty(value = "") + @JsonProperty("petId") + public Long getPetId() { + return petId; + } + public void setPetId(Long petId) { + this.petId = petId; + } + + + /** + **/ + public Order quantity(Integer quantity) { + this.quantity = quantity; + return this; + } + + + @ApiModelProperty(value = "") + @JsonProperty("quantity") + public Integer getQuantity() { + return quantity; + } + public void setQuantity(Integer quantity) { + this.quantity = quantity; + } + + + /** + **/ + public Order shipDate(Date shipDate) { + this.shipDate = shipDate; + return this; + } + + + @ApiModelProperty(value = "") + @JsonProperty("shipDate") + public Date getShipDate() { + return shipDate; + } + public void setShipDate(Date shipDate) { + this.shipDate = shipDate; + } + + + /** + * Order Status + **/ + public Order status(StatusEnum status) { + this.status = status; + return this; + } + + + @ApiModelProperty(value = "Order Status") + @JsonProperty("status") + public StatusEnum getStatus() { + return status; + } + public void setStatus(StatusEnum status) { + this.status = status; + } + + + /** + **/ + public Order complete(Boolean complete) { + this.complete = complete; + return this; + } + + + @ApiModelProperty(value = "") + @JsonProperty("complete") + public Boolean getComplete() { + return complete; + } + public void setComplete(Boolean complete) { + this.complete = complete; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Order order = (Order) o; + return Objects.equals(id, order.id) && + Objects.equals(petId, order.petId) && + Objects.equals(quantity, order.quantity) && + Objects.equals(shipDate, order.shipDate) && + Objects.equals(status, order.status) && + Objects.equals(complete, order.complete); + } + + @Override + public int hashCode() { + return Objects.hash(id, petId, quantity, shipDate, status, complete); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Order {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" petId: ").append(toIndentedString(petId)).append("\n"); + sb.append(" quantity: ").append(toIndentedString(quantity)).append("\n"); + sb.append(" shipDate: ").append(toIndentedString(shipDate)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append(" complete: ").append(toIndentedString(complete)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jersey2/src/gen/java/io/swagger/model/Pet.java b/samples/server/petstore/jersey2/src/gen/java/io/swagger/model/Pet.java new file mode 100644 index 00000000000..514bb24508d --- /dev/null +++ b/samples/server/petstore/jersey2/src/gen/java/io/swagger/model/Pet.java @@ -0,0 +1,206 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.model.Category; +import io.swagger.model.Tag; +import java.util.ArrayList; +import java.util.List; + + + + + + +public class Pet { + + private Long id = null; + private Category category = null; + private String name = null; + private List photoUrls = new ArrayList(); + private List tags = new ArrayList(); + + + public enum StatusEnum { + AVAILABLE("available"), + PENDING("pending"), + SOLD("sold"); + + private String value; + + StatusEnum(String value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return value; + } + } + + private StatusEnum status = null; + + + /** + **/ + public Pet id(Long id) { + this.id = id; + return this; + } + + + @ApiModelProperty(value = "") + @JsonProperty("id") + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + + /** + **/ + public Pet category(Category category) { + this.category = category; + return this; + } + + + @ApiModelProperty(value = "") + @JsonProperty("category") + public Category getCategory() { + return category; + } + public void setCategory(Category category) { + this.category = category; + } + + + /** + **/ + public Pet name(String name) { + this.name = name; + return this; + } + + + @ApiModelProperty(example = "doggie", required = true, value = "") + @JsonProperty("name") + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + + + /** + **/ + public Pet photoUrls(List photoUrls) { + this.photoUrls = photoUrls; + return this; + } + + + @ApiModelProperty(required = true, value = "") + @JsonProperty("photoUrls") + public List getPhotoUrls() { + return photoUrls; + } + public void setPhotoUrls(List photoUrls) { + this.photoUrls = photoUrls; + } + + + /** + **/ + public Pet tags(List tags) { + this.tags = tags; + return this; + } + + + @ApiModelProperty(value = "") + @JsonProperty("tags") + public List getTags() { + return tags; + } + public void setTags(List tags) { + this.tags = tags; + } + + + /** + * pet status in the store + **/ + public Pet status(StatusEnum status) { + this.status = status; + return this; + } + + + @ApiModelProperty(value = "pet status in the store") + @JsonProperty("status") + public StatusEnum getStatus() { + return status; + } + public void setStatus(StatusEnum status) { + this.status = status; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Pet pet = (Pet) o; + return Objects.equals(id, pet.id) && + Objects.equals(category, pet.category) && + Objects.equals(name, pet.name) && + Objects.equals(photoUrls, pet.photoUrls) && + Objects.equals(tags, pet.tags) && + Objects.equals(status, pet.status); + } + + @Override + public int hashCode() { + return Objects.hash(id, category, name, photoUrls, tags, status); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Pet {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" category: ").append(toIndentedString(category)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" photoUrls: ").append(toIndentedString(photoUrls)).append("\n"); + sb.append(" tags: ").append(toIndentedString(tags)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jersey2/src/gen/java/io/swagger/model/Tag.java b/samples/server/petstore/jersey2/src/gen/java/io/swagger/model/Tag.java new file mode 100644 index 00000000000..b46638ccb69 --- /dev/null +++ b/samples/server/petstore/jersey2/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 io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + + + + + + +public class Tag { + + private Long id = null; + private String name = null; + + + /** + **/ + public Tag id(Long id) { + this.id = id; + return this; + } + + + @ApiModelProperty(value = "") + @JsonProperty("id") + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + + /** + **/ + public Tag name(String name) { + this.name = name; + return this; + } + + + @ApiModelProperty(value = "") + @JsonProperty("name") + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Tag tag = (Tag) o; + return Objects.equals(id, tag.id) && + Objects.equals(name, tag.name); + } + + @Override + public int hashCode() { + return Objects.hash(id, name); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Tag {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jersey2/src/gen/java/io/swagger/model/User.java b/samples/server/petstore/jersey2/src/gen/java/io/swagger/model/User.java new file mode 100644 index 00000000000..7f18c02f599 --- /dev/null +++ b/samples/server/petstore/jersey2/src/gen/java/io/swagger/model/User.java @@ -0,0 +1,223 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + + + + + + +public class User { + + private Long id = null; + private String username = null; + private String firstName = null; + private String lastName = null; + private String email = null; + private String password = null; + private String phone = null; + private Integer userStatus = null; + + + /** + **/ + public User id(Long id) { + this.id = id; + return this; + } + + + @ApiModelProperty(value = "") + @JsonProperty("id") + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + + /** + **/ + public User username(String username) { + this.username = username; + return this; + } + + + @ApiModelProperty(value = "") + @JsonProperty("username") + public String getUsername() { + return username; + } + public void setUsername(String username) { + this.username = username; + } + + + /** + **/ + public User firstName(String firstName) { + this.firstName = firstName; + return this; + } + + + @ApiModelProperty(value = "") + @JsonProperty("firstName") + public String getFirstName() { + return firstName; + } + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + + /** + **/ + public User lastName(String lastName) { + this.lastName = lastName; + return this; + } + + + @ApiModelProperty(value = "") + @JsonProperty("lastName") + public String getLastName() { + return lastName; + } + public void setLastName(String lastName) { + this.lastName = lastName; + } + + + /** + **/ + public User email(String email) { + this.email = email; + return this; + } + + + @ApiModelProperty(value = "") + @JsonProperty("email") + public String getEmail() { + return email; + } + public void setEmail(String email) { + this.email = email; + } + + + /** + **/ + public User password(String password) { + this.password = password; + return this; + } + + + @ApiModelProperty(value = "") + @JsonProperty("password") + public String getPassword() { + return password; + } + public void setPassword(String password) { + this.password = password; + } + + + /** + **/ + public User phone(String phone) { + this.phone = phone; + return this; + } + + + @ApiModelProperty(value = "") + @JsonProperty("phone") + public String getPhone() { + return phone; + } + public void setPhone(String phone) { + this.phone = phone; + } + + + /** + * User Status + **/ + public User userStatus(Integer userStatus) { + this.userStatus = userStatus; + return this; + } + + + @ApiModelProperty(value = "User Status") + @JsonProperty("userStatus") + public Integer getUserStatus() { + return userStatus; + } + public void setUserStatus(Integer userStatus) { + this.userStatus = userStatus; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + User user = (User) o; + return Objects.equals(id, user.id) && + Objects.equals(username, user.username) && + Objects.equals(firstName, user.firstName) && + Objects.equals(lastName, user.lastName) && + Objects.equals(email, user.email) && + Objects.equals(password, user.password) && + Objects.equals(phone, user.phone) && + Objects.equals(userStatus, user.userStatus); + } + + @Override + public int hashCode() { + return Objects.hash(id, username, firstName, lastName, email, password, phone, userStatus); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class User {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" username: ").append(toIndentedString(username)).append("\n"); + sb.append(" firstName: ").append(toIndentedString(firstName)).append("\n"); + sb.append(" lastName: ").append(toIndentedString(lastName)).append("\n"); + sb.append(" email: ").append(toIndentedString(email)).append("\n"); + sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" phone: ").append(toIndentedString(phone)).append("\n"); + sb.append(" userStatus: ").append(toIndentedString(userStatus)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jersey2/src/main/java/io/swagger/api/Bootstrap.java b/samples/server/petstore/jersey2/src/main/java/io/swagger/api/Bootstrap.java new file mode 100644 index 00000000000..0651af80f18 --- /dev/null +++ b/samples/server/petstore/jersey2/src/main/java/io/swagger/api/Bootstrap.java @@ -0,0 +1,31 @@ +package io.swagger.api; + +import io.swagger.jaxrs.config.SwaggerContextService; +import io.swagger.models.*; + +import io.swagger.models.auth.*; + +import javax.servlet.http.HttpServlet; +import javax.servlet.ServletContext; +import javax.servlet.ServletConfig; +import javax.servlet.ServletException; + +public class Bootstrap extends HttpServlet { + @Override + public void init(ServletConfig config) throws ServletException { + Info info = new Info() + .title("Swagger Server") + .description("This is a sample server Petstore server. You can find out more about\nSwagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/).\nFor this sample, you can use the api key `special-key` to test the authorization filters.\n") + .termsOfService("http://swagger.io/terms/") + .contact(new Contact() + .email("apiteam@swagger.io")) + .license(new License() + .name("Apache 2.0") + .url("http://www.apache.org/licenses/LICENSE-2.0.html")); + + ServletContext context = config.getServletContext(); + Swagger swagger = new Swagger().info(info); + + new SwaggerContextService().withServletConfig(config).updateSwagger(swagger); + } +} diff --git a/samples/server/petstore/jersey2/src/main/java/io/swagger/api/factories/PetApiServiceFactory.java b/samples/server/petstore/jersey2/src/main/java/io/swagger/api/factories/PetApiServiceFactory.java new file mode 100644 index 00000000000..50f0288b26c --- /dev/null +++ b/samples/server/petstore/jersey2/src/main/java/io/swagger/api/factories/PetApiServiceFactory.java @@ -0,0 +1,13 @@ +package io.swagger.api.factories; + +import io.swagger.api.PetApiService; +import io.swagger.api.impl.PetApiServiceImpl; + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaJerseyServerCodegen", date = "2016-04-02T18:35:30.846-06:00") +public class PetApiServiceFactory { + private final static PetApiService service = new PetApiServiceImpl(); + + public static PetApiService getPetApi() { + return service; + } +} diff --git a/samples/server/petstore/jersey2/src/main/java/io/swagger/api/factories/StoreApiServiceFactory.java b/samples/server/petstore/jersey2/src/main/java/io/swagger/api/factories/StoreApiServiceFactory.java new file mode 100644 index 00000000000..46ebd48a86f --- /dev/null +++ b/samples/server/petstore/jersey2/src/main/java/io/swagger/api/factories/StoreApiServiceFactory.java @@ -0,0 +1,13 @@ +package io.swagger.api.factories; + +import io.swagger.api.StoreApiService; +import io.swagger.api.impl.StoreApiServiceImpl; + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaJerseyServerCodegen", date = "2016-04-02T18:35:30.846-06:00") +public class StoreApiServiceFactory { + private final static StoreApiService service = new StoreApiServiceImpl(); + + public static StoreApiService getStoreApi() { + return service; + } +} diff --git a/samples/server/petstore/jersey2/src/main/java/io/swagger/api/factories/UserApiServiceFactory.java b/samples/server/petstore/jersey2/src/main/java/io/swagger/api/factories/UserApiServiceFactory.java new file mode 100644 index 00000000000..9703e297248 --- /dev/null +++ b/samples/server/petstore/jersey2/src/main/java/io/swagger/api/factories/UserApiServiceFactory.java @@ -0,0 +1,13 @@ +package io.swagger.api.factories; + +import io.swagger.api.UserApiService; +import io.swagger.api.impl.UserApiServiceImpl; + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaJerseyServerCodegen", date = "2016-04-02T18:35:30.846-06:00") +public class UserApiServiceFactory { + private final static UserApiService service = new UserApiServiceImpl(); + + public static UserApiService getUserApi() { + return service; + } +} diff --git a/samples/server/petstore/jersey2/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java b/samples/server/petstore/jersey2/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java new file mode 100644 index 00000000000..fead74f3b6c --- /dev/null +++ b/samples/server/petstore/jersey2/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java @@ -0,0 +1,71 @@ +package io.swagger.api.impl; + +import io.swagger.api.*; +import io.swagger.model.*; + +import io.swagger.model.Pet; +import io.swagger.model.ApiResponse; +import java.io.File; + +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; + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaJerseyServerCodegen", date = "2016-04-02T18:35:30.846-06:00") +public class PetApiServiceImpl extends PetApiService { + + @Override + public Response addPet(Pet body, SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + + @Override + public Response deletePet(Long petId, String apiKey, SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + + @Override + public Response findPetsByStatus(List status, SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + + @Override + public Response findPetsByTags(List tags, SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + + @Override + public Response getPetById(Long petId, SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + + @Override + public Response updatePet(Pet body, SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + + @Override + public Response updatePetWithForm(Long petId, String name, String status, SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + + @Override + public Response uploadFile(Long petId, String additionalMetadata, InputStream inputStream, FormDataContentDisposition fileDetail, SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + +} diff --git a/samples/server/petstore/jersey2/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java b/samples/server/petstore/jersey2/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java new file mode 100644 index 00000000000..176e893db35 --- /dev/null +++ b/samples/server/petstore/jersey2/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java @@ -0,0 +1,46 @@ +package io.swagger.api.impl; + +import io.swagger.api.*; +import io.swagger.model.*; + +import java.util.Map; +import io.swagger.model.Order; + +import java.util.List; +import io.swagger.api.NotFoundException; + +import java.io.InputStream; + +import org.glassfish.jersey.media.multipart.FormDataContentDisposition; + +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaJerseyServerCodegen", date = "2016-04-02T18:35:30.846-06:00") +public class StoreApiServiceImpl extends StoreApiService { + + @Override + public Response deleteOrder(Long orderId, SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + + @Override + public Response getInventory(SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + + @Override + public Response getOrderById(Long orderId, SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + + @Override + public Response placeOrder(Order body, SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + +} diff --git a/samples/server/petstore/jersey2/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java b/samples/server/petstore/jersey2/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java new file mode 100644 index 00000000000..1c4d449a7bd --- /dev/null +++ b/samples/server/petstore/jersey2/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java @@ -0,0 +1,70 @@ +package io.swagger.api.impl; + +import io.swagger.api.*; +import io.swagger.model.*; + +import io.swagger.model.User; +import java.util.List; + +import java.util.List; +import io.swagger.api.NotFoundException; + +import java.io.InputStream; + +import org.glassfish.jersey.media.multipart.FormDataContentDisposition; + +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaJerseyServerCodegen", date = "2016-04-02T18:35:30.846-06:00") +public class UserApiServiceImpl extends UserApiService { + + @Override + public Response createUser(User body, SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + + @Override + public Response createUsersWithArrayInput(List body, SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + + @Override + public Response createUsersWithListInput(List body, SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + + @Override + public Response deleteUser(String username, SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + + @Override + public Response getUserByName(String username, SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + + @Override + public Response loginUser(String username, String password, SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + + @Override + public Response logoutUser(SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + + @Override + public Response updateUser(String username, User body, SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + +} diff --git a/samples/server/petstore/jersey2/src/main/webapp/WEB-INF/web.xml b/samples/server/petstore/jersey2/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 00000000000..66837dccab8 --- /dev/null +++ b/samples/server/petstore/jersey2/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,63 @@ + + + + + jersey + org.glassfish.jersey.servlet.ServletContainer + + jersey.config.server.provider.packages + + io.swagger.jaxrs.listing, + io.swagger.sample.resource, + io.swagger.api + + + + jersey.config.server.provider.classnames + org.glassfish.jersey.media.multipart.MultiPartFeature + + + jersey.config.server.wadl.disableWadl + true + + 1 + + + + Jersey2Config + io.swagger.jersey.config.JerseyJaxrsConfig + + api.version + 1.0.0 + + + swagger.api.title + Swagger Server + + + swagger.api.basepath + http://petstore.swagger.io/v2 + + + 2 + + + Bootstrap + io.swagger.api.Bootstrap + 2 + + + jersey + /v2/* + + + ApiOriginFilter + io.swagger.api.ApiOriginFilter + + + ApiOriginFilter + /* + + diff --git a/samples/server/petstore/nodejs/README.md b/samples/server/petstore/nodejs/README.md index 2efc45fe33e..d94aa385ec0 100644 --- a/samples/server/petstore/nodejs/README.md +++ b/samples/server/petstore/nodejs/README.md @@ -1,11 +1,11 @@ # Swagger generated server ## Overview -This server was generated by the [swagger-codegen](https://github.com/swagger-api/swagger-codegen) project. By using the [swagger-spec](https://github.com/OAI/OpenAPI-Specification) from a remote server, you can easily generate a server stub. This is an example of building a node.js server. +This server was generated by the [swagger-codegen](https://github.com/swagger-api/swagger-codegen) project. By using the [OpenAPI-Spec](https://github.com/OAI/OpenAPI-Specification) from a remote server, you can easily generate a server stub. This is an example of building a node.js server. This example uses the [expressjs](http://expressjs.com/) framework. To see how to make this your own, look here: -[README](https://github.com/swagger-api/swagger-codegen/README.md) +[README](https://github.com/swagger-api/swagger-codegen/blob/master/README.md) ### Running the server To run the server, follow these simple steps: @@ -21,4 +21,4 @@ To view the Swagger UI interface: open http://localhost:8080/docs ``` -This project leverages the mega-awesome [swagger-tools](https://github.com/apigee-127/swagger-tools) middleware which does most all the work. \ No newline at end of file +This project leverages the mega-awesome [swagger-tools](https://github.com/apigee-127/swagger-tools) middleware which does most all the work. diff --git a/samples/server/petstore/nodejs/api/swagger.yaml b/samples/server/petstore/nodejs/api/swagger.yaml index 49a3405de09..7f6eada7d8c 100644 --- a/samples/server/petstore/nodejs/api/swagger.yaml +++ b/samples/server/petstore/nodejs/api/swagger.yaml @@ -1,15 +1,14 @@ --- swagger: "2.0" info: - description: "This is a sample server Petstore server. You can find out more about\ - \ Swagger at http://swagger.io or on irc.freenode.net,\ - \ #swagger. For this sample, you can use the api key \"special-key\" to test\ - \ the authorization filters" + description: "This is a sample server Petstore server.\n\n[Learn about Swagger](http://swagger.io)\ + \ or join the IRC channel `#swagger` on irc.freenode.net.\n\nFor this sample,\ + \ you can use the api key `special-key` to test the authorization filters\n" version: "1.0.0" title: "Swagger Petstore" termsOfService: "http://swagger.io/terms/" contact: - email: "apiteam@swagger.io" + name: "apiteam@swagger.io" license: name: "Apache 2.0" url: "http://www.apache.org/licenses/LICENSE-2.0.html" @@ -18,7 +17,7 @@ basePath: "/v2" schemes: - "http" paths: - /pet: + /pets: post: tags: - "pet" @@ -43,8 +42,9 @@ paths: description: "Invalid input" security: - petstore_auth: - - "write:pets" - - "read:pets" + - "write_pets" + - "read_pets" + x-swagger-router-controller: "Pet" put: tags: - "pet" @@ -73,9 +73,10 @@ paths: description: "Validation exception" security: - petstore_auth: - - "write:pets" - - "read:pets" - /pet/findByStatus: + - "write_pets" + - "read_pets" + x-swagger-router-controller: "Pet" + /pets/findByStatus: get: tags: - "pet" @@ -94,7 +95,6 @@ paths: items: type: "string" collectionFormat: "multi" - default: "available" responses: 200: description: "successful operation" @@ -106,9 +106,10 @@ paths: description: "Invalid status value" security: - petstore_auth: - - "write:pets" - - "read:pets" - /pet/findByTags: + - "write_pets" + - "read_pets" + x-swagger-router-controller: "Pet" + /pets/findByTags: get: tags: - "pet" @@ -139,9 +140,10 @@ paths: description: "Invalid tag value" security: - petstore_auth: - - "write:pets" - - "read:pets" - /pet/{petId}: + - "write_pets" + - "read_pets" + x-swagger-router-controller: "Pet" + /pets/{petId}: get: tags: - "pet" @@ -171,8 +173,9 @@ paths: security: - api_key: [] - petstore_auth: - - "write:pets" - - "read:pets" + - "write_pets" + - "read_pets" + x-swagger-router-controller: "Pet" post: tags: - "pet" @@ -193,20 +196,21 @@ paths: - name: "name" in: "formData" description: "Updated name of the pet" - required: false + required: true type: "string" - name: "status" in: "formData" description: "Updated status of the pet" - required: false + required: true type: "string" responses: 405: description: "Invalid input" security: - petstore_auth: - - "write:pets" - - "read:pets" + - "write_pets" + - "read_pets" + x-swagger-router-controller: "Pet" delete: tags: - "pet" @@ -220,7 +224,7 @@ paths: - name: "api_key" in: "header" description: "" - required: false + required: true type: "string" - name: "petId" in: "path" @@ -233,66 +237,10 @@ paths: description: "Invalid pet value" security: - petstore_auth: - - "write:pets" - - "read:pets" - /pet/{petId}/uploadImage: - post: - tags: - - "pet" - summary: "uploads an image" - description: "" - operationId: "uploadFile" - consumes: - - "multipart/form-data" - produces: - - "application/json" - - "application/xml" - parameters: - - name: "petId" - in: "path" - description: "ID of pet to update" - required: true - type: "integer" - format: "int64" - - name: "additionalMetadata" - in: "formData" - description: "Additional data to pass to server" - required: false - type: "string" - - name: "file" - in: "formData" - description: "file to upload" - required: false - type: "file" - responses: - default: - description: "successful operation" - security: - - petstore_auth: - - "write:pets" - - "read:pets" - /store/inventory: - get: - tags: - - "store" - summary: "Returns pet inventories by status" - description: "Returns a map of status codes to quantities" - operationId: "getInventory" - produces: - - "application/json" - - "application/xml" - parameters: [] - responses: - 200: - description: "successful operation" - schema: - type: "object" - additionalProperties: - type: "integer" - format: "int32" - security: - - api_key: [] - /store/order: + - "write_pets" + - "read_pets" + x-swagger-router-controller: "Pet" + /stores/order: post: tags: - "store" @@ -316,7 +264,8 @@ paths: $ref: "#/definitions/Order" 400: description: "Invalid Order" - /store/order/{orderId}: + x-swagger-router-controller: "Store" + /stores/order/{orderId}: get: tags: - "store" @@ -342,6 +291,7 @@ paths: description: "Invalid ID supplied" 404: description: "Order not found" + x-swagger-router-controller: "Store" delete: tags: - "store" @@ -363,7 +313,8 @@ paths: description: "Invalid ID supplied" 404: description: "Order not found" - /user: + x-swagger-router-controller: "Store" + /users: post: tags: - "user" @@ -383,7 +334,8 @@ paths: responses: default: description: "successful operation" - /user/createWithArray: + x-swagger-router-controller: "User" + /users/createWithArray: post: tags: - "user" @@ -405,7 +357,8 @@ paths: responses: default: description: "successful operation" - /user/createWithList: + x-swagger-router-controller: "User" + /users/createWithList: post: tags: - "user" @@ -427,7 +380,8 @@ paths: responses: default: description: "successful operation" - /user/login: + x-swagger-router-controller: "User" + /users/login: get: tags: - "user" @@ -455,7 +409,8 @@ paths: type: "string" 400: description: "Invalid username/password supplied" - /user/logout: + x-swagger-router-controller: "User" + /users/logout: get: tags: - "user" @@ -469,7 +424,8 @@ paths: responses: default: description: "successful operation" - /user/{username}: + x-swagger-router-controller: "User" + /users/{username}: get: tags: - "user" @@ -482,7 +438,7 @@ paths: parameters: - name: "username" in: "path" - description: "The name that needs to be fetched. Use user1 for testing. " + description: "The name that needs to be fetched. Use user1 for testing." required: true type: "string" responses: @@ -490,20 +446,11 @@ paths: description: "successful operation" schema: $ref: "#/definitions/User" - examples: - application/json: - id: 1 - username: "johnp" - firstName: "John" - lastName: "Public" - email: "johnp@swagger.io" - password: "-secret-" - phone: "0123456789" - userStatus: 0 400: description: "Invalid username supplied" 404: description: "User not found" + x-swagger-router-controller: "User" put: tags: - "user" @@ -530,6 +477,7 @@ paths: description: "Invalid user supplied" 404: description: "User not found" + x-swagger-router-controller: "User" delete: tags: - "user" @@ -550,6 +498,7 @@ paths: description: "Invalid username supplied" 404: description: "User not found" + x-swagger-router-controller: "User" securityDefinitions: api_key: type: "apiKey" @@ -560,10 +509,11 @@ securityDefinitions: authorizationUrl: "http://petstore.swagger.io/api/oauth/dialog" flow: "implicit" scopes: - write:pets: "modify pets in your account" - read:pets: "read your pets" + write_pets: "modify pets in your account" + read_pets: "read your pets" definitions: User: + type: "object" properties: id: type: "integer" @@ -584,18 +534,16 @@ definitions: type: "integer" format: "int32" description: "User Status" - xml: - name: "User" Category: + type: "object" properties: id: type: "integer" format: "int64" name: type: "string" - xml: - name: "Category" Pet: + type: "object" required: - "name" - "photoUrls" @@ -610,37 +558,25 @@ definitions: example: "doggie" photoUrls: type: "array" - xml: - name: "photoUrl" - wrapped: true items: type: "string" tags: type: "array" - xml: - name: "tag" - wrapped: true items: $ref: "#/definitions/Tag" status: type: "string" description: "pet status in the store" - enum: - - "available" - - "pending" - - "sold" - xml: - name: "Pet" Tag: + type: "object" properties: id: type: "integer" format: "int64" name: type: "string" - xml: - name: "Tag" Order: + type: "object" properties: id: type: "integer" @@ -657,11 +593,5 @@ definitions: status: type: "string" description: "Order Status" - enum: - - "placed" - - "approved" - - "delivered" complete: type: "boolean" - xml: - name: "Order" diff --git a/samples/server/petstore/nodejs/controllers/Pet.js b/samples/server/petstore/nodejs/controllers/Pet.js index d272cb8240f..a7d196faa7c 100644 --- a/samples/server/petstore/nodejs/controllers/Pet.js +++ b/samples/server/petstore/nodejs/controllers/Pet.js @@ -6,14 +6,14 @@ var url = require('url'); var Pet = require('./PetService'); -module.exports.updatePet = function updatePet (req, res, next) { - Pet.updatePet(req.swagger.params, res, next); -}; - module.exports.addPet = function addPet (req, res, next) { Pet.addPet(req.swagger.params, res, next); }; +module.exports.deletePet = function deletePet (req, res, next) { + Pet.deletePet(req.swagger.params, res, next); +}; + module.exports.findPetsByStatus = function findPetsByStatus (req, res, next) { Pet.findPetsByStatus(req.swagger.params, res, next); }; @@ -26,14 +26,10 @@ module.exports.getPetById = function getPetById (req, res, next) { Pet.getPetById(req.swagger.params, res, next); }; +module.exports.updatePet = function updatePet (req, res, next) { + Pet.updatePet(req.swagger.params, res, next); +}; + module.exports.updatePetWithForm = function updatePetWithForm (req, res, next) { Pet.updatePetWithForm(req.swagger.params, res, next); }; - -module.exports.deletePet = function deletePet (req, res, next) { - Pet.deletePet(req.swagger.params, res, next); -}; - -module.exports.uploadFile = function uploadFile (req, res, next) { - Pet.uploadFile(req.swagger.params, res, next); -}; diff --git a/samples/server/petstore/nodejs/controllers/PetService.js b/samples/server/petstore/nodejs/controllers/PetService.js index 97a1d3ede62..29a51e31a2b 100644 --- a/samples/server/petstore/nodejs/controllers/PetService.js +++ b/samples/server/petstore/nodejs/controllers/PetService.js @@ -1,37 +1,30 @@ 'use strict'; -exports.updatePet = function(args, res, next) { - /** - * parameters expected in the args: - * body (Pet) - **/ - -var examples = {}; - - - - res.end(); -} exports.addPet = function(args, res, next) { /** * parameters expected in the args: - * body (Pet) - **/ - -var examples = {}; - - - + * body (Pet) + **/ + // no response value expected for this operation res.end(); } + +exports.deletePet = function(args, res, next) { + /** + * parameters expected in the args: + * apiKey (String) + * petId (Long) + **/ + // no response value expected for this operation + res.end(); +} + exports.findPetsByStatus = function(args, res, next) { /** * parameters expected in the args: - * status (List) - **/ - -var examples = {}; - + * status (List) + **/ + var examples = {}; examples['application/json'] = [ { "tags" : [ { "id" : 123456789, @@ -46,9 +39,6 @@ var examples = {}; "name" : "doggie", "photoUrls" : [ "aeiou" ] } ]; - - - if(Object.keys(examples).length > 0) { res.setHeader('Content-Type', 'application/json'); res.end(JSON.stringify(examples[Object.keys(examples)[0]] || {}, null, 2)); @@ -57,16 +47,14 @@ var examples = {}; res.end(); } - } + exports.findPetsByTags = function(args, res, next) { /** * parameters expected in the args: - * tags (List) - **/ - -var examples = {}; - + * tags (List) + **/ + var examples = {}; examples['application/json'] = [ { "tags" : [ { "id" : 123456789, @@ -81,9 +69,6 @@ var examples = {}; "name" : "doggie", "photoUrls" : [ "aeiou" ] } ]; - - - if(Object.keys(examples).length > 0) { res.setHeader('Content-Type', 'application/json'); res.end(JSON.stringify(examples[Object.keys(examples)[0]] || {}, null, 2)); @@ -92,16 +77,14 @@ var examples = {}; res.end(); } - } + exports.getPetById = function(args, res, next) { /** * parameters expected in the args: - * petId (Long) - **/ - -var examples = {}; - + * petId (Long) + **/ + var examples = {}; examples['application/json'] = { "tags" : [ { "id" : 123456789, @@ -116,9 +99,6 @@ var examples = {}; "name" : "doggie", "photoUrls" : [ "aeiou" ] }; - - - if(Object.keys(examples).length > 0) { res.setHeader('Content-Type', 'application/json'); res.end(JSON.stringify(examples[Object.keys(examples)[0]] || {}, null, 2)); @@ -127,46 +107,25 @@ var examples = {}; res.end(); } - } + +exports.updatePet = function(args, res, next) { + /** + * parameters expected in the args: + * body (Pet) + **/ + // no response value expected for this operation + res.end(); +} + exports.updatePetWithForm = function(args, res, next) { /** * parameters expected in the args: - * petId (String) - * name (String) - * status (String) - **/ - -var examples = {}; - - - + * petId (String) + * name (String) + * status (String) + **/ + // no response value expected for this operation res.end(); } -exports.deletePet = function(args, res, next) { - /** - * parameters expected in the args: - * petId (Long) - * apiKey (String) - **/ -var examples = {}; - - - - res.end(); -} -exports.uploadFile = function(args, res, next) { - /** - * parameters expected in the args: - * petId (Long) - * additionalMetadata (String) - * file (file) - **/ - -var examples = {}; - - - - res.end(); -} diff --git a/samples/server/petstore/nodejs/controllers/Store.js b/samples/server/petstore/nodejs/controllers/Store.js index 8a07dc76ed3..95fcb02711e 100644 --- a/samples/server/petstore/nodejs/controllers/Store.js +++ b/samples/server/petstore/nodejs/controllers/Store.js @@ -6,18 +6,14 @@ var url = require('url'); var Store = require('./StoreService'); -module.exports.getInventory = function getInventory (req, res, next) { - Store.getInventory(req.swagger.params, res, next); -}; - -module.exports.placeOrder = function placeOrder (req, res, next) { - Store.placeOrder(req.swagger.params, res, next); +module.exports.deleteOrder = function deleteOrder (req, res, next) { + Store.deleteOrder(req.swagger.params, res, next); }; module.exports.getOrderById = function getOrderById (req, res, next) { Store.getOrderById(req.swagger.params, res, next); }; -module.exports.deleteOrder = function deleteOrder (req, res, next) { - Store.deleteOrder(req.swagger.params, res, next); +module.exports.placeOrder = function placeOrder (req, res, next) { + Store.placeOrder(req.swagger.params, res, next); }; diff --git a/samples/server/petstore/nodejs/controllers/StoreService.js b/samples/server/petstore/nodejs/controllers/StoreService.js index 3bb37b6c01f..6ee8ff36f94 100644 --- a/samples/server/petstore/nodejs/controllers/StoreService.js +++ b/samples/server/petstore/nodejs/controllers/StoreService.js @@ -1,95 +1,59 @@ 'use strict'; -exports.getInventory = function(args, res, next) { - /** - * parameters expected in the args: - **/ - -var examples = {}; - - examples['application/json'] = { - "key" : 123 -}; - - - - if(Object.keys(examples).length > 0) { - res.setHeader('Content-Type', 'application/json'); - res.end(JSON.stringify(examples[Object.keys(examples)[0]] || {}, null, 2)); - } - else { - res.end(); - } - - -} -exports.placeOrder = function(args, res, next) { - /** - * parameters expected in the args: - * body (Order) - **/ - -var examples = {}; - - examples['application/json'] = { - "id" : 123456789, - "petId" : 123456789, - "complete" : true, - "status" : "aeiou", - "quantity" : 123, - "shipDate" : "2015-11-18T02:43:54.540+0000" -}; - - - - if(Object.keys(examples).length > 0) { - res.setHeader('Content-Type', 'application/json'); - res.end(JSON.stringify(examples[Object.keys(examples)[0]] || {}, null, 2)); - } - else { - res.end(); - } - - -} -exports.getOrderById = function(args, res, next) { - /** - * parameters expected in the args: - * orderId (String) - **/ - -var examples = {}; - - examples['application/json'] = { - "id" : 123456789, - "petId" : 123456789, - "complete" : true, - "status" : "aeiou", - "quantity" : 123, - "shipDate" : "2015-11-18T02:43:54.544+0000" -}; - - - - if(Object.keys(examples).length > 0) { - res.setHeader('Content-Type', 'application/json'); - res.end(JSON.stringify(examples[Object.keys(examples)[0]] || {}, null, 2)); - } - else { - res.end(); - } - - -} exports.deleteOrder = function(args, res, next) { /** * parameters expected in the args: - * orderId (String) - **/ - -var examples = {}; - - - + * orderId (String) + **/ + // no response value expected for this operation res.end(); } + +exports.getOrderById = function(args, res, next) { + /** + * parameters expected in the args: + * orderId (String) + **/ + var examples = {}; + examples['application/json'] = { + "id" : 123456789, + "petId" : 123456789, + "complete" : true, + "status" : "aeiou", + "quantity" : 123, + "shipDate" : "2000-01-23T04:56:07.000+0000" +}; + if(Object.keys(examples).length > 0) { + res.setHeader('Content-Type', 'application/json'); + res.end(JSON.stringify(examples[Object.keys(examples)[0]] || {}, null, 2)); + } + else { + res.end(); + } + +} + +exports.placeOrder = function(args, res, next) { + /** + * parameters expected in the args: + * body (Order) + **/ + var examples = {}; + examples['application/json'] = { + "id" : 123456789, + "petId" : 123456789, + "complete" : true, + "status" : "aeiou", + "quantity" : 123, + "shipDate" : "2000-01-23T04:56:07.000+0000" +}; + if(Object.keys(examples).length > 0) { + res.setHeader('Content-Type', 'application/json'); + res.end(JSON.stringify(examples[Object.keys(examples)[0]] || {}, null, 2)); + } + else { + res.end(); + } + +} + diff --git a/samples/server/petstore/nodejs/controllers/User.js b/samples/server/petstore/nodejs/controllers/User.js index d2ce361da52..bac1d7f6a88 100644 --- a/samples/server/petstore/nodejs/controllers/User.js +++ b/samples/server/petstore/nodejs/controllers/User.js @@ -18,6 +18,14 @@ module.exports.createUsersWithListInput = function createUsersWithListInput (req User.createUsersWithListInput(req.swagger.params, res, next); }; +module.exports.deleteUser = function deleteUser (req, res, next) { + User.deleteUser(req.swagger.params, res, next); +}; + +module.exports.getUserByName = function getUserByName (req, res, next) { + User.getUserByName(req.swagger.params, res, next); +}; + module.exports.loginUser = function loginUser (req, res, next) { User.loginUser(req.swagger.params, res, next); }; @@ -26,14 +34,6 @@ module.exports.logoutUser = function logoutUser (req, res, next) { User.logoutUser(req.swagger.params, res, next); }; -module.exports.getUserByName = function getUserByName (req, res, next) { - User.getUserByName(req.swagger.params, res, next); -}; - module.exports.updateUser = function updateUser (req, res, next) { User.updateUser(req.swagger.params, res, next); }; - -module.exports.deleteUser = function deleteUser (req, res, next) { - User.deleteUser(req.swagger.params, res, next); -}; diff --git a/samples/server/petstore/nodejs/controllers/UserService.js b/samples/server/petstore/nodejs/controllers/UserService.js index 71f34f35bfb..69fc1a81391 100644 --- a/samples/server/petstore/nodejs/controllers/UserService.js +++ b/samples/server/petstore/nodejs/controllers/UserService.js @@ -3,126 +3,98 @@ exports.createUser = function(args, res, next) { /** * parameters expected in the args: - * body (User) - **/ - -var examples = {}; - - - + * body (User) + **/ + // no response value expected for this operation res.end(); } + exports.createUsersWithArrayInput = function(args, res, next) { /** * parameters expected in the args: - * body (List) - **/ - -var examples = {}; - - - + * body (List) + **/ + // no response value expected for this operation res.end(); } + exports.createUsersWithListInput = function(args, res, next) { /** * parameters expected in the args: - * body (List) - **/ - -var examples = {}; - - - + * body (List) + **/ + // no response value expected for this operation res.end(); } -exports.loginUser = function(args, res, next) { - /** - * parameters expected in the args: - * username (String) - * password (String) - **/ -var examples = {}; - - examples['application/json'] = "aeiou"; - - - - if(Object.keys(examples).length > 0) { - res.setHeader('Content-Type', 'application/json'); - res.end(JSON.stringify(examples[Object.keys(examples)[0]] || {}, null, 2)); - } - else { - res.end(); - } - - -} -exports.logoutUser = function(args, res, next) { - /** - * parameters expected in the args: - **/ - -var examples = {}; - - - - res.end(); -} -exports.getUserByName = function(args, res, next) { - /** - * parameters expected in the args: - * username (String) - **/ - -var examples = {}; - - examples['application/json'] = { - "id" : 1, - "username" : "johnp", - "firstName" : "John", - "lastName" : "Public", - "email" : "johnp@swagger.io", - "password" : "-secret-", - "phone" : "0123456789", - "userStatus" : 0 -}; - - - - if(Object.keys(examples).length > 0) { - res.setHeader('Content-Type', 'application/json'); - res.end(JSON.stringify(examples[Object.keys(examples)[0]] || {}, null, 2)); - } - else { - res.end(); - } - - -} -exports.updateUser = function(args, res, next) { - /** - * parameters expected in the args: - * username (String) - * body (User) - **/ - -var examples = {}; - - - - res.end(); -} exports.deleteUser = function(args, res, next) { /** * parameters expected in the args: - * username (String) - **/ - -var examples = {}; - - - + * username (String) + **/ + // no response value expected for this operation res.end(); } + +exports.getUserByName = function(args, res, next) { + /** + * parameters expected in the args: + * username (String) + **/ + var examples = {}; + examples['application/json'] = { + "id" : 123456789, + "lastName" : "aeiou", + "phone" : "aeiou", + "username" : "aeiou", + "email" : "aeiou", + "userStatus" : 123, + "firstName" : "aeiou", + "password" : "aeiou" +}; + if(Object.keys(examples).length > 0) { + res.setHeader('Content-Type', 'application/json'); + res.end(JSON.stringify(examples[Object.keys(examples)[0]] || {}, null, 2)); + } + else { + res.end(); + } + +} + +exports.loginUser = function(args, res, next) { + /** + * parameters expected in the args: + * username (String) + * password (String) + **/ + var examples = {}; + examples['application/json'] = "aeiou"; + if(Object.keys(examples).length > 0) { + res.setHeader('Content-Type', 'application/json'); + res.end(JSON.stringify(examples[Object.keys(examples)[0]] || {}, null, 2)); + } + else { + res.end(); + } + +} + +exports.logoutUser = function(args, res, next) { + /** + * parameters expected in the args: + **/ + // no response value expected for this operation + res.end(); +} + +exports.updateUser = function(args, res, next) { + /** + * parameters expected in the args: + * username (String) + * body (User) + **/ + // no response value expected for this operation + res.end(); +} + diff --git a/samples/server/petstore/nodejs/package.json b/samples/server/petstore/nodejs/package.json index 8befd2669d2..2ebddec5e2e 100644 --- a/samples/server/petstore/nodejs/package.json +++ b/samples/server/petstore/nodejs/package.json @@ -1,7 +1,7 @@ { - "name": "", + "name": "swagger-petstore", "version": "1.0.0", - "description": "This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters", + "description": "This is a sample server Petstore server.\n\n[Learn about Swagger](http://swagger.io) or join the IRC channel `#swagger` on irc.freenode.net.\n\nFor this sample, you can use the api key `special-key` to test the authorization filters\n", "main": "index.js", "keywords": [ "swagger" diff --git a/samples/server/petstore/sinatra/api/pet_api.rb b/samples/server/petstore/sinatra/api/pet_api.rb index 7ccad2056b9..3ca40f568d3 100644 --- a/samples/server/petstore/sinatra/api/pet_api.rb +++ b/samples/server/petstore/sinatra/api/pet_api.rb @@ -1,39 +1,12 @@ require 'json' -MyApp.add_route('PUT', '/v2/pet', { - "resourcePath" => "/Pet", - "summary" => "Update an existing pet", - "nickname" => "update_pet", - "responseClass" => "void", - "endpoint" => "/pet", - "notes" => "", - "parameters" => [ - - - - - { - "name" => "body", - "description" => "Pet object that needs to be added to the store", - "dataType" => "Pet", - "paramType" => "body", - } - - ]}) do - cross_origin - # the guts live here - - {"message" => "yes, it worked"}.to_json -end - - -MyApp.add_route('POST', '/v2/pet', { +MyApp.add_route('POST', '/v2/pets', { "resourcePath" => "/Pet", "summary" => "Add a new pet to the store", "nickname" => "add_pet", "responseClass" => "void", - "endpoint" => "/pet", + "endpoint" => "/pets", "notes" => "", "parameters" => [ @@ -55,126 +28,12 @@ MyApp.add_route('POST', '/v2/pet', { end -MyApp.add_route('GET', '/v2/pet/findByStatus', { - "resourcePath" => "/Pet", - "summary" => "Finds Pets by status", - "nickname" => "find_pets_by_status", - "responseClass" => "array[Pet]", - "endpoint" => "/pet/findByStatus", - "notes" => "Multiple status values can be provided with comma seperated strings", - "parameters" => [ - - { - "name" => "status", - "description" => "Status values that need to be considered for filter", - "dataType" => "array[string]", - "paramType" => "query", - "collectionFormat" => "multi", - "allowableValues" => "", - "defaultValue" => "available" - }, - - - - - ]}) do - cross_origin - # the guts live here - - {"message" => "yes, it worked"}.to_json -end - - -MyApp.add_route('GET', '/v2/pet/findByTags', { - "resourcePath" => "/Pet", - "summary" => "Finds Pets by tags", - "nickname" => "find_pets_by_tags", - "responseClass" => "array[Pet]", - "endpoint" => "/pet/findByTags", - "notes" => "Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.", - "parameters" => [ - - { - "name" => "tags", - "description" => "Tags to filter by", - "dataType" => "array[string]", - "paramType" => "query", - "collectionFormat" => "multi", - "allowableValues" => "", - - }, - - - - - ]}) do - cross_origin - # the guts live here - - {"message" => "yes, it worked"}.to_json -end - - -MyApp.add_route('GET', '/v2/pet/{petId}', { - "resourcePath" => "/Pet", - "summary" => "Find pet by ID", - "nickname" => "get_pet_by_id", - "responseClass" => "Pet", - "endpoint" => "/pet/{petId}", - "notes" => "Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions", - "parameters" => [ - - - { - "name" => "pet_id", - "description" => "ID of pet that needs to be fetched", - "dataType" => "int", - "paramType" => "path", - }, - - - - ]}) do - cross_origin - # the guts live here - - {"message" => "yes, it worked"}.to_json -end - - -MyApp.add_route('POST', '/v2/pet/{petId}', { - "resourcePath" => "/Pet", - "summary" => "Updates a pet in the store with form data", - "nickname" => "update_pet_with_form", - "responseClass" => "void", - "endpoint" => "/pet/{petId}", - "notes" => "", - "parameters" => [ - - - { - "name" => "pet_id", - "description" => "ID of pet that needs to be updated", - "dataType" => "string", - "paramType" => "path", - }, - - - - ]}) do - cross_origin - # the guts live here - - {"message" => "yes, it worked"}.to_json -end - - -MyApp.add_route('DELETE', '/v2/pet/{petId}', { +MyApp.add_route('DELETE', '/v2/pets/{petId}', { "resourcePath" => "/Pet", "summary" => "Deletes a pet", "nickname" => "delete_pet", "responseClass" => "void", - "endpoint" => "/pet/{petId}", + "endpoint" => "/pets/{petId}", "notes" => "", "parameters" => [ @@ -203,25 +62,139 @@ MyApp.add_route('DELETE', '/v2/pet/{petId}', { end -MyApp.add_route('POST', '/v2/pet/{petId}/uploadImage', { +MyApp.add_route('GET', '/v2/pets/findByStatus', { "resourcePath" => "/Pet", - "summary" => "uploads an image", - "nickname" => "upload_file", - "responseClass" => "void", - "endpoint" => "/pet/{petId}/uploadImage", - "notes" => "", + "summary" => "Finds Pets by status", + "nickname" => "find_pets_by_status", + "responseClass" => "array[Pet]", + "endpoint" => "/pets/findByStatus", + "notes" => "Multiple status values can be provided with comma seperated strings", + "parameters" => [ + + { + "name" => "status", + "description" => "Status values that need to be considered for filter", + "dataType" => "array[string]", + "paramType" => "query", + "collectionFormat" => "multi", + "allowableValues" => "", + + }, + + + + + ]}) do + cross_origin + # the guts live here + + {"message" => "yes, it worked"}.to_json +end + + +MyApp.add_route('GET', '/v2/pets/findByTags', { + "resourcePath" => "/Pet", + "summary" => "Finds Pets by tags", + "nickname" => "find_pets_by_tags", + "responseClass" => "array[Pet]", + "endpoint" => "/pets/findByTags", + "notes" => "Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.", + "parameters" => [ + + { + "name" => "tags", + "description" => "Tags to filter by", + "dataType" => "array[string]", + "paramType" => "query", + "collectionFormat" => "multi", + "allowableValues" => "", + + }, + + + + + ]}) do + cross_origin + # the guts live here + + {"message" => "yes, it worked"}.to_json +end + + +MyApp.add_route('GET', '/v2/pets/{petId}', { + "resourcePath" => "/Pet", + "summary" => "Find pet by ID", + "nickname" => "get_pet_by_id", + "responseClass" => "Pet", + "endpoint" => "/pets/{petId}", + "notes" => "Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions", "parameters" => [ { "name" => "pet_id", - "description" => "ID of pet to update", + "description" => "ID of pet that needs to be fetched", "dataType" => "int", "paramType" => "path", }, + ]}) do + cross_origin + # the guts live here + + {"message" => "yes, it worked"}.to_json +end + + +MyApp.add_route('PUT', '/v2/pets', { + "resourcePath" => "/Pet", + "summary" => "Update an existing pet", + "nickname" => "update_pet", + "responseClass" => "void", + "endpoint" => "/pets", + "notes" => "", + "parameters" => [ + + + + + { + "name" => "body", + "description" => "Pet object that needs to be added to the store", + "dataType" => "Pet", + "paramType" => "body", + } + + ]}) do + cross_origin + # the guts live here + + {"message" => "yes, it worked"}.to_json +end + + +MyApp.add_route('POST', '/v2/pets/{petId}', { + "resourcePath" => "/Pet", + "summary" => "Updates a pet in the store with form data", + "nickname" => "update_pet_with_form", + "responseClass" => "void", + "endpoint" => "/pets/{petId}", + "notes" => "", + "parameters" => [ + + + { + "name" => "pet_id", + "description" => "ID of pet that needs to be updated", + "dataType" => "string", + "paramType" => "path", + }, + + + ]}) do cross_origin # the guts live here diff --git a/samples/server/petstore/sinatra/api/store_api.rb b/samples/server/petstore/sinatra/api/store_api.rb index 37938b304db..26ac567759b 100644 --- a/samples/server/petstore/sinatra/api/store_api.rb +++ b/samples/server/petstore/sinatra/api/store_api.rb @@ -1,44 +1,24 @@ require 'json' -MyApp.add_route('GET', '/v2/store/inventory', { +MyApp.add_route('DELETE', '/v2/stores/order/{orderId}', { "resourcePath" => "/Store", - "summary" => "Returns pet inventories by status", - "nickname" => "get_inventory", - "responseClass" => "map[string,int]", - "endpoint" => "/store/inventory", - "notes" => "Returns a map of status codes to quantities", + "summary" => "Delete purchase order by ID", + "nickname" => "delete_order", + "responseClass" => "void", + "endpoint" => "/stores/order/{orderId}", + "notes" => "For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors", "parameters" => [ - - - ]}) do - cross_origin - # the guts live here - - {"message" => "yes, it worked"}.to_json -end - - -MyApp.add_route('POST', '/v2/store/order', { - "resourcePath" => "/Store", - "summary" => "Place an order for a pet", - "nickname" => "place_order", - "responseClass" => "Order", - "endpoint" => "/store/order", - "notes" => "", - "parameters" => [ - - - - { - "name" => "body", - "description" => "order placed for purchasing the pet", - "dataType" => "Order", - "paramType" => "body", - } + "name" => "order_id", + "description" => "ID of the order that needs to be deleted", + "dataType" => "string", + "paramType" => "path", + }, + + ]}) do cross_origin @@ -48,12 +28,12 @@ MyApp.add_route('POST', '/v2/store/order', { end -MyApp.add_route('GET', '/v2/store/order/{orderId}', { +MyApp.add_route('GET', '/v2/stores/order/{orderId}', { "resourcePath" => "/Store", "summary" => "Find purchase order by ID", "nickname" => "get_order_by_id", "responseClass" => "Order", - "endpoint" => "/store/order/{orderId}", + "endpoint" => "/stores/order/{orderId}", "notes" => "For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions", "parameters" => [ @@ -75,24 +55,24 @@ MyApp.add_route('GET', '/v2/store/order/{orderId}', { end -MyApp.add_route('DELETE', '/v2/store/order/{orderId}', { +MyApp.add_route('POST', '/v2/stores/order', { "resourcePath" => "/Store", - "summary" => "Delete purchase order by ID", - "nickname" => "delete_order", - "responseClass" => "void", - "endpoint" => "/store/order/{orderId}", - "notes" => "For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors", + "summary" => "Place an order for a pet", + "nickname" => "place_order", + "responseClass" => "Order", + "endpoint" => "/stores/order", + "notes" => "", "parameters" => [ + + { - "name" => "order_id", - "description" => "ID of the order that needs to be deleted", - "dataType" => "string", - "paramType" => "path", - }, - - + "name" => "body", + "description" => "order placed for purchasing the pet", + "dataType" => "Order", + "paramType" => "body", + } ]}) do cross_origin diff --git a/samples/server/petstore/sinatra/api/user_api.rb b/samples/server/petstore/sinatra/api/user_api.rb index 7b890004891..aaa76430310 100644 --- a/samples/server/petstore/sinatra/api/user_api.rb +++ b/samples/server/petstore/sinatra/api/user_api.rb @@ -1,12 +1,12 @@ require 'json' -MyApp.add_route('POST', '/v2/user', { +MyApp.add_route('POST', '/v2/users', { "resourcePath" => "/User", "summary" => "Create user", "nickname" => "create_user", "responseClass" => "void", - "endpoint" => "/user", + "endpoint" => "/users", "notes" => "This can only be done by the logged in user.", "parameters" => [ @@ -28,12 +28,12 @@ MyApp.add_route('POST', '/v2/user', { end -MyApp.add_route('POST', '/v2/user/createWithArray', { +MyApp.add_route('POST', '/v2/users/createWithArray', { "resourcePath" => "/User", "summary" => "Creates list of users with given input array", "nickname" => "create_users_with_array_input", "responseClass" => "void", - "endpoint" => "/user/createWithArray", + "endpoint" => "/users/createWithArray", "notes" => "", "parameters" => [ @@ -55,12 +55,12 @@ MyApp.add_route('POST', '/v2/user/createWithArray', { end -MyApp.add_route('POST', '/v2/user/createWithList', { +MyApp.add_route('POST', '/v2/users/createWithList', { "resourcePath" => "/User", "summary" => "Creates list of users with given input array", "nickname" => "create_users_with_list_input", "responseClass" => "void", - "endpoint" => "/user/createWithList", + "endpoint" => "/users/createWithList", "notes" => "", "parameters" => [ @@ -82,12 +82,66 @@ MyApp.add_route('POST', '/v2/user/createWithList', { end -MyApp.add_route('GET', '/v2/user/login', { +MyApp.add_route('DELETE', '/v2/users/{username}', { + "resourcePath" => "/User", + "summary" => "Delete user", + "nickname" => "delete_user", + "responseClass" => "void", + "endpoint" => "/users/{username}", + "notes" => "This can only be done by the logged in user.", + "parameters" => [ + + + { + "name" => "username", + "description" => "The name that needs to be deleted", + "dataType" => "string", + "paramType" => "path", + }, + + + + ]}) do + cross_origin + # the guts live here + + {"message" => "yes, it worked"}.to_json +end + + +MyApp.add_route('GET', '/v2/users/{username}', { + "resourcePath" => "/User", + "summary" => "Get user by user name", + "nickname" => "get_user_by_name", + "responseClass" => "User", + "endpoint" => "/users/{username}", + "notes" => "", + "parameters" => [ + + + { + "name" => "username", + "description" => "The name that needs to be fetched. Use user1 for testing.", + "dataType" => "string", + "paramType" => "path", + }, + + + + ]}) do + cross_origin + # the guts live here + + {"message" => "yes, it worked"}.to_json +end + + +MyApp.add_route('GET', '/v2/users/login', { "resourcePath" => "/User", "summary" => "Logs user into the system", "nickname" => "login_user", "responseClass" => "string", - "endpoint" => "/user/login", + "endpoint" => "/users/login", "notes" => "", "parameters" => [ @@ -122,12 +176,12 @@ MyApp.add_route('GET', '/v2/user/login', { end -MyApp.add_route('GET', '/v2/user/logout', { +MyApp.add_route('GET', '/v2/users/logout', { "resourcePath" => "/User", "summary" => "Logs out current logged in user session", "nickname" => "logout_user", "responseClass" => "void", - "endpoint" => "/user/logout", + "endpoint" => "/users/logout", "notes" => "", "parameters" => [ @@ -142,39 +196,12 @@ MyApp.add_route('GET', '/v2/user/logout', { end -MyApp.add_route('GET', '/v2/user/{username}', { - "resourcePath" => "/User", - "summary" => "Get user by user name", - "nickname" => "get_user_by_name", - "responseClass" => "User", - "endpoint" => "/user/{username}", - "notes" => "", - "parameters" => [ - - - { - "name" => "username", - "description" => "The name that needs to be fetched. Use user1 for testing.", - "dataType" => "string", - "paramType" => "path", - }, - - - - ]}) do - cross_origin - # the guts live here - - {"message" => "yes, it worked"}.to_json -end - - -MyApp.add_route('PUT', '/v2/user/{username}', { +MyApp.add_route('PUT', '/v2/users/{username}', { "resourcePath" => "/User", "summary" => "Updated user", "nickname" => "update_user", "responseClass" => "void", - "endpoint" => "/user/{username}", + "endpoint" => "/users/{username}", "notes" => "This can only be done by the logged in user.", "parameters" => [ @@ -202,30 +229,3 @@ MyApp.add_route('PUT', '/v2/user/{username}', { {"message" => "yes, it worked"}.to_json end - -MyApp.add_route('DELETE', '/v2/user/{username}', { - "resourcePath" => "/User", - "summary" => "Delete user", - "nickname" => "delete_user", - "responseClass" => "void", - "endpoint" => "/user/{username}", - "notes" => "This can only be done by the logged in user.", - "parameters" => [ - - - { - "name" => "username", - "description" => "The name that needs to be deleted", - "dataType" => "string", - "paramType" => "path", - }, - - - - ]}) do - cross_origin - # the guts live here - - {"message" => "yes, it worked"}.to_json -end - diff --git a/samples/server/petstore/sinatra/lib/swaggering.rb b/samples/server/petstore/sinatra/lib/swaggering.rb index 1357bb19134..69cc74556ac 100644 --- a/samples/server/petstore/sinatra/lib/swaggering.rb +++ b/samples/server/petstore/sinatra/lib/swaggering.rb @@ -39,7 +39,7 @@ class Swaggering < Sinatra::Base def self.add_route(method, path, swag={}, opts={}, &block) #fullPath = swag["resourcePath"].to_s + @@configuration.format_specifier + path - fullPath = path.gsub(/{(.*)}/, ':\1') + fullPath = path.gsub(/{(.*?)}/, ':\1') accepted = case method.to_s.downcase when 'get' diff --git a/samples/server/petstore/sinatra/swagger.yaml b/samples/server/petstore/sinatra/swagger.yaml index 49a3405de09..4aa26a9539c 100644 --- a/samples/server/petstore/sinatra/swagger.yaml +++ b/samples/server/petstore/sinatra/swagger.yaml @@ -1,15 +1,14 @@ --- swagger: "2.0" info: - description: "This is a sample server Petstore server. You can find out more about\ - \ Swagger at http://swagger.io or on irc.freenode.net,\ - \ #swagger. For this sample, you can use the api key \"special-key\" to test\ - \ the authorization filters" + description: "This is a sample server Petstore server.\n\n[Learn about Swagger](http://swagger.io)\ + \ or join the IRC channel `#swagger` on irc.freenode.net.\n\nFor this sample,\ + \ you can use the api key `special-key` to test the authorization filters\n" version: "1.0.0" title: "Swagger Petstore" - termsOfService: "http://swagger.io/terms/" + termsOfService: "http://helloreverb.com/terms/" contact: - email: "apiteam@swagger.io" + name: "apiteam@swagger.io" license: name: "Apache 2.0" url: "http://www.apache.org/licenses/LICENSE-2.0.html" @@ -18,7 +17,7 @@ basePath: "/v2" schemes: - "http" paths: - /pet: + /pets: post: tags: - "pet" @@ -43,8 +42,8 @@ paths: description: "Invalid input" security: - petstore_auth: - - "write:pets" - - "read:pets" + - "write_pets" + - "read_pets" put: tags: - "pet" @@ -73,9 +72,9 @@ paths: description: "Validation exception" security: - petstore_auth: - - "write:pets" - - "read:pets" - /pet/findByStatus: + - "write_pets" + - "read_pets" + /pets/findByStatus: get: tags: - "pet" @@ -94,7 +93,6 @@ paths: items: type: "string" collectionFormat: "multi" - default: "available" responses: 200: description: "successful operation" @@ -106,9 +104,9 @@ paths: description: "Invalid status value" security: - petstore_auth: - - "write:pets" - - "read:pets" - /pet/findByTags: + - "write_pets" + - "read_pets" + /pets/findByTags: get: tags: - "pet" @@ -139,9 +137,9 @@ paths: description: "Invalid tag value" security: - petstore_auth: - - "write:pets" - - "read:pets" - /pet/{petId}: + - "write_pets" + - "read_pets" + /pets/{petId}: get: tags: - "pet" @@ -171,8 +169,8 @@ paths: security: - api_key: [] - petstore_auth: - - "write:pets" - - "read:pets" + - "write_pets" + - "read_pets" post: tags: - "pet" @@ -193,20 +191,20 @@ paths: - name: "name" in: "formData" description: "Updated name of the pet" - required: false + required: true type: "string" - name: "status" in: "formData" description: "Updated status of the pet" - required: false + required: true type: "string" responses: 405: description: "Invalid input" security: - petstore_auth: - - "write:pets" - - "read:pets" + - "write_pets" + - "read_pets" delete: tags: - "pet" @@ -220,7 +218,7 @@ paths: - name: "api_key" in: "header" description: "" - required: false + required: true type: "string" - name: "petId" in: "path" @@ -233,66 +231,9 @@ paths: description: "Invalid pet value" security: - petstore_auth: - - "write:pets" - - "read:pets" - /pet/{petId}/uploadImage: - post: - tags: - - "pet" - summary: "uploads an image" - description: "" - operationId: "uploadFile" - consumes: - - "multipart/form-data" - produces: - - "application/json" - - "application/xml" - parameters: - - name: "petId" - in: "path" - description: "ID of pet to update" - required: true - type: "integer" - format: "int64" - - name: "additionalMetadata" - in: "formData" - description: "Additional data to pass to server" - required: false - type: "string" - - name: "file" - in: "formData" - description: "file to upload" - required: false - type: "file" - responses: - default: - description: "successful operation" - security: - - petstore_auth: - - "write:pets" - - "read:pets" - /store/inventory: - get: - tags: - - "store" - summary: "Returns pet inventories by status" - description: "Returns a map of status codes to quantities" - operationId: "getInventory" - produces: - - "application/json" - - "application/xml" - parameters: [] - responses: - 200: - description: "successful operation" - schema: - type: "object" - additionalProperties: - type: "integer" - format: "int32" - security: - - api_key: [] - /store/order: + - "write_pets" + - "read_pets" + /stores/order: post: tags: - "store" @@ -316,7 +257,7 @@ paths: $ref: "#/definitions/Order" 400: description: "Invalid Order" - /store/order/{orderId}: + /stores/order/{orderId}: get: tags: - "store" @@ -363,7 +304,7 @@ paths: description: "Invalid ID supplied" 404: description: "Order not found" - /user: + /users: post: tags: - "user" @@ -383,7 +324,7 @@ paths: responses: default: description: "successful operation" - /user/createWithArray: + /users/createWithArray: post: tags: - "user" @@ -405,7 +346,7 @@ paths: responses: default: description: "successful operation" - /user/createWithList: + /users/createWithList: post: tags: - "user" @@ -427,7 +368,7 @@ paths: responses: default: description: "successful operation" - /user/login: + /users/login: get: tags: - "user" @@ -455,7 +396,7 @@ paths: type: "string" 400: description: "Invalid username/password supplied" - /user/logout: + /users/logout: get: tags: - "user" @@ -469,7 +410,7 @@ paths: responses: default: description: "successful operation" - /user/{username}: + /users/{username}: get: tags: - "user" @@ -482,7 +423,7 @@ paths: parameters: - name: "username" in: "path" - description: "The name that needs to be fetched. Use user1 for testing. " + description: "The name that needs to be fetched. Use user1 for testing." required: true type: "string" responses: @@ -490,16 +431,6 @@ paths: description: "successful operation" schema: $ref: "#/definitions/User" - examples: - application/json: - id: 1 - username: "johnp" - firstName: "John" - lastName: "Public" - email: "johnp@swagger.io" - password: "-secret-" - phone: "0123456789" - userStatus: 0 400: description: "Invalid username supplied" 404: @@ -560,10 +491,11 @@ securityDefinitions: authorizationUrl: "http://petstore.swagger.io/api/oauth/dialog" flow: "implicit" scopes: - write:pets: "modify pets in your account" - read:pets: "read your pets" + write_pets: "modify pets in your account" + read_pets: "read your pets" definitions: User: + type: "object" properties: id: type: "integer" @@ -584,18 +516,16 @@ definitions: type: "integer" format: "int32" description: "User Status" - xml: - name: "User" Category: + type: "object" properties: id: type: "integer" format: "int64" name: type: "string" - xml: - name: "Category" Pet: + type: "object" required: - "name" - "photoUrls" @@ -610,37 +540,25 @@ definitions: example: "doggie" photoUrls: type: "array" - xml: - name: "photoUrl" - wrapped: true items: type: "string" tags: type: "array" - xml: - name: "tag" - wrapped: true items: $ref: "#/definitions/Tag" status: type: "string" description: "pet status in the store" - enum: - - "available" - - "pending" - - "sold" - xml: - name: "Pet" Tag: + type: "object" properties: id: type: "integer" format: "int64" name: type: "string" - xml: - name: "Tag" Order: + type: "object" properties: id: type: "integer" @@ -657,11 +575,5 @@ definitions: status: type: "string" description: "Order Status" - enum: - - "placed" - - "approved" - - "delivered" complete: type: "boolean" - xml: - name: "Order"