diff --git a/.gitignore b/.gitignore index d55a8014a34..db34c76636c 100644 --- a/.gitignore +++ b/.gitignore @@ -13,6 +13,7 @@ generated-sources/* generated-code/* *.swp *.swo +*.csproj.user /target /generated-files @@ -36,6 +37,9 @@ 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 @@ -60,4 +64,4 @@ samples/client/petstore/python/.venv/ *.java~ *.pm~ *.xml~ -*.t~ \ No newline at end of file +*.t~ diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 00000000000..4bef580bb26 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,62 @@ +# Guidelines For Contributing + +## Before submitting an issue + + - Before submitting an issue, search the [open issue](https://github.com/swagger-api/swagger-codegen/issues) and [closed issue](https://github.com/swagger-api/swagger-codegen/issues?q=is%3Aissue+is%3Aclosed) to ensure no one else has reported something similar before. + - The issue should contain details on how to repeat the issue, e.g. + - the Swagger spec for reproducing the issue (:bulb: use [Gist](https://gist.github.com) to share). If the Swagger spec cannot be shared publicly, it will be hard for the community to help + - version of Swagger Codegen + - language (`-l` in the command line, e.g. java, csharp, php) + - You can also make a suggestion or ask a question by opening an "issue" + +## Before submitting a PR + + - Search the [open issue](https://github.com/swagger-api/swagger-codegen/issues) to ensure no one else has reported something similar and no one is actively working on similar proposed change. + - If no one has suggested something similar, open an ["issue"](https://github.com/swagger-api/swagger-codegen/issues) with your suggestion to gather feedback from the community. + +## How to contribute + +### Code generators + +All the code generators can be found in [modules/swagger-codegen/src/main/java/io/swagger/codegen/languages](https://github.com/swagger-api/swagger-codegen/tree/master/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages) + +### Templates + +All the templates ([mustache](https://mustache.github.io/)) can be found in [modules/swagger-codegen/src/main/resources](https://github.com/swagger-api/swagger-codegen/tree/master/modules/swagger-codegen/src/main/resources). + +For a list of variables available in the template, please refer to this [page](https://github.com/swagger-api/swagger-codegen/wiki/Mustache-Template-Variables) + + +### Style guide +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 +- ObjC: https://github.com/NYTimes/objective-c-style-guide +- 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 +- TypeScript: https://github.com/Microsoft/TypeScript/wiki/Coding-guidelines + + +For other languages, feel free to suggest. + +You may find the current code base not 100% conform to the coding style and we welcome contributions to fix those. + +### Testing + +To add test cases (optional) covering the change in the code generator, please refer to [modules/swagger-codegen/src/test/java/io/swagger/codegen](https://github.com/swagger-api/swagger-codegen/tree/master/modules/swagger-codegen/src/test/java/io/swagger/codegen) + +To test the templates, please perform the following: +- Update the [Petstore](http://petstore.swagger.io/) sample by running the shell script under `bin` folder. For example, run `./bin/ruby-petstore.sh` to update the Ruby PetStore API client under [`samples/client/petstore/ruby`](https://github.com/swagger-api/swagger-codegen/tree/master/samples/client/petstore/ruby) (For Windows, the batch files can be found under `bin\windows` folder) +- Run the tests in the sample folder, e.g. in `samples/client/petstore/ruby`, run `mvn integration-test -rf :RubyPetstoreClientTests`. (some languages may not contain unit testing for Petstore and we're looking for contribution from the community to implement those tests) +- Finally, git commit the updated samples files: `git commit -a` + (`git add -A` if added files with new test cases) + +To start the CI tests, you can run `mvn verify -Psamples` (assuming you've all the required tools installed to run tests for different languages) or you can leverage http://travis-ci.org to run the CI tests by adding your own Swagger-Codegen repository. + +### Tips +- Smaller changes are easier to review +- [Optional] For bug fixes, provide a Swagger spec to repeat the issue so that the reviewer can use it to confirm the fix +- Add test case(s) to cover the change +- Document the fix in the code to make the code more readable +- Make sure test cases passed after the change (one way is to leverage https://travis-ci.org/ to run the CI tests) diff --git a/README.md b/README.md index ef321e4bb59..3f1691144b9 100644 --- a/README.md +++ b/README.md @@ -3,6 +3,8 @@ [![Build Status](https://travis-ci.org/swagger-api/swagger-codegen.png)](https://travis-ci.org/swagger-api/swagger-codegen) [![Maven Central](https://maven-badges.herokuapp.com/maven-central/io.swagger/swagger-codegen-project/badge.svg?style=plastic)](https://maven-badges.herokuapp.com/maven-central/io.swagger/swagger-codegen-project) +:star::star::star: If you would like to contribute, please refer to [guidelines](https://github.com/swagger-api/swagger-codegen/blob/master/CONTRIBUTING.md) and a list of [open tasks](https://github.com/swagger-api/swagger-codegen/issues?q=is%3Aopen+is%3Aissue+label%3A%22Need+community+contribution%22).:star::star::star: + ## Overview This is the swagger codegen project, which allows generation of client libraries automatically from a Swagger-compliant server. @@ -117,6 +119,8 @@ You can build a client against the swagger sample [petstore](http://petstore.swa ./bin/java-petstore.sh ``` +(On Windows, run `./bin/windows/java-petstore.bat` instead) + This will run the generator with this command: ``` @@ -212,11 +216,28 @@ java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar meta \ This will write, in the folder `output/myLibrary`, all the files you need to get started, including a README.md. Once modified and compiled, you can load your library with the codegen and generate clients with your own, custom-rolled logic. +You would then compile your library in the `output/myLibrary` folder with `mvn package` and execute the codegen like such: + + +``` +java -cp output/myLibrary/target/myClientCodegen-swagger-codegen-1.0.0.jar:modules/swagger-codegen-cli/target/swagger-codegen-cli.jar io.swagger.codegen.Codegen +``` + +Note the `myClientCodegen` is an option now, and you can use the usual arguments for generating your library: + +``` +java -cp output/myLibrary/target/myClientCodegen-swagger-codegen-1.0.0.jar:modules/swagger-codegen-cli/target/swagger-codegen-cli.jar \ + io.swagger.codegen.Codegen generate -l myClientCodegen\ + -i http://petstore.swagger.io/v2/swagger.json \ + -o myClient +``` + ### Where is Javascript??? See our [javascript library](http://github.com/swagger-api/swagger-js)--it's completely dynamic and doesn't require static code generation. There is a third-party component called [swagger-js-codegen](https://github.com/wcandillon/swagger-js-codegen) that can generate angularjs or nodejs source code from a swagger specification. +:exclamation: On Dec 7th 2015, a Javascript API client generator has been added by @jfiala. ### Generating a client from local files If you don't want to call your server, you can save the swagger spec files into a directory and pass an argument @@ -276,7 +297,9 @@ FlashClientCodegen.java FlaskConnexionCodegen.java JavaClientCodegen.java JavaInflectorServerCodegen.java +JavascriptClientCodegen.java JaxRSServerCodegen.java +JMeterCodegen.java NodeJSServerCodegen.java ObjcClientCodegen.java PerlClientCodegen.java @@ -288,6 +311,7 @@ ScalaClientCodegen.java ScalatraServerCodegen.java SilexServerCodegen.java SinatraServerCodegen.java +SlimFrameworkServerCodegen.java SpringMVCServerCodegen.java StaticDocCodegen.java StaticHtmlGenerator.java @@ -353,9 +377,10 @@ CONFIG OPTIONS library template (sub-template) to use: - HTTP client: Jersey client 1.18. JSON processing: Jackson 2.4.2 jersey2 - HTTP client: Jersey client 2.6 + feign - HTTP client: Netflix Feign 8.1.1. JSON processing: Jackson 2.6.3 okhttp-gson - HTTP client: OkHttp 2.4.0. JSON processing: Gson 2.3.1 retrofit - HTTP client: OkHttp 2.4.0. JSON processing: Gson 2.3.1 (Retrofit 1.9.0) - retrofit2 - HTTP client: OkHttp 2.5.0. JSON processing: Gson 2.4 (Retrofit 2.0.0-beta2) + retrofit2 - HTTP client: OkHttp 2.5.0. JSON processing: Gson 2.4 (Retrofit 2.0.0-beta2) ``` Your config file for java can look like @@ -364,7 +389,8 @@ Your config file for java can look like { "groupId":"com.my.company", "artifactId":"MyClent", - "artifactVersion":"1.2.0" + "artifactVersion":"1.2.0", + "library":"feign" } ``` @@ -511,7 +537,7 @@ Then you will receieve a JSON response with the URL to download the zipped code. Guidelines for Contribution --------------------------- -Please refer to this [page](https://github.com/swagger-api/swagger-codegen/wiki/Guidelines-for-Contribution) +Please refer to this [page](https://github.com/swagger-api/swagger-codegen/blob/master/CONTRIBUTING.md) License ------- diff --git a/bin/all-petstore.sh b/bin/all-petstore.sh index a439d015337..f6156dbcee9 100755 --- a/bin/all-petstore.sh +++ b/bin/all-petstore.sh @@ -41,6 +41,7 @@ cd $APP_DIR ./bin/scala-petstore.sh ./bin/scalatra-petstore-server.sh ./bin/silex-petstore-server.sh +./bin/slim-petstore-server.sh ./bin/spring-mvc-petstore-server.sh ./bin/swift-petstore.sh ./bin/tizen-petstore.sh diff --git a/bin/flaskConnexion.sh b/bin/flaskConnexion.sh index f300d3124b1..1745d2a3ba2 100755 --- a/bin/flaskConnexion.sh +++ b/bin/flaskConnexion.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 flaskConnexion -o samples/server/petstore/flaskConnexion " +ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l python-flask -o samples/server/petstore/flaskConnexion " java $JAVA_OPTS -Dservice -jar $executable $ags diff --git a/bin/java-petstore-feign.json b/bin/java-petstore-feign.json new file mode 100644 index 00000000000..5502ee3bbad --- /dev/null +++ b/bin/java-petstore-feign.json @@ -0,0 +1,4 @@ +{ + "library": "feign", + "artifactId": "swagger-petstore-feign" +} diff --git a/bin/java-petstore-feign.sh b/bin/java-petstore-feign.sh new file mode 100755 index 00000000000..6f0a5fdf8ff --- /dev/null +++ b/bin/java-petstore-feign.sh @@ -0,0 +1,31 @@ +#!/bin/sh + +SCRIPT="$0" + +while [ -h "$SCRIPT" ] ; do + ls=`ls -ld "$SCRIPT"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + SCRIPT="$link" + else + SCRIPT=`dirname "$SCRIPT"`/"$link" + fi +done + +if [ ! -d "${APP_DIR}" ]; then + APP_DIR=`dirname "$SCRIPT"`/.. + APP_DIR=`cd "${APP_DIR}"; pwd` +fi + +executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar" + +if [ ! -f "$executable" ] +then + mvn clean package +fi + +# if you've executed sbt assembly previously it will use that instead. +export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" +ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l java -c bin/java-petstore-feign.json -o samples/client/petstore/java/feign" + +java $JAVA_OPTS -jar $executable $ags diff --git a/bin/javascript-petstore.sh b/bin/javascript-petstore.sh new file mode 100755 index 00000000000..9bf3ae70898 --- /dev/null +++ b/bin/javascript-petstore.sh @@ -0,0 +1,31 @@ +#!/bin/sh + +SCRIPT="$0" + +while [ -h "$SCRIPT" ] ; do + ls=`ls -ld "$SCRIPT"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + SCRIPT="$link" + else + SCRIPT=`dirname "$SCRIPT"`/"$link" + fi +done + +if [ ! -d "${APP_DIR}" ]; then + APP_DIR=`dirname "$SCRIPT"`/.. + APP_DIR=`cd "${APP_DIR}"; pwd` +fi + +executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar" + +if [ ! -f "$executable" ] +then + mvn clean package +fi + +# if you've executed sbt assembly previously it will use that instead. +export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" +ags="$@ generate -t modules/swagger-codegen/src/main/resources/javascript -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l javascript -o samples/client/petstore/javascript" + +java -DappName=PetstoreClient $JAVA_OPTS -jar $executable $ags diff --git a/bin/slim-petstore-server.sh b/bin/slim-petstore-server.sh new file mode 100644 index 00000000000..654fc1d0e01 --- /dev/null +++ b/bin/slim-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/slim -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l slim -o samples/server/petstore/slim" + +java $JAVA_OPTS -jar $executable $ags diff --git a/bin/windows/akka-scala-petstore.bat b/bin/windows/akka-scala-petstore.bat new file mode 100755 index 00000000000..ecd7433d2e2 --- /dev/null +++ b/bin/windows/akka-scala-petstore.bat @@ -0,0 +1,10 @@ +set executable=.\modules\swagger-codegen-cli\target\swagger-codegen-cli.jar + +If Not Exist %executable% ( + mvn clean package +) + +set JAVA_OPTS=%JAVA_OPTS% -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties +set ags=generate -t modules\swagger-codegen\src\main\resources\akka-scala -i modules\swagger-codegen\src\test\resources\2_0\petstore.json -l akka-scala -o samples\client\petstore\akka-scala + +java %JAVA_OPTS% -jar %executable% %ags% diff --git a/bin/windows/android-java-petstore.bat b/bin/windows/android-java-petstore.bat new file mode 100755 index 00000000000..73997ee789a --- /dev/null +++ b/bin/windows/android-java-petstore.bat @@ -0,0 +1,10 @@ +set executable=.\modules\swagger-codegen-cli\target\swagger-codegen-cli.jar + +If Not Exist %executable% ( + mvn clean package +) + +set JAVA_OPTS=%JAVA_OPTS% -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties +set ags=generate -t modules\swagger-codegen\src\main\resources\android-java -i modules\swagger-codegen\src\test\resources\2_0\petstore.json -l android -o samples\client\petstore\android-java + +java %JAVA_OPTS% -jar %executable% %ags% diff --git a/bin/windows/async-scala-petstore.sh b/bin/windows/async-scala-petstore.sh new file mode 100755 index 00000000000..d2b772b91b8 --- /dev/null +++ b/bin/windows/async-scala-petstore.sh @@ -0,0 +1,10 @@ +set executable=.\modules\swagger-codegen-cli\target\swagger-codegen-cli.jar + +If Not Exist %executable% ( + mvn clean package +) + +set JAVA_OPTS=%JAVA_OPTS% -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties +set ags=generate -t modules\swagger-codegen\src\main\resources\asyncscala -i modules\swagger-codegen\src\test\resources\2_0\petstore.json -l async-scala -o samples\client\petstore\async-scala + +java %JAVA_OPTS% -jar %executable% %ags% diff --git a/bin/windows/clojure-petstore.bat b/bin/windows/clojure-petstore.bat new file mode 100755 index 00000000000..bfbb6663d11 --- /dev/null +++ b/bin/windows/clojure-petstore.bat @@ -0,0 +1,10 @@ +set executable=.\modules\swagger-codegen-cli\target\swagger-codegen-cli.jar + +If Not Exist %executable% ( + mvn clean package +) + +set JAVA_OPTS=%JAVA_OPTS% -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties +set ags=generate -t modules\swagger-codegen\src\main\resources\clojure -i modules\swagger-codegen\src\test\resources\2_0\petstore.json -l clojure -o samples\client\petstore\clojure + +java %JAVA_OPTS% -jar %executable% %ags% diff --git a/bin/windows/csharp-petstore.bat b/bin/windows/csharp-petstore.bat new file mode 100755 index 00000000000..227ed319441 --- /dev/null +++ b/bin/windows/csharp-petstore.bat @@ -0,0 +1,10 @@ +set executable=.\modules\swagger-codegen-cli\target\swagger-codegen-cli.jar + +If Not Exist %executable% ( + mvn clean package +) + +set JAVA_OPTS=%JAVA_OPTS% -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties +set ags=generate -t modules\swagger-codegen\src\main\resources\csharp -i modules\swagger-codegen\src\test\resources\2_0\petstore.json -l csharp -o samples\client\petstore\csharp\SwaggerClientTest\Lib\SwaggerClient + +java %JAVA_OPTS% -jar %executable% %ags% diff --git a/bin/windows/dart-petstore.bat b/bin/windows/dart-petstore.bat new file mode 100755 index 00000000000..bbf77fed2cc --- /dev/null +++ b/bin/windows/dart-petstore.bat @@ -0,0 +1,10 @@ +set executable=.\modules\swagger-codegen-cli\target\swagger-codegen-cli.jar + +If Not Exist %executable% ( + mvn clean package +) + +set JAVA_OPTS=%JAVA_OPTS% -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties +set ags=generate -t modules\swagger-codegen\src\main\resources\dart -i modules\swagger-codegen\src\test\resources\2_0\petstore.json -l dart -o samples\client\petstore\dart + +java %JAVA_OPTS% -jar %executable% %ags% diff --git a/bin/windows/dynamic-html-petstore.bat b/bin/windows/dynamic-html-petstore.bat new file mode 100755 index 00000000000..27595a54a16 --- /dev/null +++ b/bin/windows/dynamic-html-petstore.bat @@ -0,0 +1,10 @@ +set executable=.\modules\swagger-codegen-cli\target\swagger-codegen-cli.jar + +If Not Exist %executable% ( + mvn clean package +) + +set JAVA_OPTS=%JAVA_OPTS% -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties +set ags=generate -t modules\swagger-codegen\src\main\resources\dynamic-html -i modules\swagger-codegen\src\test\resources\2_0\petstore.json -l dynamic-html -o samples\client\petstore\dynamic-html + +java %JAVA_OPTS% -jar %executable% %ags% diff --git a/bin/windows/flash-petstore.bat b/bin/windows/flash-petstore.bat new file mode 100755 index 00000000000..9e4445b77ea --- /dev/null +++ b/bin/windows/flash-petstore.bat @@ -0,0 +1,10 @@ +set executable=.\modules\swagger-codegen-cli\target\swagger-codegen-cli.jar + +If Not Exist %executable% ( + mvn clean package +) + +set JAVA_OPTS=%JAVA_OPTS% -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties +set ags=generate -t modules\swagger-codegen\src\main\resources\flash -i modules\swagger-codegen\src\test\resources\2_0\petstore.json -l flash -o samples\client\petstore\flash + +java %JAVA_OPTS% -jar %executable% %ags% diff --git a/bin/windows/html-petstore.bat b/bin/windows/html-petstore.bat new file mode 100755 index 00000000000..82cc490027a --- /dev/null +++ b/bin/windows/html-petstore.bat @@ -0,0 +1,10 @@ +set executable=.\modules\swagger-codegen-cli\target\swagger-codegen-cli.jar + +If Not Exist %executable% ( + mvn clean package +) + +set JAVA_OPTS=%JAVA_OPTS% -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties +set ags=generate -t modules\swagger-codegen\src\main\resources\html -i modules\swagger-codegen\src\test\resources\2_0\petstore.json -l html -o samples\client\petstore\html + +java %JAVA_OPTS% -jar %executable% %ags% diff --git a/bin/windows/java-petstore.bat b/bin/windows/java-petstore.bat new file mode 100755 index 00000000000..18544cbad36 --- /dev/null +++ b/bin/windows/java-petstore.bat @@ -0,0 +1,10 @@ +set executable=.\modules\swagger-codegen-cli\target\swagger-codegen-cli.jar + +If Not Exist %executable% ( + mvn clean package +) + +set JAVA_OPTS=%JAVA_OPTS% -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties +set ags=generate -t modules\swagger-codegen\src\main\resources\java -i modules\swagger-codegen\src\test\resources\2_0\petstore.json -l java -o samples\client\petstore\java + +java %JAVA_OPTS% -jar %executable% %ags% diff --git a/bin/windows/javascript-petstore.bat b/bin/windows/javascript-petstore.bat new file mode 100755 index 00000000000..6ee220a7062 --- /dev/null +++ b/bin/windows/javascript-petstore.bat @@ -0,0 +1,10 @@ +set executable=.\modules\swagger-codegen-cli\target\swagger-codegen-cli.jar + +If Not Exist %executable% ( + mvn clean package +) + +set JAVA_OPTS=%JAVA_OPTS% -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties +set ags=generate -t modules\swagger-codegen\src\main\resources\javascript -i modules\swagger-codegen\src\test\resources\2_0\petstore.json -l javascript -o samples\client\petstore\javascript + +java %JAVA_OPTS% -jar %executable% %ags% diff --git a/bin/windows/objc-petstore.bat b/bin/windows/objc-petstore.bat new file mode 100755 index 00000000000..a26b0dad566 --- /dev/null +++ b/bin/windows/objc-petstore.bat @@ -0,0 +1,10 @@ +set executable=.\modules\swagger-codegen-cli\target\swagger-codegen-cli.jar + +If Not Exist %executable% ( + mvn clean package +) + +set JAVA_OPTS=%JAVA_OPTS% -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties +set ags=generate -t modules\swagger-codegen\src\main\resources\objc -i modules\swagger-codegen\src\test\resources\2_0\petstore.json -l objc -o samples\client\petstore\objc + +java %JAVA_OPTS% -DappName=PetstoreClient -jar %executable% %ags% diff --git a/bin/windows/perl-petstore.bat b/bin/windows/perl-petstore.bat new file mode 100755 index 00000000000..da526e40dd7 --- /dev/null +++ b/bin/windows/perl-petstore.bat @@ -0,0 +1,10 @@ +set executable=.\modules\swagger-codegen-cli\target\swagger-codegen-cli.jar + +If Not Exist %executable% ( + mvn clean package +) + +set JAVA_OPTS=%JAVA_OPTS% -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties +set ags=generate -t modules\swagger-codegen\src\main\resources\perl -i modules\swagger-codegen\src\test\resources\2_0\petstore.json -l perl -o samples\client\petstore\perl + +java %JAVA_OPTS% -jar %executable% %ags% diff --git a/bin/windows/php-petstore.bat b/bin/windows/php-petstore.bat new file mode 100755 index 00000000000..cc10b72a609 --- /dev/null +++ b/bin/windows/php-petstore.bat @@ -0,0 +1,10 @@ +set executable=.\modules\swagger-codegen-cli\target\swagger-codegen-cli.jar + +If Not Exist %executable% ( + mvn clean package +) + +set JAVA_OPTS=%JAVA_OPTS% -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties +set ags=generate -t modules\swagger-codegen\src\main\resources\php -i modules\swagger-codegen\src\test\resources\2_0\petstore.json -l php -o samples\client\petstore\php + +java %JAVA_OPTS% -jar %executable% %ags% diff --git a/bin/windows/python-petstore.bat b/bin/windows/python-petstore.bat new file mode 100755 index 00000000000..2762cf15b81 --- /dev/null +++ b/bin/windows/python-petstore.bat @@ -0,0 +1,10 @@ +set executable=.\modules\swagger-codegen-cli\target\swagger-codegen-cli.jar + +If Not Exist %executable% ( + mvn clean package +) + +set JAVA_OPTS=%JAVA_OPTS% -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties +set ags=generate -t modules\swagger-codegen\src\main\resources\python -i modules\swagger-codegen\src\test\resources\2_0\petstore.json -l python -o samples\client\petstore\python + +java %JAVA_OPTS% -jar %executable% %ags% diff --git a/bin/windows/qt5cpp-petstore.bat b/bin/windows/qt5cpp-petstore.bat new file mode 100755 index 00000000000..3c5b849a3f1 --- /dev/null +++ b/bin/windows/qt5cpp-petstore.bat @@ -0,0 +1,10 @@ +set executable=.\modules\swagger-codegen-cli\target\swagger-codegen-cli.jar + +If Not Exist %executable% ( + mvn clean package +) + +set JAVA_OPTS=%JAVA_OPTS% -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties +set ags=generate -t modules\swagger-codegen\src\main\resources\qt5cpp -i modules\swagger-codegen\src\test\resources\2_0\petstore.json -l qt5cpp -o samples\client\petstore\qt5cpp + +java %JAVA_OPTS% -jar %executable% %ags% diff --git a/bin/windows/ruby-petstore.bat b/bin/windows/ruby-petstore.bat new file mode 100755 index 00000000000..3642a6e19ba --- /dev/null +++ b/bin/windows/ruby-petstore.bat @@ -0,0 +1,10 @@ +set executable=.\modules\swagger-codegen-cli\target\swagger-codegen-cli.jar + +If Not Exist %executable% ( + mvn clean package +) + +set JAVA_OPTS=%JAVA_OPTS% -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties +set ags=generate -t modules\swagger-codegen\src\main\resources\ruby -i modules\swagger-codegen\src\test\resources\2_0\petstore.json -l ruby -o samples\client\petstore\ruby + +java %JAVA_OPTS% -jar %executable% %ags% diff --git a/bin/windows/scala-petstore.bat b/bin/windows/scala-petstore.bat new file mode 100755 index 00000000000..5d72d6e0c61 --- /dev/null +++ b/bin/windows/scala-petstore.bat @@ -0,0 +1,10 @@ +set executable=.\modules\swagger-codegen-cli\target\swagger-codegen-cli.jar + +If Not Exist %executable% ( + mvn clean package +) + +set JAVA_OPTS=%JAVA_OPTS% -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties +set ags=generate -t modules\swagger-codegen\src\main\resources\scala -i modules\swagger-codegen\src\test\resources\2_0\petstore.json -l scala -o samples\client\petstore\scala + +java %JAVA_OPTS% -jar %executable% %ags% diff --git a/bin/windows/swift-petstore.bat b/bin/windows/swift-petstore.bat new file mode 100755 index 00000000000..31d19c18399 --- /dev/null +++ b/bin/windows/swift-petstore.bat @@ -0,0 +1,10 @@ +set executable=.\modules\swagger-codegen-cli\target\swagger-codegen-cli.jar + +If Not Exist %executable% ( + mvn clean package +) + +set JAVA_OPTS=%JAVA_OPTS% -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties +set ags=generate -t modules\swagger-codegen\src\main\resources\swift -i modules\swagger-codegen\src\test\resources\2_0\petstore.json -l swift -o samples\client\petstore\swift + +java %JAVA_OPTS% -jar %executable% %ags% diff --git a/bin/windows/tizen-petstore.bat b/bin/windows/tizen-petstore.bat new file mode 100755 index 00000000000..27122c2cb94 --- /dev/null +++ b/bin/windows/tizen-petstore.bat @@ -0,0 +1,10 @@ +set executable=.\modules\swagger-codegen-cli\target\swagger-codegen-cli.jar + +If Not Exist %executable% ( + mvn clean package +) + +set JAVA_OPTS=%JAVA_OPTS% -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties +set ags=generate -t modules\swagger-codegen\src\main\resources\tizen -i modules\swagger-codegen\src\test\resources\2_0\petstore.json -l tizen -o samples\client\petstore\tizen + +java %JAVA_OPTS% -jar %executable% %ags% diff --git a/bin/windows/typescript-angular.bat b/bin/windows/typescript-angular.bat new file mode 100755 index 00000000000..d77012e1b3d --- /dev/null +++ b/bin/windows/typescript-angular.bat @@ -0,0 +1,10 @@ +set executable=.\modules\swagger-codegen-cli\target\swagger-codegen-cli.jar + +If Not Exist %executable% ( + mvn clean package +) + +set JAVA_OPTS=%JAVA_OPTS% -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties +set ags=generate -t modules\swagger-codegen\src\main\resources\typescript-angular -i modules\swagger-codegen\src\test\resources\2_0\petstore.json -l typescript-angular -o samples\client\petstore\typescript-angular + +java %JAVA_OPTS% -jar %executable% %ags% diff --git a/bin/windows/typescript-node.bat b/bin/windows/typescript-node.bat new file mode 100755 index 00000000000..b6d47abd1af --- /dev/null +++ b/bin/windows/typescript-node.bat @@ -0,0 +1,10 @@ +set executable=.\modules\swagger-codegen-cli\target\swagger-codegen-cli.jar + +If Not Exist %executable% ( + mvn clean package +) + +set JAVA_OPTS=%JAVA_OPTS% -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties +set ags=generate -t modules\swagger-codegen\src\main\resources\typescript-node -i modules\swagger-codegen\src\test\resources\2_0\petstore.json -l typescript-node -o samples\client\petstore\typescript-node + +java %JAVA_OPTS% -jar %executable% %ags% diff --git a/config-feign.json b/config-feign.json new file mode 100644 index 00000000000..3b8c48c3caa --- /dev/null +++ b/config-feign.json @@ -0,0 +1 @@ +{"library":"feign"} \ No newline at end of file diff --git a/modules/swagger-codegen/.gitignore b/modules/swagger-codegen/.gitignore new file mode 100644 index 00000000000..d027396de4e --- /dev/null +++ b/modules/swagger-codegen/.gitignore @@ -0,0 +1 @@ +/.settings/ diff --git a/modules/swagger-codegen/pom.xml b/modules/swagger-codegen/pom.xml index fc51a41fcdf..656223ff42b 100644 --- a/modules/swagger-codegen/pom.xml +++ b/modules/swagger-codegen/pom.xml @@ -154,6 +154,7 @@ target/site + org.apache.maven.plugins maven-javadoc-plugin 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 a5bb97e5a93..9c2711f8cad 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 @@ -41,9 +41,11 @@ public class CodegenConstants { public static final String SORT_PARAMS_BY_REQUIRED_FLAG_DESC = "Sort method arguments to place required parameters before optional parameters."; public static final String ENSURE_UNIQUE_PARAMS = "ensureUniqueParams"; - public static final String ENSURE_UNIQUE_PARAMS_DESC = "Whether to ensure parameter names are unique in an operation (rename parameters that are not). Default: true"; + public static final String ENSURE_UNIQUE_PARAMS_DESC = "Whether to ensure parameter names are unique in an operation (rename parameters that are not)."; public static final String PACKAGE_NAME = "packageName"; public static final String PACKAGE_VERSION = "packageVersion"; public static final String POD_VERSION = "podVersion"; + + public static final String OPTIONAL_METHOD_ARGUMENT = "optionalMethodArgument"; } 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 f4dcd074404..d5702b5c50a 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenModel.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenModel.java @@ -9,11 +9,16 @@ import java.util.Set; public class CodegenModel { public String parent; - public String name, classname, description, classVarName, modelJson; + public String name, classname, description, classVarName, modelJson, dataType; public String unescapedDescription; public String defaultValue; public List vars = new ArrayList(); + public List allowableValues; + + // list of all required parameters + public Set mandatory = new HashSet(); + public Set imports = new HashSet(); - public Boolean hasVars, emptyVars, hasMoreModels, hasEnums; + public Boolean hasVars, emptyVars, hasMoreModels, hasEnums, isEnum; public ExternalDocs externalDocs; } 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 38c70fcc82e..ab934075a53 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 @@ -23,6 +23,51 @@ public class CodegenParameter { */ public Boolean required; + /** + * See http://json-schema.org/latest/json-schema-validation.html#anchor17. + */ + public Number maximum; + /** + * See http://json-schema.org/latest/json-schema-validation.html#anchor17 + */ + public Boolean exclusiveMaximum; + /** + * See http://json-schema.org/latest/json-schema-validation.html#anchor21 + */ + public Number minimum; + /** + * See http://json-schema.org/latest/json-schema-validation.html#anchor21 + */ + public Boolean exclusiveMinimum; + /** + * See http://json-schema.org/latest/json-schema-validation.html#anchor26 + */ + public Integer maxLength; + /** + * See http://json-schema.org/latest/json-schema-validation.html#anchor29 + */ + public Integer minLength; + /** + * See http://json-schema.org/latest/json-schema-validation.html#anchor33 + */ + public String pattern; + /** + * See http://json-schema.org/latest/json-schema-validation.html#anchor42 + */ + public Integer maxItems; + /** + * See http://json-schema.org/latest/json-schema-validation.html#anchor45 + */ + public Integer minItems; + /** + * See http://json-schema.org/latest/json-schema-validation.html#anchor49 + */ + public Boolean uniqueItems; + /** + * See http://json-schema.org/latest/json-schema-validation.html#anchor14 + */ + public Number multipleOf; + public CodegenParameter copy() { CodegenParameter output = new CodegenParameter(); output.isFile = this.isFile; @@ -44,6 +89,17 @@ public class CodegenParameter { output.isCookieParam = this.isCookieParam; output.isBodyParam = this.isBodyParam; output.required = this.required; + output.maximum = this.maximum; + output.exclusiveMaximum = this.exclusiveMaximum; + output.minimum = this.minimum; + output.exclusiveMinimum = this.exclusiveMinimum; + output.maxLength = this.maxLength; + output.minLength = this.minLength; + output.pattern = this.pattern; + output.maxItems = this.maxItems; + output.minItems = this.minItems; + output.uniqueItems = this.uniqueItems; + output.multipleOf = this.multipleOf; output.jsonSchema = this.jsonSchema; output.defaultValue = this.defaultValue; output.isEnum = this.isEnum; @@ -58,3 +114,4 @@ public class CodegenParameter { return output; } } + 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 e78fb72fcf5..32e169ac878 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 @@ -5,7 +5,7 @@ import java.util.Map; public class CodegenProperty { public String baseName, complexType, getter, setter, description, datatype, datatypeWithEnum, - name, min, max, defaultValue, baseType, containerType; + name, min, max, defaultValue, defaultValueWithParam, baseType, containerType; public String unescapedDescription; 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 99ceca6796c..8d84f065284 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java @@ -2,6 +2,7 @@ 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; @@ -42,11 +43,13 @@ import io.swagger.models.properties.PropertyBuilder.PropertyId; import io.swagger.models.properties.RefProperty; import io.swagger.models.properties.StringProperty; import io.swagger.util.Json; + 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; @@ -445,7 +448,8 @@ public class DefaultCodegen { cliOptions.add(new CliOption(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG_DESC).defaultValue("true")); - cliOptions.add(new CliOption(CodegenConstants.ENSURE_UNIQUE_PARAMS, CodegenConstants.ENSURE_UNIQUE_PARAMS_DESC)); + cliOptions.add(new CliOption(CodegenConstants.ENSURE_UNIQUE_PARAMS, CodegenConstants.ENSURE_UNIQUE_PARAMS_DESC) + .defaultValue("true")); } /** @@ -574,6 +578,52 @@ public class DefaultCodegen { return "null"; } } + + /** + * Return the property initialized from a data object + * Useful for initialization with a plain object in Javascript + * + * @param name Name of the property object + * @param p Swagger property object + * @return string presentation of the default value of the property + */ + public String toDefaultValueWithParam(String name, Property p) { + if (p instanceof StringProperty) { + return " = data." + name + ";"; + } else if (p instanceof BooleanProperty) { + return " = data." + name + ";"; + } else if (p instanceof DateProperty) { + return " = data." + name + ";"; + } else if (p instanceof DateTimeProperty) { + return " = data." + name + ";"; + } else if (p instanceof DoubleProperty) { + DoubleProperty dp = (DoubleProperty) p; + if (dp.getDefault() != null) { + return dp.getDefault().toString(); + } + return " = data." + name + ";"; + } else if (p instanceof FloatProperty) { + FloatProperty dp = (FloatProperty) p; + if (dp.getDefault() != null) { + return dp.getDefault().toString(); + } + return " = data." + name + ";"; + } else if (p instanceof IntegerProperty) { + IntegerProperty dp = (IntegerProperty) p; + if (dp.getDefault() != null) { + return dp.getDefault().toString(); + } + return " = data." + name + ";"; + } else if (p instanceof LongProperty) { + LongProperty dp = (LongProperty) p; + if (dp.getDefault() != null) { + return dp.getDefault().toString(); + } + return " = data." + name + ";"; + } else { + return " = data." + name + ";"; + } + } /** * returns the swagger type for the property @@ -788,6 +838,12 @@ public class DefaultCodegen { addVars(m, properties, required); } else { ModelImpl impl = (ModelImpl) model; + if(impl.getEnum() != null && impl.getEnum().size() > 0) { + m.isEnum = true; + m.allowableValues = impl.getEnum(); + Property p = PropertyBuilder.build(impl.getType(), impl.getFormat(), null); + m.dataType = getSwaggerType(p); + } if (impl.getAdditionalProperties() != null) { MapProperty mapProperty = new MapProperty(impl.getAdditionalProperties()); addParentContainer(m, name, mapProperty); @@ -835,6 +891,8 @@ public class DefaultCodegen { property.setter = "set" + getterAndSetterCapitalize(name); property.example = p.getExample(); property.defaultValue = toDefaultValue(p); + property.defaultValueWithParam = toDefaultValueWithParam(name, p); + property.jsonSchema = Json.pretty(p); property.isReadOnly = p.getReadOnly(); @@ -1081,31 +1139,7 @@ public class DefaultCodegen { Set imports = new HashSet(); op.vendorExtensions = operation.getVendorExtensions(); - String operationId = operation.getOperationId(); - if (operationId == null) { - String tmpPath = path; - tmpPath = tmpPath.replaceAll("\\{", ""); - tmpPath = tmpPath.replaceAll("\\}", ""); - String[] parts = (tmpPath + "/" + httpMethod).split("/"); - StringBuilder builder = new StringBuilder(); - if ("/".equals(tmpPath)) { - // must be root tmpPath - builder.append("root"); - } - for (int i = 0; i < parts.length; i++) { - String part = parts[i]; - if (part.length() > 0) { - if (builder.toString().length() == 0) { - part = Character.toLowerCase(part.charAt(0)) + part.substring(1); - } else { - part = initialCaps(part); - } - builder.append(part); - } - } - operationId = builder.toString(); - LOGGER.info("generated operationId " + operationId + "\tfor Path: " + httpMethod + " " + path); - } + String operationId = getOrGenerateOperationId(operation, path, httpMethod); operationId = removeNonNameElementToCamelCase(operationId); op.path = path; op.operationId = toOperationId(operationId); @@ -1491,6 +1525,21 @@ public class DefaultCodegen { if (model.complexType != null) { imports.add(model.complexType); } + p.maxLength = qp.getMaxLength(); + p.minLength = qp.getMinLength(); + p.pattern = qp.getPattern(); + + p.maximum = qp.getMaximum(); + p.exclusiveMaximum = qp.isExclusiveMaximum(); + p.minimum = qp.getMinimum(); + p.exclusiveMinimum = qp.isExclusiveMinimum(); + p.maxLength = qp.getMaxLength(); + p.minLength = qp.getMinLength(); + p.pattern = qp.getPattern(); + p.maxItems = qp.getMaxItems(); + p.minItems = qp.getMinItems(); + p.uniqueItems = qp.isUniqueItems(); + p.multipleOf = qp.getMultipleOf(); } else { if (!(param instanceof BodyParameter)) { LOGGER.error("Cannot use Parameter " + param + " as Body Parameter"); @@ -1620,6 +1669,43 @@ public class DefaultCodegen { return secs; } + /** + * Get operationId from the operation object, and if it's blank, generate a new one from the given parameters. + * + * @param operation the operation object + * @param path the path of the operation + * @param httpMethod the HTTP method of the operation + * @return the (generated) operationId + */ + protected String getOrGenerateOperationId(Operation operation, String path, String httpMethod) { + String operationId = operation.getOperationId(); + if (StringUtils.isBlank(operationId)) { + String tmpPath = path; + tmpPath = tmpPath.replaceAll("\\{", ""); + tmpPath = tmpPath.replaceAll("\\}", ""); + String[] parts = (tmpPath + "/" + httpMethod).split("/"); + StringBuilder builder = new StringBuilder(); + if ("/".equals(tmpPath)) { + // must be root tmpPath + builder.append("root"); + } + for (int i = 0; i < parts.length; i++) { + String part = parts[i]; + if (part.length() > 0) { + if (builder.toString().length() == 0) { + part = Character.toLowerCase(part.charAt(0)) + part.substring(1); + } else { + part = initialCaps(part); + } + builder.append(part); + } + } + operationId = builder.toString(); + LOGGER.info("generated operationId " + operationId + "\tfor Path: " + httpMethod + " " + path); + } + return operationId; + } + /** * Check the type to see if it needs import the library/module/package * @@ -1628,8 +1714,7 @@ public class DefaultCodegen { */ protected boolean needToImport(String type) { return !defaultIncludes.contains(type) - && !languageSpecificPrimitives.contains(type) - && type.indexOf(".") < 0; + && !languageSpecificPrimitives.contains(type); } protected List> toExamples(Map examples) { @@ -1743,6 +1828,16 @@ public class DefaultCodegen { return word; } + /** + * Dashize the given word. + * + * @param word The word + * @return The dashized version of the word, e.g. "my-name" + */ + protected String dashize(String word) { + return underscore(word).replaceAll("[_ ]", "-"); + } + /** * Generate the next name for the given name, i.e. append "2" to the base name if not ending with a number, * otherwise increase the number by 1. For example: @@ -1802,6 +1897,9 @@ public class DefaultCodegen { m.vars.add(cp); } } + + m.mandatory = mandatory; + } else { m.emptyVars = true; m.hasVars = false; diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/InlineModelResolver.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/InlineModelResolver.java index d2f47f2a6f6..f727560210a 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/InlineModelResolver.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/InlineModelResolver.java @@ -45,13 +45,15 @@ public class InlineModelResolver { if (bp.getSchema() != null) { Model model = bp.getSchema(); if(model instanceof ModelImpl) { - String modelName = uniqueName(bp.getName()); ModelImpl obj = (ModelImpl) model; - flattenProperties(obj.getProperties(), pathname); + if (obj.getType() == null || "object".equals(obj.getType())) { + String modelName = uniqueName(bp.getName()); + flattenProperties(obj.getProperties(), pathname); - bp.setSchema(new RefModel(modelName)); - addGenerated(modelName, model); - swagger.addDefinition(modelName, model); + bp.setSchema(new RefModel(modelName)); + addGenerated(modelName, model); + swagger.addDefinition(modelName, model); + } } else if (model instanceof ArrayModel) { ArrayModel am = (ArrayModel) model; 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 ad25eb62a73..22c02c32fe2 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 @@ -8,9 +8,7 @@ import io.swagger.codegen.DefaultCodegen; import io.swagger.codegen.SupportingFile; import io.swagger.codegen.CodegenProperty; import io.swagger.codegen.CodegenModel; -import io.swagger.models.properties.ArrayProperty; -import io.swagger.models.properties.MapProperty; -import io.swagger.models.properties.Property; +import io.swagger.models.properties.*; import io.swagger.codegen.CliOption; import io.swagger.models.Model; @@ -30,6 +28,7 @@ import org.slf4j.LoggerFactory; public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig { private static final Logger LOGGER = LoggerFactory.getLogger(CSharpClientCodegen.class); + protected boolean optionalMethodArgumentFlag = true; protected String packageName = "IO.Swagger"; protected String packageVersion = "1.0.0"; protected String clientPackage = "IO.Swagger.Client"; @@ -97,6 +96,7 @@ public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig .defaultValue("IO.Swagger")); cliOptions.add(new CliOption(CodegenConstants.PACKAGE_VERSION, "C# package version.").defaultValue("1.0.0")); cliOptions.add(new CliOption(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG_DESC)); + cliOptions.add(new CliOption(CodegenConstants.OPTIONAL_METHOD_ARGUMENT, "C# Optional method argument, e.g. void square(int x=10) (.net 4.0+ only). Default: false").defaultValue("false")); } @Override @@ -119,6 +119,12 @@ public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig } additionalProperties.put("clientPackage", clientPackage); + + if (additionalProperties.containsKey(CodegenConstants.OPTIONAL_METHOD_ARGUMENT)) { + setOptionalMethodArgumentFlag(Boolean.valueOf(additionalProperties + .get(CodegenConstants.OPTIONAL_METHOD_ARGUMENT).toString())); + } + additionalProperties.put("optionalMethodArgument", optionalMethodArgumentFlag); supportingFiles.add(new SupportingFile("Configuration.mustache", sourceFolder + File.separator + clientPackage.replace(".", java.io.File.separator), "Configuration.cs")); @@ -126,6 +132,8 @@ public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig sourceFolder + File.separator + clientPackage.replace(".", java.io.File.separator), "ApiClient.cs")); supportingFiles.add(new SupportingFile("ApiException.mustache", sourceFolder + File.separator + clientPackage.replace(".", java.io.File.separator), "ApiException.cs")); + supportingFiles.add(new SupportingFile("ApiResponse.mustache", + sourceFolder + File.separator + clientPackage.replace(".", java.io.File.separator), "ApiResponse.cs")); supportingFiles.add(new SupportingFile("Newtonsoft.Json.dll", "bin", "Newtonsoft.Json.dll")); supportingFiles.add(new SupportingFile("RestSharp.dll", "bin", "RestSharp.dll")); supportingFiles.add(new SupportingFile("compile.mustache", "", "compile.bat")); @@ -267,6 +275,10 @@ public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig return camelize(sanitizeName(operationId)); } + public void setOptionalMethodArgumentFlag(boolean flag) { + this.optionalMethodArgumentFlag = flag; + } + @Override public CodegenModel fromModel(String name, Model model, Map allDefinitions) { CodegenModel codegenModel = super.fromModel(name, model, allDefinitions); @@ -416,4 +428,50 @@ public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig public void setPackageVersion(String packageVersion) { this.packageVersion = packageVersion; } + /** + * Return the default value of the property + * + * @param p Swagger property object + * @return string presentation of the default value of the property + */ + @Override + public String toDefaultValue(Property p) { + if (p instanceof StringProperty) { + StringProperty dp = (StringProperty) p; + if (dp.getDefault() != null) { + return "\"" + dp.getDefault().toString() + "\""; + } + } else if (p instanceof BooleanProperty) { + BooleanProperty dp = (BooleanProperty) p; + if (dp.getDefault() != null) { + 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; + } } 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 a358cc05b51..c8b581b3d3a 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 @@ -177,6 +177,14 @@ public class ClojureClientCodegen extends DefaultCodegen implements CodegenConfi return name; } + @Override + public String escapeText(String input) { + if (input == null) { + return null; + } + return input.trim().replace("\\", "\\\\").replace("\"", "\\\""); + } + @Override public Map postProcessOperations(Map operations) { Map objs = (Map) operations.get("operations"); @@ -191,8 +199,4 @@ public class ClojureClientCodegen extends DefaultCodegen implements CodegenConfi protected String namespaceToFolder(String ns) { return ns.replace(".", File.separator).replace("-", "_"); } - - protected String dashize(String s) { - return underscore(s).replaceAll("[_ ]", "-"); - } } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FlaskConnexionCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FlaskConnexionCodegen.java index b3de913501a..7a06ee8b845 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FlaskConnexionCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FlaskConnexionCodegen.java @@ -5,6 +5,7 @@ import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.Lists; import com.google.common.collect.Multimap; import io.swagger.codegen.*; +import io.swagger.models.HttpMethod; import io.swagger.models.Operation; import io.swagger.models.Path; import io.swagger.models.Swagger; @@ -205,13 +206,17 @@ public class FlaskConnexionCodegen extends DefaultCodegen implements CodegenConf for(String pathname : swagger.getPaths().keySet()) { Path path = swagger.getPath(pathname); if(path.getOperations() != null) { - for(Operation operation : path.getOperations()) { - String operationId = operation.getOperationId(); - if(operationId != null && operationId.indexOf(".") == -1) { - operation.setVendorExtension("x-operationId", underscore(sanitizeName(operationId))); - operationId = controllerPackage + "." + defaultController + "." + underscore(sanitizeName(operationId)); - operation.setOperationId(operationId); + for(Map.Entry entry : path.getOperationMap().entrySet()) { + // Normalize `operationId` and add package/class path in front, e.g. + // controllers.default_controller.add_pet + String httpMethod = entry.getKey().name().toLowerCase(); + Operation operation = entry.getValue(); + String operationId = getOrGenerateOperationId(operation, pathname, httpMethod); + if(!operationId.contains(".")) { + operationId = underscore(sanitizeName(operationId)); + operationId = controllerPackage + "." + defaultController + "." + operationId; } + operation.setOperationId(operationId); if(operation.getTags() != null) { List> tags = new ArrayList>(); for(String tag : operation.getTags()) { @@ -292,4 +297,15 @@ public class FlaskConnexionCodegen extends DefaultCodegen implements CodegenConf } return super.postProcessSupportingFileData(objs); } + + @Override + public String toOperationId(String operationId) { + operationId = super.toOperationId(operationId); + // Use the part after the last dot, e.g. + // controllers.defaultController.addPet => addPet + operationId = operationId.replaceAll(".*\\.", ""); + // Need to underscore it since it has been processed via removeNonNameElementToCamelCase, e.g. + // addPet => add_pet + return underscore(operationId); + } } \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JMeterCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JMeterCodegen.java new file mode 100644 index 00000000000..fb167477214 --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JMeterCodegen.java @@ -0,0 +1,183 @@ +package io.swagger.codegen.languages; + +import io.swagger.codegen.*; +import io.swagger.models.Operation; +import io.swagger.models.Path; +import io.swagger.models.Swagger; +import io.swagger.models.properties.*; +import org.apache.commons.lang.StringUtils; + +import java.util.*; +import java.io.File; + +public class JMeterCodegen extends DefaultCodegen implements CodegenConfig { + + // source folder where to write the files + protected String sourceFolder = ""; + protected String apiVersion = "1.0.0"; + + /** + * Configures the type of generator. + * + * @return the CodegenType for this generator + * @see io.swagger.codegen.CodegenType + */ + public CodegenType getTag() { + return CodegenType.CLIENT; + } + + /** + * Configures a friendly name for the generator. This will be used by the generator + * to select the library with the -l flag. + * + * @return the friendly name for the generator + */ + public String getName() { + return "jmeter"; + } + + /** + * Returns human-friendly help for the generator. Provide the consumer with help + * tips, parameters here + * + * @return A string value for the help message + */ + public String getHelp() { + return "Generates a JMeter .jmx file."; + } + + public JMeterCodegen() { + super(); + + // set the output folder here + outputFolder = "generated-code/JMeterCodegen"; + + /** + * Api classes. You can write classes for each Api file with the apiTemplateFiles map. + * as with models, add multiple entries with different extensions for multiple files per + * class + */ + apiTemplateFiles.put( + "api.mustache", // the template to use + ".jmx"); // the extension for each file to write + + apiTemplateFiles.put("testdata-localhost.mustache", ".csv"); + + /** + * Template Location. This is the location which templates will be read from. The generator + * will use the resource stream to attempt to read the templates. + */ + templateDir = "JMeter"; + + /** + * Api Package. Optional, if needed, this can be used in templates + */ + apiPackage = ""; + + /** + * Model Package. Optional, if needed, this can be used in templates + */ + modelPackage = ""; + + /** + * Reserved words. Override this with reserved words specific to your language + */ + reservedWords = new HashSet ( + Arrays.asList( + "sample1", // replace with static values + "sample2") + ); + + /** + * Additional Properties. These values can be passed to the templates and + * are available in models, apis, and supporting files + */ + additionalProperties.put("apiVersion", apiVersion); + +// supportingFiles.add(new SupportingFile("testdata-localhost.mustache", "input", "testdata-localhost.csv")); + } + + public void preprocessSwagger(Swagger swagger) { + if (swagger != null && swagger.getPaths() != null) { + for (String pathname : swagger.getPaths().keySet()) { + Path path = swagger.getPath(pathname); + if (path.getOperations() != null) { + for (Operation operation : path.getOperations()) { + String pathWithDollars = pathname.replaceAll("\\{", "\\$\\{"); + operation.setVendorExtension("x-path", pathWithDollars); + } + } + } + } + } + + /** + * Escapes a reserved word as defined in the `reservedWords` array. Handle escaping + * those terms here. This logic is only called if a variable matches the reseved words + * + * @return the escaped term + */ + @Override + public String escapeReservedWord(String name) { + return "_" + name; // add an underscore to the name + } + + /** + * Location to write model files. You can use the modelPackage() as defined when the class is + * instantiated + */ + public String modelFileFolder() { + return outputFolder + "/" + sourceFolder + "/" + modelPackage().replace('.', File.separatorChar); + } + + /** + * Location to write api files. You can use the apiPackage() as defined when the class is + * instantiated + */ + @Override + public String apiFileFolder() { + return outputFolder + "/" + sourceFolder + "/" + apiPackage().replace('.', File.separatorChar); + } + + /** + * Optional - type declaration. This is a String which is used by the templates to instantiate your + * types. There is typically special handling for different property types + * + * @return a string value used as the `dataType` field for model templates, `returnType` for api templates + */ + @Override + public String getTypeDeclaration(Property p) { + if(p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + Property inner = ap.getItems(); + return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]"; + } + else if (p instanceof MapProperty) { + MapProperty mp = (MapProperty) p; + Property inner = mp.getAdditionalProperties(); + return getSwaggerType(p) + "[String, " + getTypeDeclaration(inner) + "]"; + } + return super.getTypeDeclaration(p); + } + + /** + * Optional - swagger type conversion. This is used to map swagger types in a `Property` into + * either language specific types via `typeMapping` or into complex models if there is not a mapping. + * + * @return a string value of the type or complex model for this property + * @see io.swagger.models.properties.Property + */ + @Override + public String getSwaggerType(Property p) { + String swaggerType = super.getSwaggerType(p); + String type = null; + if(typeMapping.containsKey(swaggerType)) { + type = typeMapping.get(swaggerType); + if(languageSpecificPrimitives.contains(type)) + return toModelName(type); + } + else + type = swaggerType; + return toModelName(type); + } +} \ No newline at end of file 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 636f0157a52..1c03e6c9e6f 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 @@ -11,6 +11,12 @@ 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.Path; +import io.swagger.models.Swagger; +import io.swagger.models.parameters.BodyParameter; +import io.swagger.models.parameters.FormParameter; +import io.swagger.models.parameters.Parameter; import io.swagger.models.properties.ArrayProperty; import io.swagger.models.properties.BooleanProperty; import io.swagger.models.properties.DoubleProperty; @@ -98,6 +104,7 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { .defaultValue("false")); supportedLibraries.put(DEFAULT_LIBRARY, "HTTP client: Jersey client 1.18. JSON processing: Jackson 2.4.2"); + supportedLibraries.put("feign", "HTTP client: Netflix Feign 8.1.1"); supportedLibraries.put("jersey2", "HTTP client: Jersey client 2.6"); supportedLibraries.put("okhttp-gson", "HTTP client: OkHttp 2.4.0. JSON processing: Gson 2.3.1"); supportedLibraries.put("retrofit", "HTTP client: OkHttp 2.4.0. JSON processing: Gson 2.3.1 (Retrofit 1.9.0)"); @@ -215,15 +222,18 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { supportingFiles.add(new SupportingFile("StringUtil.mustache", invokerFolder, "StringUtil.java")); final String authFolder = (sourceFolder + '/' + invokerPackage + ".auth").replace(".", "/"); - supportingFiles.add(new SupportingFile("auth/HttpBasicAuth.mustache", authFolder, "HttpBasicAuth.java")); - supportingFiles.add(new SupportingFile("auth/ApiKeyAuth.mustache", authFolder, "ApiKeyAuth.java")); - supportingFiles.add(new SupportingFile("auth/OAuth.mustache", authFolder, "OAuth.java")); - supportingFiles.add(new SupportingFile("auth/OAuthFlow.mustache", authFolder, "OAuthFlow.java")); + if ("feign".equals(getLibrary())) { + supportingFiles.add(new SupportingFile("FormAwareEncoder.mustache", invokerFolder, "FormAwareEncoder.java")); + } else { + supportingFiles.add(new SupportingFile("auth/HttpBasicAuth.mustache", authFolder, "HttpBasicAuth.java")); + supportingFiles.add(new SupportingFile("auth/ApiKeyAuth.mustache", authFolder, "ApiKeyAuth.java")); + supportingFiles.add(new SupportingFile("auth/OAuth.mustache", authFolder, "OAuth.java")); + supportingFiles.add(new SupportingFile("auth/OAuthFlow.mustache", authFolder, "OAuthFlow.java")); + } - if (!("retrofit".equals(getLibrary()) || "retrofit2".equals(getLibrary()))) { + if (!("feign".equals(getLibrary()) || "retrofit".equals(getLibrary()) || "retrofit2".equals(getLibrary()))) { supportingFiles.add(new SupportingFile("apiException.mustache", invokerFolder, "ApiException.java")); supportingFiles.add(new SupportingFile("Configuration.mustache", invokerFolder, "Configuration.java")); - supportingFiles.add(new SupportingFile("JSON.mustache", invokerFolder, "JSON.java")); supportingFiles.add(new SupportingFile("Pair.mustache", invokerFolder, "Pair.java")); supportingFiles.add(new SupportingFile("auth/Authentication.mustache", authFolder, "Authentication.java")); } @@ -232,13 +242,17 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { if ("okhttp-gson".equals(getLibrary())) { // the "okhttp-gson" library template requires "ApiCallback.mustache" for async call supportingFiles.add(new SupportingFile("ApiCallback.mustache", invokerFolder, "ApiCallback.java")); + supportingFiles.add(new SupportingFile("ApiResponse.mustache", invokerFolder, "ApiResponse.java")); + supportingFiles.add(new SupportingFile("JSON.mustache", invokerFolder, "JSON.java")); + supportingFiles.add(new SupportingFile("ProgressRequestBody.mustache", invokerFolder, "ProgressRequestBody.java")); + supportingFiles.add(new SupportingFile("ProgressResponseBody.mustache", invokerFolder, "ProgressResponseBody.java")); // "build.sbt" is for development with SBT supportingFiles.add(new SupportingFile("build.sbt.mustache", "", "build.sbt")); } else if ("retrofit".equals(getLibrary()) || "retrofit2".equals(getLibrary())) { supportingFiles.add(new SupportingFile("auth/OAuthOkHttpClient.mustache", authFolder, "OAuthOkHttpClient.java")); supportingFiles.add(new SupportingFile("CollectionFormats.mustache", invokerFolder, "CollectionFormats.java")); - } else { - supportingFiles.add(new SupportingFile("TypeRef.mustache", invokerFolder, "TypeRef.java")); + } else if("jersey2".equals(getLibrary())) { + supportingFiles.add(new SupportingFile("JSON.mustache", invokerFolder, "JSON.java")); } } @@ -541,6 +555,57 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { return objs; } + public void preprocessSwagger(Swagger swagger) { + if (swagger != null && swagger.getPaths() != null) { + for (String pathname : swagger.getPaths().keySet()) { + Path path = swagger.getPath(pathname); + if (path.getOperations() != null) { + for (Operation operation : path.getOperations()) { + boolean hasFormParameters = false; + for (Parameter parameter : operation.getParameters()) { + if (parameter instanceof FormParameter) { + hasFormParameters = true; + } + } + + String defaultContentType = hasFormParameters ? "application/x-www-form-urlencoded" : "application/json"; + String contentType = operation.getConsumes() == null || operation.getConsumes().isEmpty() + ? defaultContentType : operation.getConsumes().get(0); + String accepts = getAccept(operation); + operation.setVendorExtension("x-contentType", contentType); + operation.setVendorExtension("x-accepts", accepts); + } + } + } + } + } + + private String getAccept(Operation operation) { + String accepts = null; + String defaultContentType = "application/json"; + if (operation.getProduces() != null && !operation.getProduces().isEmpty()) { + StringBuilder sb = new StringBuilder(); + for (String produces : operation.getProduces()) { + if (defaultContentType.equalsIgnoreCase(produces)) { + accepts = defaultContentType; + break; + } else { + if (sb.length() > 0) { + sb.append(","); + } + sb.append(produces); + } + } + if (accepts == null) { + accepts = sb.toString(); + } + } else { + accepts = defaultContentType; + } + + return accepts; + } + protected boolean needToImport(String type) { return super.needToImport(type) && type.indexOf(".") < 0; } 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 c0061bf39e7..a7a0420d984 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 @@ -1,27 +1,15 @@ package io.swagger.codegen.languages; -import io.swagger.codegen.CodegenConfig; -import io.swagger.codegen.CodegenConstants; -import io.swagger.codegen.CodegenModel; -import io.swagger.codegen.CodegenOperation; -import io.swagger.codegen.CodegenProperty; -import io.swagger.codegen.CodegenType; -import io.swagger.codegen.SupportingFile; +import com.fasterxml.jackson.core.JsonProcessingException; +import io.swagger.codegen.*; import io.swagger.models.Operation; import io.swagger.models.Swagger; import io.swagger.models.properties.ArrayProperty; import io.swagger.models.properties.MapProperty; import io.swagger.models.properties.Property; -import io.swagger.util.Json; +import io.swagger.util.Yaml; -import java.io.File; -import java.io.FileWriter; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashSet; -import java.util.List; -import java.util.Map; +import java.util.*; public class JavaInflectorServerCodegen extends JavaClientCodegen implements CodegenConfig { protected String title = "Swagger Inflector"; @@ -78,6 +66,10 @@ public class JavaInflectorServerCodegen extends JavaClientCodegen implements Cod supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); supportingFiles.add(new SupportingFile("web.mustache", "src/main/webapp/WEB-INF", "web.xml")); supportingFiles.add(new SupportingFile("inflector.mustache", "", "inflector.yaml")); + supportingFiles.add(new SupportingFile("swagger.mustache", + "src/main/swagger", + "swagger.yaml") + ); } @Override @@ -173,21 +165,18 @@ public class JavaInflectorServerCodegen extends JavaClientCodegen implements Cod return objs; } + @Override - public void processSwagger(Swagger swagger) { - super.processSwagger(swagger); - - try { - File file = new File( outputFolder + "/src/main/swagger/swagger.json" ); - file.getParentFile().mkdirs(); - - FileWriter swaggerFile = new FileWriter(file); - swaggerFile.write( Json.pretty( swagger )); - swaggerFile.flush(); - swaggerFile.close(); - } catch (IOException e) { - e.printStackTrace(); + public Map postProcessSupportingFileData(Map objs) { + Swagger swagger = (Swagger)objs.get("swagger"); + if(swagger != null) { + try { + objs.put("swagger-yaml", Yaml.mapper().writeValueAsString(swagger)); + } catch (JsonProcessingException e) { + e.printStackTrace(); + } } + return super.postProcessSupportingFileData(objs); } @Override 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 new file mode 100644 index 00000000000..55b847668c0 --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavascriptClientCodegen.java @@ -0,0 +1,539 @@ +package io.swagger.codegen.languages; + +import com.google.common.base.Strings; + +import io.swagger.codegen.CliOption; +import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.CodegenConstants; +import io.swagger.codegen.CodegenModel; +import io.swagger.codegen.CodegenOperation; +import io.swagger.codegen.CodegenProperty; +import io.swagger.codegen.CodegenType; +import io.swagger.codegen.DefaultCodegen; +import io.swagger.codegen.SupportingFile; +import io.swagger.models.*; +import io.swagger.models.properties.ArrayProperty; +import io.swagger.models.properties.LongProperty; +import io.swagger.models.properties.MapProperty; +import io.swagger.models.properties.Property; +import io.swagger.models.properties.RefProperty; + +import java.io.File; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import org.apache.commons.lang.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class JavascriptClientCodegen extends DefaultCodegen implements CodegenConfig { + 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"; + + protected String projectName = null; + protected String moduleName = null; + protected String projectDescription = null; + protected String projectVersion = null; + + protected String sourceFolder = "src"; + protected String localVariablePrefix = ""; + + public JavascriptClientCodegen() { + super(); + outputFolder = "generated-code/js"; + modelTemplateFiles.put("model.mustache", ".js"); + apiTemplateFiles.put("api.mustache", ".js"); + templateDir = "Javascript"; + apiPackage = "api"; + modelPackage = "model"; + + // reference: http://www.w3schools.com/js/js_reserved.asp + reservedWords = new HashSet( + Arrays.asList( + "abstract", "arguments", "boolean", "break", "byte", + "case", "catch", "char", "class", "const", + "continue", "debugger", "default", "delete", "do", + "double", "else", "enum", "eval", "export", + "extends", "false", "final", "finally", "float", + "for", "function", "goto", "if", "implements", + "import", "in", "instanceof", "int", "interface", + "let", "long", "native", "new", "null", + "package", "private", "protected", "public", "return", + "short", "static", "super", "switch", "synchronized", + "this", "throw", "throws", "transient", "true", + "try", "typeof", "var", "void", "volatile", + "while", "with", "yield", + "Array", "Date", "eval", "function", "hasOwnProperty", + "Infinity", "isFinite", "isNaN", "isPrototypeOf", + "Math", "NaN", "Number", "Object", + "prototype", "String", "toString", "undefined", "valueOf") + ); + + languageSpecificPrimitives = new HashSet( + Arrays.asList("String", "Boolean", "Integer", "Number", "Array", "Object", "Date", "File") + ); + defaultIncludes = new HashSet(languageSpecificPrimitives); + + 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(PROJECT_NAME, + "name of the project (Default: generated from info.title or \"swagger-js-client\")")); + cliOptions.add(new CliOption(MODULE_NAME, + "module name for AMD, Node or globals (Default: generated from )")); + cliOptions.add(new CliOption(PROJECT_DESCRIPTION, + "description of the project (Default: using info.description or \"Client library of \")")); + cliOptions.add(new CliOption(PROJECT_VERSION, + "version of the project (Default: using info.version or \"1.0.0\")")); + cliOptions.add(new CliOption(PROJECT_LICENSE_NAME, + "name of the license the project uses (Default: using info.license.name)")); + } + + @Override + public CodegenType getTag() { + return CodegenType.CLIENT; + } + + @Override + public String getName() { + return "javascript"; + } + + @Override + public String getHelp() { + return "Generates a Javascript client library."; + } + + @Override + 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"); + + importMapping.clear(); + } + + @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 (swagger.getInfo() != null) { + Info info = swagger.getInfo(); + if (projectName == null && info.getTitle() != null) { + // when projectName is not specified, generate it from info.title + projectName = dashize(info.getTitle()); + } + if (projectVersion == null) { + // when projectVersion is not specified, use info.version + projectVersion = info.getVersion(); + } + if (projectDescription == null) { + // 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) { + additionalProperties.put(PROJECT_LICENSE_NAME, license.getName()); + } + } + } + + // default values + if (projectName == null) { + projectName = "swagger-js-client"; + } + if (moduleName == null) { + moduleName = camelize(underscore(projectName)); + } + if (projectVersion == null) { + projectVersion = "1.0.0"; + } + if (projectDescription == null) { + projectDescription = "Client library of " + projectName; + } + + additionalProperties.put(PROJECT_NAME, projectName); + additionalProperties.put(MODULE_NAME, moduleName); + additionalProperties.put(PROJECT_DESCRIPTION, escapeText(projectDescription)); + additionalProperties.put(PROJECT_VERSION, projectVersion); + additionalProperties.put(CodegenConstants.LOCAL_VARIABLE_PREFIX, localVariablePrefix); + additionalProperties.put(CodegenConstants.SOURCE_FOLDER, sourceFolder); + + supportingFiles.add(new SupportingFile("package.mustache", "", "package.json")); + supportingFiles.add(new SupportingFile("index.mustache", sourceFolder, "index.js")); + } + + @Override + public String escapeReservedWord(String name) { + return "_" + name; + } + + @Override + public String apiFileFolder() { + return outputFolder + "/" + sourceFolder + "/" + apiPackage().replace('.', File.separatorChar); + } + + @Override + public String modelFileFolder() { + return outputFolder + "/" + sourceFolder + "/" + modelPackage().replace('.', File.separatorChar); + } + + @Override + public String toVarName(String name) { + // sanitize name + name = sanitizeName(name); + + 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 (reservedWords.contains(name) || name.matches("^\\d.*")) { + name = escapeReservedWord(name); + } + + return name; + } + + @Override + public String toParamName(String name) { + // should be the same as variable name + return toVarName(name); + } + + @Override + public String toModelName(String name) { + name = sanitizeName(name); + + // model name cannot use reserved keyword, e.g. return + if (reservedWords.contains(name)) { + throw new RuntimeException(name + " (reserved word) cannot be used as a model name"); + } + + // camelize the model name + // phone_number => PhoneNumber + return camelize(name); + } + + @Override + public String toModelFilename(String name) { + // should be the same as the model name + return toModelName(name); + } + + @Override + public String toModelImport(String name) { + return name; + } + + @Override + public String toApiImport(String name) { + return toApiName(name); + } + + @Override + public String getTypeDeclaration(Property p) { + if (p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + Property inner = ap.getItems(); + return getSwaggerType(p); // TODO: + "/* <" + getTypeDeclaration(inner) + "> */"; + } else if (p instanceof MapProperty) { + MapProperty mp = (MapProperty) p; + Property inner = mp.getAdditionalProperties(); + + return getSwaggerType(p) + ""; + } + return super.getTypeDeclaration(p); + } + + @Override + public String toDefaultValue(Property p) { + if (p instanceof ArrayProperty) { + return "[]"; + } else if (p instanceof MapProperty) { + return "{}"; + } else if (p instanceof LongProperty) { + LongProperty dp = (LongProperty) p; + if (dp.getDefault() != null) { + return dp.getDefault().toString()+"l"; + } + return "null"; + + // added for Javascript + } else if (p instanceof RefProperty) { + RefProperty rp = (RefProperty)p; + return "new " +rp.getSimpleRef() + "()"; + } + + return super.toDefaultValue(p); + } + + + @Override + public String toDefaultValueWithParam(String name, Property p) { + if (p instanceof ArrayProperty) { + return " = new Array();"; + } else if (p instanceof MapProperty) { + return " = {}"; + } else if (p instanceof LongProperty) { + LongProperty dp = (LongProperty) p; + return " = data." + name + ";"; + + // added for Javascript + } else if (p instanceof RefProperty) { + RefProperty rp = (RefProperty)p; + return ".constructFromObject(data." + name + ");"; + } + + return super.toDefaultValueWithParam(name, p); + } + + + @Override + public String getSwaggerType(Property p) { + String swaggerType = super.getSwaggerType(p); + String type = null; + if (typeMapping.containsKey(swaggerType)) { + type = typeMapping.get(swaggerType); + if (!needToImport(type)) { + return type; + } + } else { + type = swaggerType; + } + if (null == type) { + LOGGER.error("No Type defined for Property " + p); + } + return toModelName(type); + } + + @Override + public String toOperationId(String operationId) { + // throw exception if method name is empty + if (StringUtils.isEmpty(operationId)) { + throw new RuntimeException("Empty method/operation name (operationId) not allowed"); + } + + // method name cannot use reserved keyword, e.g. return + if (reservedWords.contains(operationId)) { + throw new RuntimeException(operationId + " (reserved word) cannot be used as method name"); + } + + return camelize(sanitizeName(operationId), true); + } + + @Override + public CodegenModel fromModel(String name, Model model, Map allDefinitions) { + CodegenModel codegenModel = super.fromModel(name, model, allDefinitions); + + if (allDefinitions != null && codegenModel != null && codegenModel.parent != null && codegenModel.hasEnums) { + final Model parentModel = allDefinitions.get(toModelName(codegenModel.parent)); + final CodegenModel parentCodegenModel = super.fromModel(codegenModel.parent, parentModel); + codegenModel = this.reconcileInlineEnums(codegenModel, parentCodegenModel); + } + + return codegenModel; + } + + @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"); + for (CodegenProperty var : cm.vars) { + Map allowableValues = var.allowableValues; + + // handle ArrayProperty + if (var.items != null) { + allowableValues = var.items.allowableValues; + } + + if (allowableValues == null) { + continue; + } + List values = (List) allowableValues.get("values"); + if (values == null) { + continue; + } + + // put "enumVars" map into `allowableValues", including `name` and `value` + List> enumVars = new ArrayList>(); + String commonPrefix = findCommonPrefixOfVars(values); + int truncateIdx = commonPrefix.length(); + for (String value : values) { + Map enumVar = new HashMap(); + String enumName; + if (truncateIdx == 0) { + enumName = value; + } else { + enumName = value.substring(truncateIdx); + if ("".equals(enumName)) { + enumName = value; + } + } + enumVar.put("name", toEnumVarName(enumName)); + enumVar.put("value", value); + enumVars.add(enumVar); + } + allowableValues.put("enumVars", enumVars); + } + } + return objs; + } + + public Map postProcessOperations(Map objs) { + if("retrofit".equals(getLibrary())) { + Map operations = (Map) objs.get("operations"); + if (operations != null) { + List ops = (List) operations.get("operation"); + for (CodegenOperation operation : ops) { + if (operation.hasConsumes == Boolean.TRUE) { + Map firstType = operation.consumes.get(0); + if (firstType != null) { + if ("multipart/form-data".equals(firstType.get("mediaType"))) { + operation.isMultipart = Boolean.TRUE; + } + } + } + if (operation.returnType == null) { + operation.returnType = "Void"; + } + } + } + } + return objs; + } + + protected boolean needToImport(String type) { + return !defaultIncludes.contains(type) + && !languageSpecificPrimitives.contains(type); + } + + private String findCommonPrefixOfVars(List vars) { + String prefix = StringUtils.getCommonPrefix(vars.toArray(new String[vars.size()])); + // exclude trailing characters that should be part of a valid variable + // e.g. ["status-on", "status-off"] => "status-" (not "status-o") + return prefix.replaceAll("[a-zA-Z0-9]+\\z", ""); + } + + private String toEnumVarName(String value) { + String var = value.replaceAll("\\W+", "_").toUpperCase(); + if (var.matches("\\d.*")) { + return "_" + var; + } else { + return var; + } + } + + private CodegenModel reconcileInlineEnums(CodegenModel codegenModel, CodegenModel parentCodegenModel) { + // This generator uses inline classes to define enums, which breaks when + // dealing with models that have subTypes. To clean this up, we will analyze + // the parent and child models, look for enums that match, and remove + // them from the child models and leave them in the parent. + // Because the child models extend the parents, the enums will be available via the parent. + + // Only bother with reconciliation if the parent model has enums. + if (parentCodegenModel.hasEnums) { + + // Get the properties for the parent and child models + final List parentModelCodegenProperties = parentCodegenModel.vars; + List codegenProperties = codegenModel.vars; + + // Iterate over all of the parent model properties + boolean removedChildEnum = false; + for (CodegenProperty parentModelCodegenPropery : parentModelCodegenProperties) { + // Look for enums + if (parentModelCodegenPropery.isEnum) { + // Now that we have found an enum in the parent class, + // and search the child class for the same enum. + Iterator iterator = codegenProperties.iterator(); + while (iterator.hasNext()) { + CodegenProperty codegenProperty = iterator.next(); + if (codegenProperty.isEnum && codegenProperty.equals(parentModelCodegenPropery)) { + // We found an enum in the child class that is + // a duplicate of the one in the parent, so remove it. + iterator.remove(); + removedChildEnum = true; + } + } + } + } + + if(removedChildEnum) { + // If we removed an entry from this model's vars, we need to ensure hasMore is updated + int count = 0, numVars = codegenProperties.size(); + for(CodegenProperty codegenProperty : codegenProperties) { + count += 1; + codegenProperty.hasMore = (count < numVars) ? true : null; + } + codegenModel.vars = codegenProperties; + } + } + + return codegenModel; + } + + private String sanitizePackageName(String packageName) { + packageName = packageName.trim(); + packageName = packageName.replaceAll("[^a-zA-Z0-9_\\.]", "_"); + if(Strings.isNullOrEmpty(packageName)) { + return "invalidPackageName"; + } + return packageName; + } + +} diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JaxRSServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JaxRSServerCodegen.java index 375f5d72bff..6bc1a392414 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JaxRSServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JaxRSServerCodegen.java @@ -33,18 +33,6 @@ public class JaxRSServerCodegen extends JavaClientCodegen implements CodegenConf additionalProperties.put(CodegenConstants.ARTIFACT_ID, artifactId); additionalProperties.put(CodegenConstants.ARTIFACT_VERSION, artifactVersion); additionalProperties.put("title", title); - - - languageSpecificPrimitives = new HashSet( - Arrays.asList( - "String", - "boolean", - "Boolean", - "Double", - "Integer", - "Long", - "Float") - ); } public CodegenType getTag() { @@ -109,6 +97,9 @@ public class JaxRSServerCodegen extends JavaClientCodegen implements CodegenConf @Override public void preprocessSwagger(Swagger swagger) { + if("/".equals(swagger.getBasePath())) { + swagger.setBasePath(""); + } if(swagger != null && swagger.getPaths() != null) { for(String pathname : swagger.getPaths().keySet()) { Path path = swagger.getPath(pathname); 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 4555aa5f216..9c488db1254 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 @@ -7,9 +7,7 @@ import io.swagger.codegen.CodegenProperty; import io.swagger.codegen.CodegenType; import io.swagger.codegen.DefaultCodegen; import io.swagger.codegen.SupportingFile; -import io.swagger.models.properties.ArrayProperty; -import io.swagger.models.properties.MapProperty; -import io.swagger.models.properties.Property; +import io.swagger.models.properties.*; import java.io.File; import java.util.Arrays; @@ -34,6 +32,7 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { protected String authorEmail = "apiteam@swagger.io"; protected String license = "MIT"; protected String gitRepoURL = "https://github.com/swagger-api/swagger-codegen"; + protected String[] specialWords = {"new", "copy"}; public ObjcClientCodegen() { super(); @@ -86,6 +85,7 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { typeMapping.put("object", "NSObject"); typeMapping.put("file", "NSURL"); + // ref: http://www.tutorialspoint.com/objective_c/objective_c_basic_syntax.htm reservedWords = new HashSet( Arrays.asList( @@ -341,11 +341,6 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { return name; } - @Override - public String toDefaultValue(Property p) { - return null; - } - @Override public String apiFileFolder() { return outputFolder + File.separatorChar + apiPackage(); @@ -375,6 +370,12 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { return name; } + // if name starting with special word, escape with '_' + for(int i =0; i < specialWords.length; i++) { + if (name.matches("(?i:^" + specialWords[i] + ".*)")) + name = escapeSpecialWord(name); + } + // camelize (lower first character) the variable name // e.g. `pet_id` to `petId` name = camelize(name, true); @@ -384,6 +385,7 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { name = escapeReservedWord(name); } + return name; } @@ -397,6 +399,10 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { return "_" + name; } + public String escapeSpecialWord(String name) { + return "var_" + name; + } + @Override public String toOperationId(String operationId) { // throw exception if method name is empty @@ -439,4 +445,55 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { public void setLicense(String license) { this.license = license; } + + /** + * Return the default value of the property + * + * @param p Swagger property object + * @return string presentation of the default value of the property + */ + @Override + public String toDefaultValue(Property p) { + if (p instanceof StringProperty) { + StringProperty dp = (StringProperty) p; + if (dp.getDefault() != null) { + return "@\"" + dp.getDefault().toString() + "\""; + } + } else if (p instanceof BooleanProperty) { + BooleanProperty dp = (BooleanProperty) p; + if (dp.getDefault() != null) { + if (dp.getDefault().toString().equalsIgnoreCase("false")) + return "@0"; + else + return "@1"; + } + } 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; + } + } 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 5b22fbdbadb..c712374f424 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 @@ -6,19 +6,22 @@ import io.swagger.codegen.CodegenConstants; import io.swagger.codegen.CodegenType; import io.swagger.codegen.DefaultCodegen; import io.swagger.codegen.SupportingFile; -import io.swagger.models.properties.ArrayProperty; -import io.swagger.models.properties.MapProperty; -import io.swagger.models.properties.Property; -import io.swagger.models.properties.RefProperty; +import io.swagger.models.properties.*; import java.io.File; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; +import java.util.regex.Matcher; import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { + static Logger LOGGER = LoggerFactory.getLogger(PhpClientCodegen.class); + public static final String VARIABLE_NAMING_CONVENTION = "variableNamingConvention"; public static final String PACKAGE_PATH = "packagePath"; public static final String SRC_BASE_PATH = "srcBasePath"; @@ -129,7 +132,7 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { return (getPackagePath() + File.separatorChar + basePath // Replace period, backslash, forward slash with file separator in package name - + packageName.replaceAll("[\\.\\\\/]", File.separator) + + packageName.replaceAll("[\\.\\\\/]", Matcher.quoteReplacement(File.separator)) // Trim prefix file separators from package path .replaceAll(regFirstPathSeparator, "")) // Trim trailing file separators from the overall path @@ -217,11 +220,11 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { @Override public String apiFileFolder() { - return (outputFolder + "/" + toPackagePath(apiPackage(), srcBasePath)); + return (outputFolder + "/" + toPackagePath(apiPackage, srcBasePath)); } public String modelFileFolder() { - return (outputFolder + "/" + toPackagePath(modelPackage(), srcBasePath)); + return (outputFolder + "/" + toPackagePath(modelPackage, srcBasePath)); } @Override @@ -270,10 +273,6 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { return toModelName(type); } - public String toDefaultValue(Property p) { - return "null"; - } - public void setInvokerPackage(String invokerPackage) { this.invokerPackage = invokerPackage; } @@ -371,4 +370,51 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { return camelize(sanitizeName(operationId), true); } + /** + * Return the default value of the property + * + * @param p Swagger property object + * @return string presentation of the default value of the property + */ + @Override + public String toDefaultValue(Property p) { + if (p instanceof StringProperty) { + StringProperty dp = (StringProperty) p; + if (dp.getDefault() != null) { + return "'" + dp.getDefault().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; + } + } 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 1759e515258..b5aa56aa2c4 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 @@ -6,9 +6,7 @@ import io.swagger.codegen.CodegenConstants; import io.swagger.codegen.CodegenType; import io.swagger.codegen.DefaultCodegen; import io.swagger.codegen.SupportingFile; -import io.swagger.models.properties.ArrayProperty; -import io.swagger.models.properties.MapProperty; -import io.swagger.models.properties.Property; +import io.swagger.models.properties.*; import java.io.File; import java.util.Arrays; @@ -166,10 +164,6 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig return type; } - public String toDefaultValue(Property p) { - return "None"; - } - @Override public String toVarName(String name) { // sanitize name @@ -291,4 +285,55 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig public String generatePackageName(String packageName) { return underscore(packageName.replaceAll("[^\\w]+", "")); } + + /** + * Return the default value of the property + * + * @param p Swagger property object + * @return string presentation of the default value of the property + */ + @Override + public String toDefaultValue(Property p) { + if (p instanceof StringProperty) { + StringProperty dp = (StringProperty) p; + if (dp.getDefault() != null) { + return "'" + dp.getDefault().toString() + "'"; + } + } else if (p instanceof BooleanProperty) { + BooleanProperty dp = (BooleanProperty) p; + if (dp.getDefault() != null) { + if (dp.getDefault().toString().equalsIgnoreCase("false")) + return "False"; + else + return "True"; + } + } else if (p instanceof DateProperty) { + // TODO + } else if (p instanceof DateTimeProperty) { + // TODO + } else if (p instanceof DoubleProperty) { + DoubleProperty dp = (DoubleProperty) p; + if (dp.getDefault() != null) { + return dp.getDefault().toString(); + } + } else if (p instanceof FloatProperty) { + FloatProperty dp = (FloatProperty) p; + if (dp.getDefault() != null) { + return dp.getDefault().toString(); + } + } else if (p instanceof IntegerProperty) { + IntegerProperty dp = (IntegerProperty) p; + if (dp.getDefault() != null) { + return dp.getDefault().toString(); + } + } else if (p instanceof LongProperty) { + LongProperty dp = (LongProperty) p; + if (dp.getDefault() != null) { + return dp.getDefault().toString(); + } + } + + return null; + } + } 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 f30b2ef8b85..2fd6d8d8bc0 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 @@ -6,9 +6,7 @@ import io.swagger.codegen.CodegenConstants; import io.swagger.codegen.CodegenType; import io.swagger.codegen.DefaultCodegen; import io.swagger.codegen.SupportingFile; -import io.swagger.models.properties.ArrayProperty; -import io.swagger.models.properties.MapProperty; -import io.swagger.models.properties.Property; +import io.swagger.models.properties.*; import java.io.File; import java.util.Arrays; @@ -186,6 +184,43 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { return super.getTypeDeclaration(p); } + @Override + public String toDefaultValue(Property p) { + if (p instanceof IntegerProperty) { + IntegerProperty dp = (IntegerProperty) p; + if (dp.getDefault() != null) { + return dp.getDefault().toString(); + } + } else if (p instanceof LongProperty) { + LongProperty dp = (LongProperty) p; + if (dp.getDefault() != null) { + return dp.getDefault().toString(); + } + } else if (p instanceof DoubleProperty) { + DoubleProperty dp = (DoubleProperty) p; + if (dp.getDefault() != null) { + return dp.getDefault().toString(); + } + } else if (p instanceof FloatProperty) { + FloatProperty dp = (FloatProperty) p; + if (dp.getDefault() != null) { + return dp.getDefault().toString(); + } + } else if (p instanceof BooleanProperty) { + BooleanProperty bp = (BooleanProperty) p; + if (bp.getDefault() != null) { + return bp.getDefault().toString(); + } + } else if (p instanceof StringProperty) { + StringProperty sp = (StringProperty) p; + if (sp.getDefault() != null) { + return "\"" + escapeText(sp.getDefault()) + "\""; + } + } + + return null; + } + @Override public String getSwaggerType(Property p) { String swaggerType = super.getSwaggerType(p); @@ -204,10 +239,6 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { return type; } - public String toDefaultValue(Property p) { - return "null"; - } - @Override public String toVarName(String name) { // sanitize name diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SinatraServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SinatraServerCodegen.java index 9bcece87429..1c31b45664e 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SinatraServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SinatraServerCodegen.java @@ -1,5 +1,7 @@ package io.swagger.codegen.languages; +import com.fasterxml.jackson.core.JsonProcessingException; + import io.swagger.codegen.CliOption; import io.swagger.codegen.CodegenConfig; import io.swagger.codegen.CodegenType; @@ -8,10 +10,13 @@ import io.swagger.codegen.SupportingFile; import io.swagger.models.properties.ArrayProperty; import io.swagger.models.properties.MapProperty; import io.swagger.models.properties.Property; +import io.swagger.models.Swagger; +import io.swagger.util.Yaml; import java.io.File; import java.util.Arrays; import java.util.HashSet; +import java.util.Map; import org.apache.commons.lang.StringUtils; @@ -73,6 +78,7 @@ public class SinatraServerCodegen extends DefaultCodegen implements CodegenConfi supportingFiles.add(new SupportingFile("config.ru", "", "config.ru")); supportingFiles.add(new SupportingFile("Gemfile", "", "Gemfile")); supportingFiles.add(new SupportingFile("README.md", "", "README.md")); + supportingFiles.add(new SupportingFile("swagger.mustache","","swagger.yaml")); } public CodegenType getTag() { @@ -213,5 +219,17 @@ public class SinatraServerCodegen extends DefaultCodegen implements CodegenConfi return underscore(operationId); } + @Override + public Map postProcessSupportingFileData(Map objs) { + Swagger swagger = (Swagger)objs.get("swagger"); + if(swagger != null) { + try { + objs.put("swagger-yaml", Yaml.mapper().writeValueAsString(swagger)); + } catch (JsonProcessingException e) { + e.printStackTrace(); + } + } + return super.postProcessSupportingFileData(objs); + } } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SlimFrameworkServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SlimFrameworkServerCodegen.java new file mode 100644 index 00000000000..ef318cb6bdd --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SlimFrameworkServerCodegen.java @@ -0,0 +1,221 @@ +package io.swagger.codegen.languages; + +import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.CodegenConstants; +import io.swagger.codegen.CodegenType; +import io.swagger.codegen.DefaultCodegen; +import io.swagger.codegen.SupportingFile; +import io.swagger.models.properties.ArrayProperty; +import io.swagger.models.properties.MapProperty; +import io.swagger.models.properties.Property; +import io.swagger.models.properties.RefProperty; + +import java.io.File; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; + +public class SlimFrameworkServerCodegen extends DefaultCodegen implements CodegenConfig { + protected String invokerPackage; + protected String groupId = "io.swagger"; + protected String artifactId = "swagger-server"; + protected String artifactVersion = "1.0.0"; + private String variableNamingConvention = "camelCase"; + + public SlimFrameworkServerCodegen() { + super(); + + invokerPackage = camelize("SwaggerServer"); + + String packagePath = "SwaggerServer"; + + modelPackage = packagePath + "\\lib\\Models"; + apiPackage = packagePath + "\\lib"; + outputFolder = "generated-code" + File.separator + "slim"; + modelTemplateFiles.put("model.mustache", ".php"); + + // no api files + apiTemplateFiles.clear(); + + embeddedTemplateDir = templateDir = "slim"; + + reservedWords = new HashSet( + Arrays.asList( + "__halt_compiler", "abstract", "and", "array", "as", "break", "callable", "case", "catch", "class", "clone", "const", "continue", "declare", "default", "die", "do", "echo", "else", "elseif", "empty", "enddeclare", "endfor", "endforeach", "endif", "endswitch", "endwhile", "eval", "exit", "extends", "final", "for", "foreach", "function", "global", "goto", "if", "implements", "include", "include_once", "instanceof", "insteadof", "interface", "isset", "list", "namespace", "new", "or", "print", "private", "protected", "public", "require", "require_once", "return", "static", "switch", "throw", "trait", "try", "unset", "use", "var", "while", "xor") + ); + + additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, invokerPackage); + additionalProperties.put(CodegenConstants.GROUP_ID, groupId); + additionalProperties.put(CodegenConstants.ARTIFACT_ID, artifactId); + additionalProperties.put(CodegenConstants.ARTIFACT_VERSION, artifactVersion); + + // ref: http://php.net/manual/en/language.types.intro.php + languageSpecificPrimitives = new HashSet( + Arrays.asList( + "boolean", + "int", + "integer", + "double", + "float", + "string", + "object", + "DateTime", + "mixed", + "number") + ); + + instantiationTypes.put("array", "array"); + instantiationTypes.put("map", "map"); + + // ref: https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#data-types + typeMapping = new HashMap(); + typeMapping.put("integer", "int"); + typeMapping.put("long", "int"); + typeMapping.put("float", "float"); + typeMapping.put("double", "double"); + typeMapping.put("string", "string"); + typeMapping.put("byte", "int"); + typeMapping.put("boolean", "bool"); + typeMapping.put("date", "\\DateTime"); + typeMapping.put("datetime", "\\DateTime"); + typeMapping.put("file", "\\SplFileObject"); + typeMapping.put("map", "map"); + typeMapping.put("array", "array"); + typeMapping.put("list", "array"); + typeMapping.put("object", "object"); + + supportingFiles.add(new SupportingFile("README.mustache", packagePath.replace('/', File.separatorChar), "README.md")); + supportingFiles.add(new SupportingFile("composer.json", packagePath.replace('/', File.separatorChar), "composer.json")); + supportingFiles.add(new SupportingFile("index.mustache", packagePath.replace('/', File.separatorChar), "index.php")); + supportingFiles.add(new SupportingFile(".htaccess", packagePath.replace('/', File.separatorChar), ".htaccess")); + } + + public CodegenType getTag() { + return CodegenType.SERVER; + } + + public String getName() { + return "slim"; + } + + public String getHelp() { + return "Generates a Slim Framework server library."; + } + + @Override + public String escapeReservedWord(String name) { + return "_" + name; + } + + @Override + public String apiFileFolder() { + return (outputFolder + "/" + apiPackage()).replace('/', File.separatorChar); + } + + public String modelFileFolder() { + return (outputFolder + "/" + modelPackage()).replace('/', File.separatorChar); + } + + @Override + public String getTypeDeclaration(Property p) { + if (p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + Property inner = ap.getItems(); + return getTypeDeclaration(inner) + "[]"; + } else if (p instanceof MapProperty) { + MapProperty mp = (MapProperty) p; + Property inner = mp.getAdditionalProperties(); + return getSwaggerType(p) + "[string," + getTypeDeclaration(inner) + "]"; + } else if (p instanceof RefProperty) { + String type = super.getTypeDeclaration(p); + return (!languageSpecificPrimitives.contains(type)) + ? "\\" + modelPackage + "\\" + type : type; + } + return super.getTypeDeclaration(p); + } + + @Override + public String getSwaggerType(Property p) { + String swaggerType = super.getSwaggerType(p); + String type = null; + if (typeMapping.containsKey(swaggerType)) { + type = typeMapping.get(swaggerType); + if (languageSpecificPrimitives.contains(type)) { + return type; + } else if (instantiationTypes.containsKey(type)) { + return type; + } + } else { + type = swaggerType; + } + if (type == null) { + return null; + } + return toModelName(type); + } + + @Override + public String getTypeDeclaration(String name) { + if (!languageSpecificPrimitives.contains(name)) { + return "\\" + modelPackage + "\\" + name; + } + return super.getTypeDeclaration(name); + } + + public String toDefaultValue(Property p) { + return "null"; + } + + public void setParameterNamingConvention(String variableNamingConvention) { + this.variableNamingConvention = variableNamingConvention; + } + + @Override + public String toVarName(String name) { + // sanitize name + name = sanitizeName(name); + + if ("camelCase".equals(variableNamingConvention)) { + // return the name in camelCase style + // phone_number => phoneNumber + name = camelize(name, true); + } else { // default to snake case + // return the name in underscore style + // PhoneNumber => phone_number + name = underscore(name); + } + + // parameter name starting with number won't compile + // need to escape it by appending _ at the beginning + if (name.matches("^\\d.*")) { + name = "_" + name; + } + + return name; + } + + @Override + public String toParamName(String name) { + // should be the same as variable name + return toVarName(name); + } + + @Override + public String toModelName(String name) { + // model name cannot use reserved keyword + if (reservedWords.contains(name)) { + escapeReservedWord(name); // e.g. return => _return + } + + // camelize the model name + // phone_number => PhoneNumber + return camelize(name); + } + + @Override + public String toModelFilename(String name) { + // should be the same as the model name + return toModelName(name); + } + +} diff --git a/modules/swagger-codegen/src/main/resources/CsharpDotNet2/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/CsharpDotNet2/ApiClient.mustache index 8e64db5af31..a428cdc3630 100644 --- a/modules/swagger-codegen/src/main/resources/CsharpDotNet2/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/CsharpDotNet2/ApiClient.mustache @@ -134,7 +134,7 @@ namespace {{packageName}}.Client } /// - /// If parameter is DateTime, output in ISO8601 format. + /// If parameter is DateTime, output in a formatted string (default ISO 8601), customizable with Configuration.DateTime. /// If parameter is a list of string, join the list with ",". /// Otherwise just return the string. /// @@ -143,7 +143,11 @@ namespace {{packageName}}.Client public string ParameterToString(object obj) { if (obj is DateTime) - return ((DateTime)obj).ToString ("u"); + // Return a formatted date string - Can be customized with Configuration.DateTimeFormat + // Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o") + // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 + // For example: 2009-06-15T13:45:30.0000000 + return ((DateTime)obj).ToString (Configuration.DateTimeFormat); else if (obj is List) return String.Join(",", (obj as List).ToArray()); else diff --git a/modules/swagger-codegen/src/main/resources/CsharpDotNet2/Configuration.mustache b/modules/swagger-codegen/src/main/resources/CsharpDotNet2/Configuration.mustache index 67b07069e2f..56f4e617556 100644 --- a/modules/swagger-codegen/src/main/resources/CsharpDotNet2/Configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/CsharpDotNet2/Configuration.mustache @@ -78,7 +78,40 @@ namespace {{packageName}}.Client _tempFolderPath = value + Path.DirectorySeparatorChar; } } - + + private const string ISO8601_DATETIME_FORMAT = "o"; + + private static string _dateTimeFormat = ISO8601_DATETIME_FORMAT; + + /// + /// Gets or sets the the date time format used when serializing in the ApiClient + /// By default, it's set to ISO 8601 - "o", for others see: + /// https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx + /// and https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx + /// No validation is done to ensure that the string you're providing is valid + /// + /// The DateTimeFormat string + public static String DateTimeFormat + { + get + { + return _dateTimeFormat; + } + set + { + if (string.IsNullOrEmpty(value)) + { + // Never allow a blank or null string, go back to the default + _dateTimeFormat = ISO8601_DATETIME_FORMAT; + return; + } + + // Caution, no validation when you choose date time format other than ISO 8601 + // Take a look at the above links + _dateTimeFormat = value; + } + } + /// /// Returns a string with essential information for debugging. /// diff --git a/modules/swagger-codegen/src/main/resources/JMeter/api.mustache b/modules/swagger-codegen/src/main/resources/JMeter/api.mustache new file mode 100644 index 00000000000..1af63c2d66d --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JMeter/api.mustache @@ -0,0 +1,178 @@ + + + + + + false + false + + + + host + localhost + = + + + port + 8080 + = + + + + + + + + + + testCases + ${__P(host,10)} + = + + + host + ${__P(host,localhost)} + = + + + port + ${__P(port,8080)} + = + {{#operations}}{{#operation}} + + testData.{{operationId}}File + ${__P(testData.{{operationId}}File,{{classname}}.csv)} + = + {{/operation}}{{/operations}} + + + + + + + + ${host} + ${port} + + + + + + 4 + + + {{#operations}}{{#operation}} + continue + + false + ${testCases} + + 1 + 1 + 1448391617000 + 1448391617000 + false + + + + + + {{#headerParams}} + + {{paramName}} + ${__RandomString(10,qwertyuiopasdfghjklzxcvbnm)} + {{/headerParams}} + + + + + + {{#queryParams}} + + false + 0 + = + true + {{paramName}} + {{/queryParams}} + + + + + + + + + {{vendorExtensions.x-path}} + {{httpMethod}} + true + false + true + false + HttpClient3.1 + false + + {{summary}} {{notes}} + + + + , + + ${testData.{{operationId}}File} + true + true + shareMode.all + false + + + + + + + ${httpStatusCode} + + Assertion.response_code + false + 8 + + + + {{/operation}} + {{/operations}} + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + false + false + false + false + false + false + 0 + true + true + + + + + + + + diff --git a/modules/swagger-codegen/src/main/resources/JMeter/testdata-localhost.mustache b/modules/swagger-codegen/src/main/resources/JMeter/testdata-localhost.mustache new file mode 100644 index 00000000000..48708a1d0fa --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JMeter/testdata-localhost.mustache @@ -0,0 +1,2 @@ +testCase,httpStatusCode{{#operations}}{{#operation}}{{#hasParams}},{{/hasParams}}{{#allParams}}{{paramName}}{{#hasMore}},{{/hasMore}}{{/allParams}}{{/operation}}{{/operations}} +Success,200{{#operations}}{{#operation}}{{#hasParams}},{{/hasParams}}{{#allParams}}0{{#hasMore}},{{/hasMore}}{{/allParams}}{{/operation}}{{/operations}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache index 91d1eb93daf..ef31058d561 100644 --- a/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache @@ -1,8 +1,13 @@ package {{invokerPackage}}; +import com.fasterxml.jackson.annotation.*; +import com.fasterxml.jackson.databind.*; +import com.fasterxml.jackson.datatype.joda.*; +import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider; + import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.ClientResponse; -import com.sun.jersey.api.client.config.ClientConfig; +import com.sun.jersey.api.client.GenericType; import com.sun.jersey.api.client.config.DefaultClientConfig; import com.sun.jersey.api.client.filter.LoggingFilter; import com.sun.jersey.api.client.WebResource.Builder; @@ -25,14 +30,11 @@ import java.util.TimeZone; import java.net.URLEncoder; -import java.io.IOException; import java.io.File; import java.io.UnsupportedEncodingException; -import java.io.DataInputStream; import java.text.DateFormat; import java.text.SimpleDateFormat; -import java.text.ParseException; import {{invokerPackage}}.auth.Authentication; import {{invokerPackage}}.auth.HttpBasicAuth; @@ -45,7 +47,7 @@ public class ApiClient { private Map defaultHeaderMap = new HashMap(); private boolean debugging = false; private String basePath = "{{basePath}}"; - private JSON json = new JSON(); + private ObjectMapper mapper; private Map authentications; @@ -55,6 +57,14 @@ public class ApiClient { private DateFormat dateFormat; public ApiClient() { + mapper = new ObjectMapper(); + mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); + mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING); + mapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING); + mapper.registerModule(new JodaModule()); + // Use RFC3339 format for date and datetime. // See http://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14 this.dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); @@ -62,7 +72,7 @@ public class ApiClient { // Use UTC as the default time zone. this.dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); - this.json.setDateFormat((DateFormat) dateFormat.clone()); + this.mapper.setDateFormat((DateFormat) dateFormat.clone()); // Set default User-Agent. setUserAgent("Java-Swagger"); @@ -76,13 +86,6 @@ public class ApiClient { authentications = Collections.unmodifiableMap(authentications); } - /** - * Gets the JSON instance to do JSON serialization and deserialization. - */ - public JSON getJSON() { - return json; - } - public String getBasePath() { return basePath; } @@ -237,7 +240,7 @@ public class ApiClient { public ApiClient setDateFormat(DateFormat dateFormat) { this.dateFormat = dateFormat; // also set the date format for model (de)serialization with Date properties - this.json.setDateFormat((DateFormat) dateFormat.clone()); + this.mapper.setDateFormat((DateFormat) dateFormat.clone()); return this; } @@ -269,7 +272,7 @@ public class ApiClient { return formatDate((Date) param); } else if (param instanceof Collection) { StringBuilder b = new StringBuilder(); - for(Object o : (Collection)param) { + for(Object o : (Collection)param) { if(b.length() > 0) { b.append(","); } @@ -290,9 +293,9 @@ public class ApiClient { // preconditions if (name == null || name.isEmpty() || value == null) return params; - Collection valueCollection = null; - if (value instanceof Collection) { - valueCollection = (Collection) value; + Collection valueCollection = null; + if (value instanceof Collection) { + valueCollection = (Collection) value; } else { params.add(new Pair(name, parameterToString(value))); return params; @@ -337,6 +340,17 @@ public class ApiClient { return params; } + /** + * Check if the given MIME is a JSON MIME. + * JSON MIME examples: + * application/json + * application/json; charset=UTF8 + * APPLICATION/JSON + */ + public boolean isJsonMime(String mime) { + return mime != null && mime.matches("(?i)application\\/json(;.*)?"); + } + /** * Select the Accept header's value from the given accepts array: * if JSON exists in the given array, use it; @@ -347,8 +361,14 @@ public class ApiClient { * null will be returned (not to set the Accept header explicitly). */ public String selectHeaderAccept(String[] accepts) { - if (accepts.length == 0) return null; - if (StringUtil.containsIgnoreCase(accepts, "application/json")) return "application/json"; + if (accepts.length == 0) { + return null; + } + for (String accept : accepts) { + if (isJsonMime(accept)) { + return accept; + } + } return StringUtil.join(accepts, ","); } @@ -362,8 +382,14 @@ public class ApiClient { * JSON will be used. */ public String selectHeaderContentType(String[] contentTypes) { - if (contentTypes.length == 0) return "application/json"; - if (StringUtil.containsIgnoreCase(contentTypes, "application/json")) return "application/json"; + if (contentTypes.length == 0) { + return "application/json"; + } + for (String contentType : contentTypes) { + if (isJsonMime(contentType)) { + return contentType; + } + } return contentTypes[0]; } @@ -382,49 +408,30 @@ public class ApiClient { * Serialize the given Java object into string according the given * Content-Type (only JSON is supported for now). */ - public String serialize(Object obj, String contentType) throws ApiException { - if (contentType.startsWith("application/json")) { - return json.serialize(obj); + public Object serialize(Object obj, String contentType, Map formParams) throws ApiException { + if (contentType.startsWith("multipart/form-data")) { + FormDataMultiPart mp = new FormDataMultiPart(); + for (Entry param: formParams.entrySet()) { + if (param.getValue() instanceof File) { + File file = (File) param.getValue(); + mp.bodyPart(new FileDataBodyPart(param.getKey(), file, MediaType.MULTIPART_FORM_DATA_TYPE)); + } else { + mp.field(param.getKey(), parameterToString(param.getValue()), MediaType.MULTIPART_FORM_DATA_TYPE); + } + } + return mp; + } else if (contentType.startsWith("application/x-www-form-urlencoded")) { + return this.getXWWWFormUrlencodedParams(formParams); } else { - throw new ApiException(400, "can not serialize object into Content-Type: " + contentType); + // We let Jersey attempt to serialize the body + return obj; } } - /** - * Deserialize response body to Java object according to the Content-Type. - */ - public T deserialize(ClientResponse response, TypeRef returnType) throws ApiException { - String contentType = null; - List contentTypes = response.getHeaders().get("Content-Type"); - if (contentTypes != null && !contentTypes.isEmpty()) - contentType = contentTypes.get(0); - if (contentType == null) - throw new ApiException(500, "missing Content-Type in response"); + private ClientResponse getAPIResponse(String path, String method, List queryParams, Object body, Map headerParams, Map formParams, String accept, String contentType, String[] authNames) throws ApiException { - String body; - if (response.hasEntity()) - body = (String) response.getEntity(String.class); - else - body = ""; - - if (contentType.startsWith("application/json")) { - return json.deserialize(body, returnType); - } else if (returnType.getType().equals(String.class)) { - // Expecting string, return the raw response body. - return (T) body; - } else { - throw new ApiException( - 500, - "Content type \"" + contentType + "\" is not supported for type: " - + returnType.getType() - ); - } - } - - private ClientResponse getAPIResponse(String path, String method, List queryParams, Object body, byte[] binaryBody, Map headerParams, Map formParams, String accept, String contentType, String[] authNames) throws ApiException { - - if (body != null && binaryBody != null){ - throw new ApiException(500, "either body or binaryBody must be null"); + if (body != null && !formParams.isEmpty()){ + throw new ApiException(500, "Cannot have body and form params"); } updateParamsForAuth(authNames, queryParams, headerParams); @@ -461,62 +468,16 @@ public class ApiClient { } } - String encodedFormParams = null; - if (contentType.startsWith("multipart/form-data")) { - FormDataMultiPart mp = new FormDataMultiPart(); - for (Entry param: formParams.entrySet()) { - if (param.getValue() instanceof File) { - File file = (File) param.getValue(); - mp.field(param.getKey(), file.getName()); - mp.bodyPart(new FileDataBodyPart(param.getKey(), file, MediaType.MULTIPART_FORM_DATA_TYPE)); - } else { - mp.field(param.getKey(), parameterToString(param.getValue()), MediaType.MULTIPART_FORM_DATA_TYPE); - } - } - body = mp; - } else if (contentType.startsWith("application/x-www-form-urlencoded")) { - encodedFormParams = this.getXWWWFormUrlencodedParams(formParams); - } - ClientResponse response = null; if ("GET".equals(method)) { response = (ClientResponse) builder.get(ClientResponse.class); } else if ("POST".equals(method)) { - if (encodedFormParams != null) { - response = builder.type(contentType).post(ClientResponse.class, encodedFormParams); - } else if (body == null) { - if(binaryBody == null) - response = builder.post(ClientResponse.class, null); - else - response = builder.type(contentType).post(ClientResponse.class, binaryBody); - } else if (body instanceof FormDataMultiPart) { - response = builder.type(contentType).post(ClientResponse.class, body); - } else { - response = builder.type(contentType).post(ClientResponse.class, serialize(body, contentType)); - } + response = builder.type(contentType).post(ClientResponse.class, serialize(body, contentType, formParams)); } else if ("PUT".equals(method)) { - if (encodedFormParams != null) { - response = builder.type(contentType).put(ClientResponse.class, encodedFormParams); - } else if(body == null) { - if(binaryBody == null) - response = builder.put(ClientResponse.class, null); - else - response = builder.type(contentType).put(ClientResponse.class, binaryBody); - } else { - response = builder.type(contentType).put(ClientResponse.class, serialize(body, contentType)); - } + response = builder.type(contentType).put(ClientResponse.class, serialize(body, contentType, formParams)); } else if ("DELETE".equals(method)) { - if (encodedFormParams != null) { - response = builder.type(contentType).delete(ClientResponse.class, encodedFormParams); - } else if(body == null) { - if(binaryBody == null) - response = builder.delete(ClientResponse.class); - else - response = builder.type(contentType).delete(ClientResponse.class, binaryBody); - } else { - response = builder.type(contentType).delete(ClientResponse.class, serialize(body, contentType)); - } + response = builder.type(contentType).delete(ClientResponse.class, serialize(body, contentType, formParams)); } else { throw new ApiException(500, "unknown method type " + method); } @@ -530,7 +491,6 @@ public class ApiClient { * @param method The request method, one of "GET", "POST", "PUT", and "DELETE" * @param queryParams The query parameters * @param body The request body object - if it is not binary, otherwise null - * @param binaryBody The request body object - if it is binary, otherwise null * @param headerParams The header parameters * @param formParams The form parameters * @param accept The request's Accept header @@ -538,9 +498,9 @@ public class ApiClient { * @param authNames The authentications to apply * @return The response body in type of string */ - public T invokeAPI(String path, String method, List queryParams, Object body, byte[] binaryBody, Map headerParams, Map formParams, String accept, String contentType, String[] authNames, TypeRef returnType) throws ApiException { + public T invokeAPI(String path, String method, List queryParams, Object body, Map headerParams, Map formParams, String accept, String contentType, String[] authNames, GenericType returnType) throws ApiException { - ClientResponse response = getAPIResponse(path, method, queryParams, body, binaryBody, headerParams, formParams, accept, contentType, authNames); + ClientResponse response = getAPIResponse(path, method, queryParams, body, headerParams, formParams, accept, contentType, authNames); statusCode = response.getStatusInfo().getStatusCode(); responseHeaders = response.getHeaders(); @@ -551,13 +511,13 @@ public class ApiClient { if (returnType == null) return null; else - return deserialize(response, returnType); + return response.getEntity(returnType); } else { String message = "error"; String respBody = null; if (response.hasEntity()) { try { - respBody = String.valueOf(response.getEntity(String.class)); + respBody = response.getEntity(String.class); message = respBody; } catch (RuntimeException e) { // e.printStackTrace(); @@ -570,58 +530,6 @@ public class ApiClient { respBody); } } - /** - * Invoke API by sending HTTP request with the given options - return binary result - * - * @param path The sub-path of the HTTP URL - * @param method The request method, one of "GET", "POST", "PUT", and "DELETE" - * @param queryParams The query parameters - * @param body The request body object - if it is not binary, otherwise null - * @param binaryBody The request body object - if it is binary, otherwise null - * @param headerParams The header parameters - * @param formParams The form parameters - * @param accept The request's Accept header - * @param contentType The request's Content-Type header - * @param authNames The authentications to apply - * @return The response body in type of string - */ - public byte[] invokeBinaryAPI(String path, String method, List queryParams, Object body, byte[] binaryBody, Map headerParams, Map formParams, String accept, String contentType, String[]authNames) throws ApiException { - - ClientResponse response = getAPIResponse(path, method, queryParams, body, binaryBody, headerParams, formParams, accept, contentType, authNames); - - if(response.getStatusInfo() == ClientResponse.Status.NO_CONTENT) { - return null; - } - else if(response.getStatusInfo().getFamily() == Family.SUCCESSFUL) { - if(response.hasEntity()) { - DataInputStream stream = new DataInputStream(response.getEntityInputStream()); - byte[] data = new byte[response.getLength()]; - try { - stream.readFully(data); - } catch (IOException ex) { - throw new ApiException(500, "Error obtaining binary response data"); - } - return data; - } - else { - return new byte[0]; - } - } - else { - String message = "error"; - if(response.hasEntity()) { - try{ - message = String.valueOf(response.getEntity(String.class)); - } - catch (RuntimeException e) { - // e.printStackTrace(); - } - } - throw new ApiException( - response.getStatusInfo().getStatusCode(), - message); - } - } /** * Update query and header parameters based on authentication settings. @@ -643,7 +551,6 @@ public class ApiClient { StringBuilder formParamBuilder = new StringBuilder(); for (Entry param : formParams.entrySet()) { - String keyStr = param.getKey(); String valueStr = parameterToString(param.getValue()); try { formParamBuilder.append(URLEncoder.encode(param.getKey(), "utf8")) @@ -668,7 +575,11 @@ public class ApiClient { */ private Client getClient() { if(!hostMap.containsKey(basePath)) { - Client client = Client.create(); + // Add the JSON serialization support to Jersey + JacksonJsonProvider jsonProvider = new JacksonJsonProvider(mapper); + DefaultClientConfig conf = new DefaultClientConfig(); + conf.getSingletons().add(jsonProvider); + Client client = Client.create(conf); if (debugging) client.addFilter(new LoggingFilter()); hostMap.put(basePath, client); diff --git a/modules/swagger-codegen/src/main/resources/Java/JSON.mustache b/modules/swagger-codegen/src/main/resources/Java/JSON.mustache deleted file mode 100644 index 54faed8dcb3..00000000000 --- a/modules/swagger-codegen/src/main/resources/Java/JSON.mustache +++ /dev/null @@ -1,64 +0,0 @@ -package {{invokerPackage}}; - -import com.fasterxml.jackson.annotation.*; -import com.fasterxml.jackson.databind.*; -import com.fasterxml.jackson.datatype.joda.*; - -import java.text.DateFormat; - -import java.io.IOException; - -{{>generatedAnnotation}} -public class JSON { - private ObjectMapper mapper; - - public JSON() { - mapper = new ObjectMapper(); - mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); - mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING); - mapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING); - mapper.registerModule(new JodaModule()); - } - - /** - * Set the date format for JSON (de)serialization with Date properties. - */ - public void setDateFormat(DateFormat dateFormat) { - mapper.setDateFormat(dateFormat); - } - - /** - * Serialize the given Java object into JSON string. - */ - public String serialize(Object obj) throws ApiException { - try { - if (obj != null) - return mapper.writeValueAsString(obj); - else - return null; - } catch (Exception e) { - throw new ApiException(400, e.getMessage()); - } - } - - /** - * Deserialize the given JSON string to Java object. - * - * @param body The JSON string - * @param returnType The type to deserialize inot - * @return The deserialized Java object - */ - public T deserialize(String body, TypeRef returnType) throws ApiException { - JavaType javaType = mapper.constructType(returnType.getType()); - try { - return mapper.readValue(body, javaType); - } catch (IOException e) { - if (returnType.getType().equals(String.class)) - return (T) body; - else - throw new ApiException(500, e.getMessage(), null, body); - } - } -} diff --git a/modules/swagger-codegen/src/main/resources/Java/TypeRef.mustache b/modules/swagger-codegen/src/main/resources/Java/TypeRef.mustache deleted file mode 100644 index 9e9ba5f8895..00000000000 --- a/modules/swagger-codegen/src/main/resources/Java/TypeRef.mustache +++ /dev/null @@ -1,26 +0,0 @@ -package {{invokerPackage}}; - -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.Type; - -{{>generatedAnnotation}} -public class TypeRef { - private final Type type; - - public TypeRef() { - this.type = getGenericType(getClass()); - } - - private static Type getGenericType(Class klass) { - Type superclass = klass.getGenericSuperclass(); - if (superclass instanceof Class) { - throw new RuntimeException("No type parameter provided"); - } - ParameterizedType parameterized = (ParameterizedType) superclass; - return parameterized.getActualTypeArguments()[0]; - } - - public Type getType() { - return type; - } -} diff --git a/modules/swagger-codegen/src/main/resources/Java/api.mustache b/modules/swagger-codegen/src/main/resources/Java/api.mustache index 3ac280b2d70..fc441df954a 100644 --- a/modules/swagger-codegen/src/main/resources/Java/api.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/api.mustache @@ -1,10 +1,11 @@ package {{package}}; +import com.sun.jersey.api.client.GenericType; + import {{invokerPackage}}.ApiException; import {{invokerPackage}}.ApiClient; import {{invokerPackage}}.Configuration; import {{invokerPackage}}.Pair; -import {{invokerPackage}}.TypeRef; {{#imports}}import {{import}}; {{/imports}} @@ -41,13 +42,12 @@ public class {{classname}} { {{#allParams}} * @param {{paramName}} {{description}} {{/allParams}} * @return {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} */ - public {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}}{{nickname}} ({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) throws ApiException { - Object {{localVariablePrefix}}postBody = {{#bodyParam}}{{^isBinary}}{{paramName}}{{/isBinary}}{{#isBinary}}null{{/isBinary}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}}; - byte[] {{localVariablePrefix}}postBinaryBody = {{#bodyParam}}{{#isBinary}}{{paramName}}{{/isBinary}}{{^isBinary}}null{{/isBinary}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}}; + public {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}}{{operationId}}({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) throws ApiException { + Object {{localVariablePrefix}}postBody = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}}; {{#allParams}}{{#required}} // verify the required parameter '{{paramName}}' is set if ({{paramName}} == null) { - throw new ApiException(400, "Missing the required parameter '{{paramName}}' when calling {{nickname}}"); + throw new ApiException(400, "Missing the required parameter '{{paramName}}' when calling {{operationId}}"); } {{/required}}{{/allParams}} // create path and map variables @@ -83,22 +83,12 @@ public class {{classname}} { String[] {{localVariablePrefix}}authNames = new String[] { {{#authMethods}}"{{name}}"{{#hasMore}}, {{/hasMore}}{{/authMethods}} }; - {{#isResponseBinary}} - byte[] {{localVariablePrefix}}response = null; - {{localVariablePrefix}}response = {{localVariablePrefix}}apiClient.invokeBinaryAPI({{localVariablePrefix}}path, "{{httpMethod}}", {{localVariablePrefix}}queryParams,{{localVariablePrefix}} postBody, {{localVariablePrefix}}postBinaryBody, {{localVariablePrefix}}headerParams, {{localVariablePrefix}}formParams, {{localVariablePrefix}}accept, {{localVariablePrefix}}contentType, {{localVariablePrefix}}authNames); - return {{localVariablePrefix}}response; - {{/isResponseBinary}} - - {{^isResponseBinary}} {{#returnType}} - TypeRef {{localVariablePrefix}}returnType = new TypeRef<{{{returnType}}}>() {}; - return {{localVariablePrefix}}apiClient.invokeAPI({{localVariablePrefix}}path, "{{httpMethod}}", {{localVariablePrefix}}queryParams, {{localVariablePrefix}}postBody, {{localVariablePrefix}}postBinaryBody, {{localVariablePrefix}}headerParams, {{localVariablePrefix}}formParams, {{localVariablePrefix}}accept, {{localVariablePrefix}}contentType, {{localVariablePrefix}}authNames, {{localVariablePrefix}}returnType); + GenericType<{{{returnType}}}> {{localVariablePrefix}}returnType = new GenericType<{{{returnType}}}>() {}; + return {{localVariablePrefix}}apiClient.invokeAPI({{localVariablePrefix}}path, "{{httpMethod}}", {{localVariablePrefix}}queryParams, {{localVariablePrefix}}postBody, {{localVariablePrefix}}headerParams, {{localVariablePrefix}}formParams, {{localVariablePrefix}}accept, {{localVariablePrefix}}contentType, {{localVariablePrefix}}authNames, {{localVariablePrefix}}returnType); {{/returnType}}{{^returnType}} - {{localVariablePrefix}}apiClient.invokeAPI({{localVariablePrefix}}path, "{{httpMethod}}", {{localVariablePrefix}}queryParams, {{localVariablePrefix}}postBody, {{localVariablePrefix}}postBinaryBody, {{localVariablePrefix}}headerParams, {{localVariablePrefix}}formParams, {{localVariablePrefix}}accept, {{localVariablePrefix}}contentType, {{localVariablePrefix}}authNames, null); + {{localVariablePrefix}}apiClient.invokeAPI({{localVariablePrefix}}path, "{{httpMethod}}", {{localVariablePrefix}}queryParams, {{localVariablePrefix}}postBody, {{localVariablePrefix}}headerParams, {{localVariablePrefix}}formParams, {{localVariablePrefix}}accept, {{localVariablePrefix}}contentType, {{localVariablePrefix}}authNames, null); {{/returnType}} - {{/isResponseBinary}} - - } {{/operation}} } diff --git a/modules/swagger-codegen/src/main/resources/Java/enumClass.mustache b/modules/swagger-codegen/src/main/resources/Java/enumClass.mustache index fd8e8442254..e0ec74385ff 100644 --- a/modules/swagger-codegen/src/main/resources/Java/enumClass.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/enumClass.mustache @@ -1,14 +1,16 @@ -public enum {{datatypeWithEnum}} { - {{#allowableValues}}{{#enumVars}}{{name}}("{{value}}"){{^-last}}, + +public enum {{{datatypeWithEnum}}} { + {{#allowableValues}}{{#enumVars}}{{{name}}}("{{{value}}}"){{^-last}}, {{/-last}}{{#-last}};{{/-last}}{{/enumVars}}{{/allowableValues}} private String value; - {{datatypeWithEnum}}(String value) { + {{{datatypeWithEnum}}}(String value) { this.value = value; } @Override + @JsonValue public String toString() { return value; } diff --git a/modules/swagger-codegen/src/main/resources/Java/enumOuterClass.mustache b/modules/swagger-codegen/src/main/resources/Java/enumOuterClass.mustache new file mode 100644 index 00000000000..7aea7b92f22 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/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/Java/libraries/feign/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/ApiClient.mustache new file mode 100644 index 00000000000..3f2bfcebd5b --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/ApiClient.mustache @@ -0,0 +1,86 @@ +package {{invokerPackage}}; + +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; +import feign.Feign; +import feign.jackson.JacksonDecoder; +import feign.jackson.JacksonEncoder; +import feign.slf4j.Slf4jLogger; + +{{>generatedAnnotation}} +public class ApiClient { + public interface Api {} + + private ObjectMapper objectMapper; + private String basePath = "{{basePath}}"; + + public ApiClient() { + objectMapper = createObjectMapper(); + } + + public String getBasePath() { + return basePath; + } + + public ApiClient setBasePath(String basePath) { + this.basePath = basePath; + return this; + } + + private ObjectMapper createObjectMapper() { + ObjectMapper objectMapper = new ObjectMapper(); + objectMapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING); + objectMapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING); + return objectMapper; + } + + /** + * Creates a feign client for given API interface. + * + * Usage: + * ApiClient apiClient = new ApiClient(); + * apiClient.setBasePath("http://localhost:8080"); + * XYZApi api = apiClient.buildClient(XYZApi.class); + * XYZResponse response = api.someMethod(...); + */ + public T buildClient(Class clientClass) { + return Feign.builder() + .encoder(new FormAwareEncoder(new JacksonEncoder(objectMapper))) + .decoder(new JacksonDecoder(objectMapper)) +// enable for basic auth: +// .requestInterceptor(new feign.auth.BasicAuthRequestInterceptor(username, password)) + .logger(new Slf4jLogger()) + .target(clientClass, basePath); + } + + /** + * Select the Accept header's value from the given accepts array: + * if JSON exists in the given array, use it; + * otherwise use all of them (joining into a string) + * + * @param accepts The accepts array to select from + * @return The Accept header to use. If the given array is empty, + * null will be returned (not to set the Accept header explicitly). + */ + public String selectHeaderAccept(String[] accepts) { + if (accepts.length == 0) return null; + if (StringUtil.containsIgnoreCase(accepts, "application/json")) return "application/json"; + return StringUtil.join(accepts, ","); + } + + /** + * Select the Content-Type header's value from the given array: + * if JSON exists in the given array, use it; + * otherwise use the first one of the array. + * + * @param contentTypes The Content-Type array to select from + * @return The Content-Type header to use. If the given array is empty, + * JSON will be used. + */ + public String selectHeaderContentType(String[] contentTypes) { + if (contentTypes.length == 0) return "application/json"; + if (StringUtil.containsIgnoreCase(contentTypes, "application/json")) return "application/json"; + return contentTypes[0]; + } +} diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/feign/FormAwareEncoder.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/FormAwareEncoder.mustache new file mode 100644 index 00000000000..822aad582d4 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/FormAwareEncoder.mustache @@ -0,0 +1,197 @@ +package {{invokerPackage}}; + +import java.io.*; +import java.lang.reflect.Type; +import java.net.URLEncoder; +import java.net.URLConnection; +import java.nio.charset.Charset; +import java.util.*; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; + +import feign.codec.EncodeException; +import feign.codec.Encoder; +import feign.RequestTemplate; + +{{>generatedAnnotation}} +public class FormAwareEncoder implements Encoder { + public static final String UTF_8 = "utf-8"; + private static final String LINE_FEED = "\r\n"; + private static final String TWO_DASH = "--"; + private static final String BOUNDARY = "----------------314159265358979323846"; + + private byte[] lineFeedBytes; + private byte[] boundaryBytes; + private byte[] twoDashBytes; + private byte[] atBytes; + private byte[] eqBytes; + + private final Encoder delegate; + private final DateFormat dateFormat; + + public FormAwareEncoder(Encoder delegate) { + this.delegate = delegate; + // Use RFC3339 format for date and datetime. + // See http://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14 + this.dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); + + // Use UTC as the default time zone. + this.dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); + try { + this.lineFeedBytes = LINE_FEED.getBytes(UTF_8); + this.boundaryBytes = BOUNDARY.getBytes(UTF_8); + this.twoDashBytes = TWO_DASH.getBytes(UTF_8); + this.atBytes = "&".getBytes(UTF_8); + this.eqBytes = "=".getBytes(UTF_8); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + } + } + + public void encode(Object object, Type bodyType, RequestTemplate template) throws EncodeException { + if (object instanceof Map) { + try { + encodeFormParams(template, (Map) object); + } catch (IOException e) { + throw new EncodeException("Failed to create request", e); + } + } else { + delegate.encode(object, bodyType, template); + } + } + + private void encodeFormParams(RequestTemplate template, Map formParams) throws IOException { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + + boolean isMultiPart = isMultiPart(formParams); + boolean isFirstField = true; + for (Map.Entry param : formParams.entrySet()) { + String keyStr = param.getKey(); + if (param.getValue() instanceof File) { + addFilePart(baos, keyStr, (File) param.getValue()); + } else { + String valueStr = parameterToString(param.getValue()); + if (isMultiPart) { + addMultiPartFormField(baos, keyStr, valueStr); + } else { + addEncodedFormField(baos, keyStr, valueStr, isFirstField); + isFirstField = false; + } + } + } + + if (isMultiPart) { + baos.write(lineFeedBytes); + baos.write(twoDashBytes); + baos.write(boundaryBytes); + baos.write(twoDashBytes); + baos.write(lineFeedBytes); + } + + String contentType = isMultiPart ? "multipart/form-data; boundary=" + BOUNDARY : "application/x-www-form-urlencoded"; + template.header("Content-type"); + template.header("Content-type", contentType); + template.header("MIME-Version", "1.0"); + template.body(baos.toByteArray(), Charset.forName(UTF_8)); + } + + /* + * Currently only supports text files + */ + private void addFilePart(ByteArrayOutputStream baos, String fieldName, File uploadFile) throws IOException { + String fileName = uploadFile.getName(); + baos.write(twoDashBytes); + baos.write(boundaryBytes); + baos.write(lineFeedBytes); + + String contentDisposition = "Content-Disposition: form-data; name=\"" + fieldName + + "\"; filename=\"" + fileName + "\""; + baos.write(contentDisposition.getBytes(UTF_8)); + baos.write(lineFeedBytes); + String contentType = "Content-Type: " + URLConnection.guessContentTypeFromName(fileName); + baos.write(contentType.getBytes(UTF_8)); + baos.write(lineFeedBytes); + baos.write(lineFeedBytes); + + BufferedReader reader = new BufferedReader(new FileReader(uploadFile)); + InputStream input = new FileInputStream(uploadFile); + byte[] bytes = new byte[4096]; + int len = bytes.length; + while ((len = input.read(bytes)) != -1) { + baos.write(bytes, 0, len); + baos.write(lineFeedBytes); + } + + baos.write(lineFeedBytes); + } + + private void addEncodedFormField(ByteArrayOutputStream baos, String name, String value, boolean isFirstField) throws IOException { + if (!isFirstField) { + baos.write(atBytes); + } + + String encodedName = URLEncoder.encode(name, UTF_8); + String encodedValue = URLEncoder.encode(value, UTF_8); + baos.write(encodedName.getBytes(UTF_8)); + baos.write("=".getBytes(UTF_8)); + baos.write(encodedValue.getBytes(UTF_8)); + } + + private void addMultiPartFormField(ByteArrayOutputStream baos, String name, String value) throws IOException { + baos.write(twoDashBytes); + baos.write(boundaryBytes); + baos.write(lineFeedBytes); + + String contentDisposition = "Content-Disposition: form-data; name=\"" + name + "\""; + String contentType = "Content-Type: text/plain; charset=utf-8"; + + baos.write(contentDisposition.getBytes(UTF_8)); + baos.write(lineFeedBytes); + baos.write(contentType.getBytes(UTF_8)); + baos.write(lineFeedBytes); + baos.write(lineFeedBytes); + baos.write(value.getBytes(UTF_8)); + baos.write(lineFeedBytes); + } + + private boolean isMultiPart(Map formParams) { + boolean isMultiPart = false; + for (Map.Entry entry : formParams.entrySet()) { + if (entry.getValue() instanceof File) { + isMultiPart = true; + break; + } + } + return isMultiPart; + } + + /** + * Format the given parameter object into string. + */ + public String parameterToString(Object param) { + if (param == null) { + return ""; + } else if (param instanceof Date) { + return formatDate((Date) param); + } else if (param instanceof Collection) { + StringBuilder b = new StringBuilder(); + for(Object o : (Collection)param) { + if(b.length() > 0) { + b.append(","); + } + b.append(String.valueOf(o)); + } + return b.toString(); + } else { + return String.valueOf(param); + } + } + + /** + * Format the given Date object into string. + */ + public String formatDate(Date date) { + return dateFormat.format(date); + } +} 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 new file mode 100644 index 00000000000..729320bd2e5 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/api.mustache @@ -0,0 +1,32 @@ +package {{package}}; + +import {{invokerPackage}}.ApiClient; + +{{#imports}}import {{import}}; +{{/imports}} + +{{^fullJavaUtil}}import java.util.*; +{{/fullJavaUtil}} +import feign.*; + +{{>generatedAnnotation}} +public interface {{classname}} extends ApiClient.Api { + +{{#operations}}{{#operation}} + /** + * {{summary}} + * {{notes}} +{{#allParams}} * @param {{paramName}} {{description}} +{{/allParams}} * @return {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} + */ + @RequestLine("{{httpMethod}} {{{path}}}{{#hasQueryParams}}?{{/hasQueryParams}}{{#queryParams}}{{paramName}}={{=<% %>=}}{<%paramName%>}<%={{ }}=%>{{#hasMore}}&{{/hasMore}}{{/queryParams}}") + @Headers({ + "Content-type: {{vendorExtensions.x-contentType}}", + "Accepts: {{vendorExtensions.x-accepts}}",{{#headerParams}} + "{{paramName}}: {{=<% %>=}}{<%paramName%>}<%={{ }}=%>"{{#hasMore}}, + {{/hasMore}}{{/headerParams}} + }) + {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}}{{nickname}}({{#allParams}}{{^isBodyParam}}@Param("{{paramName}}") {{/isBodyParam}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); + {{/operation}} +{{/operations}} +} diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/feign/build.gradle.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/build.gradle.mustache new file mode 100644 index 00000000000..a528180df28 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/build.gradle.mustache @@ -0,0 +1,113 @@ +group = '{{groupId}}' +version = '{{artifactVersion}}' + +buildscript { + repositories { + jcenter() + } + dependencies { + classpath 'com.android.tools.build:gradle:1.2.2' + classpath 'com.github.dcendents:android-maven-plugin:1.2' + } +} + +repositories { + jcenter() +} + + +if(hasProperty('target') && target == 'android') { + + apply plugin: 'com.android.library' + apply plugin: 'com.github.dcendents.android-maven' + + android { + compileSdkVersion 22 + buildToolsVersion '22.0.0' + defaultConfig { + minSdkVersion 14 + targetSdkVersion 22 + } + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_7 + targetCompatibility JavaVersion.VERSION_1_7 + } + + // Rename the aar correctly + libraryVariants.all { variant -> + variant.outputs.each { output -> + def outputFile = output.outputFile + if (outputFile != null && outputFile.name.endsWith('.aar')) { + def fileName = "${project.name}-${variant.baseName}-${version}.aar" + output.outputFile = new File(outputFile.parent, fileName) + } + } + } + + dependencies { + provided 'javax.annotation:jsr250-api:1.0' + } + } + + afterEvaluate { + android.libraryVariants.all { variant -> + def task = project.tasks.create "jar${variant.name.capitalize()}", Jar + task.description = "Create jar artifact for ${variant.name}" + task.dependsOn variant.javaCompile + task.from variant.javaCompile.destinationDir + task.destinationDir = project.file("${project.buildDir}/outputs/jar") + task.archiveName = "${project.name}-${variant.baseName}-${version}.jar" + artifacts.add('archives', task); + } + } + + task sourcesJar(type: Jar) { + from android.sourceSets.main.java.srcDirs + classifier = 'sources' + } + + artifacts { + archives sourcesJar + } + +} else { + + apply plugin: 'java' + apply plugin: 'maven' + + sourceCompatibility = JavaVersion.VERSION_1_7 + targetCompatibility = JavaVersion.VERSION_1_7 + + install { + repositories.mavenInstaller { + pom.artifactId = '{{artifactId}}' + } + } + + task execute(type:JavaExec) { + main = System.getProperty('mainClass') + classpath = sourceSets.main.runtimeClasspath + } +} + +ext { + swagger_annotations_version = "1.5.0" + jackson_version = "2.6.3" + feign_version = "8.1.1" + jodatime_version = "2.5" + junit_version = "4.12" +} + +dependencies { + compile "io.swagger:swagger-annotations:$swagger_annotations_version" + compile "com.netflix.feign:feign-core:$feign_version" + compile "com.netflix.feign:feign-jackson:$feign_version" + compile "com.netflix.feign:feign-slf4j:$feign_version" + compile "com.fasterxml.jackson.core:jackson-core:$jackson_version" + compile "com.fasterxml.jackson.core:jackson-annotations:$jackson_version" + compile "com.fasterxml.jackson.core:jackson-databind:$jackson_version" + compile "com.fasterxml.jackson.datatype:jackson-datatype-joda:2.1.5" + compile "joda-time:joda-time:$jodatime_version" + compile "com.brsanthu:migbase64:2.2" + testCompile "junit:junit:$junit_version" +} 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 new file mode 100644 index 00000000000..e8069b82931 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/pom.mustache @@ -0,0 +1,183 @@ + + 4.0.0 + {{groupId}} + {{artifactId}} + jar + {{artifactId}} + {{artifactVersion}} + + scm:git:git@github.com:swagger-api/swagger-mustache.git + scm:git:git@github.com:swagger-api/swagger-codegen.git + https://github.com/swagger-api/swagger-codegen + + + 2.2.0 + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.12 + + + + loggerPath + conf/log4j.properties + + + -Xms512m -Xmx1500m + methods + pertest + + + + maven-dependency-plugin + + + package + + copy-dependencies + + + ${project.build.directory}/lib + + + + + + + + org.apache.maven.plugins + maven-jar-plugin + 2.2 + + + + jar + test-jar + + + + + + + + + org.codehaus.mojo + build-helper-maven-plugin + + + add_sources + generate-sources + + add-source + + + + src/main/java + + + + + add_test_sources + generate-test-sources + + add-test-source + + + + src/test/java + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 2.3.2 + + 1.6 + 1.6 + + + + + + + io.swagger + swagger-annotations + ${swagger-annotations-version} + + + + + com.netflix.feign + feign-core + ${feign-version} + + + com.netflix.feign + feign-jackson + ${feign-version} + + + com.netflix.feign + feign-slf4j + ${feign-version} + + + + + com.fasterxml.jackson.core + jackson-core + ${jackson-version} + + + com.fasterxml.jackson.core + jackson-annotations + ${jackson-version} + + + com.fasterxml.jackson.core + jackson-databind + ${jackson-version} + + + com.fasterxml.jackson.datatype + jackson-datatype-joda + 2.1.5 + + + joda-time + joda-time + ${jodatime-version} + + + + + com.brsanthu + migbase64 + 2.2 + + + + + junit + junit + ${junit-version} + test + + + + 1.5.0 + 8.1.1 + 2.6.3 + 2.5 + 4.12 + 1.0.0 + + diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/ApiClient.mustache index bd64a6fe659..f482b8c34d4 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 @@ -6,6 +6,7 @@ import javax.ws.rs.client.Entity; import javax.ws.rs.client.Invocation; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.Form; +import javax.ws.rs.core.GenericType; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; @@ -13,10 +14,9 @@ import javax.ws.rs.core.Response.Status; import org.glassfish.jersey.client.ClientConfig; import org.glassfish.jersey.filter.LoggingFilter; import org.glassfish.jersey.media.multipart.FormDataBodyPart; -import org.glassfish.jersey.media.multipart.FormDataMultiPart; +import org.glassfish.jersey.media.multipart.FormDataContentDisposition; import org.glassfish.jersey.media.multipart.MultiPart; import org.glassfish.jersey.media.multipart.MultiPartFeature; -import org.glassfish.jersey.media.multipart.file.FileDataBodyPart; import java.util.Collection; import java.util.Collections; @@ -30,13 +30,11 @@ import java.util.TimeZone; import java.net.URLEncoder; -import java.io.IOException; import java.io.File; import java.io.UnsupportedEncodingException; import java.text.DateFormat; import java.text.SimpleDateFormat; -import java.text.ParseException; import {{invokerPackage}}.auth.Authentication; import {{invokerPackage}}.auth.HttpBasicAuth; @@ -345,6 +343,17 @@ public class ApiClient { return params; } + /** + * Check if the given MIME is a JSON MIME. + * JSON MIME examples: + * application/json + * application/json; charset=UTF8 + * APPLICATION/JSON + */ + public boolean isJsonMime(String mime) { + return mime != null && mime.matches("(?i)application\\/json(;.*)?"); + } + /** * Select the Accept header's value from the given accepts array: * if JSON exists in the given array, use it; @@ -355,8 +364,14 @@ public class ApiClient { * null will be returned (not to set the Accept header explicitly). */ public String selectHeaderAccept(String[] accepts) { - if (accepts.length == 0) return null; - if (StringUtil.containsIgnoreCase(accepts, "application/json")) return "application/json"; + if (accepts.length == 0) { + return null; + } + for (String accept : accepts) { + if (isJsonMime(accept)) { + return accept; + } + } return StringUtil.join(accepts, ","); } @@ -370,8 +385,14 @@ public class ApiClient { * JSON will be used. */ public String selectHeaderContentType(String[] contentTypes) { - if (contentTypes.length == 0) return "application/json"; - if (StringUtil.containsIgnoreCase(contentTypes, "application/json")) return "application/json"; + if (contentTypes.length == 0) { + return "application/json"; + } + for (String contentType : contentTypes) { + if (isJsonMime(contentType)) { + return contentType; + } + } return contentTypes[0]; } @@ -390,18 +411,39 @@ public class ApiClient { * Serialize the given Java object into string entity according the given * Content-Type (only JSON is supported for now). */ - public Entity serialize(Object obj, String contentType) throws ApiException { - if (contentType.startsWith("application/json")) { - return Entity.json(json.serialize(obj)); + public Entity serialize(Object obj, Map formParams, String contentType) throws ApiException { + Entity entity = null; + if (contentType.startsWith("multipart/form-data")) { + MultiPart multiPart = new MultiPart(); + for (Entry param: formParams.entrySet()) { + if (param.getValue() instanceof File) { + File file = (File) param.getValue(); + FormDataContentDisposition contentDisp = FormDataContentDisposition.name(param.getKey()) + .fileName(file.getName()).size(file.length()).build(); + multiPart.bodyPart(new FormDataBodyPart(contentDisp, file, MediaType.APPLICATION_OCTET_STREAM_TYPE)); + } else { + FormDataContentDisposition contentDisp = FormDataContentDisposition.name(param.getKey()).build(); + multiPart.bodyPart(new FormDataBodyPart(contentDisp, parameterToString(param.getValue()))); + } + } + entity = Entity.entity(multiPart, MediaType.MULTIPART_FORM_DATA_TYPE); + } else if (contentType.startsWith("application/x-www-form-urlencoded")) { + Form form = new Form(); + for (Entry param: formParams.entrySet()) { + form.param(param.getKey(), parameterToString(param.getValue())); + } + entity = Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE); } else { - throw new ApiException(400, "can not serialize object into Content-Type: " + contentType); + // We let jersey handle the serialization + entity = Entity.entity(obj, contentType); } + return entity; } /** * Deserialize response body to Java object according to the Content-Type. */ - public T deserialize(Response response, TypeRef returnType) throws ApiException { + public T deserialize(Response response, GenericType returnType) throws ApiException { String contentType = null; List contentTypes = response.getHeaders().get("Content-Type"); if (contentTypes != null && !contentTypes.isEmpty()) @@ -409,24 +451,7 @@ public class ApiClient { if (contentType == null) throw new ApiException(500, "missing Content-Type in response"); - String body; - if (response.hasEntity()) - body = (String) response.readEntity(String.class); - else - body = ""; - - if (contentType.startsWith("application/json")) { - return json.deserialize(body, returnType); - } else if (returnType.getType().equals(String.class)) { - // Expecting string, return the raw response body. - return (T) body; - } else { - throw new ApiException( - 500, - "Content type \"" + contentType + "\" is not supported for type: " - + returnType.getType() - ); - } + return response.readEntity(returnType); } /** @@ -444,7 +469,7 @@ public class ApiClient { * @param returnType The return type into which to deserialize the response * @return The response body in type of string */ - public T invokeAPI(String path, String method, List queryParams, Object body, Map headerParams, Map formParams, String accept, String contentType, String[] authNames, TypeRef returnType) throws ApiException { + public T invokeAPI(String path, String method, List queryParams, Object body, Map headerParams, Map formParams, String accept, String contentType, String[] authNames, GenericType returnType) throws ApiException { updateParamsForAuth(authNames, queryParams, headerParams); WebTarget target = client.target(this.basePath).path(path); @@ -475,54 +500,16 @@ public class ApiClient { } } - Entity formEntity = null; - - if (contentType.startsWith("multipart/form-data")) { - MultiPart multipart = new MultiPart(); - for (Entry param: formParams.entrySet()) { - if (param.getValue() instanceof File) { - File file = (File) param.getValue(); - - FormDataMultiPart mp = new FormDataMultiPart(); - mp.bodyPart(new FormDataBodyPart(param.getKey(), file.getName())); - multipart.bodyPart(mp, MediaType.MULTIPART_FORM_DATA_TYPE); - - multipart.bodyPart(new FileDataBodyPart(param.getKey(), file, MediaType.APPLICATION_OCTET_STREAM_TYPE)); - } else { - FormDataMultiPart mp = new FormDataMultiPart(); - mp.bodyPart(new FormDataBodyPart(param.getKey(), parameterToString(param.getValue()))); - multipart.bodyPart(mp, MediaType.MULTIPART_FORM_DATA_TYPE); - } - } - formEntity = Entity.entity(multipart, MediaType.MULTIPART_FORM_DATA_TYPE); - } else if (contentType.startsWith("application/x-www-form-urlencoded")) { - Form form = new Form(); - for (Entry param: formParams.entrySet()) { - form.param(param.getKey(), parameterToString(param.getValue())); - } - formEntity = Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE); - } + Entity entity = serialize(body, formParams, contentType); Response response = null; if ("GET".equals(method)) { response = invocationBuilder.get(); } else if ("POST".equals(method)) { - if (formEntity != null) { - response = invocationBuilder.post(formEntity); - } else if (body == null) { - response = invocationBuilder.post(null); - } else { - response = invocationBuilder.post(serialize(body, contentType)); - } + response = invocationBuilder.post(entity); } else if ("PUT".equals(method)) { - if (formEntity != null) { - response = invocationBuilder.put(formEntity); - } else if (body == null) { - response = invocationBuilder.put(null); - } else { - response = invocationBuilder.put(serialize(body, contentType)); - } + response = invocationBuilder.put(entity); } else if ("DELETE".equals(method)) { response = invocationBuilder.delete(); } else { @@ -561,6 +548,8 @@ public class ApiClient { private void buildClient() { final ClientConfig clientConfig = new ClientConfig(); clientConfig.register(MultiPartFeature.class); + clientConfig.register(json); + clientConfig.register(org.glassfish.jersey.jackson.JacksonFeature.class); if (debugging) { clientConfig.register(LoggingFilter.class); } diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/JSON.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/JSON.mustache new file mode 100644 index 00000000000..cc3f1baba14 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/JSON.mustache @@ -0,0 +1,36 @@ +package {{invokerPackage}}; + +import com.fasterxml.jackson.annotation.*; +import com.fasterxml.jackson.databind.*; +import com.fasterxml.jackson.datatype.joda.*; + +import java.text.DateFormat; + +import javax.ws.rs.ext.ContextResolver; + +{{>generatedAnnotation}} +public class JSON implements ContextResolver { + private ObjectMapper mapper; + + public JSON() { + mapper = new ObjectMapper(); + mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); + mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING); + mapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING); + mapper.registerModule(new JodaModule()); + } + + /** + * Set the date format for JSON (de)serialization with Date properties. + */ + public void setDateFormat(DateFormat dateFormat) { + mapper.setDateFormat(dateFormat); + } + + @Override + public ObjectMapper getContext(Class type) { + return mapper; + } +} diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/api.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/api.mustache index 10f2fa2f744..f9572359ded 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 @@ -4,7 +4,8 @@ import {{invokerPackage}}.ApiException; import {{invokerPackage}}.ApiClient; import {{invokerPackage}}.Configuration; import {{invokerPackage}}.Pair; -import {{invokerPackage}}.TypeRef; + +import javax.ws.rs.core.GenericType; {{#imports}}import {{import}}; {{/imports}} @@ -41,12 +42,12 @@ public class {{classname}} { {{#allParams}} * @param {{paramName}} {{description}} {{/allParams}} * @return {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} */ - public {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}}{{nickname}} ({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) throws ApiException { + public {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}}{{operationId}}({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) throws ApiException { Object {{localVariablePrefix}}postBody = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}}; {{#allParams}}{{#required}} // verify the required parameter '{{paramName}}' is set if ({{paramName}} == null) { - throw new ApiException(400, "Missing the required parameter '{{paramName}}' when calling {{nickname}}"); + throw new ApiException(400, "Missing the required parameter '{{paramName}}' when calling {{operationId}}"); } {{/required}}{{/allParams}} // create path and map variables @@ -83,7 +84,7 @@ public class {{classname}} { String[] {{localVariablePrefix}}authNames = new String[] { {{#authMethods}}"{{name}}"{{#hasMore}}, {{/hasMore}}{{/authMethods}} }; {{#returnType}} - TypeRef {{localVariablePrefix}}returnType = new TypeRef<{{{returnType}}}>() {}; + GenericType<{{{returnType}}}> {{localVariablePrefix}}returnType = new GenericType<{{{returnType}}}>() {}; return {{localVariablePrefix}}apiClient.invokeAPI({{localVariablePrefix}}path, "{{httpMethod}}", {{localVariablePrefix}}queryParams, {{localVariablePrefix}}postBody, {{localVariablePrefix}}headerParams, {{localVariablePrefix}}formParams, {{localVariablePrefix}}accept, {{localVariablePrefix}}contentType, {{localVariablePrefix}}authNames, {{localVariablePrefix}}returnType); {{/returnType}}{{^returnType}} {{localVariablePrefix}}apiClient.invokeAPI({{localVariablePrefix}}path, "{{httpMethod}}", {{localVariablePrefix}}queryParams, {{localVariablePrefix}}postBody, {{localVariablePrefix}}headerParams, {{localVariablePrefix}}formParams, {{localVariablePrefix}}accept, {{localVariablePrefix}}contentType, {{localVariablePrefix}}authNames, null); 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 dbe0138aa54..76f2164a1ad 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 @@ -124,7 +124,12 @@ jersey-media-multipart ${jersey-version} - + + org.glassfish.jersey.media + jersey-media-json-jackson + 2.22.1 + + com.fasterxml.jackson.core diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ApiCallback.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ApiCallback.mustache index 6eee875bdcc..bfc1aedbc11 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ApiCallback.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ApiCallback.mustache @@ -28,4 +28,22 @@ public interface ApiCallback { * @param responseHeaders Headers of the response */ void onSuccess(T result, int statusCode, Map> responseHeaders); + + /** + * This is called when the API upload processing. + * + * @param bytesWritten bytes Written + * @param contentLength content length of request body + * @param done write end + */ + void onUploadProgress(long bytesWritten, long contentLength, boolean done); + + /** + * This is called when the API downlond processing. + * + * @param bytesRead bytes Read + * @param contentLength content lenngth of the response + * @param done Read end + */ + void onDownloadProgress(long bytesRead, long contentLength, boolean done); } diff --git a/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 8ce2407cbe3..99dcdb51780 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 @@ -104,9 +104,6 @@ public class ApiClient { private Map authentications; - private int statusCode; - private Map> responseHeaders; - private DateFormat dateFormat; private DateFormat datetimeFormat; private boolean lenientDatetimeFormat; @@ -177,24 +174,6 @@ public class ApiClient { return this; } - /** - * Gets the status code of the previous request. - * NOTE: Status code of last async response is not recorded here, it is - * passed to the callback methods instead. - */ - public int getStatusCode() { - return statusCode; - } - - /** - * Gets the response headers of the previous request. - * NOTE: Headers of last async response is not recorded here, it is passed - * to callback methods instead. - */ - public Map> getResponseHeaders() { - return responseHeaders; - } - public boolean isVerifyingSsl() { return verifyingSsl; } @@ -570,6 +549,17 @@ public class ApiClient { return params; } + /** + * Check if the given MIME is a JSON MIME. + * JSON MIME examples: + * application/json + * application/json; charset=UTF8 + * APPLICATION/JSON + */ + public boolean isJsonMime(String mime) { + return mime != null && mime.matches("(?i)application\\/json(;.*)?"); + } + /** * Select the Accept header's value from the given accepts array: * if JSON exists in the given array, use it; @@ -580,8 +570,14 @@ public class ApiClient { * null will be returned (not to set the Accept header explicitly). */ public String selectHeaderAccept(String[] accepts) { - if (accepts.length == 0) return null; - if (StringUtil.containsIgnoreCase(accepts, "application/json")) return "application/json"; + if (accepts.length == 0) { + return null; + } + for (String accept : accepts) { + if (isJsonMime(accept)) { + return accept; + } + } return StringUtil.join(accepts, ","); } @@ -595,8 +591,14 @@ public class ApiClient { * JSON will be used. */ public String selectHeaderContentType(String[] contentTypes) { - if (contentTypes.length == 0) return "application/json"; - if (StringUtil.containsIgnoreCase(contentTypes, "application/json")) return "application/json"; + if (contentTypes.length == 0) { + return "application/json"; + } + for (String contentType : contentTypes) { + if (isJsonMime(contentType)) { + return contentType; + } + } return contentTypes[0]; } @@ -618,6 +620,8 @@ public class ApiClient { * @param response HTTP response * @param returnType The type of the Java object * @return The deserialized Java object + * @throws ApiException If fail to deserialize response body, i.e. cannot read response body + * or the Content-Type of the response is not supported. */ public T deserialize(Response response, Type returnType) throws ApiException { if (response == null || returnType == null) @@ -645,7 +649,7 @@ public class ApiClient { // ensuring a default content type contentType = "application/json"; } - if (contentType.startsWith("application/json")) { + if (isJsonMime(contentType)) { return json.deserialize(respBody, returnType); } else if (returnType.equals(String.class)) { // Expecting string, return the raw response body. @@ -666,9 +670,10 @@ public class ApiClient { * @param obj The Java object * @param contentType The request Content-Type * @return The serialized string + * @throws ApiException If fail to serialize the given object */ public String serialize(Object obj, String contentType) throws ApiException { - if (contentType.startsWith("application/json")) { + if (isJsonMime(contentType)) { if (obj != null) return json.serialize(obj); else @@ -680,6 +685,7 @@ public class ApiClient { /** * Download file from the given response. + * @throws ApiException If fail to read file content from response and write to disk */ public File downloadFileFromResponse(Response response) throws ApiException { try { @@ -731,7 +737,7 @@ public class ApiClient { /** * @see #execute(Call, Type) */ - public T execute(Call call) throws ApiException { + public ApiResponse execute(Call call) throws ApiException { return execute(call, null); } @@ -740,14 +746,16 @@ public class ApiClient { * * @param returnType The return type used to deserialize HTTP response body * @param The return type corresponding to (same with) returnType - * @return The Java object deserialized from response body. Returns null if returnType is null. + * @return ApiResponse object containing response status, headers and + * data, which is a Java object deserialized from response body and would be null + * when returnType is null. + * @throws ApiException If fail to execute the call */ - public T execute(Call call, Type returnType) throws ApiException { + public ApiResponse execute(Call call, Type returnType) throws ApiException { try { Response response = call.execute(); - this.statusCode = response.code(); - this.responseHeaders = response.headers().toMultimap(); - return handleResponse(response, returnType); + T data = handleResponse(response, returnType); + return new ApiResponse(response.code(), response.headers().toMultimap(), data); } catch (IOException e) { throw new ApiException(e); } @@ -756,7 +764,7 @@ public class ApiClient { /** * #see executeAsync(Call, Type, ApiCallback) */ - public void executeAsync(Call call, ApiCallback callback) throws ApiException { + public void executeAsync(Call call, ApiCallback callback) { executeAsync(call, null, callback); } @@ -787,6 +795,12 @@ public class ApiClient { }); } + /** + * Handle the given response, return the deserialized object when the response is successful. + * + * @throws ApiException If the response has a unsuccessful status code or + * fail to deserialize the response body + */ public T handleResponse(Response response, Type returnType) throws ApiException { if (response.isSuccessful()) { if (returnType == null || response.code() == 204) { @@ -820,8 +834,9 @@ public class ApiClient { * @param formParams The form parameters * @param authNames The authentications to apply * @return The HTTP call + * @throws ApiException If fail to serialize the request body object */ - public Call buildCall(String path, String method, List queryParams, Object body, Map headerParams, Map formParams, String[] authNames) throws ApiException { + public Call buildCall(String path, String method, List queryParams, Object body, Map headerParams, Map formParams, String[] authNames, ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { updateParamsForAuth(authNames, queryParams, headerParams); final String url = buildUrl(path, queryParams); @@ -830,7 +845,9 @@ public class ApiClient { String contentType = (String) headerParams.get("Content-Type"); // ensuring a default content type - if (contentType == null) contentType = "application/json"; + if (contentType == null) { + contentType = "application/json"; + } RequestBody reqBody; if (!HttpMethod.permitsRequestBody(method)) { @@ -851,7 +868,15 @@ public class ApiClient { reqBody = RequestBody.create(MediaType.parse(contentType), serialize(body, contentType)); } - Request request = reqBuilder.method(method, reqBody).build(); + Request request = null; + + if(progressRequestListener != null && reqBody != null) { + ProgressRequestBody progressRequestBody = new ProgressRequestBody(reqBody, progressRequestListener); + request = reqBuilder.method(method, progressRequestBody).build(); + } else { + request = reqBuilder.method(method, reqBody).build(); + } + return httpClient.newCall(request); } diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ApiResponse.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ApiResponse.mustache new file mode 100644 index 00000000000..452f4e1e982 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ApiResponse.mustache @@ -0,0 +1,46 @@ +package {{invokerPackage}}; + +import java.util.List; +import java.util.Map; + +/** + * API response returned by API call. + * + * @param T The type of data that is deserialized from response body + */ +public class ApiResponse { + final private int statusCode; + final private Map> headers; + final private T data; + + /** + * @param statusCode The status code of HTTP response + * @param headers The headers of HTTP response + */ + public ApiResponse(int statusCode, Map> headers) { + this(statusCode, headers, null); + } + + /** + * @param statusCode The status code of HTTP response + * @param headers The headers of HTTP response + * @param data The object deserialized from response bod + */ + public ApiResponse(int statusCode, Map> headers, T data) { + this.statusCode = statusCode; + this.headers = headers; + this.data = data; + } + + public int getStatusCode() { + return statusCode; + } + + public Map> getHeaders() { + return headers; + } + + public T getData() { + return data; + } +} diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ProgressRequestBody.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ProgressRequestBody.mustache new file mode 100644 index 00000000000..57931ef4cfc --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ProgressRequestBody.mustache @@ -0,0 +1,70 @@ +package {{invokerPackage}}; + +import com.squareup.okhttp.MediaType; +import com.squareup.okhttp.RequestBody; + +import java.io.IOException; + +import okio.Buffer; +import okio.BufferedSink; +import okio.ForwardingSink; +import okio.Okio; +import okio.Sink; + +public class ProgressRequestBody extends RequestBody { + + public interface ProgressRequestListener { + void onRequestProgress(long bytesWritten, long contentLength, boolean done); + } + + private final RequestBody requestBody; + + private final ProgressRequestListener progressListener; + + private BufferedSink bufferedSink; + + public ProgressRequestBody(RequestBody requestBody, ProgressRequestListener progressListener) { + this.requestBody = requestBody; + this.progressListener = progressListener; + } + + @Override + public MediaType contentType() { + return requestBody.contentType(); + } + + @Override + public long contentLength() throws IOException { + return requestBody.contentLength(); + } + + @Override + public void writeTo(BufferedSink sink) throws IOException { + if (bufferedSink == null) { + bufferedSink = Okio.buffer(sink(sink)); + } + + requestBody.writeTo(bufferedSink); + bufferedSink.flush(); + + } + + private Sink sink(Sink sink) { + return new ForwardingSink(sink) { + + long bytesWritten = 0L; + long contentLength = 0L; + + @Override + public void write(Buffer source, long byteCount) throws IOException { + super.write(source, byteCount); + if (contentLength == 0) { + contentLength = contentLength(); + } + + bytesWritten += byteCount; + progressListener.onRequestProgress(bytesWritten, contentLength, bytesWritten == contentLength); + } + }; + } +} diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ProgressResponseBody.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ProgressResponseBody.mustache new file mode 100644 index 00000000000..061a95ac299 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ProgressResponseBody.mustache @@ -0,0 +1,63 @@ +package {{invokerPackage}}; + +import com.squareup.okhttp.MediaType; +import com.squareup.okhttp.ResponseBody; + +import java.io.IOException; + +import okio.Buffer; +import okio.BufferedSource; +import okio.ForwardingSource; +import okio.Okio; +import okio.Source; + +public class ProgressResponseBody extends ResponseBody { + + public interface ProgressListener { + void update(long bytesRead, long contentLength, boolean done); + } + + private final ResponseBody responseBody; + private final ProgressListener progressListener; + private BufferedSource bufferedSource; + + public ProgressResponseBody(ResponseBody responseBody, ProgressListener progressListener) { + this.responseBody = responseBody; + this.progressListener = progressListener; + } + + @Override + public MediaType contentType() { + return responseBody.contentType(); + } + + @Override + public long contentLength() throws IOException { + return responseBody.contentLength(); + } + + @Override + public BufferedSource source() throws IOException { + if (bufferedSource == null) { + bufferedSource = Okio.buffer(source(responseBody.source())); + } + return bufferedSource; + } + + private Source source(Source source) { + return new ForwardingSource(source) { + long totalBytesRead = 0L; + + @Override + public long read(Buffer sink, long byteCount) throws IOException { + long bytesRead = super.read(sink, byteCount); + // read() returns the number of bytes read, or -1 if this source is exhausted. + totalBytesRead += bytesRead != -1 ? bytesRead : 0; + progressListener.update(totalBytesRead, responseBody.contentLength(), bytesRead == -1); + return bytesRead; + } + }; + } +} + + diff --git a/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 efb1a14f27d..e760f4a370e 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 @@ -3,12 +3,19 @@ package {{package}}; import {{invokerPackage}}.ApiCallback; import {{invokerPackage}}.ApiClient; import {{invokerPackage}}.ApiException; +import {{invokerPackage}}.ApiResponse; import {{invokerPackage}}.Configuration; import {{invokerPackage}}.Pair; +import {{invokerPackage}}.ProgressRequestBody; +import {{invokerPackage}}.ProgressResponseBody; import com.google.gson.reflect.TypeToken; import com.squareup.okhttp.Call; +import com.squareup.okhttp.Interceptor; +import com.squareup.okhttp.Response; + +import java.io.IOException; {{#imports}}import {{import}}; {{/imports}} @@ -39,13 +46,13 @@ public class {{classname}} { } {{#operation}} - /* Build call for {{nickname}} */ - private Call {{nickname}}Call({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) throws ApiException { + /* Build call for {{operationId}} */ + private Call {{operationId}}Call({{#allParams}}{{{dataType}}} {{paramName}}, {{/allParams}}final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object {{localVariablePrefix}}postBody = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}}; {{#allParams}}{{#required}} // verify the required parameter '{{paramName}}' is set if ({{paramName}} == null) { - throw new ApiException("Missing the required parameter '{{paramName}}' when calling {{nickname}}(Async)"); + throw new ApiException("Missing the required parameter '{{paramName}}' when calling {{operationId}}(Async)"); } {{/required}}{{/allParams}} @@ -77,8 +84,20 @@ public class {{classname}} { final String {{localVariablePrefix}}contentType = {{localVariablePrefix}}apiClient.selectHeaderContentType({{localVariablePrefix}}contentTypes); {{localVariablePrefix}}headerParams.put("Content-Type", {{localVariablePrefix}}contentType); + 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[] {{localVariablePrefix}}authNames = new String[] { {{#authMethods}}"{{name}}"{{#hasMore}}, {{/hasMore}}{{/authMethods}} }; - return {{localVariablePrefix}}apiClient.buildCall({{localVariablePrefix}}path, "{{httpMethod}}", {{localVariablePrefix}}queryParams, {{localVariablePrefix}}postBody, {{localVariablePrefix}}headerParams, {{localVariablePrefix}}formParams, {{localVariablePrefix}}authNames); + return {{localVariablePrefix}}apiClient.buildCall({{localVariablePrefix}}path, "{{httpMethod}}", {{localVariablePrefix}}queryParams, {{localVariablePrefix}}postBody, {{localVariablePrefix}}headerParams, {{localVariablePrefix}}formParams, {{localVariablePrefix}}authNames, progressRequestListener); } /** @@ -86,11 +105,24 @@ public class {{classname}} { * {{notes}}{{#allParams}} * @param {{paramName}} {{description}}{{/allParams}}{{#returnType}} * @return {{{returnType}}}{{/returnType}} + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ - public {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}}{{nickname}}({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) throws ApiException { - Call {{localVariablePrefix}}call = {{nickname}}Call({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); + public {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}}{{operationId}}({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) throws ApiException { + {{#returnType}}ApiResponse<{{{returnType}}}> {{localVariablePrefix}}resp = {{/returnType}}{{operationId}}WithHttpInfo({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}});{{#returnType}} + return {{localVariablePrefix}}resp.getData();{{/returnType}} + } + + /** + * {{summary}} + * {{notes}}{{#allParams}} + * @param {{paramName}} {{description}}{{/allParams}} + * @return ApiResponse<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> {{operationId}}WithHttpInfo({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) throws ApiException { + Call {{localVariablePrefix}}call = {{operationId}}Call({{#allParams}}{{paramName}}, {{/allParams}}null, null); {{#returnType}}Type {{localVariablePrefix}}returnType = new TypeToken<{{{returnType}}}>(){}.getType(); - return {{localVariablePrefix}}apiClient.execute({{localVariablePrefix}}call, {{localVariablePrefix}}returnType);{{/returnType}}{{^returnType}}{{localVariablePrefix}}apiClient.execute({{localVariablePrefix}}call);{{/returnType}} + return {{localVariablePrefix}}apiClient.execute({{localVariablePrefix}}call, {{localVariablePrefix}}returnType);{{/returnType}}{{^returnType}}return {{localVariablePrefix}}apiClient.execute({{localVariablePrefix}}call);{{/returnType}} } /** @@ -99,9 +131,30 @@ public class {{classname}} { * @param {{paramName}} {{description}}{{/allParams}} * @param callback The callback to be executed when the API call finishes * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object */ - public Call {{nickname}}Async({{#allParams}}{{{dataType}}} {{paramName}}, {{/allParams}}ApiCallback<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> {{localVariablePrefix}}callback) throws ApiException { - Call {{localVariablePrefix}}call = {{nickname}}Call({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); + public Call {{operationId}}Async({{#allParams}}{{{dataType}}} {{paramName}}, {{/allParams}}final ApiCallback<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> {{localVariablePrefix}}callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + Call {{localVariablePrefix}}call = {{operationId}}Call({{#allParams}}{{paramName}}, {{/allParams}}progressListener, progressRequestListener); {{#returnType}}Type {{localVariablePrefix}}returnType = new TypeToken<{{{returnType}}}>(){}.getType(); {{localVariablePrefix}}apiClient.executeAsync({{localVariablePrefix}}call, {{localVariablePrefix}}returnType, {{localVariablePrefix}}callback);{{/returnType}}{{^returnType}}{{localVariablePrefix}}apiClient.executeAsync({{localVariablePrefix}}call, {{localVariablePrefix}}callback);{{/returnType}} return {{localVariablePrefix}}call; diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/enumClass.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/enumClass.mustache index bb1109c27ca..0fed02b67a3 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/enumClass.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/enumClass.mustache @@ -1,12 +1,12 @@ -public enum {{datatypeWithEnum}} { - {{#allowableValues}}{{#enumVars}}@SerializedName("{{value}}") - {{name}}("{{value}}"){{^-last}}, +public enum {{{datatypeWithEnum}}} { + {{#allowableValues}}{{#enumVars}}@SerializedName("{{{value}}}") + {{{name}}}("{{{value}}}"){{^-last}}, {{/-last}}{{#-last}};{{/-last}}{{/enumVars}}{{/allowableValues}} private String value; - {{datatypeWithEnum}}(String value) { + {{{datatypeWithEnum}}}(String value) { this.value = value; } 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 0987aa68f34..b7b4ea2cf3f 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 @@ -8,6 +8,7 @@ import com.google.gson.annotations.SerializedName; {{#serializableModel}} import java.io.Serializable;{{/serializableModel}} +import java.util.Objects; import io.swagger.annotations.*; @@ -44,6 +45,25 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#seriali {{/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(); 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 84c799d6252..9d758bddd21 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 @@ -26,7 +26,7 @@ public interface {{classname}} { {{#formParams}}{{#-first}} {{#isMultipart}}@Multipart{{/isMultipart}}{{^isMultipart}}@FormUrlEncoded{{/isMultipart}}{{/-first}}{{/formParams}} @{{httpMethod}}("{{path}}") - {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Object{{/returnType}} {{nickname}}({{^allParams}});{{/allParams}} + {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Object{{/returnType}} {{operationId}}({{^allParams}});{{/allParams}} {{#allParams}}{{>libraries/retrofit/queryParams}}{{>libraries/retrofit/pathParams}}{{>libraries/retrofit/headerParams}}{{>libraries/retrofit/bodyParams}}{{>libraries/retrofit/formParams}}{{#hasMore}}, {{/hasMore}}{{^hasMore}} );{{/hasMore}}{{/allParams}} @@ -40,7 +40,7 @@ public interface {{classname}} { {{#formParams}}{{#-first}} {{#isMultipart}}@Multipart{{/isMultipart}}{{^isMultipart}}@FormUrlEncoded{{/isMultipart}}{{/-first}}{{/formParams}} @{{httpMethod}}("{{path}}") - void {{nickname}}( + void {{operationId}}( {{#allParams}}{{>libraries/retrofit/queryParams}}{{>libraries/retrofit/pathParams}}{{>libraries/retrofit/headerParams}}{{>libraries/retrofit/bodyParams}}{{>libraries/retrofit/formParams}}, {{/allParams}}Callback<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Object{{/returnType}}> cb ); {{/operation}} 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 0987aa68f34..b7b4ea2cf3f 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 @@ -8,6 +8,7 @@ import com.google.gson.annotations.SerializedName; {{#serializableModel}} import java.io.Serializable;{{/serializableModel}} +import java.util.Objects; import io.swagger.annotations.*; @@ -44,6 +45,25 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#seriali {{/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(); 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 d0205c3d0b1..a066a625cff 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/api.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/api.mustache @@ -25,7 +25,7 @@ public interface {{classname}} { {{#formParams}}{{#-first}} {{#isMultipart}}@Multipart{{/isMultipart}}{{^isMultipart}}@FormUrlEncoded{{/isMultipart}}{{/-first}}{{/formParams}} @{{httpMethod}}("{{path}}") - Call<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Object{{/returnType}}> {{nickname}}({{^allParams}});{{/allParams}} + Call<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Object{{/returnType}}> {{operationId}}({{^allParams}});{{/allParams}} {{#allParams}}{{>libraries/retrofit2/queryParams}}{{>libraries/retrofit2/pathParams}}{{>libraries/retrofit2/headerParams}}{{>libraries/retrofit2/bodyParams}}{{>libraries/retrofit2/formParams}}{{#hasMore}}, {{/hasMore}}{{^hasMore}} );{{/hasMore}}{{/allParams}} 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 b1efe3911a8..cf0047cf283 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 @@ -98,8 +98,8 @@ ext { dependencies { compile "com.squareup.okhttp:okhttp:$okhttp_version" compile "com.squareup.retrofit:retrofit:$retrofit_version" - compile 'com.google.code.gson:gson:$gson_version' - compile 'com.squareup.retrofit:converter-gson:$retrofit_version' + compile "com.google.code.gson:gson:$gson_version" + compile "com.squareup.retrofit:converter-gson:$retrofit_version" compile "io.swagger:swagger-annotations:$swagger_annotations_version" compile "org.apache.oltu.oauth2:org.apache.oltu.oauth2.client:$oltu_version" testCompile "junit:junit:$junit_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 0987aa68f34..b7b4ea2cf3f 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 @@ -8,6 +8,7 @@ import com.google.gson.annotations.SerializedName; {{#serializableModel}} import java.io.Serializable;{{/serializableModel}} +import java.util.Objects; import io.swagger.annotations.*; @@ -44,6 +45,25 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#seriali {{/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(); diff --git a/modules/swagger-codegen/src/main/resources/Java/model.mustache b/modules/swagger-codegen/src/main/resources/Java/model.mustache index f5e48ba997f..b62cb983281 100644 --- a/modules/swagger-codegen/src/main/resources/Java/model.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/model.mustache @@ -6,51 +6,17 @@ import {{invokerPackage}}.StringUtil; {{#serializableModel}} import java.io.Serializable;{{/serializableModel}} +import java.util.Objects; import io.swagger.annotations.*; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.*; {{#models}} {{#model}}{{#description}} /** * {{description}} **/{{/description}} -@ApiModel(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}} - **/ - @ApiModelProperty({{#required}}required = {{required}}, {{/required}}value = "{{{description}}}") - @JsonProperty("{{baseName}}") - public {{{datatypeWithEnum}}} {{getter}}() { - return {{name}}; - } - public void {{setter}}({{{datatypeWithEnum}}} {{name}}) { - this.{{name}} = {{name}}; - } - - {{/vars}} - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class {{classname}} {\n"); - {{#parent}}sb.append(" ").append(StringUtil.toIndentedString(super.toString())).append("\n");{{/parent}} - {{#vars}}sb.append(" {{name}}: ").append(StringUtil.toIndentedString({{name}})).append("\n"); - {{/vars}}sb.append("}"); - return sb.toString(); - } -} +{{#isEnum}}{{>enumOuterClass}}{{/isEnum}} +{{^isEnum}}{{>pojo}}{{/isEnum}} {{/model}} {{/models}} diff --git a/modules/swagger-codegen/src/main/resources/Java/pojo.mustache b/modules/swagger-codegen/src/main/resources/Java/pojo.mustache new file mode 100644 index 00000000000..2e9facfb14d --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/pojo.mustache @@ -0,0 +1,56 @@ +@ApiModel(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}} + **/ + @ApiModelProperty({{#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(StringUtil.toIndentedString(super.toString())).append("\n");{{/parent}} + {{#vars}}sb.append(" {{name}}: ").append(StringUtil.toIndentedString({{name}})).append("\n"); + {{/vars}}sb.append("}"); + return sb.toString(); + } +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/Java/pom.mustache b/modules/swagger-codegen/src/main/resources/Java/pom.mustache index c5bfbc65b74..f2c20a96740 100644 --- a/modules/swagger-codegen/src/main/resources/Java/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/pom.mustache @@ -137,6 +137,11 @@ jackson-databind ${jackson-version} + + com.fasterxml.jackson.jaxrs + jackson-jaxrs-json-provider + ${jackson-version} + com.fasterxml.jackson.datatype jackson-datatype-joda diff --git a/modules/swagger-codegen/src/main/resources/JavaInflector/api.mustache b/modules/swagger-codegen/src/main/resources/JavaInflector/api.mustache index 74e688ee23e..0a5e225306c 100644 --- a/modules/swagger-codegen/src/main/resources/JavaInflector/api.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaInflector/api.mustache @@ -24,7 +24,7 @@ public class {{classname}} { {{#operation}} /* - public ResponseContext {{nickname}}(RequestContext request {{#allParams}}, {{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{/allParams}}) { + public ResponseContext {{operationId}}(RequestContext request {{#allParams}}, {{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{/allParams}}) { return new ResponseContext().status(Status.INTERNAL_SERVER_ERROR).entity( "Not implemented" ); } */ diff --git a/modules/swagger-codegen/src/main/resources/JavaInflector/inflector.mustache b/modules/swagger-codegen/src/main/resources/JavaInflector/inflector.mustache index 99ace468103..c61fa2054b8 100644 --- a/modules/swagger-codegen/src/main/resources/JavaInflector/inflector.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaInflector/inflector.mustache @@ -1,6 +1,6 @@ controllerPackage: {{invokerPackage}} modelPackage: {{modelPackage}} -swaggerUrl: ./src/main/swagger/swagger.json +swaggerUrl: ./src/main/swagger/swagger.yaml modelMappings: {{#models}}{{#model}}{{classname}} : {{modelPackage}}.{{classname}}{{/model}} {{/models}} diff --git a/modules/swagger-codegen/src/main/resources/JavaInflector/pom.mustache b/modules/swagger-codegen/src/main/resources/JavaInflector/pom.mustache index 0f489f4923d..c4b5fdf4922 100644 --- a/modules/swagger-codegen/src/main/resources/JavaInflector/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaInflector/pom.mustache @@ -74,11 +74,11 @@ - + io.swagger swagger-inflector - 1.0.0-SNAPSHOT + 1.0.0 diff --git a/modules/swagger-codegen/src/main/resources/JavaInflector/swagger.mustache b/modules/swagger-codegen/src/main/resources/JavaInflector/swagger.mustache new file mode 100644 index 00000000000..51560926bba --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaInflector/swagger.mustache @@ -0,0 +1 @@ +{{{swagger-yaml}}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/README.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/README.mustache index 00431f63dbc..f240464851d 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/README.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/README.mustache @@ -12,3 +12,12 @@ To run the server, please execute the following: ``` mvn clean package jetty:run ``` + +You can then view the swagger listing here: + +``` +http://localhost:8080{{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/api.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/api.mustache index ea9f2518b01..c8fd2b80800 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/api.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/api.mustache @@ -19,7 +19,9 @@ 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("/{{baseName}}") @@ -47,12 +49,10 @@ public class {{classname}} { @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}}{{#hasMore}}, - {{/hasMore}}{{/allParams}}) + public Response {{nickname}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}},{{/allParams}}@Context SecurityContext securityContext) throws NotFoundException { - return delegate.{{nickname}}({{#allParams}}{{#isFile}}fileDetail{{/isFile}}{{^isFile}}{{paramName}}{{/isFile}}{{#hasMore}},{{/hasMore}}{{/allParams}}); + return delegate.{{nickname}}({{#allParams}}{{#isFile}}fileDetail{{/isFile}}{{^isFile}}{{paramName}}{{/isFile}},{{/allParams}}securityContext); } {{/operation}} } {{/operations}} - diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/apiService.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/apiService.mustache index a731da6c11c..2cc7b8c1fec 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/apiService.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/apiService.mustache @@ -17,12 +17,13 @@ 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; {{>generatedAnnotation}} {{#operations}} public abstract class {{classname}}Service { {{#operation}} - public abstract Response {{nickname}}({{#allParams}}{{>serviceQueryParams}}{{>servicePathParams}}{{>serviceHeaderParams}}{{>serviceBodyParams}}{{>serviceFormParams}}{{#hasMore}},{{/hasMore}}{{/allParams}}) + public abstract Response {{nickname}}({{#allParams}}{{>serviceQueryParams}}{{>servicePathParams}}{{>serviceHeaderParams}}{{>serviceBodyParams}}{{>serviceFormParams}},{{/allParams}}SecurityContext securityContext) throws NotFoundException; {{/operation}} } diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/apiServiceImpl.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/apiServiceImpl.mustache index 0acd755745e..09741c1e03e 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/apiServiceImpl.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/apiServiceImpl.mustache @@ -17,13 +17,14 @@ 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; {{>generatedAnnotation}} {{#operations}} public class {{classname}}ServiceImpl extends {{classname}}Service { {{#operation}} @Override - public Response {{nickname}}({{#allParams}}{{>serviceQueryParams}}{{>servicePathParams}}{{>serviceHeaderParams}}{{>serviceBodyParams}}{{>serviceFormParams}}{{#hasMore}},{{/hasMore}}{{/allParams}}) + 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(); diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/model.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/model.mustache index 72a371280b3..63bba4a8dfb 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/model.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/model.mustache @@ -5,6 +5,8 @@ package {{package}}; import io.swagger.annotations.*; import com.fasterxml.jackson.annotation.JsonProperty; + +import java.util.Objects; {{#models}} {{#model}}{{#unescapedDescription}} @@ -38,6 +40,25 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} { {{/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(); diff --git a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/api.mustache b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/api.mustache index 6eb6358a702..a882c006975 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/api.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/api.mustache @@ -50,7 +50,7 @@ public class {{classname}} { {{#hasProduces}}produces = { {{#produces}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }, {{/hasProduces}} {{#hasConsumes}}consumes = { {{#consumes}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} },{{/hasConsumes}} method = RequestMethod.{{httpMethod}}) - public ResponseEntity<{{>returnTypes}}> {{nickname}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}}, + public ResponseEntity<{{>returnTypes}}> {{operationId}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) throws NotFoundException { // do some magic! diff --git a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/model.mustache b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/model.mustache index 39f0f0b6fa1..d1a5e396e13 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/model.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/model.mustache @@ -5,6 +5,8 @@ package {{package}}; import io.swagger.annotations.*; import com.fasterxml.jackson.annotation.JsonProperty; + +import java.util.Objects; {{#models}} {{#model}}{{#description}} @@ -38,6 +40,25 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} { {{/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(); diff --git a/modules/swagger-codegen/src/main/resources/Javascript/api.mustache b/modules/swagger-codegen/src/main/resources/Javascript/api.mustache new file mode 100644 index 00000000000..9957fc4e2c5 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Javascript/api.mustache @@ -0,0 +1,125 @@ +// require files in Node.js environment +var ${{#imports}}, {{import}}{{/imports}}; +if (typeof module === 'object' && module.exports) { + $ = require('jquery');{{#imports}} + {{import}} = require('../model/{{import}}.js');{{/imports}} +} + +// export module for AMD +if ( typeof define === "function" && define.amd ) { + define(['jquery'{{#imports}}, '{{import}}'{{/imports}}], function(${{#imports}}, {{import}}{{/imports}}) { + return {{classname}}; + }); +} + +var {{classname}} = function {{classname}}() { + var self = this; + {{#operations}} + {{#operation}} + /** + * {{summary}} + * {{notes}} +{{#allParams}} * @param {{=<% %>=}}{<% dataType %>} <%={{ }}=%> {{paramName}} {{description}} +{{/allParams}} * @param {function} callback the callback function + * @return {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} + */ + self.{{nickname}} = function({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}{{#hasParams}}, {{/hasParams}}callback) { + var {{localVariablePrefix}}postBody = {{#bodyParam}}{{^isBinary}}JSON.stringify({{paramName}}){{/isBinary}}{{#isBinary}}null{{/isBinary}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}}; + var {{localVariablePrefix}}postBinaryBody = {{#bodyParam}}{{#isBinary}}{{paramName}}{{/isBinary}}{{^isBinary}}null{{/isBinary}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}}; + {{#allParams}}{{#required}} + // verify the required parameter '{{paramName}}' is set + if ({{paramName}} == null) { + //throw new ApiException(400, "Missing the required parameter '{{paramName}}' when calling {{nickname}}"); + var errorRequiredMsg = "Missing the required parameter '{{paramName}}' when calling {{nickname}}"; + throw errorRequiredMsg; + } + {{/required}}{{/allParams}} + // create path and map variables + var basePath = '{{basePath}}'; + // if basePath ends with a /, remove it as path starts with a leading / + if (basePath.substring(basePath.length-1, basePath.length)=='/') { + basePath = basePath.substring(0, basePath.length-1); + } + + var {{localVariablePrefix}}path = basePath + replaceAll(replaceAll("{{{path}}}", "\\{format\\}","json"){{#pathParams}} +, "\\{" + "{{baseName}}" + "\\}", encodeURIComponent({{{paramName}}}.toString()){{/pathParams}}); + + var queryParams = {}; + var headerParams = {}; + var formParams = {}; + + {{#queryParams}} + queryParams.{{baseName}} = {{paramName}}; + {{/queryParams}} + {{#headerParams}}if ({{paramName}} != null) + {{localVariablePrefix}}headerParams.put("{{baseName}}", {{paramName}}); + {{/headerParams}} + {{#formParams}}if ({{paramName}} != null) + {{localVariablePrefix}}formParams.put("{{baseName}}", {{paramName}}); + {{/formParams}} + + path += createQueryString(queryParams); + + var options = {type: "{{httpMethod}}", async: true, contentType: "application/json", dataType: "json", data: postBody}; + var request = $.ajax(path, options); + + request.fail(function(jqXHR, textStatus, errorThrown){ + if (callback) { + var error = errorThrown || textStatus || jqXHR.statusText || 'error'; + callback(null, textStatus, jqXHR, error); + } + }); + + request.done(function(response, textStatus, jqXHR){ + {{#returnType}} + /** + * @returns {{{returnType}}} + */ + {{#returnTypeIsPrimitive}}var myResponse = response;{{/returnTypeIsPrimitive}} + {{^returnTypeIsPrimitive}}var myResponse = new {{{returnType}}}(); + myResponse.constructFromObject(response);{{/returnTypeIsPrimitive}} + if (callback) { + callback(myResponse, textStatus, jqXHR); + } + {{/returnType}}{{^returnType}} + if (callback) { + callback(response, textStatus, jqXHR); + } + {{/returnType}} + }); + + return request; + } + {{/operation}} + {{/operations}} + + function replaceAll (haystack, needle, replace) { + var result= haystack; + if (needle !=null && replace!=null) { + result= haystack.replace(new RegExp(needle, 'g'), replace); + } + return result; + } + + function createQueryString (queryParams) { + var queryString =''; + var i = 0; + for (var queryParamName in queryParams) { + if (i==0) { + queryString += '?' ; + } else { + queryString += '&' ; + } + + queryString += queryParamName + '=' + encodeURIComponent(queryParams[queryParamName]); + i++; + } + + return queryString; + } +} + +// export module for Node.js +if (typeof module === 'object' && module.exports) { + module.exports = {{classname}}; +} diff --git a/modules/swagger-codegen/src/main/resources/Javascript/enumClass.mustache b/modules/swagger-codegen/src/main/resources/Javascript/enumClass.mustache new file mode 100644 index 00000000000..648708c2d7e --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Javascript/enumClass.mustache @@ -0,0 +1,19 @@ + +//export module +if ( typeof define === "function" && define.amd ) { + define('{{datatypeWithEnum}}', ['jquery'], function($) { + return {{datatypeWithEnum}}; + }); +} + +var {{datatypeWithEnum}} = function {{datatypeWithEnum}}() { + var self = this; + +{{#allowableValues}}{{#enumVars}} + /** + * @const + */ + self.{{name}} = "{{value}}"{{^-last}}, + {{/-last}}{{#-last}};{{/-last}}{{/enumVars}}{{/allowableValues}} + +} diff --git a/modules/swagger-codegen/src/main/resources/Javascript/index.mustache b/modules/swagger-codegen/src/main/resources/Javascript/index.mustache new file mode 100644 index 00000000000..a0207a6cc91 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Javascript/index.mustache @@ -0,0 +1,10 @@ +if (typeof module === 'object' && module.exports) { + var {{moduleName}} = {}; + {{#models}} + {{moduleName}}.{{importPath}} = require('./model/{{importPath}}.js'); + {{/models}} + {{#apiInfo}}{{#apis}} + {{moduleName}}.{{importPath}} = require('./api/{{importPath}}.js'); + {{/apis}}{{/apiInfo}} + module.exports = {{moduleName}}; +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/Javascript/model.mustache b/modules/swagger-codegen/src/main/resources/Javascript/model.mustache new file mode 100644 index 00000000000..0588d03a8c1 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Javascript/model.mustache @@ -0,0 +1,75 @@ +// require files in Node.js environment +{{#imports}} +var {{import}};{{/imports}} +if (typeof module === 'object' && module.exports) { + {{#imports}} + {{import}} = require('./{{import}}.js');{{/imports}} +} + +{{#models}}{{#model}} +{{#vars}}{{#isEnum}}{{>enumClass}}{{/isEnum}}{{#items.isEnum}}{{#items}} +{{>enumClass}}{{/items}}*/{{/items.isEnum}}{{/vars}} + +//export module +if ( typeof define === "function" && define.amd ) { + define('{{classname}}', ['jquery'{{#vars}}{{^isPrimitiveType}}{{^-last}}, {{/-last}}'{{datatypeWithEnum}}'{{/isPrimitiveType}}{{/vars}}], + function(${{#vars}}{{^isPrimitiveType}}{{^-last}}, {{/-last}}{{datatypeWithEnum}}{{/isPrimitiveType}}{{/vars}}) { + return {{classname}}; + }); +} + +{{#description}}/** + * {{description}} + **/{{/description}} +var {{classname}} = function {{classname}}({{#mandatory}}{{this}}{{^-last}}, {{/-last}}{{/mandatory}}) { {{#parent}}/* extends {{{parent}}}*/{{/parent}} + var self = this; + {{#vars}} + /**{{#description}} + * {{{description}}}{{/description}} + * datatype: {{{datatypeWithEnum}}}{{#required}} + * required{{/required}}{{#minimum}} + * minimum: {{minimum}}{{/minimum}}{{#maximum}} + * maximum: {{maximum}}{{/maximum}} + **/ + self.{{name}} = {{#required}}{{name}}{{/required}}{{^required}}{{{defaultValue}}}{{/required}}; + {{/vars}} + + self.constructFromObject = function(data) { + if (!data) { + return; + } + {{#vars}} + self.{{name}}{{{defaultValueWithParam}}} + {{/vars}} + } + + {{#vars}} + /**{{#description}} + * get {{{description}}}{{/description}}{{#minimum}} + * minimum: {{minimum}}{{/minimum}}{{#maximum}} + * maximum: {{maximum}}{{/maximum}} + * @return {{=<% %>=}}{<% datatypeWithEnum %>}<%={{ }}=%> + **/ + self.{{getter}} = function() { + return self.{{name}}; + } + + /**{{#description}} + * set {{{description}}}{{/description}} + * @param {{=<% %>=}}{<% datatypeWithEnum %>}<%={{ }}=%> {{name}} + **/ + self.{{setter}} = function ({{name}}) { + self.{{name}} = {{name}}; + } + {{/vars}} + + self.toJson = function () { + return JSON.stringify(self); + } +} + +if (typeof module === 'object' && module.exports) { + module.exports = {{classname}}; +} +{{/model}} +{{/models}} diff --git a/modules/swagger-codegen/src/main/resources/Javascript/package.mustache b/modules/swagger-codegen/src/main/resources/Javascript/package.mustache new file mode 100644 index 00000000000..c77ee835709 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Javascript/package.mustache @@ -0,0 +1,20 @@ +{ + "name": "{{{projectName}}}", + "version": "{{{projectVersion}}}", + "description": "{{{projectDescription}}}",{{#projectLicenseName}} + "license": "{{{projectLicenseName}}}",{{/projectLicenseName}} + "main": "{{sourceFolder}}/index.js", + "scripts": { + "test": "./node_modules/mocha/bin/mocha --recursive" + }, + "dependencies": { + "jquery": "~2.1.4" + }, + "devDependencies": { + "mocha": "~2.3.4", + "expect.js": "~0.3.1", + "mockrequire": "~0.0.5", + "domino": "~1.0.20", + "xmlhttprequest": "~1.8.0" + } +} 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 5c607488d9b..5d8a4f0fc6b 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 @@ -5,8 +5,10 @@ io.swagger.codegen.languages.DartClientCodegen io.swagger.codegen.languages.FlashClientCodegen io.swagger.codegen.languages.FlaskConnexionCodegen io.swagger.codegen.languages.JavaClientCodegen +io.swagger.codegen.languages.JavascriptClientCodegen io.swagger.codegen.languages.JaxRSServerCodegen io.swagger.codegen.languages.JavaInflectorServerCodegen +io.swagger.codegen.languages.JMeterCodegen io.swagger.codegen.languages.NodeJSServerCodegen io.swagger.codegen.languages.ObjcClientCodegen io.swagger.codegen.languages.PerlClientCodegen @@ -18,6 +20,7 @@ io.swagger.codegen.languages.ScalaClientCodegen io.swagger.codegen.languages.ScalatraServerCodegen io.swagger.codegen.languages.SilexServerCodegen io.swagger.codegen.languages.SinatraServerCodegen +io.swagger.codegen.languages.SlimFrameworkServerCodegen io.swagger.codegen.languages.SpringMVCServerCodegen io.swagger.codegen.languages.StaticDocCodegen io.swagger.codegen.languages.StaticHtmlGenerator diff --git a/modules/swagger-codegen/src/main/resources/TypeScript-node/api.mustache b/modules/swagger-codegen/src/main/resources/TypeScript-node/api.mustache index c1f311fec19..62f6760a6ec 100644 --- a/modules/swagger-codegen/src/main/resources/TypeScript-node/api.mustache +++ b/modules/swagger-codegen/src/main/resources/TypeScript-node/api.mustache @@ -73,8 +73,10 @@ class ApiKeyAuth implements Authentication { } class OAuth implements Authentication { + public accessToken: string; + applyToRequest(requestOptions: request.Options): void { - // TODO: support oauth + requestOptions.headers["Authorization"] = "Bearer " + this.accessToken; } } @@ -115,13 +117,13 @@ export class {{classname}} { {{/authMethods}} } - constructor(url: string, basePath?: string); + constructor(basePath?: string); {{#authMethods}} {{#isBasic}} - constructor(url: string, username: string, password: string, basePath?: string); + constructor(username: string, password: string, basePath?: string); {{/isBasic}} {{/authMethods}} - constructor(private url: string, basePathOrUsername: string, password?: string, basePath?: string) { + constructor(basePathOrUsername: string, password?: string, basePath?: string) { if (password) { {{#authMethods}} {{#isBasic}} @@ -156,6 +158,10 @@ export class {{classname}} { } {{/isApiKey}} {{#isOAuth}} + + set accessToken(token: string) { + this.authentications.{{name}}.accessToken = token; + } {{/isOAuth}} {{/authMethods}} private extendObj(objA: T1, objB: T2) { @@ -173,7 +179,7 @@ export class {{classname}} { {{#allParams}}* @param {{paramName}} {{description}} {{/allParams}}*/ public {{nickname}} ({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) : Promise<{ response: http.ClientResponse; {{#returnType}}body: {{{returnType}}}; {{/returnType}}{{^returnType}}body?: any; {{/returnType}} }> { - const path = this.url + this.basePath + '{{path}}'{{#pathParams}} + const path = this.basePath + '{{path}}'{{#pathParams}} .replace('{' + '{{baseName}}' + '}', String({{paramName}})){{/pathParams}}; let queryParameters: any = {}; let headerParams: any = this.extendObj({}, this.defaultHeaders); diff --git a/modules/swagger-codegen/src/main/resources/clojure/api.mustache b/modules/swagger-codegen/src/main/resources/clojure/api.mustache index 1acdf94d764..a6b598fc610 100644 --- a/modules/swagger-codegen/src/main/resources/clojure/api.mustache +++ b/modules/swagger-codegen/src/main/resources/clojure/api.mustache @@ -1,19 +1,27 @@ {{=< >=}}(ns . - (:require [.core :refer [call-api check-required-params]]) + (:require [.core :refer [call-api check-required-params with-collection-format]]) (:import (java.io File))) <#operations><#operation> -(defn +(defn -with-http-info "<&summary><#notes> <¬es>"<#hasOptionalParams> - ([<#allParams><#required><#isFile>^File ] (<#allParams><#required> nil)) + ([<#allParams><#required><#isFile>^File ] (-with-http-info<#allParams><#required> nil)) <#hasOptionalParams>([<#allParams><#required><#isFile>^File <#hasOptionalParams>{:keys [<#allParams><^required><#isFile>^File ]}]<#hasRequiredParams> <#hasOptionalParams> (check-required-params<#allParams><#required> ) <#hasOptionalParams> (call-api "" : - <#hasOptionalParams> {:path-params {<#pathParams>"" } - <#hasOptionalParams> :header-params {<#headerParams>"" } - <#hasOptionalParams> :query-params {<#queryParams>"" } - <#hasOptionalParams> :form-params {<#formParams>"" }<#bodyParam> + <#hasOptionalParams> {:path-params {<#pathParams>"" <#collectionFormat>(with-collection-format :)<^collectionFormat> } + <#hasOptionalParams> :header-params {<#headerParams>"" <#collectionFormat>(with-collection-format :)<^collectionFormat> } + <#hasOptionalParams> :query-params {<#queryParams>"" <#collectionFormat>(with-collection-format :)<^collectionFormat> } + <#hasOptionalParams> :form-params {<#formParams>"" <#collectionFormat>(with-collection-format :)<^collectionFormat> }<#bodyParam> <#hasOptionalParams> :body-param <#hasOptionalParams> :content-types [<#consumes>""<#hasMore> ] - <#hasOptionalParams> :accepts [<#produces>""<#hasMore> ]}))<#hasOptionalParams>) + <#hasOptionalParams> :accepts [<#produces>""<#hasMore> ] + <#hasOptionalParams> :auth-names [<#authMethods>"<&name>"<#hasMore> ]})<#hasOptionalParams>)) + +(defn + "<&summary><#notes> + <¬es>"<#hasOptionalParams> + ([<#allParams><#required><#isFile>^File ] (<#allParams><#required> nil)) + <#hasOptionalParams>([<#allParams><#required><#isFile>^File <#hasOptionalParams>optional-params] + <#hasOptionalParams> (:data (-with-http-info<#allParams><#required> <#hasOptionalParams> optional-params))<#hasOptionalParams>)) \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/clojure/core.mustache b/modules/swagger-codegen/src/main/resources/clojure/core.mustache index 32aa8a6bc0d..0da2a451495 100644 --- a/modules/swagger-codegen/src/main/resources/clojure/core.mustache +++ b/modules/swagger-codegen/src/main/resources/clojure/core.mustache @@ -1,4 +1,4 @@ -(ns {{{baseNamespace}}}.core +{{=< >=}}(ns <&baseNamespace>.core (:require [cheshire.core :refer [generate-string parse-string]] [clojure.string :as str] [clj-http.client :as client]) @@ -7,12 +7,18 @@ (java.util Date TimeZone) (java.text SimpleDateFormat))) +(def auth-definitions + {<#authMethods>"<&name>" <#isBasic>{:type :basic}<#isApiKey>{:type :api-key<#isKeyInHeader> :in :header<#isKeyInQuery> :in :query :param-name "<&keyParamName>"}<#isOAuth>{:type :oauth2}<#hasMore> + }) + (def default-api-context "Default API context." - {:base-url "http://petstore.swagger.io/v2" + {:base-url "<&basePath>" :date-format "yyyy-MM-dd" :datetime-format "yyyy-MM-dd'T'HH:mm:ss.SSSXXX" - :debug false}) + :debug false + :auths {<#authMethods>"<&name>" nil<#hasMore> + }}) (def ^:dynamic *api-context* "Dynamic API context to be applied in API calls." @@ -20,12 +26,16 @@ (defmacro with-api-context "A helper macro to wrap *api-context* with default values." - [context & body] - `(binding [*api-context* (merge *api-context* ~context)] - ~@body)) + [api-context & body] + `(let [api-context# ~api-context + api-context# (-> *api-context* + (merge api-context#) + (assoc :auths (merge (:auths *api-context*) (:auths api-context#))))] + (binding [*api-context* api-context#] + ~@body))) (defmacro check-required-params - "Throw exception if the given parameter value is nil." + "Throw exception if any of the given parameters is nil." [& params] (->> params (map (fn [p] @@ -33,9 +43,14 @@ (throw (IllegalArgumentException. ~(str "The parameter \"" p "\" is required")))))) (list* 'do))) -(defn- make-date-format - ([format-str] (make-date-format format-str nil)) - ([format-str time-zone] +(defn with-collection-format + "Attach collection-format to meta data of the given parameter." + [param collection-format] + (and param (with-meta param {:collection-format collection-format}))) + +(defn- ^SimpleDateFormat make-date-format + ([^String format-str] (make-date-format format-str nil)) + ([^String format-str ^String time-zone] (let [date-format (SimpleDateFormat. format-str)] (when time-zone (.setTimeZone date-format (TimeZone/getTimeZone time-zone))) @@ -75,50 +90,96 @@ (-> (make-date-format datetime-format time-zone) (.parse s))))) -(defn param-to-str [param] +(defn param->str "Format the given parameter value to string." + [param] (cond (instance? Date param) (format-datetime param) (sequential? param) (str/join "," param) :else (str param))) +(defn auth->opts + "Process the given auth to an option map that might conatin request options and parameters." + [{:keys [type in param-name]} value] + (case type + :basic {:req-opts {:basic-auth value}} + :oauth2 {:req-opts {:oauth-token value}} + :api-key (case in + :header {:header-params {param-name value}} + :query {:query-params {param-name value}} + (throw (IllegalArgumentException. (str "Invalid `in` for api-key auth: " in)))) + (throw (IllegalArgumentException. (str "Invalid auth `type`: " type))))) + +(defn process-auth + "Process the given auth name into options, which is merged into the given opts." + [opts auth-name] + (if-let [value (get-in *api-context* [:auths auth-name])] + (merge-with merge + opts + (auth->opts (get auth-definitions auth-name) value)) + opts)) + +(defn auths->opts + "Process the given auth names to an option map that might conatin request options and parameters." + [auth-names] + (reduce process-auth {} auth-names)) + +(declare normalize-param) + (defn make-url "Make full URL by adding base URL and filling path parameters." [path path-params] (let [path (reduce (fn [p [k v]] - (str/replace p (re-pattern (str "\\{" k "\\}")) (param-to-str v))) + (str/replace p (re-pattern (str "\\{" k "\\}")) (normalize-param v))) path path-params)] (str (:base-url *api-context*) path))) +(defn normalize-array-param + "Normalize array paramater according to :collection-format specified in the parameter's meta data. + When the parameter contains File, a seq is returned so as to keep File parameters. + For :multi collection format, a seq is returned which will be handled properly by clj-http. + For other cases, a string is returned." + [xs] + (if (some (partial instance? File) xs) + (map normalize-param xs) + (case (-> (meta xs) :collection-format (or :csv)) + :csv (str/join "," (map normalize-param xs)) + :ssv (str/join " " (map normalize-param xs)) + :tsv (str/join "\t" (map normalize-param xs)) + :pipes (str/join "|" (map normalize-param xs)) + :multi (map normalize-param xs)))) + (defn normalize-param "Normalize parameter value, handling three cases: - for sequential value, normalize each elements of it; - for File value, do nothing with it; - otherwise, call `param-to-string`." + for sequential value, apply `normalize-array-param` which handles collection format; + for File value, use current value; + otherwise, apply `param->str`." [param] (cond - (sequential? param) (map normalize-param param) + (sequential? param) (normalize-array-param param) (instance? File param) param - :else (param-to-str param))) + :else (param->str param))) (defn normalize-params - "Normalize parameters values: remove nils, format to string with `param-to-str`." + "Normalize parameters values: remove nils, format to string with `param->str`." [params] (->> params (remove (comp nil? second)) (map (fn [[k v]] [k (normalize-param v)])) (into {}))) -(defn json-mime? [mime] +(defn json-mime? "Check if the given MIME is a standard JSON MIME or :json." + [mime] (if mime (or (= :json mime) - (re-matches #"application/json(;.*)?" (name mime))))) + (re-matches #"(?i)application/json(;.*)?" (name mime))))) -(defn json-preferred-mime [mimes] +(defn json-preferred-mime "Choose a MIME from the given MIMEs with JSON preferred, i.e. return JSON if included, otherwise return the first one." + [mimes] (-> (filter json-mime? mimes) first (or (first mimes)))) @@ -139,12 +200,13 @@ (try (parse-string body true) (catch JsonParseException e - ;; return the body string directly on JSON parsing error + ;; Return the body string directly on JSON parsing error. body)) - ;; for non-JSON response, return the body string directly + + ;; For other cases, return the body string directly. :else body)) -(defn form-params-to-multipart +(defn form-params->multipart "Convert the given form parameters map into a vector as clj-http's :multipart option." [form-params] (->> form-params @@ -153,26 +215,28 @@ (defn call-api "Call an API by making HTTP request and return its response." - [path method {:keys [path-params query-params header-params form-params body-param content-types accepts]}] + [path method {:keys [path-params body-param content-types accepts auth-names] :as opts}] (let [{:keys [debug]} *api-context* + {:keys [req-opts query-params header-params form-params]} (auths->opts auth-names) + query-params (merge query-params (:query-params opts)) + header-params (merge header-params (:header-params opts)) + form-params (merge form-params (:form-params opts)) url (make-url path path-params) - content-type (or (json-preferred-mime content-types) - (and body-param :json)) + content-type (or (json-preferred-mime content-types) (and body-param :json)) accept (or (json-preferred-mime accepts) :json) multipart? (= "multipart/form-data" content-type) - opts (cond-> {:url url :method method} - accept (assoc :accept accept) - (seq query-params) (assoc :query-params (normalize-params query-params)) - (seq header-params) (assoc :header-params (normalize-params header-params)) - (and content-type (not multipart?)) (assoc :content-type content-type) - multipart? (assoc :multipart (-> form-params - normalize-params - form-params-to-multipart)) - (and (not multipart?) (seq form-params)) (assoc :form-params (normalize-params form-params)) - body-param (assoc :body (serialize body-param content-type)) - debug (assoc :debug true :debug-body true)) - resp (client/request opts)] + req-opts (cond-> req-opts + true (assoc :url url :method method) + accept (assoc :accept accept) + (seq query-params) (assoc :query-params (normalize-params query-params)) + (seq header-params) (assoc :headers (normalize-params header-params)) + (and content-type (not multipart?)) (assoc :content-type content-type) + multipart? (assoc :multipart (-> form-params normalize-params form-params->multipart)) + (and (not multipart?) (seq form-params)) (assoc :form-params (normalize-params form-params)) + body-param (assoc :body (serialize body-param content-type)) + debug (assoc :debug true :debug-body true)) + resp (client/request req-opts)] (when debug (println "Response:") (println resp)) - (deserialize resp))) + (assoc resp :data (deserialize resp)))) diff --git a/modules/swagger-codegen/src/main/resources/codegen/api.template b/modules/swagger-codegen/src/main/resources/codegen/api.template index 9dbc8dd4ba1..62802f7f1e7 100644 --- a/modules/swagger-codegen/src/main/resources/codegen/api.template +++ b/modules/swagger-codegen/src/main/resources/codegen/api.template @@ -14,8 +14,8 @@ classname: {{classname}} # loop over each operation in the API: {{#operation}} -# each operation has a `nickname`: -nickname: {{nickname}} +# each operation has an `operationId`: +operationId: {{operationId}} # and parameters: {{#allParams}} diff --git a/modules/swagger-codegen/src/main/resources/csharp/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/csharp/ApiClient.mustache index 87d55ab3f6e..142b2e6bbb9 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/ApiClient.mustache @@ -18,62 +18,71 @@ namespace {{packageName}}.Client /// public class ApiClient { - private readonly Dictionary _defaultHeaderMap = new Dictionary(); - /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class + /// with default configuration and base path ({{basePath}}). + /// + public ApiClient() + { + Configuration = Configuration.Default; + RestClient = new RestClient("{{basePath}}"); + } + + /// + /// Initializes a new instance of the class + /// with default base path ({{basePath}}). + /// + /// An instance of Configuration. + public ApiClient(Configuration config = null) + { + if (config == null) + Configuration = Configuration.Default; + else + Configuration = config; + + RestClient = new RestClient("{{basePath}}"); + } + + /// + /// Initializes a new instance of the class + /// with default configuration. /// /// The base path. - public ApiClient(String basePath="{{basePath}}") + public ApiClient(String basePath = "{{basePath}}") { - BasePath = basePath; - RestClient = new RestClient(BasePath); + if (String.IsNullOrEmpty(basePath)) + throw new ArgumentException("basePath cannot be empty"); + + RestClient = new RestClient(basePath); + Configuration = Configuration.Default; } + + /// + /// Gets or sets the default API client for making HTTP calls. + /// + /// The default API client. + public static ApiClient Default = new ApiClient(Configuration.Default); /// - /// Gets or sets the base path. + /// Gets or sets the Configuration. /// - /// The base path - public string BasePath { get; set; } - + /// An instance of the Configuration. + public Configuration Configuration { get; set; } + /// /// Gets or sets the RestClient. /// /// An instance of the RestClient public RestClient RestClient { get; set; } - /// - /// Gets the default header. - /// - public Dictionary DefaultHeader - { - get { return _defaultHeaderMap; } - } - - /// - /// Gets the status code of the previous request - /// - public int StatusCode { get; private set; } - - /// - /// Gets the response headers of the previous request - /// - public Dictionary ResponseHeaders { get; private set; } - // Creates and sets up a RestRequest prior to a call. private RestRequest PrepareRequest( String path, RestSharp.Method method, Dictionary queryParams, String postBody, Dictionary headerParams, Dictionary formParams, - Dictionary fileParams, Dictionary pathParams, String[] authSettings) + Dictionary fileParams, Dictionary pathParams) { var request = new RestRequest(path, method); - UpdateParamsForAuth(queryParams, headerParams, authSettings); - - // add default header, if any - foreach(var defaultHeader in _defaultHeaderMap) - request.AddHeader(defaultHeader.Key, defaultHeader.Value); - // add path parameter, if any foreach(var param in pathParams) request.AddParameter(param.Key, param.Value, ParameterType.UrlSegment); @@ -111,18 +120,15 @@ namespace {{packageName}}.Client /// Form parameters. /// File parameters. /// Path parameters. - /// Authentication settings. /// Object public Object CallApi( String path, RestSharp.Method method, Dictionary queryParams, String postBody, Dictionary headerParams, Dictionary formParams, - Dictionary fileParams, Dictionary pathParams, String[] authSettings) + Dictionary fileParams, Dictionary pathParams) { var request = PrepareRequest( - path, method, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); + path, method, queryParams, postBody, headerParams, formParams, fileParams, pathParams); var response = RestClient.Execute(request); - StatusCode = (int) response.StatusCode; - ResponseHeaders = response.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()); return (Object) response; } @@ -137,32 +143,18 @@ namespace {{packageName}}.Client /// Form parameters. /// File parameters. /// Path parameters. - /// Authentication settings. /// The Task instance. public async System.Threading.Tasks.Task CallApiAsync( String path, RestSharp.Method method, Dictionary queryParams, String postBody, Dictionary headerParams, Dictionary formParams, - Dictionary fileParams, Dictionary pathParams, String[] authSettings) + Dictionary fileParams, Dictionary pathParams) { var request = PrepareRequest( - path, method, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); + path, method, queryParams, postBody, headerParams, formParams, fileParams, pathParams); var response = await RestClient.ExecuteTaskAsync(request); - StatusCode = (int)response.StatusCode; - ResponseHeaders = response.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()); return (Object)response; } - /// - /// Add default header. - /// - /// Header field name. - /// Header field value. - /// - public void AddDefaultHeader(string key, string value) - { - _defaultHeaderMap.Add(key, value); - } - /// /// Escape string (url-encoded). /// @@ -188,7 +180,7 @@ namespace {{packageName}}.Client } /// - /// If parameter is DateTime, output in ISO8601 format. + /// If parameter is DateTime, output in a formatted string (default ISO 8601), customizable with Configuration.DateTime. /// If parameter is a list, join the list with ",". /// Otherwise just return the string. /// @@ -197,14 +189,21 @@ namespace {{packageName}}.Client public string ParameterToString(object obj) { if (obj is DateTime) - return ((DateTime)obj).ToString ("u"); - else if (obj is IList) { - string flattenString = ""; - string separator = ","; - foreach (var param in (IList)obj) { - flattenString += param.ToString() + separator; + // Return a formatted date string - Can be customized with Configuration.DateTimeFormat + // Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o") + // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 + // For example: 2009-06-15T13:45:30.0000000 + return ((DateTime)obj).ToString (Configuration.DateTimeFormat); + else if (obj is IList) + { + var flattenedString = new StringBuilder(); + foreach (var param in (IList)obj) + { + if (flattenedString.Length > 0) + flattenedString.Append(","); + flattenedString.Append(param); } - return flattenString.Remove(flattenString.Length - 1);; + return flattenedString.ToString(); } else return Convert.ToString (obj); @@ -233,13 +232,16 @@ namespace {{packageName}}.Client var filePath = String.IsNullOrEmpty(Configuration.TempFolderPath) ? Path.GetTempPath() : Configuration.TempFolderPath; - var regex = new Regex(@"Content-Disposition:.*filename=['""]?([^'""\s]+)['""]?$"); - var match = regex.Match(headers.ToString()); - if (match.Success) + var regex = new Regex(@"Content-Disposition=.*filename=['""]?([^'""\s]+)['""]?$"); + foreach (var header in headers) { - string fileName = filePath + match.Value.Replace("\"", "").Replace("'", ""); - File.WriteAllBytes(fileName, data); - return new FileStream(fileName, FileMode.Open); + var match = regex.Match(header.ToString()); + if (match.Success) + { + string fileName = filePath + match.Groups[1].Value.Replace("\"", "").Replace("'", ""); + File.WriteAllBytes(fileName, data); + return new FileStream(fileName, FileMode.Open); + } } } var stream = new MemoryStream(data); @@ -284,50 +286,6 @@ namespace {{packageName}}.Client } } - /// - /// Get the API key with prefix. - /// - /// API key identifier (authentication scheme). - /// API key with prefix. - public string GetApiKeyWithPrefix (string apiKeyIdentifier) - { - var apiKeyValue = ""; - Configuration.ApiKey.TryGetValue (apiKeyIdentifier, out apiKeyValue); - var apiKeyPrefix = ""; - if (Configuration.ApiKeyPrefix.TryGetValue (apiKeyIdentifier, out apiKeyPrefix)) - return apiKeyPrefix + " " + apiKeyValue; - else - return apiKeyValue; - } - - /// - /// Update parameters based on authentication. - /// - /// Query parameters. - /// Header parameters. - /// Authentication settings. - public void UpdateParamsForAuth(Dictionary queryParams, Dictionary headerParams, string[] authSettings) - { - if (authSettings == null || authSettings.Length == 0) - return; - - foreach (string auth in authSettings) - { - // determine which one to use - switch(auth) - { - {{#authMethods}} - case "{{name}}": - {{#isApiKey}}{{#isKeyInHeader}}headerParams["{{keyParamName}}"] = GetApiKeyWithPrefix("{{keyParamName}}");{{/isKeyInHeader}}{{#isKeyInQuery}}queryParams["{{keyParamName}}"] = GetApiKeyWithPrefix("{{keyParamName}}");{{/isKeyInQuery}}{{/isApiKey}}{{#isBasic}}headerParams["Authorization"] = "Basic " + Base64Encode(Configuration.Username + ":" + Configuration.Password);{{/isBasic}}{{#isOAuth}}headerParams["Authorization"] = "Bearer " + Configuration.AccessToken;{{/isOAuth}} - break; - {{/authMethods}} - default: - //TODO show warning about security definition not found - break; - } - } - } - /// /// Select the Accept header's value from the given accepts array: /// if JSON exists in the given array, use it; @@ -335,11 +293,14 @@ namespace {{packageName}}.Client /// /// The accepts array to select from. /// The Accept header to use. - public String SelectHeaderAccept(String[] accepts) { + public String SelectHeaderAccept(String[] accepts) + { if (accepts.Length == 0) return null; + if (accepts.Contains("application/json", StringComparer.OrdinalIgnoreCase)) return "application/json"; + return String.Join(",", accepts); } @@ -350,8 +311,7 @@ namespace {{packageName}}.Client /// Encoded string. public static string Base64Encode(string text) { - var textByte = System.Text.Encoding.UTF8.GetBytes(text); - return System.Convert.ToBase64String(textByte); + return System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(text)); } /// @@ -361,7 +321,8 @@ namespace {{packageName}}.Client /// Object to be casted /// Target type /// Casted object - public static dynamic ConvertType(dynamic source, Type dest) { + public static dynamic ConvertType(dynamic source, Type dest) + { return Convert.ChangeType(source, dest); } diff --git a/modules/swagger-codegen/src/main/resources/csharp/ApiException.mustache b/modules/swagger-codegen/src/main/resources/csharp/ApiException.mustache index 68e3a032765..09dbd0dce50 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/ApiException.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/ApiException.mustache @@ -1,47 +1,50 @@ using System; -namespace {{packageName}}.Client { - /// - /// API Exception - /// - public class ApiException : Exception { - /// - /// Gets or sets the error code (HTTP status code) - /// - /// The error code (HTTP status code). - public int ErrorCode { get; set; } - - /// - /// Gets or sets the error content (body json object) - /// - /// The error content (Http response body). - public dynamic ErrorContent { get; private set; } - - /// - /// Initializes a new instance of the class. - /// - public ApiException() {} - - /// - /// Initializes a new instance of the class. - /// - /// HTTP status code. - /// Error message. - public ApiException(int errorCode, string message) : base(message) { - this.ErrorCode = errorCode; - } - - /// - /// Initializes a new instance of the class. - /// - /// HTTP status code. - /// Error message. - /// Error content. - public ApiException(int errorCode, string message, dynamic errorContent = null) : base(message) { - this.ErrorCode = errorCode; - this.ErrorContent = errorContent; - } - - } - +namespace {{packageName}}.Client +{ + /// + /// API Exception + /// + public class ApiException : Exception + { + /// + /// Gets or sets the error code (HTTP status code) + /// + /// The error code (HTTP status code). + public int ErrorCode { get; set; } + + /// + /// Gets or sets the error content (body json object) + /// + /// The error content (Http response body). + public dynamic ErrorContent { get; private set; } + + /// + /// Initializes a new instance of the class. + /// + public ApiException() {} + + /// + /// Initializes a new instance of the class. + /// + /// HTTP status code. + /// Error message. + public ApiException(int errorCode, string message) : base(message) + { + this.ErrorCode = errorCode; + } + + /// + /// Initializes a new instance of the class. + /// + /// HTTP status code. + /// Error message. + /// Error content. + public ApiException(int errorCode, string message, dynamic errorContent = null) : base(message) + { + this.ErrorCode = errorCode; + this.ErrorContent = errorContent; + } + } + } diff --git a/modules/swagger-codegen/src/main/resources/csharp/ApiResponse.mustache b/modules/swagger-codegen/src/main/resources/csharp/ApiResponse.mustache new file mode 100644 index 00000000000..32816110a1b --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/csharp/ApiResponse.mustache @@ -0,0 +1,44 @@ +using System; +using System.Collections.Generic; + +namespace {{packageName}}.Client +{ + /// + /// API Response + /// + public class ApiResponse + { + /// + /// Gets or sets the status code (HTTP status code) + /// + /// The status code. + public int StatusCode { get; private set; } + + /// + /// Gets or sets the HTTP headers + /// + /// HTTP headers + public IDictionary Headers { get; private set; } + + /// + /// Gets or sets the data (parsed HTTP body) + /// + /// The data. + public T Data { get; private set; } + + /// + /// Initializes a new instance of the class. + /// + /// HTTP status code. + /// Error message. + /// Data (parsed HTTP body) + public ApiResponse(int statusCode, IDictionary headers, T data) + { + this.StatusCode= statusCode; + 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 79b20c6062c..7062a73c1e1 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/Configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/Configuration.mustache @@ -12,6 +12,62 @@ namespace {{packageName}}.Client /// public class Configuration { + /// + /// Initializes a new instance of the Configuration class with different settings + /// + /// Api client + /// Dictionary of default HTTP header + /// Username + /// Password + /// accessToken + /// Dictionary of API key + /// Dictionary of API key prefix + /// Temp folder path + /// DateTime format string + public Configuration(ApiClient apiClient = null, + Dictionary defaultHeader = null, + string username = null, + string password = null, + string accessToken = null, + Dictionary apiKey = null, + Dictionary apiKeyPrefix = null, + string tempFolderPath = null, + string dateTimeFormat = null, + int timeout = 100000 + ) + { + if (apiClient == null) + ApiClient = ApiClient.Default; + else + ApiClient = apiClient; + + Username = username; + Password = password; + AccessToken = accessToken; + + if (defaultHeader != null) + DefaultHeader = defaultHeader; + if (apiKey != null) + ApiKey = apiKey; + if (apiKeyPrefix != null) + ApiKeyPrefix = apiKeyPrefix; + + TempFolderPath = tempFolderPath; + DateTimeFormat = dateTimeFormat; + Timeout = timeout; + } + + /// + /// Initializes a new instance of the Configuration class. + /// + /// Api client. + public Configuration(ApiClient apiClient) + { + if (apiClient == null) + ApiClient = ApiClient.Default; + else + ApiClient = apiClient; + } /// /// Version of the package. @@ -19,49 +75,111 @@ namespace {{packageName}}.Client /// Version of the package. public const string Version = "{{packageVersion}}"; + /// + /// Gets or sets the default Configuration. + /// + /// Configuration. + public static Configuration Default = new Configuration(); + + /// + /// Gets or sets the HTTP timeout (milliseconds) of ApiClient. Default to 100000 milliseconds. + /// + /// Timeout. + public int Timeout + { + get { return ApiClient.RestClient.Timeout; } + + set + { + ApiClient.RestClient.Timeout = value; + } + } + /// /// Gets or sets the default API client for making HTTP calls. /// /// The API client. - public static ApiClient DefaultApiClient = new ApiClient(); - + public ApiClient ApiClient; + + private Dictionary _defaultHeaderMap = new Dictionary(); + + /// + /// Gets or sets the default header. + /// + public Dictionary DefaultHeader + { + get { return _defaultHeaderMap; } + + set + { + _defaultHeaderMap = value; + } + } + + /// + /// Add default header. + /// + /// Header field name. + /// Header field value. + /// + public void AddDefaultHeader(string key, string value) + { + _defaultHeaderMap.Add(key, value); + } + /// /// Gets or sets the username (HTTP basic authentication). /// /// The username. - public static String Username { get; set; } + public String Username { get; set; } /// /// Gets or sets the password (HTTP basic authentication). /// /// The password. - public static String Password { get; set; } + public String Password { get; set; } /// /// Gets or sets the access token for OAuth2 authentication. /// /// The access token. - public static String AccessToken { get; set; } + public String AccessToken { get; set; } /// /// Gets or sets the API key based on the authentication name. /// /// The API key. - public static Dictionary ApiKey = new Dictionary(); + public Dictionary ApiKey = new Dictionary(); /// /// Gets or sets the prefix (e.g. Token) of the API key based on the authentication name. /// /// The prefix of the API key. - public static Dictionary ApiKeyPrefix = new Dictionary(); + public Dictionary ApiKeyPrefix = new Dictionary(); + + /// + /// Get the API key with prefix. + /// + /// API key identifier (authentication scheme). + /// API key with prefix. + public string GetApiKeyWithPrefix (string apiKeyIdentifier) + { + var apiKeyValue = ""; + ApiKey.TryGetValue (apiKeyIdentifier, out apiKeyValue); + var apiKeyPrefix = ""; + if (ApiKeyPrefix.TryGetValue (apiKeyIdentifier, out apiKeyPrefix)) + return apiKeyPrefix + " " + apiKeyValue; + else + return apiKeyValue; + } - private static string _tempFolderPath = Path.GetTempPath(); + private string _tempFolderPath = Path.GetTempPath(); /// /// Gets or sets the temporary folder path to store the files downloaded from the server. /// /// Folder path. - public static String TempFolderPath + public String TempFolderPath { get { return _tempFolderPath; } @@ -84,7 +202,40 @@ namespace {{packageName}}.Client _tempFolderPath = value + Path.DirectorySeparatorChar; } } - + + private const string ISO8601_DATETIME_FORMAT = "o"; + + private string _dateTimeFormat = ISO8601_DATETIME_FORMAT; + + /// + /// Gets or sets the the date time format used when serializing in the ApiClient + /// By default, it's set to ISO 8601 - "o", for others see: + /// https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx + /// and https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx + /// No validation is done to ensure that the string you're providing is valid + /// + /// The DateTimeFormat string + public String DateTimeFormat + { + get + { + return _dateTimeFormat; + } + set + { + if (string.IsNullOrEmpty(value)) + { + // Never allow a blank or null string, go back to the default + _dateTimeFormat = ISO8601_DATETIME_FORMAT; + return; + } + + // Caution, no validation when you choose date time format other than ISO 8601 + // Take a look at the above links + _dateTimeFormat = value; + } + } + /// /// Returns a string with essential information for debugging. /// diff --git a/modules/swagger-codegen/src/main/resources/csharp/api.mustache b/modules/swagger-codegen/src/main/resources/csharp/api.mustache index 6708fa1e16d..51f8b3f9394 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/api.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/api.mustache @@ -1,6 +1,7 @@ using System; using System.IO; using System.Collections.Generic; +using System.Linq; using RestSharp; using {{packageName}}.Client; {{#hasImport}}using {{packageName}}.Model; @@ -22,8 +23,8 @@ namespace {{packageName}}.Api /// {{notes}} /// {{#allParams}}/// {{description}} - {{/allParams}}/// {{#returnType}}{{^returnContainer}}{{{returnType}}}{{/returnContainer}}{{/returnType}} - {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} {{nickname}} ({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); + {{/allParams}}/// {{#returnType}}{{returnType}}{{/returnType}} + {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} {{operationId}} ({{#allParams}}{{{dataType}}} {{paramName}}{{^required}}{{#optionalMethodArgument}} = null{{/optionalMethodArgument}}{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); /// /// {{summary}} @@ -32,8 +33,28 @@ namespace {{packageName}}.Api /// {{notes}} /// {{#allParams}}/// {{description}} - {{/allParams}}/// {{#returnType}}{{^returnContainer}}{{{returnType}}}{{/returnContainer}}{{/returnType}} - {{#returnType}}System.Threading.Tasks.Task<{{{returnType}}}>{{/returnType}}{{^returnType}}System.Threading.Tasks.Task{{/returnType}} {{nickname}}Async ({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); + {{/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}}); + + /// + /// {{summary}} + /// + /// + /// {{notes}} + /// + {{#allParams}}/// {{description}} + {{/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}}); + + /// + /// {{summary}} + /// + /// + /// {{notes}} + /// + {{#allParams}}/// {{description}} + {{/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}} } @@ -42,71 +63,105 @@ namespace {{packageName}}.Api /// public class {{classname}} : I{{classname}} { - /// - /// Initializes a new instance of the class. - /// - /// an instance of ApiClient (optional) - /// - public {{classname}}(ApiClient apiClient = null) - { - if (apiClient == null) // use the default one in Configuration - this.ApiClient = Configuration.DefaultApiClient; - else - this.ApiClient = apiClient; - } - /// /// Initializes a new instance of the class. /// /// public {{classname}}(String basePath) { - this.ApiClient = new ApiClient(basePath); + this.Configuration = new Configuration(new ApiClient(basePath)); } /// - /// Sets the base path of the API client. + /// Initializes a new instance of the class + /// using Configuration object /// - /// The base path - /// The base path - public void SetBasePath(String basePath) + /// An instance of Configuration + /// + public {{classname}}(Configuration configuration = null) { - this.ApiClient.BasePath = basePath; + if (configuration == null) // use the default one in Configuration + this.Configuration = Configuration.Default; + else + this.Configuration = configuration; } - + /// /// Gets the base path of the API client. /// /// The base path public String GetBasePath() { - return this.ApiClient.BasePath; + return this.Configuration.ApiClient.RestClient.BaseUrl.ToString(); + } + + /// + /// Sets the base path of the API client. + /// + /// The base path + [Obsolete("SetBasePath is deprecated, please do 'Configuraiton.ApiClient = new ApiClient(\"http://new-path\")' instead.")] + public void SetBasePath(String basePath) + { + // do nothing } /// - /// Gets or sets the API client. + /// Gets or sets the configuration object /// - /// An instance of the ApiClient - public ApiClient ApiClient {get; set;} - + /// An instance of the Configuration + public Configuration Configuration {get; set;} + + /// + /// Gets the default header. + /// + /// Dictionary of HTTP header + [Obsolete("DefaultHeader is deprecated, please use Configuration.DefaultHeader instead.")] + public Dictionary DefaultHeader() + { + return this.Configuration.DefaultHeader; + } + + /// + /// Add default header. + /// + /// Header field name. + /// Header field value. + /// + [Obsolete("AddDefaultHeader is deprecated, please use Configuration.AddDefaultHeader instead.")] + public void AddDefaultHeader(string key, string value) + { + this.Configuration.AddDefaultHeader(key, value); + } + {{#operation}} /// /// {{summary}} {{notes}} /// {{#allParams}}/// {{description}} - {{/allParams}}/// {{#returnType}}{{^returnContainer}}{{{returnType}}}{{/returnContainer}}{{/returnType}} - public {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} {{nickname}} ({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) + {{/allParams}}/// {{#returnType}}{{returnType}}{{/returnType}} + public {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} {{operationId}} ({{#allParams}}{{{dataType}}} {{paramName}}{{^required}}{{#optionalMethodArgument}} = null{{/optionalMethodArgument}}{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) + { + {{#returnType}}ApiResponse<{{{returnType}}}> response = {{operationId}}WithHttpInfo({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); + return response.Data;{{/returnType}}{{^returnType}}{{operationId}}WithHttpInfo({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}});{{/returnType}} + } + + /// + /// {{summary}} {{notes}} + /// + {{#allParams}}/// {{description}} + {{/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}}) { {{#allParams}}{{#required}} // verify the required parameter '{{paramName}}' is set - if ({{paramName}} == null) throw new ApiException(400, "Missing required parameter '{{paramName}}' when calling {{nickname}}"); + if ({{paramName}} == null) throw new ApiException(400, "Missing required parameter '{{paramName}}' when calling {{operationId}}"); {{/required}}{{/allParams}} var path_ = "{{path}}"; var pathParams = new Dictionary(); var queryParams = new Dictionary(); - var headerParams = new Dictionary(); + var headerParams = new Dictionary(Configuration.DefaultHeader); var formParams = new Dictionary(); var fileParams = new Dictionary(); String postBody = null; @@ -115,47 +170,88 @@ namespace {{packageName}}.Api String[] http_header_accepts = new String[] { {{#produces}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }; - String http_header_accept = ApiClient.SelectHeaderAccept(http_header_accepts); + String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); if (http_header_accept != null) - headerParams.Add("Accept", ApiClient.SelectHeaderAccept(http_header_accepts)); + headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json pathParams.Add("format", "json"); - {{#pathParams}}if ({{paramName}} != null) pathParams.Add("{{baseName}}", ApiClient.ParameterToString({{paramName}})); // path parameter + {{#pathParams}}if ({{paramName}} != null) pathParams.Add("{{baseName}}", Configuration.ApiClient.ParameterToString({{paramName}})); // path parameter {{/pathParams}} - {{#queryParams}}if ({{paramName}} != null) queryParams.Add("{{baseName}}", ApiClient.ParameterToString({{paramName}})); // query parameter + {{#queryParams}}if ({{paramName}} != null) queryParams.Add("{{baseName}}", Configuration.ApiClient.ParameterToString({{paramName}})); // query parameter {{/queryParams}} - {{#headerParams}}if ({{paramName}} != null) headerParams.Add("{{baseName}}", ApiClient.ParameterToString({{paramName}})); // header parameter + {{#headerParams}}if ({{paramName}} != null) headerParams.Add("{{baseName}}", Configuration.ApiClient.ParameterToString({{paramName}})); // header parameter {{/headerParams}} - {{#formParams}}if ({{paramName}} != null) {{#isFile}}fileParams.Add("{{baseName}}", ApiClient.ParameterToFile("{{baseName}}", {{paramName}}));{{/isFile}}{{^isFile}}formParams.Add("{{baseName}}", ApiClient.ParameterToString({{paramName}})); // form parameter{{/isFile}} + {{#formParams}}if ({{paramName}} != null) {{#isFile}}fileParams.Add("{{baseName}}", Configuration.ApiClient.ParameterToFile("{{baseName}}", {{paramName}}));{{/isFile}}{{^isFile}}formParams.Add("{{baseName}}", Configuration.ApiClient.ParameterToString({{paramName}})); // form parameter{{/isFile}} {{/formParams}} - {{#bodyParam}}postBody = ApiClient.Serialize({{paramName}}); // http body (model) parameter + {{#bodyParam}}postBody = Configuration.ApiClient.Serialize({{paramName}}); // http body (model) parameter {{/bodyParam}} - - // authentication setting, if any - String[] authSettings = new String[] { {{#authMethods}}"{{name}}"{{#hasMore}}, {{/hasMore}}{{/authMethods}} }; + + {{#authMethods}} + // authentication ({{name}}) required + {{#isApiKey}}{{#isKeyInHeader}} + var apiKeyValue = Configuration.GetApiKeyWithPrefix("{{keyParamName}}"); + if (!String.IsNullOrEmpty(apiKeyValue)) + { + headerParams["{{keyParamName}}"] = apiKeyValue; + }{{/isKeyInHeader}}{{#isKeyInQuery}} + var apiKeyValue = Configuration.GetApiKeyWithPrefix("{{keyParamName}}"); + if (!String.IsNullOrEmpty(apiKeyValue)) + { + queryParams["{{keyParamName}}"] = apiKeyValue; + }{{/isKeyInQuery}}{{/isApiKey}}{{#isBasic}} + // http basic authentication required + if (!String.IsNullOrEmpty(Configuration.Username) || !String.IsNullOrEmpty(Configuration.Password)) + { + headerParams["Authorization"] = "Basic " + Base64Encode(Configuration.Username + ":" + Configuration.Password); + }{{/isBasic}}{{#isOAuth}} + // oauth required + if (!String.IsNullOrEmpty(Configuration.AccessToken)) + { + headerParams["Authorization"] = "Bearer " + Configuration.AccessToken; + }{{/isOAuth}} + {{/authMethods}} // make the HTTP request - IRestResponse response = (IRestResponse) ApiClient.CallApi(path_, Method.{{httpMethod}}, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); + IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, Method.{{httpMethod}}, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + + int statusCode = (int) response.StatusCode; - if (((int)response.StatusCode) >= 400) - throw new ApiException ((int)response.StatusCode, "Error calling {{nickname}}: " + response.Content, response.Content); - else if (((int)response.StatusCode) == 0) - throw new ApiException ((int)response.StatusCode, "Error calling {{nickname}}: " + response.ErrorMessage, response.ErrorMessage); + if (statusCode >= 400) + throw new ApiException (statusCode, "Error calling {{operationId}}: " + response.Content, response.Content); + else if (statusCode == 0) + throw new ApiException (statusCode, "Error calling {{operationId}}: " + response.ErrorMessage, response.ErrorMessage); - {{#returnType}}return ({{{returnType}}}) ApiClient.Deserialize(response, typeof({{{returnType}}}));{{/returnType}}{{^returnType}}return;{{/returnType}} + {{#returnType}}return new ApiResponse<{{{returnType}}}>(statusCode, + response.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), + ({{{returnType}}}) Configuration.ApiClient.Deserialize(response, typeof({{{returnType}}})));{{/returnType}} + {{^returnType}}return new ApiResponse(statusCode, + response.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), + null);{{/returnType}} } /// /// {{summary}} {{notes}} /// {{#allParams}}/// {{description}} - {{/allParams}}/// {{#returnType}}{{^returnContainer}}{{{returnType}}}{{/returnContainer}}{{/returnType}} - {{#returnType}}public async System.Threading.Tasks.Task<{{{returnType}}}>{{/returnType}}{{^returnType}}public async System.Threading.Tasks.Task{{/returnType}} {{nickname}}Async ({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) + {{/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}}) + { + {{#returnType}}ApiResponse<{{{returnType}}}> response = await {{operationId}}AsyncWithHttpInfo({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); + return response.Data;{{/returnType}}{{^returnType}}await {{operationId}}AsyncWithHttpInfo({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}});{{/returnType}} + + } + + /// + /// {{summary}} {{notes}} + /// + {{#allParams}}/// {{description}} + {{/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 {{nickname}}"); + if ({{paramName}} == null) throw new ApiException(400, "Missing required parameter '{{paramName}}' when calling {{operationId}}"); {{/required}}{{/allParams}} var path_ = "{{path}}"; @@ -171,34 +267,65 @@ namespace {{packageName}}.Api String[] http_header_accepts = new String[] { {{#produces}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }; - String http_header_accept = ApiClient.SelectHeaderAccept(http_header_accepts); + String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); if (http_header_accept != null) - headerParams.Add("Accept", ApiClient.SelectHeaderAccept(http_header_accepts)); + headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json pathParams.Add("format", "json"); - {{#pathParams}}if ({{paramName}} != null) pathParams.Add("{{baseName}}", ApiClient.ParameterToString({{paramName}})); // path parameter + {{#pathParams}}if ({{paramName}} != null) pathParams.Add("{{baseName}}", Configuration.ApiClient.ParameterToString({{paramName}})); // path parameter {{/pathParams}} - {{#queryParams}}if ({{paramName}} != null) queryParams.Add("{{baseName}}", ApiClient.ParameterToString({{paramName}})); // query parameter + {{#queryParams}}if ({{paramName}} != null) queryParams.Add("{{baseName}}", Configuration.ApiClient.ParameterToString({{paramName}})); // query parameter {{/queryParams}} - {{#headerParams}}if ({{paramName}} != null) headerParams.Add("{{baseName}}", ApiClient.ParameterToString({{paramName}})); // header parameter + {{#headerParams}}if ({{paramName}} != null) headerParams.Add("{{baseName}}", Configuration.ApiClient.ParameterToString({{paramName}})); // header parameter {{/headerParams}} - {{#formParams}}if ({{paramName}} != null) {{#isFile}}fileParams.Add("{{baseName}}", ApiClient.ParameterToFile("{{baseName}}", {{paramName}}));{{/isFile}}{{^isFile}}formParams.Add("{{baseName}}", ApiClient.ParameterToString({{paramName}})); // form parameter{{/isFile}} + {{#formParams}}if ({{paramName}} != null) {{#isFile}}fileParams.Add("{{baseName}}", Configuration.ApiClient.ParameterToFile("{{baseName}}", {{paramName}}));{{/isFile}}{{^isFile}}formParams.Add("{{baseName}}", Configuration.ApiClient.ParameterToString({{paramName}})); // form parameter{{/isFile}} {{/formParams}} - {{#bodyParam}}postBody = ApiClient.Serialize({{paramName}}); // http body (model) parameter + {{#bodyParam}}postBody = Configuration.ApiClient.Serialize({{paramName}}); // http body (model) parameter {{/bodyParam}} - - // authentication setting, if any - String[] authSettings = new String[] { {{#authMethods}}"{{name}}"{{#hasMore}}, {{/hasMore}}{{/authMethods}} }; - - // make the HTTP request - IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path_, Method.{{httpMethod}}, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); - if (((int)response.StatusCode) >= 400) - throw new ApiException ((int)response.StatusCode, "Error calling {{nickname}}: " + response.Content, response.Content); - {{#returnType}}return ({{{returnType}}}) ApiClient.Deserialize(response, typeof({{{returnType}}}));{{/returnType}}{{^returnType}} - return;{{/returnType}} + {{#authMethods}} + // authentication ({{name}}) required + {{#isApiKey}}{{#isKeyInHeader}} + var apiKeyValue = Configuration.GetApiKeyWithPrefix("{{keyParamName}}"); + if (!String.IsNullOrEmpty(apiKeyValue)) + { + headerParams["{{keyParamName}}"] = apiKeyValue; + }{{/isKeyInHeader}}{{#isKeyInQuery}} + var apiKeyValue = Configuration.GetApiKeyWithPrefix("{{keyParamName}}"); + if (!String.IsNullOrEmpty(apiKeyValue)) + { + queryParams["{{keyParamName}}"] = apiKeyValue; + }{{/isKeyInQuery}}{{/isApiKey}}{{#isBasic}} + // http basic authentication required + if (!String.IsNullOrEmpty(Configuration.Username) || !String.IsNullOrEmpty(Configuration.Password)) + { + headerParams["Authorization"] = "Basic " + Base64Encode(Configuration.Username + ":" + Configuration.Password); + }{{/isBasic}}{{#isOAuth}} + // oauth required + if (!String.IsNullOrEmpty(Configuration.AccessToken)) + { + headerParams["Authorization"] = "Bearer " + Configuration.AccessToken; + }{{/isOAuth}} + {{/authMethods}} + + // make the HTTP request + IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, Method.{{httpMethod}}, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + + int statusCode = (int) response.StatusCode; + + if (statusCode >= 400) + throw new ApiException (statusCode, "Error calling {{operationId}}: " + response.Content, response.Content); + else if (statusCode == 0) + throw new ApiException (statusCode, "Error calling {{operationId}}: " + response.ErrorMessage, response.ErrorMessage); + + {{#returnType}}return new ApiResponse<{{{returnType}}}>(statusCode, + response.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), + ({{{returnType}}}) Configuration.ApiClient.Deserialize(response, typeof({{{returnType}}})));{{/returnType}} + {{^returnType}}return new ApiResponse(statusCode, + response.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), + null);{{/returnType}} } {{/operation}} } diff --git a/modules/swagger-codegen/src/main/resources/csharp/model.mustache b/modules/swagger-codegen/src/main/resources/csharp/model.mustache index 606745b47f6..2504646b8ef 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/model.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/model.mustache @@ -50,6 +50,20 @@ namespace {{packageName}}.Model return sb.ToString(); } + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + var sb = new StringBuilder(); + sb.Append("class {{classname}} {\n"); + {{#vars}}sb.Append(" {{name}}: ").Append({{name}}).Append("\n"); + {{/vars}} + sb.Append("}\n"); + return sb.ToString(); + } + /// /// Returns the JSON string presentation of the object /// @@ -91,7 +105,7 @@ namespace {{packageName}}.Model this.{{name}} == other.{{name}} || this.{{name}} != null && this.{{name}}.SequenceEqual(other.{{name}}) - ){{#hasMore}} && {{/hasMore}}{{/isNotContainer}}{{/vars}}; + ){{#hasMore}} && {{/hasMore}}{{/isNotContainer}}{{/vars}}{{^vars}}false{{/vars}}; } /// diff --git a/modules/swagger-codegen/src/main/resources/flaskConnexion/controller.mustache b/modules/swagger-codegen/src/main/resources/flaskConnexion/controller.mustache index cb8544aa1b4..06b3c63fdb0 100644 --- a/modules/swagger-codegen/src/main/resources/flaskConnexion/controller.mustache +++ b/modules/swagger-codegen/src/main/resources/flaskConnexion/controller.mustache @@ -3,7 +3,7 @@ {{#operations}} {{#operation}} -def {{vendorExtensions.x-operationId}}({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) -> str: +def {{operationId}}({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) -> str: return 'do some magic!' {{/operation}} {{/operations}} 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 d1908e5d2f1..25b5d9adfbf 100644 --- a/modules/swagger-codegen/src/main/resources/objc/ApiClient-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/ApiClient-body.mustache @@ -128,24 +128,25 @@ static void (^reachabilityChangeBlock)(int); /* * Detect `Accept` from accepts */ -+ (NSString *) selectHeaderAccept:(NSArray *)accepts -{ ++ (NSString *) selectHeaderAccept:(NSArray *)accepts { if (accepts == nil || [accepts count] == 0) { return @""; } NSMutableArray *lowerAccepts = [[NSMutableArray alloc] initWithCapacity:[accepts count]]; - [accepts enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { - [lowerAccepts addObject:[obj lowercaseString]]; - }]; - - - if ([lowerAccepts containsObject:@"application/json"]) { - return @"application/json"; + for (NSString *string in accepts) { + NSString * lowerAccept = [string lowercaseString]; + if ([lowerAccept containsString:@"application/json"]) { + return @"application/json"; + } + [lowerAccepts addObject:lowerAccept]; } - else { - return [lowerAccepts componentsJoinedByString:@", "]; + + if (lowerAccepts.count == 1) { + return [lowerAccepts firstObject]; } + + return [lowerAccepts componentsJoinedByString:@", "]; } /* @@ -171,7 +172,7 @@ static void (^reachabilityChangeBlock)(int); } + (NSString*)escape:(id)unescaped { - if([unescaped isKindOfClass:[NSString class]]){ + if ([unescaped isKindOfClass:[NSString class]]){ return (NSString *)CFBridgingRelease (CFURLCreateStringByAddingPercentEscapes( NULL, @@ -212,7 +213,7 @@ static void (^reachabilityChangeBlock)(int); -(Boolean) executeRequestWithId:(NSNumber*) requestId { NSSet* matchingItems = [queuedRequests objectsPassingTest:^BOOL(id obj, BOOL *stop) { - if([obj intValue] == [requestId intValue]) { + if ([obj intValue] == [requestId intValue]) { return YES; } else { @@ -220,7 +221,7 @@ static void (^reachabilityChangeBlock)(int); } }]; - if(matchingItems.count == 1) { + if (matchingItems.count == 1) { {{classPrefix}}DebugLog(@"removed request id %@", requestId); [queuedRequests removeObject:requestId]; return YES; @@ -268,7 +269,7 @@ static void (^reachabilityChangeBlock)(int); } // call the reachability block, if configured - if(reachabilityChangeBlock != nil) { + if (reachabilityChangeBlock != nil) { reachabilityChangeBlock(status); } }]; @@ -410,16 +411,16 @@ static void (^reachabilityChangeBlock)(int); completionBlock: (void (^)(id, NSError *))completionBlock { AFHTTPRequestOperation *op = [self HTTPRequestOperationWithRequest:request success:^(AFHTTPRequestOperation *operation, id response) { - if([self executeRequestWithId:requestId]) { + if ([self executeRequestWithId:requestId]) { [self logResponse:operation forRequest:request error:nil]; NSDictionary *responseHeaders = [[operation response] allHeaderFields]; self.HTTPResponseHeaders = responseHeaders; completionBlock(response, nil); } } failure:^(AFHTTPRequestOperation *operation, NSError *error) { - if([self executeRequestWithId:requestId]) { + if ([self executeRequestWithId:requestId]) { NSMutableDictionary *userInfo = [error.userInfo mutableCopy]; - if(operation.responseObject) { + if (operation.responseObject) { // Add in the (parsed) response body. userInfo[{{classPrefix}}ResponseObjectErrorKey] = operation.responseObject; } @@ -590,10 +591,10 @@ static void (^reachabilityChangeBlock)(int); // request cache BOOL hasHeaderParams = false; - if(headerParams != nil && [headerParams count] > 0) { + if (headerParams != nil && [headerParams count] > 0) { hasHeaderParams = true; } - if(offlineState) { + if (offlineState) { {{classPrefix}}DebugLog(@"%@ cache forced", resourcePath); [request setCachePolicy:NSURLRequestReturnCacheDataDontLoad]; } @@ -606,7 +607,7 @@ static void (^reachabilityChangeBlock)(int); [request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData]; } - if(hasHeaderParams){ + if (hasHeaderParams){ for(NSString * key in [headerParams keyEnumerator]){ [request setValue:[headerParams valueForKey:key] forHTTPHeaderField:key]; } @@ -639,36 +640,36 @@ static void (^reachabilityChangeBlock)(int); int counter = 0; NSMutableString * requestUrl = [NSMutableString stringWithFormat:@"%@", path]; - if(queryParams != nil){ + if (queryParams != nil){ for(NSString * key in [queryParams keyEnumerator]){ - if(counter == 0) separator = @"?"; + if (counter == 0) separator = @"?"; else separator = @"&"; id queryParam = [queryParams valueForKey:key]; - if([queryParam isKindOfClass:[NSString class]]){ + if ([queryParam isKindOfClass:[NSString class]]){ [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, [{{classPrefix}}ApiClient escape:key], [{{classPrefix}}ApiClient escape:[queryParams valueForKey:key]]]]; } - else if([queryParam isKindOfClass:[{{classPrefix}}QueryParamCollection class]]){ + else if ([queryParam isKindOfClass:[{{classPrefix}}QueryParamCollection class]]){ {{classPrefix}}QueryParamCollection * coll = ({{classPrefix}}QueryParamCollection*) queryParam; NSArray* values = [coll values]; NSString* format = [coll format]; - if([format isEqualToString:@"csv"]) { + if ([format isEqualToString:@"csv"]) { [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, [{{classPrefix}}ApiClient escape:key], [NSString stringWithFormat:@"%@", [values componentsJoinedByString:@","]]]]; } - else if([format isEqualToString:@"tsv"]) { + else if ([format isEqualToString:@"tsv"]) { [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, [{{classPrefix}}ApiClient escape:key], [NSString stringWithFormat:@"%@", [values componentsJoinedByString:@"\t"]]]]; } - else if([format isEqualToString:@"pipes"]) { + else if ([format isEqualToString:@"pipes"]) { [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, [{{classPrefix}}ApiClient escape:key], [NSString stringWithFormat:@"%@", [values componentsJoinedByString:@"|"]]]]; } - else if([format isEqualToString:@"multi"]) { + else if ([format isEqualToString:@"multi"]) { for(id obj in values) { [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, [{{classPrefix}}ApiClient escape:key], [NSString stringWithFormat:@"%@", obj]]]; 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 60358e4e9da..d84e350360f 100644 --- a/modules/swagger-codegen/src/main/resources/objc/api-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/api-body.mustache @@ -105,7 +105,7 @@ static {{classname}}* singletonAPI = nil; {{/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}} @@ -114,7 +114,7 @@ static {{classname}}* singletonAPI = nil; {{/queryParams}} NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; - {{#headerParams}}if({{paramName}} != nil) { + {{#headerParams}}if ({{paramName}} != nil) { headerParams[@"{{baseName}}"] = {{paramName}}; } {{/headerParams}} @@ -159,7 +159,7 @@ static {{classname}}* singletonAPI = nil; {{#requiredParamCount}} {{#requiredParams}} - if({{paramName}} == nil) { + if ({{paramName}} == nil) { // error } {{/requiredParams}} diff --git a/modules/swagger-codegen/src/main/resources/objc/model-body.mustache b/modules/swagger-codegen/src/main/resources/objc/model-body.mustache index 33c0f8cf42b..3d70cebfae2 100644 --- a/modules/swagger-codegen/src/main/resources/objc/model-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/model-body.mustache @@ -4,6 +4,18 @@ @implementation {{classname}} +- (instancetype)init { + self = [super init]; + + if (self) { + // initalise property's default value, if any + {{#vars}}{{#defaultValue}}self.{{name}} = {{{defaultValue}}}; + {{/defaultValue}}{{/vars}} + } + + return self; +} + /** * Maps json key to property name. * This method is used by `JSONModel`. diff --git a/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache index 11fe3827d48..be18e221972 100644 --- a/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache @@ -131,7 +131,7 @@ class ApiClient * @throws \{{invokerPackage}}\ApiException on a non 2xx response * @return mixed */ - public function callApi($resourcePath, $method, $queryParams, $postData, $headerParams, $responseType=null) + public function callApi($resourcePath, $method, $queryParams, $postData, $headerParams, $responseType = null) { $headers = array(); @@ -149,7 +149,7 @@ class ApiClient // form data if ($postData and in_array('Content-Type: application/x-www-form-urlencoded', $headers)) { $postData = http_build_query($postData); - } else if ((is_object($postData) or is_array($postData)) and !in_array('Content-Type: multipart/form-data', $headers)) { // json model + } elseif ((is_object($postData) or is_array($postData)) and !in_array('Content-Type: multipart/form-data', $headers)) { // json model $postData = json_encode($this->serializer->sanitizeForSerialization($postData)); } @@ -160,7 +160,7 @@ class ApiClient if ($this->config->getCurlTimeout() != 0) { curl_setopt($curl, CURLOPT_TIMEOUT, $this->config->getCurlTimeout()); } - // return the result on success, rather than just TRUE + // return the result on success, rather than just true curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); @@ -178,21 +178,21 @@ class ApiClient if ($method == self::$POST) { curl_setopt($curl, CURLOPT_POST, true); curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); - } else if ($method == self::$HEAD) { + } elseif ($method == self::$HEAD) { curl_setopt($curl, CURLOPT_NOBODY, true); - } else if ($method == self::$OPTIONS) { + } elseif ($method == self::$OPTIONS) { curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "OPTIONS"); curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); - } else if ($method == self::$PATCH) { + } elseif ($method == self::$PATCH) { curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PATCH"); curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); - } else if ($method == self::$PUT) { + } elseif ($method == self::$PUT) { curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT"); curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); - } else if ($method == self::$DELETE) { + } elseif ($method == self::$DELETE) { curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "DELETE"); curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); - } else if ($method != self::$GET) { + } elseif ($method != self::$GET) { throw new ApiException('Method ' . $method . ' is not recognized.'); } curl_setopt($curl, CURLOPT_URL, $url); @@ -216,7 +216,7 @@ class ApiClient // Make the request $response = curl_exec($curl); $http_header_size = curl_getinfo($curl, CURLINFO_HEADER_SIZE); - $http_header = substr($response, 0, $http_header_size); + $http_header = $this->http_parse_headers(substr($response, 0, $http_header_size)); $http_body = substr($response, $http_header_size); $response_info = curl_getinfo($curl); @@ -228,10 +228,10 @@ class ApiClient // Handle the response if ($response_info['http_code'] == 0) { throw new ApiException("API call to $url timed out: ".serialize($response_info), 0, null, null); - } else if ($response_info['http_code'] >= 200 && $response_info['http_code'] <= 299 ) { + } elseif ($response_info['http_code'] >= 200 && $response_info['http_code'] <= 299 ) { // return raw body if response is a file if ($responseType == '\SplFileObject') { - return array($http_body, $http_header); + return array($http_body, $response_info['http_code'], $http_header); } $data = json_decode($http_body); @@ -249,7 +249,7 @@ class ApiClient $response_info['http_code'], $http_header, $data ); } - return array($data, $http_header); + return array($data, $response_info['http_code'], $http_header); } /** @@ -287,4 +287,52 @@ class ApiClient return implode(',', $content_type); } } + + /** + * Return an array of HTTP response headers + * + * @param string $raw_headers A string of raw HTTP response headers + * + * @return string[] Array of HTTP response heaers + */ + protected function http_parse_headers($raw_headers) + { + // ref/credit: http://php.net/manual/en/function.http-parse-headers.php#112986 + $headers = array(); + $key = ''; // [+] + + foreach(explode("\n", $raw_headers) as $i => $h) + { + $h = explode(':', $h, 2); + + if (isset($h[1])) + { + if (!isset($headers[$h[0]])) + $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]))); // [+] + } + 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]))); // [+] + } + + $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]); // [+] + } // [+] + } + + 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 45b56aa9b97..133c1b1f454 100644 --- a/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache +++ b/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache @@ -56,14 +56,14 @@ class ObjectSerializer { if (is_scalar($data) || null === $data) { $sanitized = $data; - } else if ($data instanceof \DateTime) { + } elseif ($data instanceof \DateTime) { $sanitized = $data->format(\DateTime::ISO8601); - } else if (is_array($data)) { + } elseif (is_array($data)) { foreach ($data as $property => $value) { $data[$property] = $this->sanitizeForSerialization($value); } $sanitized = $data; - } else if (is_object($data)) { + } elseif (is_object($data)) { $values = array(); foreach (array_keys($data::$swaggerTypes) as $property) { $getter = $data::$getters[$property]; @@ -198,7 +198,7 @@ class ObjectSerializer $deserialized = $data; } elseif ($class === '\SplFileObject') { // determine file name - if (preg_match('/Content-Disposition: inline; filename=[\'"]?([^\'"\s]+)[\'"]?$/i', $httpHeader, $match)) { + if (array_key_exists('Content-Disposition', $httpHeaders) && preg_match('/inline; filename=[\'"]?([^\'"\s]+)[\'"]?$/i', $httpHeader['Content-Disposition'], $match)) { $filename = Configuration::getDefaultConfiguration()->getTempFolderPath().$match[1]; } else { $filename = tempnam(Configuration::getDefaultConfiguration()->getTempFolderPath(), ''); diff --git a/modules/swagger-codegen/src/main/resources/php/api.mustache b/modules/swagger-codegen/src/main/resources/php/api.mustache index 53a81030813..cce59f4d94b 100644 --- a/modules/swagger-codegen/src/main/resources/php/api.mustache +++ b/modules/swagger-codegen/src/main/resources/php/api.mustache @@ -92,7 +92,7 @@ use \{{invokerPackage}}\ObjectSerializer; {{#operation}} /** - * {{{nickname}}} + * {{{operationId}}} * * {{{summary}}} * @@ -100,12 +100,28 @@ use \{{invokerPackage}}\ObjectSerializer; {{/allParams}} * @return {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} * @throws \{{invokerPackage}}\ApiException on non-2xx response */ - public function {{nickname}}({{#allParams}}${{paramName}}{{^required}}=null{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) + public function {{operationId}}({{#allParams}}${{paramName}}{{^required}} = null{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) + { + list($response, $statusCode, $httpHeader) = $this->{{operationId}}WithHttpInfo ({{#allParams}}${{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); + return $response; + } + + + /** + * {{{operationId}}}WithHttpInfo + * + * {{{summary}}} + * + {{#allParams}} * @param {{dataType}} ${{paramName}} {{description}} {{#required}}(required){{/required}}{{^required}}(optional){{/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 + */ + public function {{operationId}}WithHttpInfo({{#allParams}}${{paramName}}{{^required}} = null{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) { {{#allParams}}{{#required}} // verify the required parameter '{{paramName}}' is set if (${{paramName}} === null) { - throw new \InvalidArgumentException('Missing the required parameter ${{paramName}} when calling {{nickname}}'); + throw new \InvalidArgumentException('Missing the required parameter ${{paramName}} when calling {{operationId}}'); }{{/required}}{{/allParams}} // parse inputs @@ -162,37 +178,38 @@ use \{{invokerPackage}}\ObjectSerializer; // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present - } else if (count($formParams) > 0) { + } elseif (count($formParams) > 0) { $httpBody = $formParams; // for HTTP post (form) } {{#authMethods}}{{#isApiKey}} // this endpoint requires API key authentication $apiKey = $this->apiClient->getApiKeyWithPrefix('{{keyParamName}}'); - if ($apiKey !== null) { + if (strlen($apiKey) !== 0) { {{#isKeyInHeader}}$headerParams['{{keyParamName}}'] = $apiKey;{{/isKeyInHeader}}{{#isKeyInQuery}}$queryParams['{{keyParamName}}'] = $apiKey;{{/isKeyInQuery}} }{{/isApiKey}} {{#isBasic}}// this endpoint requires HTTP basic authentication - if ($this->apiClient->getConfig()->getUsername() !== null or $this->apiClient->getConfig()->getPassword() !== null) { + 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()); }{{/isBasic}}{{#isOAuth}}// this endpoint requires OAuth (access token) - if ($this->apiClient->getConfig()->getAccessToken() !== null) { + if (strlen($this->apiClient->getConfig()->getAccessToken()) !== 0) { $headerParams['Authorization'] = 'Bearer ' . $this->apiClient->getConfig()->getAccessToken(); }{{/isOAuth}} {{/authMethods}} // make the API Call - try - { - list($response, $httpHeader) = $this->apiClient->callApi( + try { + list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( $resourcePath, $method, $queryParams, $httpBody, $headerParams{{#returnType}}, '{{returnType}}'{{/returnType}} ); {{#returnType}} if (!$response) { - return null; + return array(null, $statusCode, $httpHeader); } - return $this->apiClient->getSerializer()->deserialize($response, '{{returnType}}', $httpHeader); + return array($this->apiClient->getSerializer()->deserialize($response, '{{returnType}}', $httpHeader), $statusCode, $httpHeader); + {{/returnType}}{{^returnType}} + return array(null, $statusCode, $httpHeader); {{/returnType}} } catch (ApiException $e) { switch ($e->getCode()) { {{#responses}}{{#dataType}} @@ -204,9 +221,6 @@ use \{{invokerPackage}}\ObjectSerializer; throw $e; } - {{#returnType}} - return null; - {{/returnType}} } {{/operation}} } diff --git a/modules/swagger-codegen/src/main/resources/php/configuration.mustache b/modules/swagger-codegen/src/main/resources/php/configuration.mustache index 14d7957fe54..28082851c00 100644 --- a/modules/swagger-codegen/src/main/resources/php/configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/php/configuration.mustache @@ -211,7 +211,7 @@ class Configuration */ public function setAccessToken($accessToken) { - $this->$accessToken = $accessToken; + $this->accessToken = $accessToken; return $this; } diff --git a/modules/swagger-codegen/src/main/resources/php/model.mustache b/modules/swagger-codegen/src/main/resources/php/model.mustache index 861673982f2..66cabf0122b 100644 --- a/modules/swagger-codegen/src/main/resources/php/model.mustache +++ b/modules/swagger-codegen/src/main/resources/php/model.mustache @@ -89,7 +89,7 @@ class {{classname}} implements ArrayAccess * ${{name}} {{#description}}{{{description}}}{{/description}} * @var {{datatype}} */ - protected ${{name}}; + protected ${{name}}{{#defaultValue}} = {{{defaultValue}}}{{/defaultValue}}; {{/vars}} /** diff --git a/modules/swagger-codegen/src/main/resources/python/model.mustache b/modules/swagger-codegen/src/main/resources/python/model.mustache index 81e0b05849a..aae43175a2e 100644 --- a/modules/swagger-codegen/src/main/resources/python/model.mustache +++ b/modules/swagger-codegen/src/main/resources/python/model.mustache @@ -49,7 +49,7 @@ class {{classname}}(object): } {{#vars}} - self._{{name}} = None + self._{{name}} = {{#defaultValue}}{{{defaultValue}}}{{/defaultValue}}{{^defaultValue}}None{{/defaultValue}} {{/vars}} {{#vars}} @@ -113,5 +113,18 @@ class {{classname}}(object): 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 + {{/model}} {{/models}} diff --git a/modules/swagger-codegen/src/main/resources/qt5cpp/helpers-body.mustache b/modules/swagger-codegen/src/main/resources/qt5cpp/helpers-body.mustache index 7bd9b3f46cc..6b439996724 100644 --- a/modules/swagger-codegen/src/main/resources/qt5cpp/helpers-body.mustache +++ b/modules/swagger-codegen/src/main/resources/qt5cpp/helpers-body.mustache @@ -1,9 +1,9 @@ #include "SWGHelpers.h" #include "SWGModelFactory.h" #include "SWGObject.h" -#import -#import -#import +#include +#include +#include namespace Swagger { diff --git a/modules/swagger-codegen/src/main/resources/ruby/api.mustache b/modules/swagger-codegen/src/main/resources/ruby/api.mustache index a43260c0607..d7967135336 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/api.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/api.mustache @@ -5,8 +5,8 @@ module {{moduleName}} class {{classname}} attr_accessor :api_client - def initialize(api_client = nil) - @api_client = api_client || Configuration.api_client + def initialize(api_client = ApiClient.default) + @api_client = api_client end {{#operation}} {{newline}} @@ -16,13 +16,24 @@ module {{moduleName}} {{/required}}{{/allParams}} # @param [Hash] opts the optional parameters {{#allParams}}{{^required}} # @option opts [{{{dataType}}}] :{{paramName}} {{description}} {{/required}}{{/allParams}} # @return [{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}nil{{/returnType}}] - def {{nickname}}({{#allParams}}{{#required}}{{paramName}}, {{/required}}{{/allParams}}opts = {}) - if Configuration.debugging - Configuration.logger.debug "Calling API: {{classname}}#{{nickname}} ..." + 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}}return data{{/returnType}}{{^returnType}}return nil{{/returnType}} + end + + # {{summary}} + # {{notes}} +{{#allParams}}{{#required}} # @param {{paramName}} {{description}} +{{/required}}{{/allParams}} # @param [Hash] opts the optional parameters +{{#allParams}}{{^required}} # @option opts [{{{dataType}}}] :{{paramName}} {{description}} +{{/required}}{{/allParams}} # @return [Array<({{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}nil{{/returnType}}, Fixnum, Hash)>] {{#returnType}}{{{returnType}}} data{{/returnType}}{{^returnType}}nil{{/returnType}}, response status code and response headers + def {{operationId}}_with_http_info({{#allParams}}{{#required}}{{paramName}}, {{/required}}{{/allParams}}opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug "Calling API: {{classname}}#{{operationId}} ..." end {{#allParams}}{{#required}} # verify the required parameter '{{paramName}}' is set - fail "Missing the required parameter '{{paramName}}' when calling {{nickname}}" if {{{paramName}}}.nil?{{#isEnum}} + fail "Missing the required parameter '{{paramName}}' when calling {{operationId}}" if {{{paramName}}}.nil?{{#isEnum}} unless [{{#allowableValues}}{{#values}}'{{{this}}}'{{^-last}}, {{/-last}}{{/values}}{{/allowableValues}}].include?({{{paramName}}}) fail "invalid value for '{{{paramName}}}', must be one of {{#allowableValues}}{{#values}}{{{this}}}{{^-last}}, {{/-last}}{{/values}}{{/allowableValues}}" end{{/isEnum}} @@ -63,26 +74,17 @@ module {{moduleName}} {{/bodyParam}} auth_names = [{{#authMethods}}'{{name}}'{{#hasMore}}, {{/hasMore}}{{/authMethods}}] - {{#returnType}}result = @api_client.call_api(:{{httpMethod}}, path, + data, status_code, headers = @api_client.call_api(:{{httpMethod}}, path, :header_params => header_params, :query_params => query_params, :form_params => form_params, :body => post_body, - :auth_names => auth_names, - :return_type => '{{{returnType}}}') - if Configuration.debugging - Configuration.logger.debug "API called: {{classname}}#{{nickname}}. Result: #{result.inspect}" + :auth_names => auth_names{{#returnType}}, + :return_type => '{{{returnType}}}'{{/returnType}}) + if @api_client.config.debugging + @api_client.config.logger.debug "API called: {{classname}}#{{operationId}}\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" end - return result{{/returnType}}{{^returnType}}@api_client.call_api(:{{httpMethod}}, path, - :header_params => header_params, - :query_params => query_params, - :form_params => form_params, - :body => post_body, - :auth_names => auth_names) - if Configuration.debugging - Configuration.logger.debug "API called: {{classname}}#{{nickname}}" - end - return nil{{/returnType}} + return data, status_code, headers end {{/operation}} end 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 4ef665bddf2..837b1234fd0 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/api_client.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/api_client.mustache @@ -7,36 +7,37 @@ require 'uri' module {{moduleName}} class ApiClient - - attr_accessor :host + # The Configuration object holding settings to be used in the API client. + attr_accessor :config # Defines the headers to be used in HTTP requests of all API calls by default. # # @return [Hash] attr_accessor :default_headers - # Stores the HTTP response from the last API call using this API client. - attr_accessor :last_response - - def initialize(host = nil) - @host = host || Configuration.base_url - @format = 'json' + def initialize(config = Configuration.default) + @config = config @user_agent = "ruby-swagger-#{VERSION}" @default_headers = { - 'Content-Type' => "application/#{@format.downcase}", + 'Content-Type' => "application/json", 'User-Agent' => @user_agent } end + def self.default + @@default ||= ApiClient.new + end + + # Call an API with given options. + # + # @return [Array<(Object, Fixnum, Hash)>] an array of 3 elements: + # the data deserialized from response body (could be nil), response status code and response headers. def call_api(http_method, path, opts = {}) request = build_request(http_method, path, opts) response = request.run - # record as last response - @last_response = response - - if Configuration.debugging - Configuration.logger.debug "HTTP response body ~BEGIN~\n#{response.body}\n~END~\n" + if @config.debugging + @config.logger.debug "HTTP response body ~BEGIN~\n#{response.body}\n~END~\n" end unless response.success? @@ -47,10 +48,11 @@ module {{moduleName}} end if opts[:return_type] - deserialize(response, opts[:return_type]) + data = deserialize(response, opts[:return_type]) else - nil + data = nil end + return data, response.code, response.headers end def build_request(http_method, path, opts = {}) @@ -69,24 +71,33 @@ module {{moduleName}} :method => http_method, :headers => header_params, :params => query_params, - :ssl_verifypeer => Configuration.verify_ssl, - :sslcert => Configuration.cert_file, - :sslkey => Configuration.key_file, - :cainfo => Configuration.ssl_ca_cert, - :verbose => Configuration.debugging + :ssl_verifypeer => @config.verify_ssl, + :sslcert => @config.cert_file, + :sslkey => @config.key_file, + :cainfo => @config.ssl_ca_cert, + :verbose => @config.debugging } if [:post, :patch, :put, :delete].include?(http_method) req_body = build_request_body(header_params, form_params, opts[:body]) req_opts.update :body => req_body - if Configuration.debugging - Configuration.logger.debug "HTTP request body param ~BEGIN~\n#{req_body}\n~END~\n" + if @config.debugging + @config.logger.debug "HTTP request body param ~BEGIN~\n#{req_body}\n~END~\n" end end Typhoeus::Request.new(url, req_opts) end + # Check if the given MIME is a JSON MIME. + # JSON MIME examples: + # application/json + # application/json; charset=UTF8 + # APPLICATION/JSON + def json_mime?(mime) + !!(mime =~ /\Aapplication\/json(;.*)?\z/i) + end + # Deserialize the response to the given return type. # # @param [String] return_type some examples: "User", "Array[User]", "Hash[String,Integer]" @@ -100,9 +111,7 @@ module {{moduleName}} # ensuring a default content type content_type = response.headers['Content-Type'] || 'application/json' - unless content_type.start_with?('application/json') - fail "Content-Type is not supported: #{content_type}" - end + fail "Content-Type is not supported: #{content_type}" unless json_mime?(content_type) begin data = JSON.parse("[#{body}]", :symbolize_names => true)[0] @@ -162,7 +171,7 @@ module {{moduleName}} # @see Configuration#temp_folder_path # @return [File] the file downloaded def download_file(response) - tmp_file = Tempfile.new '', Configuration.temp_folder_path + tmp_file = Tempfile.new '', @config.temp_folder_path content_disposition = response.headers['Content-Disposition'] if content_disposition filename = content_disposition[/filename=['"]?([^'"\s]+)['"]?/, 1] @@ -174,15 +183,15 @@ module {{moduleName}} tmp_file.close! File.open(path, 'w') { |file| file.write(response.body) } - Configuration.logger.info "File written to #{path}. Please move the file to a proper "\ - "folder for further processing and delete the temp afterwards" + @config.logger.info "File written to #{path}. Please move the file to a proper folder "\ + "for further processing and delete the temp afterwards" File.new(path) end def build_request_url(path) # Add leading and trailing slashes to path path = "/#{path}".gsub(/\/+/, '/') - URI.encode(host + path) + URI.encode(@config.base_url + path) end def build_request_body(header_params, form_params, body) @@ -210,7 +219,7 @@ module {{moduleName}} # Update hearder and query params based on authentication settings. def update_params_for_auth!(header_params, query_params, auth_names) Array(auth_names).each do |auth_name| - auth_setting = Configuration.auth_settings[auth_name] + auth_setting = @config.auth_settings[auth_name] next unless auth_setting case auth_setting[:in] when 'header' then header_params[auth_setting[:key]] = auth_setting[:value] @@ -229,26 +238,21 @@ module {{moduleName}} # @param [Array] accepts array for Accept # @return [String] the Accept header (e.g. application/json) def select_header_accept(accepts) - if accepts.empty? - return - elsif accepts.any?{ |s| s.casecmp('application/json') == 0 } - 'application/json' # look for json data by default - else - accepts.join(',') - end + return nil if accepts.nil? || accepts.empty? + # use JSON when present, otherwise use all of the provided + json_accept = accepts.find { |s| json_mime?(s) } + return json_accept || accepts.join(',') end # Return Content-Type header based on an array of content types provided. # @param [Array] content_types array for Content-Type # @return [String] the Content-Type header (e.g. application/json) def select_header_content_type(content_types) - if content_types.empty? - 'application/json' # use application/json by default - elsif content_types.any?{ |s| s.casecmp('application/json')==0 } - 'application/json' # use application/json if it's included - else - content_types[0] # otherwise, use the first one - end + # use application/json by default + return 'application/json' if content_types.nil? || content_types.empty? + # use JSON when present, otherwise use the first one + json_content_type = content_types.find { |s| json_mime?(s) } + return json_content_type || content_types.first end # Convert object (array, hash, object, etc) to JSON string. diff --git a/modules/swagger-codegen/src/main/resources/ruby/configuration.mustache b/modules/swagger-codegen/src/main/resources/ruby/configuration.mustache index 89bf133b22c..4c05f2560fa 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/configuration.mustache @@ -1,14 +1,7 @@ require 'uri' -require 'singleton' module {{moduleName}} class Configuration - - include Singleton - - # Default api client - attr_accessor :api_client - # Defines url scheme attr_accessor :scheme @@ -94,17 +87,6 @@ module {{moduleName}} attr_accessor :force_ending_format - class << self - def method_missing(method_name, *args, &block) - config = Configuration.instance - if config.respond_to?(method_name) - config.send(method_name, *args, &block) - else - super - end - end - end - def initialize @scheme = '{{scheme}}' @host = '{{host}}' @@ -118,10 +100,17 @@ module {{moduleName}} @inject_format = false @force_ending_format = false @logger = defined?(Rails) ? Rails.logger : Logger.new(STDOUT) + + yield(self) if block_given? end - def api_client - @api_client ||= ApiClient.new + # The default Configuration object. + def self.default + @@default ||= Configuration.new + end + + def configure + yield(self) if block_given? end def scheme=(scheme) diff --git a/modules/swagger-codegen/src/main/resources/ruby/gem.mustache b/modules/swagger-codegen/src/main/resources/ruby/gem.mustache index eb0b8cfbf0f..2000b2be86f 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/gem.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/gem.mustache @@ -19,17 +19,17 @@ require '{{importPath}}' module {{moduleName}} class << self - # Configure sdk using block. - # {{moduleName}}.configure do |config| - # config.username = "xxx" - # config.password = "xxx" - # end - # If no block given, return the configuration singleton instance. + # Customize default settings for the SDK using block. + # {{moduleName}}.configure do |config| + # config.username = "xxx" + # config.password = "xxx" + # end + # If no block given, return the default Configuration object. def configure if block_given? - yield Configuration.instance + yield(Configuration.default) else - Configuration.instance + Configuration.default end end end diff --git a/modules/swagger-codegen/src/main/resources/ruby/model.mustache b/modules/swagger-codegen/src/main/resources/ruby/model.mustache index 1091ab5174a..f253a2c0e60 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/model.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/model.mustache @@ -1,18 +1,20 @@ -module {{moduleName}} -{{#models}} # {{description}} -{{#model}} class {{classname}} < BaseObject - attr_accessor {{#vars}}:{{{name}}}{{#hasMore}}, {{/hasMore}}{{/vars}}{{newline}} - # attribute mapping from ruby-style variable name to JSON key +module {{moduleName}}{{#models}}{{#model}}{{#description}} + # {{{description}}}{{/description}} + class {{classname}} < BaseObject{{#vars}}{{#description}} + # {{{description}}}{{/description}} + attr_accessor :{{{name}}} +{{/vars}} + + # Attribute mapping from ruby-style variable name to JSON key. def self.attribute_map { {{#vars}} - # {{description}} :'{{{name}}}' => :'{{{baseName}}}'{{#hasMore}},{{/hasMore}} {{/vars}} } end - # attribute type + # Attribute type mapping. def self.swagger_types { {{#vars}}:'{{{name}}}' => :'{{{datatype}}}'{{#hasMore}},{{/hasMore}} @@ -21,7 +23,7 @@ module {{moduleName}} end def initialize(attributes = {}) - return if !attributes.is_a?(Hash) || attributes.empty? + 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} @@ -30,11 +32,14 @@ module {{moduleName}} if attributes[:'{{{baseName}}}'] {{#isContainer}}if (value = attributes[:'{{{baseName}}}']).is_a?(Array) self.{{{name}}} = value - end{{/isContainer}}{{^isContainer}}self.{{{name}}} = attributes[:'{{{baseName}}}']{{/isContainer}} + end{{/isContainer}}{{^isContainer}}self.{{{name}}} = attributes[:'{{{baseName}}}']{{/isContainer}}{{#defaultValue}} + else + self.{{{name}}} = {{{defaultValue}}}{{/defaultValue}} end {{/vars}} end {{#vars}}{{#isEnum}} + # Custom attribute writer method checking allowed values (enum). def {{{name}}}=({{{name}}}) allowed_values = [{{#allowableValues}}{{#values}}"{{{this}}}"{{^-last}}, {{/-last}}{{/values}}{{/allowableValues}}] if {{{name}}} && !allowed_values.include?({{{name}}}) @@ -43,6 +48,22 @@ module {{moduleName}} @{{{name}}} = {{{name}}} end {{/isEnum}}{{/vars}} + # Check equality by comparing each attribute. + def ==(o) + return true if self.equal?(o) + self.class == o.class{{#vars}} && + {{name}} == o.{{name}}{{/vars}} + end + + # @see the `==` method + def eql?(o) + self == o + end + + # Calculate hash code according to all attributes. + def hash + [{{#vars}}{{name}}{{#hasMore}}, {{/hasMore}}{{/vars}}].hash + end end {{/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 87b04b5900f..3b74dca8162 100644 --- a/modules/swagger-codegen/src/main/resources/scala/api.mustache +++ b/modules/swagger-codegen/src/main/resources/scala/api.mustache @@ -30,7 +30,7 @@ class {{classname}}(val defBasePath: String = "{{basePath}}", {{#allParams}} * @param {{paramName}} {{description}} {{/allParams}} * @return {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} */ - def {{nickname}} ({{#allParams}}{{paramName}}: {{dataType}}{{#defaultValue}} /* = {{{defaultValue}}} */{{/defaultValue}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) {{#returnType}}: Option[{{returnType}}]{{/returnType}} = { + def {{operationId}} ({{#allParams}}{{paramName}}: {{dataType}}{{#defaultValue}} /* = {{{defaultValue}}} */{{/defaultValue}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) {{#returnType}}: Option[{{returnType}}]{{/returnType}} = { // create path and map variables val path = "{{path}}".replaceAll("\\{format\\}","json"){{#pathParams}}.replaceAll("\\{" + "{{baseName}}" + "\\}",apiInvoker.escape({{paramName}})) diff --git a/modules/swagger-codegen/src/main/resources/sinatra/Swaggering.rb b/modules/swagger-codegen/src/main/resources/sinatra/Swaggering.rb index 79aca1da2c9..69cc74556ac 100644 --- a/modules/swagger-codegen/src/main/resources/sinatra/Swaggering.rb +++ b/modules/swagger-codegen/src/main/resources/sinatra/Swaggering.rb @@ -26,14 +26,22 @@ class Swaggering < Sinatra::Base cross_origin Swaggering.to_resource_listing } + + # for swagger.yaml + get("/swagger.yaml") { + cross_origin + File.read("./swagger.yaml"); + } + @@configuration ||= Configuration.new yield(@@configuration) if block_given? end def self.add_route(method, path, swag={}, opts={}, &block) - fullPath = swag["resourcePath"].to_s + @@configuration.format_specifier + path + #fullPath = swag["resourcePath"].to_s + @@configuration.format_specifier + path + fullPath = path.gsub(/{(.*?)}/, ':\1') - accepted = case method + accepted = case method.to_s.downcase when 'get' get(fullPath, opts, &block) true @@ -47,6 +55,7 @@ class Swaggering < Sinatra::Base put(fullPath, opts, &block) true else + puts "Error adding route: #{method} #{fullPath}" false end diff --git a/modules/swagger-codegen/src/main/resources/sinatra/api.mustache b/modules/swagger-codegen/src/main/resources/sinatra/api.mustache index 7dffb94cdf0..27830feed31 100644 --- a/modules/swagger-codegen/src/main/resources/sinatra/api.mustache +++ b/modules/swagger-codegen/src/main/resources/sinatra/api.mustache @@ -3,7 +3,7 @@ require 'json' {{#operations}} {{#operation}} -MyApp.add_route('{{httpMethod}}', '{{path}}', { +MyApp.add_route('{{httpMethod}}', '{{basePathWithoutHost}}{{path}}', { "resourcePath" => "/{{baseName}}", "summary" => "{{{summary}}}", "nickname" => "{{nickname}}", diff --git a/modules/swagger-codegen/src/main/resources/sinatra/my_app.mustache b/modules/swagger-codegen/src/main/resources/sinatra/my_app.mustache index 8c4a16d7ff5..7d4e87adffc 100644 --- a/modules/swagger-codegen/src/main/resources/sinatra/my_app.mustache +++ b/modules/swagger-codegen/src/main/resources/sinatra/my_app.mustache @@ -7,6 +7,7 @@ class MyApp < Swaggering end end -{{#apis}} -require './lib/{{className}}.rb' -{{/apis}} +# include the api files +Dir["./api/*.rb"].each { |file| + require file +} diff --git a/modules/swagger-codegen/src/main/resources/sinatra/swagger.mustache b/modules/swagger-codegen/src/main/resources/sinatra/swagger.mustache new file mode 100644 index 00000000000..51560926bba --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/sinatra/swagger.mustache @@ -0,0 +1 @@ +{{{swagger-yaml}}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/slim/.htaccess b/modules/swagger-codegen/src/main/resources/slim/.htaccess new file mode 100644 index 00000000000..e47b5fb8a0c --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/slim/.htaccess @@ -0,0 +1,5 @@ + + RewriteEngine On + RewriteCond %{REQUEST_FILENAME} !-f + RewriteRule ^(.*)$ index.php?_url=/$1 [QSA,L] + \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/slim/README.mustache b/modules/swagger-codegen/src/main/resources/slim/README.mustache new file mode 100644 index 00000000000..3b19f46bd38 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/slim/README.mustache @@ -0,0 +1,10 @@ +# 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/swagger-api/swagger-core/wiki) from a remote server, you can easily generate a server stub. This +is an example of building a PHP server. + +This example uses the [Slim Framework](http://www.slimframework.com/). To see how to make this your own, please take a look at the template here: + +[TEMPLATES](https://github.com/swagger-api/swagger-codegen/tree/master/modules/swagger-codegen/src/main/resources/slim/) diff --git a/modules/swagger-codegen/src/main/resources/slim/composer.json b/modules/swagger-codegen/src/main/resources/slim/composer.json new file mode 100644 index 00000000000..c55c8181765 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/slim/composer.json @@ -0,0 +1,6 @@ +{ + "minimum-stability": "RC", + "require": { + "slim/slim": "3.*" + } +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/slim/index.mustache b/modules/swagger-codegen/src/main/resources/slim/index.mustache new file mode 100644 index 00000000000..4fdd77681c3 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/slim/index.mustache @@ -0,0 +1,30 @@ +{{httpMethod}}('{{path}}', function($request, $response, $args) { + {{#hasHeaderParams}}$headers = $request->getHeaders();{{/hasHeaderParams}} + {{#hasQueryParams}}$queryParams = $request->getQueryParams(); + {{#queryParams}}${{paramName}} = $queryParams['{{paramName}}'];{{newline}} {{/queryParams}}{{/hasQueryParams}} + {{#hasFormParams}}{{#formParams}}${{paramName}} = $args['{{paramName}}'];{{newline}} {{/formParams}}{{/hasFormParams}} + {{#hasBodyParam}}$body = $request->getParsedBody();{{/hasBodyParam}} + $response->write('How about implementing {{nickname}} as a {{httpMethod}} method ?'); + return $response; + }); + +{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} + +$app->run(); diff --git a/modules/swagger-codegen/src/main/resources/slim/model.mustache b/modules/swagger-codegen/src/main/resources/slim/model.mustache new file mode 100644 index 00000000000..48f586793ee --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/slim/model.mustache @@ -0,0 +1,15 @@ += 3.0.0{{#usePromiseKit}} +github "Alamofire/Alamofire" >= 3.1.0{{#usePromiseKit}} github "mxcl/PromiseKit" >=1.5.3{{/usePromiseKit}} diff --git a/modules/swagger-codegen/src/main/resources/swift/Podspec.mustache b/modules/swagger-codegen/src/main/resources/swift/Podspec.mustache index 5cf337ad6f2..d156ef14417 100644 --- a/modules/swagger-codegen/src/main/resources/swift/Podspec.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/Podspec.mustache @@ -16,5 +16,5 @@ Pod::Spec.new do |s| s.documentation_url = '{{podDocumentationURL}}'{{/podDocumentationURL}} s.source_files = '{{projectName}}/Classes/Swaggers/**/*.swift'{{#usePromiseKit}} s.dependency 'PromiseKit', '~> 2.1'{{/usePromiseKit}} - s.dependency 'Alamofire', '~> 3.0.0' + s.dependency 'Alamofire', '~> 3.1.0' end 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 0fa8953e7bf..3adc19e6db9 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 @@ -14,7 +14,7 @@ public class CodegenTest { @Test(description = "read a file upload param from a 2.0 spec") public void fileUploadParamTest() { - final Swagger model = new SwaggerParser().read("src/test/resources/2_0/petstore.json"); + final Swagger model = parseAndPrepareSwagger("src/test/resources/2_0/petstore.json"); final DefaultCodegen codegen = new DefaultCodegen(); final String path = "/pet/{petId}/uploadImage"; final Operation p = model.getPaths().get(path).getPost(); @@ -39,7 +39,7 @@ public class CodegenTest { @Test(description = "read formParam values from a 2.0 spec") public void formParamTest() { - final Swagger model = new SwaggerParser().read("src/test/resources/2_0/petstore.json"); + final Swagger model = parseAndPrepareSwagger("src/test/resources/2_0/petstore.json"); final DefaultCodegen codegen = new DefaultCodegen(); final String path = "/pet/{petId}"; final Operation p = model.getPaths().get(path).getPost(); @@ -83,7 +83,7 @@ public class CodegenTest { @Test(description = "handle required parameters from a 2.0 spec as required when figuring out Swagger types") public void requiredParametersTest() { - final Swagger model = new SwaggerParser().read("src/test/resources/2_0/requiredTest.json"); + final Swagger model = parseAndPrepareSwagger("src/test/resources/2_0/requiredTest.json"); final DefaultCodegen codegen = new DefaultCodegen() { public String getSwaggerType(Property p) { @@ -106,7 +106,7 @@ public class CodegenTest { @Test(description = "select main response from a 2.0 spec using the lowest 2XX code") public void responseSelectionTest1() { - final Swagger model = new SwaggerParser().read("src/test/resources/2_0/responseSelectionTest.json"); + final Swagger model = parseAndPrepareSwagger("src/test/resources/2_0/responseSelectionTest.json"); final DefaultCodegen codegen = new DefaultCodegen(); final String path = "/tests/withTwoHundredAndDefault"; final Operation p = model.getPaths().get(path).getGet(); @@ -117,7 +117,7 @@ public class CodegenTest { @Test(description = "select main response from a 2.0 spec using the default keyword when no 2XX code") public void responseSelectionTest2() { - final Swagger model = new SwaggerParser().read("src/test/resources/2_0/responseSelectionTest.json"); + final Swagger model = parseAndPrepareSwagger("src/test/resources/2_0/responseSelectionTest.json"); final DefaultCodegen codegen = new DefaultCodegen(); final String path = "/tests/withoutTwoHundredButDefault"; final Operation p = model.getPaths().get(path).getGet(); @@ -128,7 +128,7 @@ public class CodegenTest { @Test(description = "return byte array when response format is byte") public void binaryDataTest() { - final Swagger model = new SwaggerParser().read("src/test/resources/2_0/binaryDataTest.json"); + final Swagger model = parseAndPrepareSwagger("src/test/resources/2_0/binaryDataTest.json"); final DefaultCodegen codegen = new DefaultCodegen(); final String path = "/tests/binaryResponse"; final Operation p = model.getPaths().get(path).getPost(); @@ -142,7 +142,7 @@ public class CodegenTest { @Test(description = "use operation consumes and produces") public void localConsumesAndProducesTest() { - final Swagger model = new SwaggerParser().read("src/test/resources/2_0/globalConsumesAndProduces.json"); + final Swagger model = parseAndPrepareSwagger("src/test/resources/2_0/globalConsumesAndProduces.json"); final DefaultCodegen codegen = new DefaultCodegen(); final String path = "/tests/localConsumesAndProduces"; final Operation p = model.getPaths().get(path).getGet(); @@ -158,7 +158,7 @@ public class CodegenTest { @Test(description = "use spec consumes and produces") public void globalConsumesAndProducesTest() { - final Swagger model = new SwaggerParser().read("src/test/resources/2_0/globalConsumesAndProduces.json"); + final Swagger model = parseAndPrepareSwagger("src/test/resources/2_0/globalConsumesAndProduces.json"); final DefaultCodegen codegen = new DefaultCodegen(); final String path = "/tests/globalConsumesAndProduces"; final Operation p = model.getPaths().get(path).getGet(); @@ -174,7 +174,7 @@ public class CodegenTest { @Test(description = "use operation consumes and produces (reset in operation with empty array)") public void localResetConsumesAndProducesTest() { - final Swagger model = new SwaggerParser().read("src/test/resources/2_0/globalConsumesAndProduces.json"); + final Swagger model = parseAndPrepareSwagger("src/test/resources/2_0/globalConsumesAndProduces.json"); final DefaultCodegen codegen = new DefaultCodegen(); final String path = "/tests/localResetConsumesAndProduces"; final Operation p = model.getPaths().get(path).getGet(); @@ -187,4 +187,11 @@ public class CodegenTest { Assert.assertNull(op.produces); } + + private Swagger parseAndPrepareSwagger(String path) { + Swagger swagger = new SwaggerParser().read(path); + // resolve inline models + new InlineModelResolver().flatten(swagger); + return swagger; + } } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/InlineModelResolverTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/InlineModelResolverTest.java index fa1bf8bab40..68d64562eba 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/InlineModelResolverTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/InlineModelResolverTest.java @@ -127,6 +127,28 @@ public class InlineModelResolverTest { assertNotNull(impl.getProperties().get("address")); } + @Test + public void notResolveNonModelBodyParameter() throws Exception { + Swagger swagger = new Swagger(); + + swagger.path("/hello", new Path() + .get(new Operation() + .parameter(new BodyParameter() + .name("body") + .schema(new ModelImpl() + .type("string") + .format("binary"))))); + + new InlineModelResolver().flatten(swagger); + + Operation operation = swagger.getPaths().get("/hello").getGet(); + BodyParameter bp = (BodyParameter)operation.getParameters().get(0); + assertTrue(bp.getSchema() instanceof ModelImpl); + ModelImpl m = (ModelImpl) bp.getSchema(); + assertEquals("string", m.getType()); + assertEquals("binary", m.getFormat()); + } + @Test public void resolveInlineArrayBodyParameter() throws Exception { Swagger swagger = new Swagger(); diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/csharp/CSharpClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/csharp/CSharpClientOptionsTest.java index 4c0d5f366a1..ec5246f7723 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/csharp/CSharpClientOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/csharp/CSharpClientOptionsTest.java @@ -27,6 +27,8 @@ public class CSharpClientOptionsTest extends AbstractOptionsTest { new Expectations(clientCodegen) {{ clientCodegen.setPackageName(CSharpClientOptionsProvider.PACKAGE_NAME_VALUE); times = 1; + clientCodegen.setOptionalMethodArgumentFlag(true); + times = 1; clientCodegen.setPackageVersion(CSharpClientOptionsProvider.PACKAGE_VERSION_VALUE); times = 1; }}; diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/CSharpClientOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/CSharpClientOptionsProvider.java index 442465dfcf9..94440db97c0 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/CSharpClientOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/CSharpClientOptionsProvider.java @@ -21,6 +21,7 @@ public class CSharpClientOptionsProvider implements OptionsProvider { return builder.put(CodegenConstants.PACKAGE_NAME, PACKAGE_NAME_VALUE) .put(CodegenConstants.PACKAGE_VERSION, PACKAGE_VERSION_VALUE) .put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, "true") + .put(CodegenConstants.OPTIONAL_METHOD_ARGUMENT, "true") .build(); } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/SlimFrameworkServerOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/SlimFrameworkServerOptionsProvider.java new file mode 100644 index 00000000000..d7676725750 --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/SlimFrameworkServerOptionsProvider.java @@ -0,0 +1,30 @@ +package io.swagger.codegen.options; + +import io.swagger.codegen.CodegenConstants; + +import com.google.common.collect.ImmutableMap; + +import java.util.Map; + +public class SlimFrameworkServerOptionsProvider implements OptionsProvider { + public static final String SORT_PARAMS_VALUE = "false"; + public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; + + @Override + public String getLanguage() { + return "slim"; + } + + @Override + public Map createOptions() { + ImmutableMap.Builder builder = new ImmutableMap.Builder(); + return builder.put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) + .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) + .build(); + } + + @Override + public boolean isServer() { + return true; + } +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/php/PhpModelTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/php/PhpModelTest.java index 52ca64f2f59..79da2d2ccda 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/php/PhpModelTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/php/PhpModelTest.java @@ -42,7 +42,7 @@ public class PhpModelTest { Assert.assertEquals(property1.baseName, "id"); Assert.assertEquals(property1.datatype, "int"); Assert.assertEquals(property1.name, "id"); - Assert.assertEquals(property1.defaultValue, "null"); + Assert.assertEquals(property1.defaultValue, null); Assert.assertEquals(property1.baseType, "int"); Assert.assertTrue(property1.hasMore); Assert.assertTrue(property1.required); @@ -53,7 +53,7 @@ public class PhpModelTest { Assert.assertEquals(property2.baseName, "name"); Assert.assertEquals(property2.datatype, "string"); Assert.assertEquals(property2.name, "name"); - Assert.assertEquals(property2.defaultValue, "null"); + Assert.assertEquals(property2.defaultValue, null); Assert.assertEquals(property2.baseType, "string"); Assert.assertTrue(property2.hasMore); Assert.assertTrue(property2.required); @@ -65,7 +65,7 @@ public class PhpModelTest { Assert.assertEquals(property3.complexType, "\\DateTime"); Assert.assertEquals(property3.datatype, "\\DateTime"); Assert.assertEquals(property3.name, "created_at"); - Assert.assertEquals(property3.defaultValue, "null"); + Assert.assertEquals(property3.defaultValue, null); Assert.assertEquals(property3.baseType, "\\DateTime"); Assert.assertNull(property3.hasMore); Assert.assertNull(property3.required); @@ -92,7 +92,7 @@ public class PhpModelTest { Assert.assertEquals(property1.baseName, "id"); Assert.assertEquals(property1.datatype, "int"); Assert.assertEquals(property1.name, "id"); - Assert.assertEquals(property1.defaultValue, "null"); + Assert.assertEquals(property1.defaultValue, null); Assert.assertEquals(property1.baseType, "int"); Assert.assertTrue(property1.hasMore); Assert.assertTrue(property1.required); diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/slim/SlimFrameworkServerOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/slim/SlimFrameworkServerOptionsTest.java new file mode 100644 index 00000000000..51c668bd931 --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/slim/SlimFrameworkServerOptionsTest.java @@ -0,0 +1,32 @@ +package io.swagger.codegen.slim; + +import io.swagger.codegen.AbstractOptionsTest; +import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.languages.SlimFrameworkServerCodegen; +import io.swagger.codegen.options.SlimFrameworkServerOptionsProvider; + +import mockit.Expectations; +import mockit.Tested; + +public class SlimFrameworkServerOptionsTest extends AbstractOptionsTest { + + @Tested + private SlimFrameworkServerCodegen clientCodegen; + + public SlimFrameworkServerOptionsTest() { + super(new SlimFrameworkServerOptionsProvider()); + } + + @Override + protected CodegenConfig getCodegenConfig() { + return clientCodegen; + } + + @Override + protected void setExpectations() { + new Expectations(clientCodegen) {{ + clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(SlimFrameworkServerOptionsProvider.SORT_PARAMS_VALUE)); + times = 1; + }}; + } +} 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 66762d74b2b..ad9cbead5e9 100644 --- a/modules/swagger-codegen/src/test/resources/2_0/petstore.json +++ b/modules/swagger-codegen/src/test/resources/2_0/petstore.json @@ -402,6 +402,23 @@ ] } }, + "/pet/{petId}/downloadImage" : { + "get" : { + "tags" : [ "pet" ], + "summary" : "downloads an image", + "description" : "", + "operationId" : "downloadFile", + "produces" : [ "application/octet-stream" ], + "responses" : { + "200" : { + "description" : "successful operation", + "schema" : { + "$ref" : "#/definitions/File" + } + } + } + } + }, "/store/inventory": { "get": { "tags": [ @@ -972,6 +989,65 @@ "xml": { "name": "Order" } + }, + "definitions" : { + "File": { + "type": "object", + "properties": { + "path": { + "type": "string" + }, + "name": { + "type": "string" + }, + "canonicalPath": { + "type": "string" + }, + "parent": { + "type": "string" + }, + "absolute": { + "type": "boolean", + "default": false + }, + "absoluteFile": { + "$ref": "#/definitions/File" + }, + "absolutePath": { + "type": "string" + }, + "canonicalFile": { + "$ref": "#/definitions/File" + }, + "freeSpace": { + "type": "integer", + "format": "int64" + }, + "parentFile": { + "$ref": "#/definitions/File" + }, + "totalSpace": { + "type": "integer", + "format": "int64" + }, + "usableSpace": { + "type": "integer", + "format": "int64" + }, + "directory": { + "type": "boolean", + "default": false + }, + "file": { + "type": "boolean", + "default": false + }, + "hidden": { + "type": "boolean", + "default": false + } + } + } } } } 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 74e3828a8f4..adbd8b0184a 100644 --- a/modules/swagger-generator/src/main/webapp/WEB-INF/web.xml +++ b/modules/swagger-generator/src/main/webapp/WEB-INF/web.xml @@ -41,7 +41,6 @@ Bootstrap io.swagger.generator.Bootstrap - 2 generator.host localhost:8001 @@ -50,6 +49,7 @@ generator.protocol http + 2 ApiOriginFilter diff --git a/modules/swagger-generator/src/test/java/io/swagger/generator/online/OnlineGeneratorOptionsTest.java b/modules/swagger-generator/src/test/java/io/swagger/generator/online/OnlineGeneratorOptionsTest.java index fc015f433ea..8ec4d1760e8 100644 --- a/modules/swagger-generator/src/test/java/io/swagger/generator/online/OnlineGeneratorOptionsTest.java +++ b/modules/swagger-generator/src/test/java/io/swagger/generator/online/OnlineGeneratorOptionsTest.java @@ -28,6 +28,7 @@ import io.swagger.codegen.options.ScalaClientOptionsProvider; import io.swagger.codegen.options.ScalatraServerOptionsProvider; import io.swagger.codegen.options.SilexServerOptionsProvider; import io.swagger.codegen.options.SinatraServerOptionsProvider; +import io.swagger.codegen.options.SlimFrameworkServerOptionsProvider; import io.swagger.codegen.options.SpringMVCServerOptionsProvider; import io.swagger.codegen.options.StaticDocOptionsProvider; import io.swagger.codegen.options.StaticHtmlOptionsProvider; @@ -77,11 +78,12 @@ public class OnlineGeneratorOptionsTest { {new PythonClientOptionsProvider()}, {new Qt5CPPOptionsProvider()}, {new RubyClientOptionsProvider()}, {new ScalaClientOptionsProvider()}, {new ScalatraServerOptionsProvider()}, {new SilexServerOptionsProvider()}, - {new SinatraServerOptionsProvider()}, {new SpringMVCServerOptionsProvider()}, - {new StaticDocOptionsProvider()}, {new StaticHtmlOptionsProvider()}, - {new SwaggerOptionsProvider()}, {new SwaggerYamlOptionsProvider()}, - {new SwiftOptionsProvider()}, {new TizenClientOptionsProvider()}, - {new TypeScriptAngularClientOptionsProvider()}, {new TypeScriptNodeClientOptionsProvider()} + {new SinatraServerOptionsProvider()}, {new SlimFrameworkServerOptionsProvider()}, + {new SpringMVCServerOptionsProvider()}, {new StaticDocOptionsProvider()}, + {new StaticHtmlOptionsProvider()}, {new SwaggerOptionsProvider()}, + {new SwaggerYamlOptionsProvider()}, {new SwiftOptionsProvider()}, + {new TizenClientOptionsProvider()}, {new TypeScriptAngularClientOptionsProvider()}, + {new TypeScriptNodeClientOptionsProvider()} }; } @@ -107,7 +109,12 @@ public class OnlineGeneratorOptionsTest { outputFilename = Generator.generateClient(provider.getLanguage(), input); } final File dir = new File(new File(outputFilename).getParent()); - FileUtils.deleteDirectory(dir); + + try { + FileUtils.deleteDirectory(dir); + } catch (Exception e) { // directory can't be deleted for some reasons + e.printStackTrace(); + } for (InvocationCounter option : options.values()) { assertNotEquals(option.getCounter(), 0, String.format("Option \"%s\" wasn't processed.", option.getValue())); diff --git a/pom.xml b/pom.xml index ada3dc0dc4a..cd1dd28b9d9 100644 --- a/pom.xml +++ b/pom.xml @@ -377,6 +377,30 @@ samples/client/petstore/java/retrofit2 + + java-client-feign + + + env + java + + + + samples/client/petstore/java/feign + + + + javascript-client + + + env + javascript + + + + samples/client/petstore/javascript + + scala-client @@ -453,6 +477,7 @@ samples/client/petstore/java/okhttp-gson samples/client/petstore/java/retrofit samples/client/petstore/java/retrofit2 + samples/client/petstore/javascript samples/client/petstore/scala samples/server/petstore/spring-mvc @@ -543,10 +568,10 @@ - 1.0.12 + 1.0.14-SNAPSHOT 2.11.1 2.3.4 - 1.5.4 + 1.5.5-SNAPSHOT 2.1.5-SNAPSHOT 2.3 1.2 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 c331444c886..36bdefeffcd 100644 --- a/samples/client/petstore/clojure/src/swagger_petstore/api/pet.clj +++ b/samples/client/petstore/clojure/src/swagger_petstore/api/pet.clj @@ -1,11 +1,11 @@ (ns swagger-petstore.api.pet - (:require [swagger-petstore.core :refer [call-api check-required-params]]) + (:require [swagger-petstore.core :refer [call-api check-required-params with-collection-format]]) (:import (java.io File))) -(defn update-pet +(defn update-pet-with-http-info "Update an existing pet " - ([] (update-pet nil)) + ([] (update-pet-with-http-info nil)) ([{:keys [body ]}] (call-api "/pet" :put {:path-params {} @@ -14,12 +14,20 @@ :form-params {} :body-param body :content-types ["application/json" "application/xml"] - :accepts ["application/json" "application/xml"]}))) + :accepts ["application/json" "application/xml"] + :auth-names ["petstore_auth"]}))) -(defn add-pet +(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 " - ([] (add-pet nil)) + ([] (add-pet-with-http-info nil)) ([{:keys [body ]}] (call-api "/pet" :post {:path-params {} @@ -28,35 +36,59 @@ :form-params {} :body-param body :content-types ["application/json" "application/xml"] - :accepts ["application/json" "application/xml"]}))) + :accepts ["application/json" "application/xml"] + :auth-names ["petstore_auth"]}))) + +(defn add-pet + "Add a new pet to the store + " + ([] (add-pet nil)) + ([optional-params] + (:data (add-pet-with-http-info optional-params)))) + +(defn find-pets-by-status-with-http-info + "Finds Pets by status + Multiple status values can be provided with comma seperated strings" + ([] (find-pets-by-status-with-http-info nil)) + ([{:keys [status ]}] + (call-api "/pet/findByStatus" :get + {:path-params {} + :header-params {} + :query-params {"status" (with-collection-format status :multi) } + :form-params {} + :content-types [] + :accepts ["application/json" "application/xml"] + :auth-names ["petstore_auth"]}))) (defn find-pets-by-status "Finds Pets by status Multiple status values can be provided with comma seperated strings" ([] (find-pets-by-status nil)) - ([{:keys [status ]}] - (call-api "/pet/findByStatus" :get + ([optional-params] + (:data (find-pets-by-status-with-http-info optional-params)))) + +(defn find-pets-by-tags-with-http-info + "Finds Pets by tags + Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing." + ([] (find-pets-by-tags-with-http-info nil)) + ([{:keys [tags ]}] + (call-api "/pet/findByTags" :get {:path-params {} :header-params {} - :query-params {"status" status } + :query-params {"tags" (with-collection-format tags :multi) } :form-params {} :content-types [] - :accepts ["application/json" "application/xml"]}))) + :accepts ["application/json" "application/xml"] + :auth-names ["petstore_auth"]}))) (defn find-pets-by-tags "Finds Pets by tags Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing." ([] (find-pets-by-tags nil)) - ([{:keys [tags ]}] - (call-api "/pet/findByTags" :get - {:path-params {} - :header-params {} - :query-params {"tags" tags } - :form-params {} - :content-types [] - :accepts ["application/json" "application/xml"]}))) + ([optional-params] + (:data (find-pets-by-tags-with-http-info optional-params)))) -(defn get-pet-by-id +(defn get-pet-by-id-with-http-info "Find pet by ID Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions" [pet-id ] @@ -66,12 +98,19 @@ :query-params {} :form-params {} :content-types [] - :accepts ["application/json" "application/xml"]})) + :accepts ["application/json" "application/xml"] + :auth-names ["api_key"]})) -(defn update-pet-with-form +(defn get-pet-by-id + "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-with-http-info pet-id))) + +(defn update-pet-with-form-with-http-info "Updates a pet in the store with form data " - ([pet-id ] (update-pet-with-form pet-id nil)) + ([pet-id ] (update-pet-with-form-with-http-info pet-id nil)) ([pet-id {:keys [name status ]}] (call-api "/pet/{petId}" :post {:path-params {"petId" pet-id } @@ -79,12 +118,20 @@ :query-params {} :form-params {"name" name "status" status } :content-types ["application/x-www-form-urlencoded"] - :accepts ["application/json" "application/xml"]}))) + :accepts ["application/json" "application/xml"] + :auth-names ["petstore_auth"]}))) -(defn delete-pet +(defn update-pet-with-form + "Updates a pet in the store with form data + " + ([pet-id ] (update-pet-with-form pet-id nil)) + ([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 pet-id nil)) + ([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 } @@ -92,12 +139,20 @@ :query-params {} :form-params {} :content-types [] - :accepts ["application/json" "application/xml"]}))) + :accepts ["application/json" "application/xml"] + :auth-names ["petstore_auth"]}))) -(defn upload-file +(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 " - ([pet-id ] (upload-file pet-id nil)) + ([pet-id ] (upload-file-with-http-info pet-id nil)) ([pet-id {:keys [additional-metadata ^File file ]}] (call-api "/pet/{petId}/uploadImage" :post {:path-params {"petId" pet-id } @@ -105,4 +160,12 @@ :query-params {} :form-params {"additionalMetadata" additional-metadata "file" file } :content-types ["multipart/form-data"] - :accepts ["application/json" "application/xml"]}))) + :accepts ["application/json" "application/xml"] + :auth-names ["petstore_auth"]}))) + +(defn upload-file + "uploads an image + " + ([pet-id ] (upload-file pet-id nil)) + ([pet-id optional-params] + (:data (upload-file-with-http-info pet-id 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 f2a18cea2e8..d3877e5887b 100644 --- a/samples/client/petstore/clojure/src/swagger_petstore/api/store.clj +++ b/samples/client/petstore/clojure/src/swagger_petstore/api/store.clj @@ -1,8 +1,8 @@ (ns swagger-petstore.api.store - (:require [swagger-petstore.core :refer [call-api check-required-params]]) + (:require [swagger-petstore.core :refer [call-api check-required-params with-collection-format]]) (:import (java.io File))) -(defn get-inventory +(defn get-inventory-with-http-info "Returns pet inventories by status Returns a map of status codes to quantities" [] @@ -12,12 +12,19 @@ :query-params {} :form-params {} :content-types [] - :accepts ["application/json" "application/xml"]})) + :accepts ["application/json" "application/xml"] + :auth-names ["api_key"]})) -(defn place-order +(defn get-inventory + "Returns pet inventories by status + Returns a map of status codes to quantities" + [] + (:data (get-inventory-with-http-info))) + +(defn place-order-with-http-info "Place an order for a pet " - ([] (place-order nil)) + ([] (place-order-with-http-info nil)) ([{:keys [body ]}] (call-api "/store/order" :post {:path-params {} @@ -26,9 +33,17 @@ :form-params {} :body-param body :content-types [] - :accepts ["application/json" "application/xml"]}))) + :accepts ["application/json" "application/xml"] + :auth-names []}))) -(defn get-order-by-id +(defn place-order + "Place an order for a pet + " + ([] (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 ] @@ -38,9 +53,16 @@ :query-params {} :form-params {} :content-types [] - :accepts ["application/json" "application/xml"]})) + :accepts ["application/json" "application/xml"] + :auth-names []})) -(defn delete-order +(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 ] @@ -50,4 +72,11 @@ :query-params {} :form-params {} :content-types [] - :accepts ["application/json" "application/xml"]})) + :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 15d41515ebb..c25d97aa7c4 100644 --- a/samples/client/petstore/clojure/src/swagger_petstore/api/user.clj +++ b/samples/client/petstore/clojure/src/swagger_petstore/api/user.clj @@ -1,11 +1,11 @@ (ns swagger-petstore.api.user - (:require [swagger-petstore.core :refer [call-api check-required-params]]) + (:require [swagger-petstore.core :refer [call-api check-required-params with-collection-format]]) (:import (java.io File))) -(defn create-user +(defn create-user-with-http-info "Create user This can only be done by the logged in user." - ([] (create-user nil)) + ([] (create-user-with-http-info nil)) ([{:keys [body ]}] (call-api "/user" :post {:path-params {} @@ -14,12 +14,20 @@ :form-params {} :body-param body :content-types [] - :accepts ["application/json" "application/xml"]}))) + :accepts ["application/json" "application/xml"] + :auth-names []}))) -(defn create-users-with-array-input +(defn create-user + "Create user + This can only be done by the logged in user." + ([] (create-user nil)) + ([optional-params] + (:data (create-user-with-http-info optional-params)))) + +(defn create-users-with-array-input-with-http-info "Creates list of users with given input array " - ([] (create-users-with-array-input nil)) + ([] (create-users-with-array-input-with-http-info nil)) ([{:keys [body ]}] (call-api "/user/createWithArray" :post {:path-params {} @@ -28,12 +36,20 @@ :form-params {} :body-param body :content-types [] - :accepts ["application/json" "application/xml"]}))) + :accepts ["application/json" "application/xml"] + :auth-names []}))) -(defn create-users-with-list-input +(defn create-users-with-array-input "Creates list of users with given input array " - ([] (create-users-with-list-input nil)) + ([] (create-users-with-array-input nil)) + ([optional-params] + (:data (create-users-with-array-input-with-http-info optional-params)))) + +(defn create-users-with-list-input-with-http-info + "Creates list of users with given input array + " + ([] (create-users-with-list-input-with-http-info nil)) ([{:keys [body ]}] (call-api "/user/createWithList" :post {:path-params {} @@ -42,12 +58,20 @@ :form-params {} :body-param body :content-types [] - :accepts ["application/json" "application/xml"]}))) + :accepts ["application/json" "application/xml"] + :auth-names []}))) -(defn login-user +(defn create-users-with-list-input + "Creates list of users with given input array + " + ([] (create-users-with-list-input nil)) + ([optional-params] + (:data (create-users-with-list-input-with-http-info optional-params)))) + +(defn login-user-with-http-info "Logs user into the system " - ([] (login-user nil)) + ([] (login-user-with-http-info nil)) ([{:keys [username password ]}] (call-api "/user/login" :get {:path-params {} @@ -55,9 +79,17 @@ :query-params {"username" username "password" password } :form-params {} :content-types [] - :accepts ["application/json" "application/xml"]}))) + :accepts ["application/json" "application/xml"] + :auth-names []}))) -(defn logout-user +(defn login-user + "Logs user into the system + " + ([] (login-user nil)) + ([optional-params] + (:data (login-user-with-http-info optional-params)))) + +(defn logout-user-with-http-info "Logs out current logged in user session " [] @@ -67,9 +99,16 @@ :query-params {} :form-params {} :content-types [] - :accepts ["application/json" "application/xml"]})) + :accepts ["application/json" "application/xml"] + :auth-names []})) -(defn get-user-by-name +(defn logout-user + "Logs out current logged in user session + " + [] + (:data (logout-user-with-http-info))) + +(defn get-user-by-name-with-http-info "Get user by user name " [username ] @@ -79,12 +118,19 @@ :query-params {} :form-params {} :content-types [] - :accepts ["application/json" "application/xml"]})) + :accepts ["application/json" "application/xml"] + :auth-names []})) -(defn update-user +(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." - ([username ] (update-user username nil)) + ([username ] (update-user-with-http-info username nil)) ([username {:keys [body ]}] (call-api "/user/{username}" :put {:path-params {"username" username } @@ -93,9 +139,17 @@ :form-params {} :body-param body :content-types [] - :accepts ["application/json" "application/xml"]}))) + :accepts ["application/json" "application/xml"] + :auth-names []}))) -(defn delete-user +(defn update-user + "Updated user + This can only be done by the logged in user." + ([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 ] @@ -105,4 +159,11 @@ :query-params {} :form-params {} :content-types [] - :accepts ["application/json" "application/xml"]})) + :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 e7c55258e79..665adfbc775 100644 --- a/samples/client/petstore/clojure/src/swagger_petstore/core.clj +++ b/samples/client/petstore/clojure/src/swagger_petstore/core.clj @@ -7,12 +7,18 @@ (java.util Date TimeZone) (java.text SimpleDateFormat))) +(def auth-definitions + {"petstore_auth" {:type :oauth2} + "api_key" {:type :api-key :in :header :param-name "api_key"}}) + (def default-api-context "Default API context." {:base-url "http://petstore.swagger.io/v2" :date-format "yyyy-MM-dd" :datetime-format "yyyy-MM-dd'T'HH:mm:ss.SSSXXX" - :debug false}) + :debug false + :auths {"petstore_auth" nil + "api_key" nil}}) (def ^:dynamic *api-context* "Dynamic API context to be applied in API calls." @@ -20,12 +26,16 @@ (defmacro with-api-context "A helper macro to wrap *api-context* with default values." - [context & body] - `(binding [*api-context* (merge *api-context* ~context)] - ~@body)) + [api-context & body] + `(let [api-context# ~api-context + api-context# (-> *api-context* + (merge api-context#) + (assoc :auths (merge (:auths *api-context*) (:auths api-context#))))] + (binding [*api-context* api-context#] + ~@body))) (defmacro check-required-params - "Throw exception if the given parameter value is nil." + "Throw exception if any of the given parameters is nil." [& params] (->> params (map (fn [p] @@ -33,9 +43,14 @@ (throw (IllegalArgumentException. ~(str "The parameter \"" p "\" is required")))))) (list* 'do))) -(defn- make-date-format - ([format-str] (make-date-format format-str nil)) - ([format-str time-zone] +(defn with-collection-format + "Attach collection-format to meta data of the given parameter." + [param collection-format] + (and param (with-meta param {:collection-format collection-format}))) + +(defn- ^SimpleDateFormat make-date-format + ([^String format-str] (make-date-format format-str nil)) + ([^String format-str ^String time-zone] (let [date-format (SimpleDateFormat. format-str)] (when time-zone (.setTimeZone date-format (TimeZone/getTimeZone time-zone))) @@ -75,50 +90,96 @@ (-> (make-date-format datetime-format time-zone) (.parse s))))) -(defn param-to-str [param] +(defn param->str "Format the given parameter value to string." + [param] (cond (instance? Date param) (format-datetime param) (sequential? param) (str/join "," param) :else (str param))) +(defn auth->opts + "Process the given auth to an option map that might conatin request options and parameters." + [{:keys [type in param-name]} value] + (case type + :basic {:req-opts {:basic-auth value}} + :oauth2 {:req-opts {:oauth-token value}} + :api-key (case in + :header {:header-params {param-name value}} + :query {:query-params {param-name value}} + (throw (IllegalArgumentException. (str "Invalid `in` for api-key auth: " in)))) + (throw (IllegalArgumentException. (str "Invalid auth `type`: " type))))) + +(defn process-auth + "Process the given auth name into options, which is merged into the given opts." + [opts auth-name] + (if-let [value (get-in *api-context* [:auths auth-name])] + (merge-with merge + opts + (auth->opts (get auth-definitions auth-name) value)) + opts)) + +(defn auths->opts + "Process the given auth names to an option map that might conatin request options and parameters." + [auth-names] + (reduce process-auth {} auth-names)) + +(declare normalize-param) + (defn make-url "Make full URL by adding base URL and filling path parameters." [path path-params] (let [path (reduce (fn [p [k v]] - (str/replace p (re-pattern (str "\\{" k "\\}")) (param-to-str v))) + (str/replace p (re-pattern (str "\\{" k "\\}")) (normalize-param v))) path path-params)] (str (:base-url *api-context*) path))) +(defn normalize-array-param + "Normalize array paramater according to :collection-format specified in the parameter's meta data. + When the parameter contains File, a seq is returned so as to keep File parameters. + For :multi collection format, a seq is returned which will be handled properly by clj-http. + For other cases, a string is returned." + [xs] + (if (some (partial instance? File) xs) + (map normalize-param xs) + (case (-> (meta xs) :collection-format (or :csv)) + :csv (str/join "," (map normalize-param xs)) + :ssv (str/join " " (map normalize-param xs)) + :tsv (str/join "\t" (map normalize-param xs)) + :pipes (str/join "|" (map normalize-param xs)) + :multi (map normalize-param xs)))) + (defn normalize-param "Normalize parameter value, handling three cases: - for sequential value, normalize each elements of it; - for File value, do nothing with it; - otherwise, call `param-to-string`." + for sequential value, apply `normalize-array-param` which handles collection format; + for File value, use current value; + otherwise, apply `param->str`." [param] (cond - (sequential? param) (map normalize-param param) + (sequential? param) (normalize-array-param param) (instance? File param) param - :else (param-to-str param))) + :else (param->str param))) (defn normalize-params - "Normalize parameters values: remove nils, format to string with `param-to-str`." + "Normalize parameters values: remove nils, format to string with `param->str`." [params] (->> params (remove (comp nil? second)) (map (fn [[k v]] [k (normalize-param v)])) (into {}))) -(defn json-mime? [mime] +(defn json-mime? "Check if the given MIME is a standard JSON MIME or :json." + [mime] (if mime (or (= :json mime) - (re-matches #"application/json(;.*)?" (name mime))))) + (re-matches #"(?i)application/json(;.*)?" (name mime))))) -(defn json-preferred-mime [mimes] +(defn json-preferred-mime "Choose a MIME from the given MIMEs with JSON preferred, i.e. return JSON if included, otherwise return the first one." + [mimes] (-> (filter json-mime? mimes) first (or (first mimes)))) @@ -139,12 +200,13 @@ (try (parse-string body true) (catch JsonParseException e - ;; return the body string directly on JSON parsing error + ;; Return the body string directly on JSON parsing error. body)) - ;; for non-JSON response, return the body string directly + + ;; For other cases, return the body string directly. :else body)) -(defn form-params-to-multipart +(defn form-params->multipart "Convert the given form parameters map into a vector as clj-http's :multipart option." [form-params] (->> form-params @@ -153,26 +215,28 @@ (defn call-api "Call an API by making HTTP request and return its response." - [path method {:keys [path-params query-params header-params form-params body-param content-types accepts]}] + [path method {:keys [path-params body-param content-types accepts auth-names] :as opts}] (let [{:keys [debug]} *api-context* + {:keys [req-opts query-params header-params form-params]} (auths->opts auth-names) + query-params (merge query-params (:query-params opts)) + header-params (merge header-params (:header-params opts)) + form-params (merge form-params (:form-params opts)) url (make-url path path-params) - content-type (or (json-preferred-mime content-types) - (and body-param :json)) + content-type (or (json-preferred-mime content-types) (and body-param :json)) accept (or (json-preferred-mime accepts) :json) multipart? (= "multipart/form-data" content-type) - opts (cond-> {:url url :method method} - accept (assoc :accept accept) - (seq query-params) (assoc :query-params (normalize-params query-params)) - (seq header-params) (assoc :header-params (normalize-params header-params)) - (and content-type (not multipart?)) (assoc :content-type content-type) - multipart? (assoc :multipart (-> form-params - normalize-params - form-params-to-multipart)) - (and (not multipart?) (seq form-params)) (assoc :form-params (normalize-params form-params)) - body-param (assoc :body (serialize body-param content-type)) - debug (assoc :debug true :debug-body true)) - resp (client/request opts)] + req-opts (cond-> req-opts + true (assoc :url url :method method) + accept (assoc :accept accept) + (seq query-params) (assoc :query-params (normalize-params query-params)) + (seq header-params) (assoc :headers (normalize-params header-params)) + (and content-type (not multipart?)) (assoc :content-type content-type) + multipart? (assoc :multipart (-> form-params normalize-params form-params->multipart)) + (and (not multipart?) (seq form-params)) (assoc :form-params (normalize-params form-params)) + body-param (assoc :body (serialize body-param content-type)) + debug (assoc :debug true :debug-body true)) + resp (client/request req-opts)] (when debug (println "Response:") (println resp)) - (deserialize resp))) + (assoc resp :data (deserialize resp)))) diff --git a/samples/client/petstore/clojure/test/swagger_petstore/api/pet_test.clj b/samples/client/petstore/clojure/test/swagger_petstore/api/pet_test.clj index 7327b44c45d..c825b995e39 100644 --- a/samples/client/petstore/clojure/test/swagger_petstore/api/pet_test.clj +++ b/samples/client/petstore/clojure/test/swagger_petstore/api/pet_test.clj @@ -1,8 +1,15 @@ (ns swagger-petstore.api.pet-test (:require [clojure.test :refer :all] [clojure.java.io :as io] + [swagger-petstore.core :refer [with-api-context]] [swagger-petstore.api.pet :refer :all])) +(defn credentials-fixture [f] + (with-api-context {:auths {"api_key" "special-key"}} + (f))) + +(use-fixtures :once credentials-fixture) + (defn- make-random-pet ([] (make-random-pet nil)) ([{:keys [id] :as attrs :or {id (System/currentTimeMillis)}}] @@ -23,6 +30,18 @@ (is (= (get-in pet [:category :name]) (get-in fetched [:category :name]))) (delete-pet id))) +(deftest test-create-and-get-pet-with-http-info + (let [{:keys [id] :as pet} (make-random-pet) + _ (add-pet-with-http-info {:body pet}) + {:keys [status headers data]} (get-pet-by-id-with-http-info id)] + (is (= 200 status)) + (is (= "application/json" (:content-type headers))) + (is (identity data)) + (is (= id (:id data))) + (is (identity (:category data))) + (is (= (get-in pet [:category :name]) (get-in data [:category :name]))) + (delete-pet id))) + (deftest test-find-pets-by-status (let [status "pending" {:keys [id] :as pet} (make-random-pet {:status status}) diff --git a/samples/client/petstore/clojure/test/swagger_petstore/api/store_test.clj b/samples/client/petstore/clojure/test/swagger_petstore/api/store_test.clj index 5a453e3693e..cf58b488ed4 100644 --- a/samples/client/petstore/clojure/test/swagger_petstore/api/store_test.clj +++ b/samples/client/petstore/clojure/test/swagger_petstore/api/store_test.clj @@ -1,8 +1,15 @@ (ns swagger-petstore.api.store-test (:require [clojure.test :refer :all] + [swagger-petstore.core :refer [with-api-context]] [swagger-petstore.api.store :refer :all]) (:import (java.util Date))) +(defn credentials-fixture [f] + (with-api-context {:auths {"api_key" "special-key"}} + (f))) + +(use-fixtures :once credentials-fixture) + (defn- make-random-order [] {:id (+ 90000 (rand-int 10000)) :petId 200 diff --git a/samples/client/petstore/clojure/test/swagger_petstore/api/user_test.clj b/samples/client/petstore/clojure/test/swagger_petstore/api/user_test.clj index aa05b23f19a..c24be99c284 100644 --- a/samples/client/petstore/clojure/test/swagger_petstore/api/user_test.clj +++ b/samples/client/petstore/clojure/test/swagger_petstore/api/user_test.clj @@ -1,7 +1,14 @@ (ns swagger-petstore.api.user-test (:require [clojure.test :refer :all] + [swagger-petstore.core :refer [with-api-context]] [swagger-petstore.api.user :refer :all])) +(defn credentials-fixture [f] + (with-api-context {:auths {"api_key" "special-key"}} + (f))) + +(use-fixtures :once credentials-fixture) + (defn- make-random-user ([] (make-random-user nil)) ([{:keys [id] :as attrs :or {id (System/currentTimeMillis)}}] diff --git a/samples/client/petstore/clojure/test/swagger_petstore/core_test.clj b/samples/client/petstore/clojure/test/swagger_petstore/core_test.clj index 394824aa4a9..87ac0a8b73d 100644 --- a/samples/client/petstore/clojure/test/swagger_petstore/core_test.clj +++ b/samples/client/petstore/clojure/test/swagger_petstore/core_test.clj @@ -9,30 +9,43 @@ (is (= {:base-url "http://petstore.swagger.io/v2" :date-format "yyyy-MM-dd" :datetime-format "yyyy-MM-dd'T'HH:mm:ss.SSSXXX" - :debug false} + :debug false + :auths {"api_key" nil + "petstore_auth" nil}} default-api-context *api-context* (with-api-context {} *api-context*)))) (testing "customize via with-api-context" - (with-api-context {:base-url "http://localhost" :debug true} + (with-api-context {:base-url "http://localhost" + :debug true + :auths {"api_key" "key1" + "petstore_auth" "token1"}} (is (= {:base-url "http://localhost" :date-format "yyyy-MM-dd" :datetime-format "yyyy-MM-dd'T'HH:mm:ss.SSSXXX" - :debug true} + :debug true + :auths {"api_key" "key1" + "petstore_auth" "token1"}} *api-context*)) ;; nested with-api-context inherits values from the outer api context - (with-api-context {:datetime-format "yyyy-MM-dd HH:mm:ss"} + (with-api-context {:datetime-format "yyyy-MM-dd HH:mm:ss" + :auths {"api_key" "key2"}} (is (= {:base-url "http://localhost" :date-format "yyyy-MM-dd" :datetime-format "yyyy-MM-dd HH:mm:ss" - :debug true} + :debug true + :auths {"api_key" "key2" + "petstore_auth" "token1"}} *api-context*)))) ;; back to default api context (is (= {:base-url "http://petstore.swagger.io/v2" :date-format "yyyy-MM-dd" :datetime-format "yyyy-MM-dd'T'HH:mm:ss.SSSXXX" - :debug false} + :debug false + :auths {"api_key" nil + "petstore_auth" nil}} + default-api-context *api-context*)))) (deftest test-check-required-params @@ -69,10 +82,10 @@ "2015-11-07T00:49:09-03:00") (is (thrown? ParseException (parse-datetime "2015-11-07T03:49:09.123Z")))))) -(deftest test-param-to-str +(deftest test-param->str (let [date (parse-datetime "2015-11-07T03:49:09.123Z")] (are [param expected] - (is (= expected (param-to-str param))) + (is (= expected (param->str param))) nil "" "abc" "abc" 123 "123" @@ -80,6 +93,25 @@ [12 "34"] "12,34" date (format-datetime date)))) +(deftest test-auths->opts + (testing "auth values not set by default" + (is (= {} (auths->opts ["api_key" "petstore_auth"]))) + (is (= {} (auths->opts [])))) + (testing "set api_key" + (with-api-context {:auths {"api_key" "my key"}} + (is (= {:header-params {"api_key" "my key"}} (auths->opts ["api_key" "petstore_auth"]))) + (is (= {:header-params {"api_key" "my key"}} (auths->opts ["api_key"]))) + (is (= {} (auths->opts ["petstore_auth"]))) + (is (= {} (auths->opts []))))) + (testing "set both api_key and petstore_auth" + (with-api-context {:auths {"api_key" "my key" "petstore_auth" "my token"}} + (is (= {:req-opts {:oauth-token "my token"} + :header-params {"api_key" "my key"}} + (auths->opts ["api_key" "petstore_auth"]))) + (is (= {:req-opts {:oauth-token "my token"}} (auths->opts ["petstore_auth"]))) + (is (= {:header-params {"api_key" "my key"}} (auths->opts ["api_key"]))) + (is (= {} (auths->opts [])))))) + (deftest test-make-url (are [path path-params url] (is (= url (make-url path path-params))) @@ -92,24 +124,39 @@ (let [file (-> "hello.txt" io/resource io/file)] (are [param expected] (is (= expected (normalize-param param))) - [12 "34"] ["12" "34"] file file "abc" "abc" - [[12 "34"] file "abc"] [["12" "34"] file "abc"]))) + [12 "34"] "12,34" + ^{:collection-format :csv} [12 "34"] "12,34" + ^{:collection-format :ssv} [12 "34"] "12 34" + ^{:collection-format :tsv} [12 "34"] "12\t34" + (with-collection-format [12 "34"] :pipes) "12|34" + (with-collection-format [12 "34"] :multi) ["12" "34"] + [[12 "34"] file "abc"] ["12,34" file "abc"]))) (deftest test-normalize-params - (is (= {:a "123" :b ["4" ["5" "6"]]} - (normalize-params {:a 123 :b [4 [5 "6"]] :c nil})))) + (is (= {:a "123" :b "4,5,6"} + (normalize-params {:a 123 :b [4 [5 "6"]] :c nil}))) + (is (= {:a "123" :b ["4" "5,6"]} + (normalize-params {:a 123 + :b ^{:collection-format :multi} [4 [5 "6"]] + :c nil}))) + (is (= {:a "123" :b "4 5|6"} + (normalize-params {:a 123 + :b (with-collection-format [4 (with-collection-format [5 "6"] :pipes)] :ssv) + :c nil})))) (deftest test-json-mime? (are [mime expected] (is (= expected (boolean (json-mime? mime)))) :json true "application/json" true + "APPLICATION/JSON" true "application/json; charset=utf8" true nil false :xml false - "application/pdf" false)) + "application/pdf" false + "application/jsonp" false)) (deftest test-json-preferred-mime (are [mimes expected] @@ -132,4 +179,4 @@ "{\"aa\": 1, \"bb\": \"2\"}" "application/json" {:aa 1 :bb "2"} "[1, \"2\"]" "application/json; charset=UTF8" [1 "2"] "{invalid json}" "application/json" "{invalid json}" - "plain text" "text/plain" "plain text")) \ No newline at end of file + "plain text" "text/plain" "plain text")) 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 00bd7a5e9f2..e7334aa160b 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 @@ -1,6 +1,7 @@ using System; using System.IO; using System.Collections.Generic; +using System.Linq; using RestSharp; using IO.Swagger.Client; using IO.Swagger.Model; @@ -22,7 +23,7 @@ namespace IO.Swagger.Api /// /// Pet object that needs to be added to the store /// - void UpdatePet (Pet body); + void UpdatePet (Pet body = null); /// /// Update an existing pet @@ -31,8 +32,28 @@ namespace IO.Swagger.Api /// /// /// Pet object that needs to be added to the store - /// - System.Threading.Tasks.Task UpdatePetAsync (Pet body); + /// ApiResponse of Object(void) + ApiResponse UpdatePetWithHttpInfo (Pet body = null); + + /// + /// Update an existing pet + /// + /// + /// + /// + /// Pet object that needs to be added to the store + /// Task of void + System.Threading.Tasks.Task UpdatePetAsync (Pet body = null); + + /// + /// Update an existing pet + /// + /// + /// + /// + /// Pet object that needs to be added to the store + /// Task of ApiResponse + System.Threading.Tasks.Task> UpdatePetAsyncWithHttpInfo (Pet body = null); /// /// Add a new pet to the store @@ -42,7 +63,7 @@ namespace IO.Swagger.Api /// /// Pet object that needs to be added to the store /// - void AddPet (Pet body); + void AddPet (Pet body = null); /// /// Add a new pet to the store @@ -51,8 +72,28 @@ namespace IO.Swagger.Api /// /// /// Pet object that needs to be added to the store - /// - System.Threading.Tasks.Task AddPetAsync (Pet body); + /// ApiResponse of Object(void) + ApiResponse AddPetWithHttpInfo (Pet body = null); + + /// + /// Add a new pet to the store + /// + /// + /// + /// + /// Pet object that needs to be added to the store + /// Task of void + System.Threading.Tasks.Task AddPetAsync (Pet body = null); + + /// + /// Add a new pet to the store + /// + /// + /// + /// + /// Pet object that needs to be added to the store + /// Task of ApiResponse + System.Threading.Tasks.Task> AddPetAsyncWithHttpInfo (Pet body = null); /// /// Finds Pets by status @@ -61,8 +102,8 @@ namespace IO.Swagger.Api /// Multiple status values can be provided with comma seperated strings /// /// Status values that need to be considered for filter - /// - List FindPetsByStatus (List status); + /// List<Pet> + List FindPetsByStatus (List status = null); /// /// Finds Pets by status @@ -71,8 +112,28 @@ namespace IO.Swagger.Api /// Multiple status values can be provided with comma seperated strings /// /// Status values that need to be considered for filter - /// - System.Threading.Tasks.Task> FindPetsByStatusAsync (List status); + /// ApiResponse of List<Pet> + ApiResponse> FindPetsByStatusWithHttpInfo (List status = null); + + /// + /// Finds Pets by status + /// + /// + /// Multiple status values can be provided with comma seperated strings + /// + /// Status values that need to be considered for filter + /// Task of List<Pet> + System.Threading.Tasks.Task> FindPetsByStatusAsync (List status = null); + + /// + /// Finds Pets by status + /// + /// + /// Multiple status values can be provided with comma seperated strings + /// + /// Status values that need to be considered for filter + /// Task of ApiResponse (List<Pet>) + System.Threading.Tasks.Task>> FindPetsByStatusAsyncWithHttpInfo (List status = null); /// /// Finds Pets by tags @@ -81,8 +142,8 @@ namespace IO.Swagger.Api /// Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. /// /// Tags to filter by - /// - List FindPetsByTags (List tags); + /// List<Pet> + List FindPetsByTags (List tags = null); /// /// Finds Pets by tags @@ -91,8 +152,28 @@ namespace IO.Swagger.Api /// Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. /// /// Tags to filter by - /// - System.Threading.Tasks.Task> FindPetsByTagsAsync (List tags); + /// ApiResponse of List<Pet> + ApiResponse> FindPetsByTagsWithHttpInfo (List tags = null); + + /// + /// Finds Pets by tags + /// + /// + /// Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + /// + /// Tags to filter by + /// Task of List<Pet> + System.Threading.Tasks.Task> FindPetsByTagsAsync (List tags = null); + + /// + /// Finds Pets by tags + /// + /// + /// Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + /// + /// Tags to filter by + /// Task of ApiResponse (List<Pet>) + System.Threading.Tasks.Task>> FindPetsByTagsAsyncWithHttpInfo (List tags = null); /// /// Find pet by ID @@ -111,8 +192,28 @@ namespace IO.Swagger.Api /// Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions /// /// ID of pet that needs to be fetched - /// Pet + /// ApiResponse of Pet + ApiResponse GetPetByIdWithHttpInfo (long? petId); + + /// + /// Find pet by ID + /// + /// + /// Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + /// + /// ID of pet that needs to be fetched + /// Task of Pet System.Threading.Tasks.Task GetPetByIdAsync (long? petId); + + /// + /// Find pet by ID + /// + /// + /// Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + /// + /// ID of pet that needs to be fetched + /// Task of ApiResponse (Pet) + System.Threading.Tasks.Task> GetPetByIdAsyncWithHttpInfo (long? petId); /// /// Updates a pet in the store with form data @@ -124,7 +225,7 @@ namespace IO.Swagger.Api /// Updated name of the pet /// Updated status of the pet /// - void UpdatePetWithForm (string petId, string name, string status); + void UpdatePetWithForm (string petId, string name = null, string status = null); /// /// Updates a pet in the store with form data @@ -135,8 +236,32 @@ namespace IO.Swagger.Api /// ID of pet that needs to be updated /// Updated name of the pet /// Updated status of the pet - /// - System.Threading.Tasks.Task UpdatePetWithFormAsync (string petId, string name, string status); + /// ApiResponse of Object(void) + ApiResponse UpdatePetWithFormWithHttpInfo (string petId, string name = null, string status = null); + + /// + /// Updates a pet in the store with form data + /// + /// + /// + /// + /// 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 + /// + /// + /// + /// + /// 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 @@ -147,7 +272,7 @@ namespace IO.Swagger.Api /// Pet id to delete /// /// - void DeletePet (long? petId, string apiKey); + void DeletePet (long? petId, string apiKey = null); /// /// Deletes a pet @@ -157,8 +282,66 @@ namespace IO.Swagger.Api /// /// Pet id to delete /// - /// - System.Threading.Tasks.Task DeletePetAsync (long? petId, string apiKey); + /// ApiResponse of Object(void) + ApiResponse DeletePetWithHttpInfo (long? petId, string apiKey = null); + + /// + /// Deletes a pet + /// + /// + /// + /// + /// Pet id to delete + /// + /// Task of void + System.Threading.Tasks.Task DeletePetAsync (long? petId, string apiKey = null); + + /// + /// Deletes a pet + /// + /// + /// + /// + /// Pet id to delete + /// + /// Task of ApiResponse + System.Threading.Tasks.Task> DeletePetAsyncWithHttpInfo (long? petId, string apiKey = null); + + /// + /// downloads an image + /// + /// + /// + /// + /// Stream + Stream DownloadFile (); + + /// + /// downloads an image + /// + /// + /// + /// + /// ApiResponse of Stream + ApiResponse DownloadFileWithHttpInfo (); + + /// + /// downloads an image + /// + /// + /// + /// + /// Task of Stream + System.Threading.Tasks.Task DownloadFileAsync (); + + /// + /// downloads an image + /// + /// + /// + /// + /// Task of ApiResponse (Stream) + System.Threading.Tasks.Task> DownloadFileAsyncWithHttpInfo (); /// /// uploads an image @@ -170,7 +353,7 @@ namespace IO.Swagger.Api /// Additional data to pass to server /// file to upload /// - void UploadFile (long? petId, string additionalMetadata, Stream file); + void UploadFile (long? petId, string additionalMetadata = null, Stream file = null); /// /// uploads an image @@ -181,8 +364,32 @@ namespace IO.Swagger.Api /// ID of pet to update /// Additional data to pass to server /// file to upload - /// - System.Threading.Tasks.Task UploadFileAsync (long? petId, string additionalMetadata, Stream file); + /// ApiResponse of Object(void) + ApiResponse UploadFileWithHttpInfo (long? petId, string additionalMetadata = null, Stream file = null); + + /// + /// uploads an image + /// + /// + /// + /// + /// 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 + /// + /// + /// + /// + /// 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); } @@ -191,60 +398,93 @@ namespace IO.Swagger.Api /// public class PetApi : IPetApi { - /// - /// Initializes a new instance of the class. - /// - /// an instance of ApiClient (optional) - /// - public PetApi(ApiClient apiClient = null) - { - if (apiClient == null) // use the default one in Configuration - this.ApiClient = Configuration.DefaultApiClient; - else - this.ApiClient = apiClient; - } - /// /// Initializes a new instance of the class. /// /// public PetApi(String basePath) { - this.ApiClient = new ApiClient(basePath); + this.Configuration = new Configuration(new ApiClient(basePath)); } /// - /// Sets the base path of the API client. + /// Initializes a new instance of the class + /// using Configuration object /// - /// The base path - /// The base path - public void SetBasePath(String basePath) + /// An instance of Configuration + /// + public PetApi(Configuration configuration = null) { - this.ApiClient.BasePath = basePath; + if (configuration == null) // use the default one in Configuration + this.Configuration = Configuration.Default; + else + this.Configuration = configuration; } - + /// /// Gets the base path of the API client. /// /// The base path public String GetBasePath() { - return this.ApiClient.BasePath; + return this.Configuration.ApiClient.RestClient.BaseUrl.ToString(); + } + + /// + /// Sets the base path of the API client. + /// + /// The base path + [Obsolete("SetBasePath is deprecated, please do 'Configuraiton.ApiClient = new ApiClient(\"http://new-path\")' instead.")] + public void SetBasePath(String basePath) + { + // do nothing } /// - /// Gets or sets the API client. + /// Gets or sets the configuration object /// - /// An instance of the ApiClient - public ApiClient ApiClient {get; set;} - + /// An instance of the Configuration + public Configuration Configuration {get; set;} + + /// + /// Gets the default header. + /// + /// Dictionary of HTTP header + [Obsolete("DefaultHeader is deprecated, please use Configuration.DefaultHeader instead.")] + public Dictionary DefaultHeader() + { + return this.Configuration.DefaultHeader; + } + + /// + /// Add default header. + /// + /// Header field name. + /// Header field value. + /// + [Obsolete("AddDefaultHeader is deprecated, please use Configuration.AddDefaultHeader instead.")] + public void AddDefaultHeader(string key, string value) + { + this.Configuration.AddDefaultHeader(key, value); + } + /// /// Update an existing pet /// /// Pet object that needs to be added to the store - /// - public void UpdatePet (Pet body) + /// + public void UpdatePet (Pet body = null) + { + UpdatePetWithHttpInfo(body); + } + + /// + /// Update an existing pet + /// + /// Pet object that needs to be added to the store + /// ApiResponse of Object(void) + public ApiResponse UpdatePetWithHttpInfo (Pet body = null) { @@ -252,7 +492,7 @@ namespace IO.Swagger.Api var pathParams = new Dictionary(); var queryParams = new Dictionary(); - var headerParams = new Dictionary(); + var headerParams = new Dictionary(Configuration.DefaultHeader); var formParams = new Dictionary(); var fileParams = new Dictionary(); String postBody = null; @@ -261,9 +501,9 @@ namespace IO.Swagger.Api String[] http_header_accepts = new String[] { "application/json", "application/xml" }; - String http_header_accept = ApiClient.SelectHeaderAccept(http_header_accepts); + String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); if (http_header_accept != null) - headerParams.Add("Accept", ApiClient.SelectHeaderAccept(http_header_accepts)); + headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json @@ -272,29 +512,52 @@ namespace IO.Swagger.Api - postBody = ApiClient.Serialize(body); // http body (model) parameter + postBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter + + + + // authentication (petstore_auth) required + + // oauth required + if (!String.IsNullOrEmpty(Configuration.AccessToken)) + { + headerParams["Authorization"] = "Bearer " + Configuration.AccessToken; + } - // authentication setting, if any - String[] authSettings = new String[] { "petstore_auth" }; - // make the HTTP request - IRestResponse response = (IRestResponse) ApiClient.CallApi(path_, Method.PUT, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); + IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, Method.PUT, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + + int statusCode = (int) response.StatusCode; - if (((int)response.StatusCode) >= 400) - throw new ApiException ((int)response.StatusCode, "Error calling UpdatePet: " + response.Content, response.Content); - else if (((int)response.StatusCode) == 0) - throw new ApiException ((int)response.StatusCode, "Error calling UpdatePet: " + response.ErrorMessage, response.ErrorMessage); + if (statusCode >= 400) + throw new ApiException (statusCode, "Error calling UpdatePet: " + response.Content, response.Content); + else if (statusCode == 0) + throw new ApiException (statusCode, "Error calling UpdatePet: " + response.ErrorMessage, response.ErrorMessage); - return; + + return new ApiResponse(statusCode, + response.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), + null); } /// /// Update an existing pet /// /// Pet object that needs to be added to the store - /// - public async System.Threading.Tasks.Task UpdatePetAsync (Pet body) + /// Task of void + public async System.Threading.Tasks.Task UpdatePetAsync (Pet body = null) + { + await UpdatePetAsyncWithHttpInfo(body); + + } + + /// + /// Update an existing pet + /// + /// Pet object that needs to be added to the store + /// Task of ApiResponse + public async System.Threading.Tasks.Task> UpdatePetAsyncWithHttpInfo (Pet body = null) { @@ -311,9 +574,9 @@ namespace IO.Swagger.Api String[] http_header_accepts = new String[] { "application/json", "application/xml" }; - String http_header_accept = ApiClient.SelectHeaderAccept(http_header_accepts); + String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); if (http_header_accept != null) - headerParams.Add("Accept", ApiClient.SelectHeaderAccept(http_header_accepts)); + headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json @@ -322,27 +585,51 @@ namespace IO.Swagger.Api - postBody = ApiClient.Serialize(body); // http body (model) parameter + postBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter - - // authentication setting, if any - String[] authSettings = new String[] { "petstore_auth" }; - - // make the HTTP request - IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path_, Method.PUT, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); - if (((int)response.StatusCode) >= 400) - throw new ApiException ((int)response.StatusCode, "Error calling UpdatePet: " + response.Content, response.Content); - return; + // authentication (petstore_auth) required + + // oauth required + if (!String.IsNullOrEmpty(Configuration.AccessToken)) + { + headerParams["Authorization"] = "Bearer " + Configuration.AccessToken; + } + + + // make the HTTP request + IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, Method.PUT, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + + int statusCode = (int) response.StatusCode; + + if (statusCode >= 400) + throw new ApiException (statusCode, "Error calling UpdatePet: " + response.Content, response.Content); + else if (statusCode == 0) + throw new ApiException (statusCode, "Error calling UpdatePet: " + response.ErrorMessage, response.ErrorMessage); + + + return new ApiResponse(statusCode, + response.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), + null); } /// /// Add a new pet to the store /// /// Pet object that needs to be added to the store - /// - public void AddPet (Pet body) + /// + public void AddPet (Pet body = null) + { + AddPetWithHttpInfo(body); + } + + /// + /// Add a new pet to the store + /// + /// Pet object that needs to be added to the store + /// ApiResponse of Object(void) + public ApiResponse AddPetWithHttpInfo (Pet body = null) { @@ -350,7 +637,7 @@ namespace IO.Swagger.Api var pathParams = new Dictionary(); var queryParams = new Dictionary(); - var headerParams = new Dictionary(); + var headerParams = new Dictionary(Configuration.DefaultHeader); var formParams = new Dictionary(); var fileParams = new Dictionary(); String postBody = null; @@ -359,9 +646,9 @@ namespace IO.Swagger.Api String[] http_header_accepts = new String[] { "application/json", "application/xml" }; - String http_header_accept = ApiClient.SelectHeaderAccept(http_header_accepts); + String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); if (http_header_accept != null) - headerParams.Add("Accept", ApiClient.SelectHeaderAccept(http_header_accepts)); + headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json @@ -370,29 +657,52 @@ namespace IO.Swagger.Api - postBody = ApiClient.Serialize(body); // http body (model) parameter + postBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter + + + + // authentication (petstore_auth) required + + // oauth required + if (!String.IsNullOrEmpty(Configuration.AccessToken)) + { + headerParams["Authorization"] = "Bearer " + Configuration.AccessToken; + } - // authentication setting, if any - String[] authSettings = new String[] { "petstore_auth" }; - // make the HTTP request - IRestResponse response = (IRestResponse) ApiClient.CallApi(path_, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); + IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + + int statusCode = (int) response.StatusCode; - if (((int)response.StatusCode) >= 400) - throw new ApiException ((int)response.StatusCode, "Error calling AddPet: " + response.Content, response.Content); - else if (((int)response.StatusCode) == 0) - throw new ApiException ((int)response.StatusCode, "Error calling AddPet: " + response.ErrorMessage, response.ErrorMessage); + if (statusCode >= 400) + throw new ApiException (statusCode, "Error calling AddPet: " + response.Content, response.Content); + else if (statusCode == 0) + throw new ApiException (statusCode, "Error calling AddPet: " + response.ErrorMessage, response.ErrorMessage); - return; + + return new ApiResponse(statusCode, + response.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), + null); } /// /// Add a new pet to the store /// /// Pet object that needs to be added to the store - /// - public async System.Threading.Tasks.Task AddPetAsync (Pet body) + /// Task of void + public async System.Threading.Tasks.Task AddPetAsync (Pet body = null) + { + await AddPetAsyncWithHttpInfo(body); + + } + + /// + /// Add a new pet to the store + /// + /// Pet object that needs to be added to the store + /// Task of ApiResponse + public async System.Threading.Tasks.Task> AddPetAsyncWithHttpInfo (Pet body = null) { @@ -409,9 +719,9 @@ namespace IO.Swagger.Api String[] http_header_accepts = new String[] { "application/json", "application/xml" }; - String http_header_accept = ApiClient.SelectHeaderAccept(http_header_accepts); + String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); if (http_header_accept != null) - headerParams.Add("Accept", ApiClient.SelectHeaderAccept(http_header_accepts)); + headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json @@ -420,27 +730,52 @@ namespace IO.Swagger.Api - postBody = ApiClient.Serialize(body); // http body (model) parameter + postBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter - - // authentication setting, if any - String[] authSettings = new String[] { "petstore_auth" }; - - // make the HTTP request - IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path_, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); - if (((int)response.StatusCode) >= 400) - throw new ApiException ((int)response.StatusCode, "Error calling AddPet: " + response.Content, response.Content); - return; + // authentication (petstore_auth) required + + // oauth required + if (!String.IsNullOrEmpty(Configuration.AccessToken)) + { + headerParams["Authorization"] = "Bearer " + Configuration.AccessToken; + } + + + // make the HTTP request + IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + + int statusCode = (int) response.StatusCode; + + if (statusCode >= 400) + throw new ApiException (statusCode, "Error calling AddPet: " + response.Content, response.Content); + else if (statusCode == 0) + throw new ApiException (statusCode, "Error calling AddPet: " + response.ErrorMessage, response.ErrorMessage); + + + return new ApiResponse(statusCode, + response.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), + null); } /// /// Finds Pets by status Multiple status values can be provided with comma seperated strings /// /// Status values that need to be considered for filter - /// - public List FindPetsByStatus (List status) + /// List<Pet> + public List FindPetsByStatus (List status = null) + { + ApiResponse> response = FindPetsByStatusWithHttpInfo(status); + return response.Data; + } + + /// + /// Finds Pets by status Multiple status values can be provided with comma seperated strings + /// + /// Status values that need to be considered for filter + /// ApiResponse of List<Pet> + public ApiResponse< List > FindPetsByStatusWithHttpInfo (List status = null) { @@ -448,7 +783,7 @@ namespace IO.Swagger.Api var pathParams = new Dictionary(); var queryParams = new Dictionary(); - var headerParams = new Dictionary(); + var headerParams = new Dictionary(Configuration.DefaultHeader); var formParams = new Dictionary(); var fileParams = new Dictionary(); String postBody = null; @@ -457,40 +792,64 @@ namespace IO.Swagger.Api String[] http_header_accepts = new String[] { "application/json", "application/xml" }; - String http_header_accept = ApiClient.SelectHeaderAccept(http_header_accepts); + String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); if (http_header_accept != null) - headerParams.Add("Accept", ApiClient.SelectHeaderAccept(http_header_accepts)); + headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json pathParams.Add("format", "json"); - if (status != null) queryParams.Add("status", ApiClient.ParameterToString(status)); // query parameter + if (status != null) queryParams.Add("status", Configuration.ApiClient.ParameterToString(status)); // query parameter - - // authentication setting, if any - String[] authSettings = new String[] { "petstore_auth" }; + + + // authentication (petstore_auth) required + + // oauth required + if (!String.IsNullOrEmpty(Configuration.AccessToken)) + { + headerParams["Authorization"] = "Bearer " + Configuration.AccessToken; + } + // make the HTTP request - IRestResponse response = (IRestResponse) ApiClient.CallApi(path_, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); + IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + + int statusCode = (int) response.StatusCode; - if (((int)response.StatusCode) >= 400) - throw new ApiException ((int)response.StatusCode, "Error calling FindPetsByStatus: " + response.Content, response.Content); - else if (((int)response.StatusCode) == 0) - throw new ApiException ((int)response.StatusCode, "Error calling FindPetsByStatus: " + response.ErrorMessage, response.ErrorMessage); + if (statusCode >= 400) + throw new ApiException (statusCode, "Error calling FindPetsByStatus: " + response.Content, response.Content); + else if (statusCode == 0) + throw new ApiException (statusCode, "Error calling FindPetsByStatus: " + response.ErrorMessage, response.ErrorMessage); - return (List) ApiClient.Deserialize(response, typeof(List)); + return new ApiResponse>(statusCode, + response.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), + (List) Configuration.ApiClient.Deserialize(response, typeof(List))); + } /// /// Finds Pets by status Multiple status values can be provided with comma seperated strings /// /// Status values that need to be considered for filter - /// - public async System.Threading.Tasks.Task> FindPetsByStatusAsync (List status) + /// Task of List<Pet> + public async System.Threading.Tasks.Task> FindPetsByStatusAsync (List status = null) + { + ApiResponse> response = await FindPetsByStatusAsyncWithHttpInfo(status); + return response.Data; + + } + + /// + /// Finds Pets by status Multiple status values can be provided with comma seperated strings + /// + /// Status values that need to be considered for filter + /// Task of ApiResponse (List<Pet>) + public async System.Threading.Tasks.Task>> FindPetsByStatusAsyncWithHttpInfo (List status = null) { @@ -507,37 +866,63 @@ namespace IO.Swagger.Api String[] http_header_accepts = new String[] { "application/json", "application/xml" }; - String http_header_accept = ApiClient.SelectHeaderAccept(http_header_accepts); + String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); if (http_header_accept != null) - headerParams.Add("Accept", ApiClient.SelectHeaderAccept(http_header_accepts)); + headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json pathParams.Add("format", "json"); - if (status != null) queryParams.Add("status", ApiClient.ParameterToString(status)); // query parameter + if (status != null) queryParams.Add("status", Configuration.ApiClient.ParameterToString(status)); // query parameter - - // authentication setting, if any - String[] authSettings = new String[] { "petstore_auth" }; - - // make the HTTP request - IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path_, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); - if (((int)response.StatusCode) >= 400) - throw new ApiException ((int)response.StatusCode, "Error calling FindPetsByStatus: " + response.Content, response.Content); - return (List) ApiClient.Deserialize(response, typeof(List)); + + // authentication (petstore_auth) required + + // oauth required + if (!String.IsNullOrEmpty(Configuration.AccessToken)) + { + headerParams["Authorization"] = "Bearer " + Configuration.AccessToken; + } + + + // make the HTTP request + IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + + int statusCode = (int) response.StatusCode; + + if (statusCode >= 400) + throw new ApiException (statusCode, "Error calling FindPetsByStatus: " + response.Content, response.Content); + else if (statusCode == 0) + throw new ApiException (statusCode, "Error calling FindPetsByStatus: " + response.ErrorMessage, response.ErrorMessage); + + return new ApiResponse>(statusCode, + response.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), + (List) Configuration.ApiClient.Deserialize(response, typeof(List))); + } /// /// Finds Pets by tags Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. /// /// Tags to filter by - /// - public List FindPetsByTags (List tags) + /// List<Pet> + public List FindPetsByTags (List tags = null) + { + ApiResponse> response = FindPetsByTagsWithHttpInfo(tags); + return response.Data; + } + + /// + /// Finds Pets by tags Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + /// + /// Tags to filter by + /// ApiResponse of List<Pet> + public ApiResponse< List > FindPetsByTagsWithHttpInfo (List tags = null) { @@ -545,7 +930,7 @@ namespace IO.Swagger.Api var pathParams = new Dictionary(); var queryParams = new Dictionary(); - var headerParams = new Dictionary(); + var headerParams = new Dictionary(Configuration.DefaultHeader); var formParams = new Dictionary(); var fileParams = new Dictionary(); String postBody = null; @@ -554,40 +939,64 @@ namespace IO.Swagger.Api String[] http_header_accepts = new String[] { "application/json", "application/xml" }; - String http_header_accept = ApiClient.SelectHeaderAccept(http_header_accepts); + String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); if (http_header_accept != null) - headerParams.Add("Accept", ApiClient.SelectHeaderAccept(http_header_accepts)); + headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json pathParams.Add("format", "json"); - if (tags != null) queryParams.Add("tags", ApiClient.ParameterToString(tags)); // query parameter + if (tags != null) queryParams.Add("tags", Configuration.ApiClient.ParameterToString(tags)); // query parameter - - // authentication setting, if any - String[] authSettings = new String[] { "petstore_auth" }; + + + // authentication (petstore_auth) required + + // oauth required + if (!String.IsNullOrEmpty(Configuration.AccessToken)) + { + headerParams["Authorization"] = "Bearer " + Configuration.AccessToken; + } + // make the HTTP request - IRestResponse response = (IRestResponse) ApiClient.CallApi(path_, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); + IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + + int statusCode = (int) response.StatusCode; - if (((int)response.StatusCode) >= 400) - throw new ApiException ((int)response.StatusCode, "Error calling FindPetsByTags: " + response.Content, response.Content); - else if (((int)response.StatusCode) == 0) - throw new ApiException ((int)response.StatusCode, "Error calling FindPetsByTags: " + response.ErrorMessage, response.ErrorMessage); + if (statusCode >= 400) + throw new ApiException (statusCode, "Error calling FindPetsByTags: " + response.Content, response.Content); + else if (statusCode == 0) + throw new ApiException (statusCode, "Error calling FindPetsByTags: " + response.ErrorMessage, response.ErrorMessage); - return (List) ApiClient.Deserialize(response, typeof(List)); + return new ApiResponse>(statusCode, + response.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), + (List) Configuration.ApiClient.Deserialize(response, typeof(List))); + } /// /// Finds Pets by tags Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. /// /// Tags to filter by - /// - public async System.Threading.Tasks.Task> FindPetsByTagsAsync (List tags) + /// Task of List<Pet> + public async System.Threading.Tasks.Task> FindPetsByTagsAsync (List tags = null) + { + ApiResponse> response = await FindPetsByTagsAsyncWithHttpInfo(tags); + return response.Data; + + } + + /// + /// Finds Pets by tags Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + /// + /// Tags to filter by + /// Task of ApiResponse (List<Pet>) + public async System.Threading.Tasks.Task>> FindPetsByTagsAsyncWithHttpInfo (List tags = null) { @@ -604,37 +1013,63 @@ namespace IO.Swagger.Api String[] http_header_accepts = new String[] { "application/json", "application/xml" }; - String http_header_accept = ApiClient.SelectHeaderAccept(http_header_accepts); + String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); if (http_header_accept != null) - headerParams.Add("Accept", ApiClient.SelectHeaderAccept(http_header_accepts)); + headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json pathParams.Add("format", "json"); - if (tags != null) queryParams.Add("tags", ApiClient.ParameterToString(tags)); // query parameter + if (tags != null) queryParams.Add("tags", Configuration.ApiClient.ParameterToString(tags)); // query parameter - - // authentication setting, if any - String[] authSettings = new String[] { "petstore_auth" }; - - // make the HTTP request - IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path_, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); - if (((int)response.StatusCode) >= 400) - throw new ApiException ((int)response.StatusCode, "Error calling FindPetsByTags: " + response.Content, response.Content); - return (List) ApiClient.Deserialize(response, typeof(List)); + + // authentication (petstore_auth) required + + // oauth required + if (!String.IsNullOrEmpty(Configuration.AccessToken)) + { + headerParams["Authorization"] = "Bearer " + Configuration.AccessToken; + } + + + // make the HTTP request + IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + + int statusCode = (int) response.StatusCode; + + if (statusCode >= 400) + throw new ApiException (statusCode, "Error calling FindPetsByTags: " + response.Content, response.Content); + else if (statusCode == 0) + throw new ApiException (statusCode, "Error calling FindPetsByTags: " + response.ErrorMessage, response.ErrorMessage); + + return new ApiResponse>(statusCode, + response.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), + (List) Configuration.ApiClient.Deserialize(response, typeof(List))); + } /// /// Find pet by ID Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions /// /// ID of pet that needs to be fetched - /// Pet + /// Pet public Pet GetPetById (long? petId) + { + ApiResponse response = GetPetByIdWithHttpInfo(petId); + return response.Data; + } + + /// + /// Find pet by ID Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + /// + /// ID of pet that needs to be fetched + /// ApiResponse of Pet + public ApiResponse< Pet > GetPetByIdWithHttpInfo (long? petId) { // verify the required parameter 'petId' is set @@ -645,7 +1080,7 @@ namespace IO.Swagger.Api var pathParams = new Dictionary(); var queryParams = new Dictionary(); - var headerParams = new Dictionary(); + var headerParams = new Dictionary(Configuration.DefaultHeader); var formParams = new Dictionary(); var fileParams = new Dictionary(); String postBody = null; @@ -654,40 +1089,64 @@ namespace IO.Swagger.Api String[] http_header_accepts = new String[] { "application/json", "application/xml" }; - String http_header_accept = ApiClient.SelectHeaderAccept(http_header_accepts); + String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); if (http_header_accept != null) - headerParams.Add("Accept", ApiClient.SelectHeaderAccept(http_header_accepts)); + headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json pathParams.Add("format", "json"); - if (petId != null) pathParams.Add("petId", ApiClient.ParameterToString(petId)); // path parameter + if (petId != null) pathParams.Add("petId", Configuration.ApiClient.ParameterToString(petId)); // path parameter - - // authentication setting, if any - String[] authSettings = new String[] { "api_key" }; + + + // authentication (api_key) required + + var apiKeyValue = Configuration.GetApiKeyWithPrefix("api_key"); + if (!String.IsNullOrEmpty(apiKeyValue)) + { + headerParams["api_key"] = apiKeyValue; + } + // make the HTTP request - IRestResponse response = (IRestResponse) ApiClient.CallApi(path_, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); + IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + + int statusCode = (int) response.StatusCode; - if (((int)response.StatusCode) >= 400) - throw new ApiException ((int)response.StatusCode, "Error calling GetPetById: " + response.Content, response.Content); - else if (((int)response.StatusCode) == 0) - throw new ApiException ((int)response.StatusCode, "Error calling GetPetById: " + response.ErrorMessage, response.ErrorMessage); + if (statusCode >= 400) + throw new ApiException (statusCode, "Error calling GetPetById: " + response.Content, response.Content); + else if (statusCode == 0) + throw new ApiException (statusCode, "Error calling GetPetById: " + response.ErrorMessage, response.ErrorMessage); - return (Pet) ApiClient.Deserialize(response, typeof(Pet)); + return new ApiResponse(statusCode, + response.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), + (Pet) Configuration.ApiClient.Deserialize(response, typeof(Pet))); + } /// /// Find pet by ID Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions /// /// ID of pet that needs to be fetched - /// Pet + /// Task of Pet public async System.Threading.Tasks.Task GetPetByIdAsync (long? petId) + { + ApiResponse response = await GetPetByIdAsyncWithHttpInfo(petId); + return response.Data; + + } + + /// + /// Find pet by ID Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + /// + /// ID of pet that needs to be fetched + /// Task of ApiResponse (Pet) + public async System.Threading.Tasks.Task> GetPetByIdAsyncWithHttpInfo (long? petId) { // verify the required parameter 'petId' is set if (petId == null) throw new ApiException(400, "Missing required parameter 'petId' when calling GetPetById"); @@ -706,29 +1165,44 @@ namespace IO.Swagger.Api String[] http_header_accepts = new String[] { "application/json", "application/xml" }; - String http_header_accept = ApiClient.SelectHeaderAccept(http_header_accepts); + String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); if (http_header_accept != null) - headerParams.Add("Accept", ApiClient.SelectHeaderAccept(http_header_accepts)); + headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json pathParams.Add("format", "json"); - if (petId != null) pathParams.Add("petId", ApiClient.ParameterToString(petId)); // path parameter + if (petId != null) pathParams.Add("petId", Configuration.ApiClient.ParameterToString(petId)); // path parameter - - // authentication setting, if any - String[] authSettings = new String[] { "api_key" }; - - // make the HTTP request - IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path_, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); - if (((int)response.StatusCode) >= 400) - throw new ApiException ((int)response.StatusCode, "Error calling GetPetById: " + response.Content, response.Content); - return (Pet) ApiClient.Deserialize(response, typeof(Pet)); + + // authentication (api_key) required + + var apiKeyValue = Configuration.GetApiKeyWithPrefix("api_key"); + if (!String.IsNullOrEmpty(apiKeyValue)) + { + headerParams["api_key"] = apiKeyValue; + } + + + // make the HTTP request + IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + + int statusCode = (int) response.StatusCode; + + if (statusCode >= 400) + throw new ApiException (statusCode, "Error calling GetPetById: " + response.Content, response.Content); + else if (statusCode == 0) + throw new ApiException (statusCode, "Error calling GetPetById: " + response.ErrorMessage, response.ErrorMessage); + + return new ApiResponse(statusCode, + response.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), + (Pet) Configuration.ApiClient.Deserialize(response, typeof(Pet))); + } /// @@ -737,8 +1211,20 @@ namespace IO.Swagger.Api /// 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, string status) + /// + public void UpdatePetWithForm (string petId, string name = null, string status = null) + { + UpdatePetWithFormWithHttpInfo(petId, name, status); + } + + /// + /// Updates a pet in the store with form data + /// + /// 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 @@ -749,7 +1235,7 @@ namespace IO.Swagger.Api var pathParams = new Dictionary(); var queryParams = new Dictionary(); - var headerParams = new Dictionary(); + var headerParams = new Dictionary(Configuration.DefaultHeader); var formParams = new Dictionary(); var fileParams = new Dictionary(); String postBody = null; @@ -758,34 +1244,46 @@ namespace IO.Swagger.Api String[] http_header_accepts = new String[] { "application/json", "application/xml" }; - String http_header_accept = ApiClient.SelectHeaderAccept(http_header_accepts); + String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); if (http_header_accept != null) - headerParams.Add("Accept", ApiClient.SelectHeaderAccept(http_header_accepts)); + headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json pathParams.Add("format", "json"); - if (petId != null) pathParams.Add("petId", ApiClient.ParameterToString(petId)); // path parameter + if (petId != null) pathParams.Add("petId", Configuration.ApiClient.ParameterToString(petId)); // path parameter - if (name != null) formParams.Add("name", ApiClient.ParameterToString(name)); // form parameter - if (status != null) formParams.Add("status", ApiClient.ParameterToString(status)); // form parameter + if (name != null) formParams.Add("name", Configuration.ApiClient.ParameterToString(name)); // form parameter + if (status != null) formParams.Add("status", Configuration.ApiClient.ParameterToString(status)); // form parameter - - // authentication setting, if any - String[] authSettings = new String[] { "petstore_auth" }; + + + // authentication (petstore_auth) required + + // oauth required + if (!String.IsNullOrEmpty(Configuration.AccessToken)) + { + headerParams["Authorization"] = "Bearer " + Configuration.AccessToken; + } + // make the HTTP request - IRestResponse response = (IRestResponse) ApiClient.CallApi(path_, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); + IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + + int statusCode = (int) response.StatusCode; - if (((int)response.StatusCode) >= 400) - throw new ApiException ((int)response.StatusCode, "Error calling UpdatePetWithForm: " + response.Content, response.Content); - else if (((int)response.StatusCode) == 0) - throw new ApiException ((int)response.StatusCode, "Error calling UpdatePetWithForm: " + response.ErrorMessage, response.ErrorMessage); + if (statusCode >= 400) + throw new ApiException (statusCode, "Error calling UpdatePetWithForm: " + response.Content, response.Content); + else if (statusCode == 0) + throw new ApiException (statusCode, "Error calling UpdatePetWithForm: " + response.ErrorMessage, response.ErrorMessage); - return; + + return new ApiResponse(statusCode, + response.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), + null); } /// @@ -794,8 +1292,21 @@ namespace IO.Swagger.Api /// ID of pet that needs to be updated /// Updated name of the pet /// Updated status of the pet - /// - public async System.Threading.Tasks.Task UpdatePetWithFormAsync (string petId, string name, string status) + /// 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 + /// + /// 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"); @@ -814,32 +1325,46 @@ namespace IO.Swagger.Api String[] http_header_accepts = new String[] { "application/json", "application/xml" }; - String http_header_accept = ApiClient.SelectHeaderAccept(http_header_accepts); + String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); if (http_header_accept != null) - headerParams.Add("Accept", ApiClient.SelectHeaderAccept(http_header_accepts)); + headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json pathParams.Add("format", "json"); - if (petId != null) pathParams.Add("petId", ApiClient.ParameterToString(petId)); // path parameter + if (petId != null) pathParams.Add("petId", Configuration.ApiClient.ParameterToString(petId)); // path parameter - if (name != null) formParams.Add("name", ApiClient.ParameterToString(name)); // form parameter - if (status != null) formParams.Add("status", ApiClient.ParameterToString(status)); // form parameter + if (name != null) formParams.Add("name", Configuration.ApiClient.ParameterToString(name)); // form parameter + if (status != null) formParams.Add("status", Configuration.ApiClient.ParameterToString(status)); // form parameter - - // authentication setting, if any - String[] authSettings = new String[] { "petstore_auth" }; - - // make the HTTP request - IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path_, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); - if (((int)response.StatusCode) >= 400) - throw new ApiException ((int)response.StatusCode, "Error calling UpdatePetWithForm: " + response.Content, response.Content); - return; + // authentication (petstore_auth) required + + // oauth required + if (!String.IsNullOrEmpty(Configuration.AccessToken)) + { + headerParams["Authorization"] = "Bearer " + Configuration.AccessToken; + } + + + // make the HTTP request + IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + + int statusCode = (int) response.StatusCode; + + if (statusCode >= 400) + throw new ApiException (statusCode, "Error calling UpdatePetWithForm: " + response.Content, response.Content); + else if (statusCode == 0) + throw new ApiException (statusCode, "Error calling UpdatePetWithForm: " + response.ErrorMessage, response.ErrorMessage); + + + return new ApiResponse(statusCode, + response.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), + null); } /// @@ -847,8 +1372,19 @@ namespace IO.Swagger.Api /// /// Pet id to delete /// - /// - public void DeletePet (long? petId, string apiKey) + /// + public void DeletePet (long? petId, string apiKey = null) + { + DeletePetWithHttpInfo(petId, apiKey); + } + + /// + /// Deletes a pet + /// + /// Pet id to delete + /// + /// ApiResponse of Object(void) + public ApiResponse DeletePetWithHttpInfo (long? petId, string apiKey = null) { // verify the required parameter 'petId' is set @@ -859,7 +1395,7 @@ namespace IO.Swagger.Api var pathParams = new Dictionary(); var queryParams = new Dictionary(); - var headerParams = new Dictionary(); + var headerParams = new Dictionary(Configuration.DefaultHeader); var formParams = new Dictionary(); var fileParams = new Dictionary(); String postBody = null; @@ -868,33 +1404,45 @@ namespace IO.Swagger.Api String[] http_header_accepts = new String[] { "application/json", "application/xml" }; - String http_header_accept = ApiClient.SelectHeaderAccept(http_header_accepts); + String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); if (http_header_accept != null) - headerParams.Add("Accept", ApiClient.SelectHeaderAccept(http_header_accepts)); + headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json pathParams.Add("format", "json"); - if (petId != null) pathParams.Add("petId", ApiClient.ParameterToString(petId)); // path parameter + if (petId != null) pathParams.Add("petId", Configuration.ApiClient.ParameterToString(petId)); // path parameter - if (apiKey != null) headerParams.Add("api_key", ApiClient.ParameterToString(apiKey)); // header parameter + if (apiKey != null) headerParams.Add("api_key", Configuration.ApiClient.ParameterToString(apiKey)); // header parameter - - // authentication setting, if any - String[] authSettings = new String[] { "petstore_auth" }; + + + // authentication (petstore_auth) required + + // oauth required + if (!String.IsNullOrEmpty(Configuration.AccessToken)) + { + headerParams["Authorization"] = "Bearer " + Configuration.AccessToken; + } + // make the HTTP request - IRestResponse response = (IRestResponse) ApiClient.CallApi(path_, Method.DELETE, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); + IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, Method.DELETE, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + + int statusCode = (int) response.StatusCode; - if (((int)response.StatusCode) >= 400) - throw new ApiException ((int)response.StatusCode, "Error calling DeletePet: " + response.Content, response.Content); - else if (((int)response.StatusCode) == 0) - throw new ApiException ((int)response.StatusCode, "Error calling DeletePet: " + response.ErrorMessage, response.ErrorMessage); + if (statusCode >= 400) + throw new ApiException (statusCode, "Error calling DeletePet: " + response.Content, response.Content); + else if (statusCode == 0) + throw new ApiException (statusCode, "Error calling DeletePet: " + response.ErrorMessage, response.ErrorMessage); - return; + + return new ApiResponse(statusCode, + response.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), + null); } /// @@ -902,8 +1450,20 @@ namespace IO.Swagger.Api /// /// Pet id to delete /// - /// - public async System.Threading.Tasks.Task DeletePetAsync (long? petId, string apiKey) + /// Task of void + public async System.Threading.Tasks.Task DeletePetAsync (long? petId, string apiKey = null) + { + await DeletePetAsyncWithHttpInfo(petId, apiKey); + + } + + /// + /// Deletes a pet + /// + /// 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"); @@ -922,31 +1482,170 @@ namespace IO.Swagger.Api String[] http_header_accepts = new String[] { "application/json", "application/xml" }; - String http_header_accept = ApiClient.SelectHeaderAccept(http_header_accepts); + String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); if (http_header_accept != null) - headerParams.Add("Accept", ApiClient.SelectHeaderAccept(http_header_accepts)); + headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json pathParams.Add("format", "json"); - if (petId != null) pathParams.Add("petId", ApiClient.ParameterToString(petId)); // path parameter + if (petId != null) pathParams.Add("petId", Configuration.ApiClient.ParameterToString(petId)); // path parameter - if (apiKey != null) headerParams.Add("api_key", ApiClient.ParameterToString(apiKey)); // header parameter + if (apiKey != null) headerParams.Add("api_key", Configuration.ApiClient.ParameterToString(apiKey)); // header parameter - - // authentication setting, if any - String[] authSettings = new String[] { "petstore_auth" }; - - // make the HTTP request - IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path_, Method.DELETE, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); - if (((int)response.StatusCode) >= 400) - throw new ApiException ((int)response.StatusCode, "Error calling DeletePet: " + response.Content, response.Content); - return; + // authentication (petstore_auth) required + + // oauth required + if (!String.IsNullOrEmpty(Configuration.AccessToken)) + { + headerParams["Authorization"] = "Bearer " + Configuration.AccessToken; + } + + + // make the HTTP request + IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, Method.DELETE, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + + int statusCode = (int) response.StatusCode; + + if (statusCode >= 400) + throw new ApiException (statusCode, "Error calling DeletePet: " + response.Content, response.Content); + else if (statusCode == 0) + throw new ApiException (statusCode, "Error calling DeletePet: " + response.ErrorMessage, response.ErrorMessage); + + + return new ApiResponse(statusCode, + response.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), + null); + } + + /// + /// downloads an image + /// + /// Stream + public Stream DownloadFile () + { + ApiResponse response = DownloadFileWithHttpInfo(); + return response.Data; + } + + /// + /// downloads an image + /// + /// ApiResponse of Stream + public ApiResponse< Stream > DownloadFileWithHttpInfo () + { + + + var path_ = "/pet/{petId}/downloadImage"; + + var pathParams = new Dictionary(); + var queryParams = new Dictionary(); + var headerParams = new Dictionary(Configuration.DefaultHeader); + var formParams = new Dictionary(); + var fileParams = new Dictionary(); + String postBody = null; + + // to determine the Accept header + String[] http_header_accepts = new String[] { + "application/octet-stream" + }; + String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); + if (http_header_accept != null) + headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); + + // set "format" to json by default + // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json + pathParams.Add("format", "json"); + + + + + + + + + // make the HTTP request + IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + + int statusCode = (int) response.StatusCode; + + if (statusCode >= 400) + throw new ApiException (statusCode, "Error calling DownloadFile: " + response.Content, response.Content); + else if (statusCode == 0) + throw new ApiException (statusCode, "Error calling DownloadFile: " + response.ErrorMessage, response.ErrorMessage); + + return new ApiResponse(statusCode, + response.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), + (Stream) Configuration.ApiClient.Deserialize(response, typeof(Stream))); + + } + + /// + /// downloads an image + /// + /// Task of Stream + public async System.Threading.Tasks.Task DownloadFileAsync () + { + ApiResponse response = await DownloadFileAsyncWithHttpInfo(); + return response.Data; + + } + + /// + /// downloads an image + /// + /// Task of ApiResponse (Stream) + public async System.Threading.Tasks.Task> DownloadFileAsyncWithHttpInfo () + { + + + var path_ = "/pet/{petId}/downloadImage"; + + var pathParams = new Dictionary(); + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + var fileParams = new Dictionary(); + String postBody = null; + + // to determine the Accept header + String[] http_header_accepts = new String[] { + "application/octet-stream" + }; + String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); + if (http_header_accept != null) + headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); + + // set "format" to json by default + // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json + pathParams.Add("format", "json"); + + + + + + + + + // make the HTTP request + IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + + int statusCode = (int) response.StatusCode; + + if (statusCode >= 400) + throw new ApiException (statusCode, "Error calling DownloadFile: " + response.Content, response.Content); + else if (statusCode == 0) + throw new ApiException (statusCode, "Error calling DownloadFile: " + response.ErrorMessage, response.ErrorMessage); + + return new ApiResponse(statusCode, + response.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), + (Stream) Configuration.ApiClient.Deserialize(response, typeof(Stream))); + } /// @@ -955,8 +1654,20 @@ namespace IO.Swagger.Api /// ID of pet to update /// Additional data to pass to server /// file to upload - /// - public void UploadFile (long? petId, string additionalMetadata, Stream file) + /// + public void UploadFile (long? petId, string additionalMetadata = null, Stream file = null) + { + UploadFileWithHttpInfo(petId, additionalMetadata, file); + } + + /// + /// uploads an image + /// + /// 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 @@ -967,7 +1678,7 @@ namespace IO.Swagger.Api var pathParams = new Dictionary(); var queryParams = new Dictionary(); - var headerParams = new Dictionary(); + var headerParams = new Dictionary(Configuration.DefaultHeader); var formParams = new Dictionary(); var fileParams = new Dictionary(); String postBody = null; @@ -976,34 +1687,46 @@ namespace IO.Swagger.Api String[] http_header_accepts = new String[] { "application/json", "application/xml" }; - String http_header_accept = ApiClient.SelectHeaderAccept(http_header_accepts); + String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); if (http_header_accept != null) - headerParams.Add("Accept", ApiClient.SelectHeaderAccept(http_header_accepts)); + headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json pathParams.Add("format", "json"); - if (petId != null) pathParams.Add("petId", ApiClient.ParameterToString(petId)); // path parameter + if (petId != null) pathParams.Add("petId", Configuration.ApiClient.ParameterToString(petId)); // path parameter - if (additionalMetadata != null) formParams.Add("additionalMetadata", ApiClient.ParameterToString(additionalMetadata)); // form parameter - if (file != null) fileParams.Add("file", ApiClient.ParameterToFile("file", file)); + if (additionalMetadata != null) formParams.Add("additionalMetadata", Configuration.ApiClient.ParameterToString(additionalMetadata)); // form parameter + if (file != null) fileParams.Add("file", Configuration.ApiClient.ParameterToFile("file", file)); - - // authentication setting, if any - String[] authSettings = new String[] { "petstore_auth" }; + + + // authentication (petstore_auth) required + + // oauth required + if (!String.IsNullOrEmpty(Configuration.AccessToken)) + { + headerParams["Authorization"] = "Bearer " + Configuration.AccessToken; + } + // make the HTTP request - IRestResponse response = (IRestResponse) ApiClient.CallApi(path_, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); + IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + + int statusCode = (int) response.StatusCode; - if (((int)response.StatusCode) >= 400) - throw new ApiException ((int)response.StatusCode, "Error calling UploadFile: " + response.Content, response.Content); - else if (((int)response.StatusCode) == 0) - throw new ApiException ((int)response.StatusCode, "Error calling UploadFile: " + response.ErrorMessage, response.ErrorMessage); + if (statusCode >= 400) + throw new ApiException (statusCode, "Error calling UploadFile: " + response.Content, response.Content); + else if (statusCode == 0) + throw new ApiException (statusCode, "Error calling UploadFile: " + response.ErrorMessage, response.ErrorMessage); - return; + + return new ApiResponse(statusCode, + response.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), + null); } /// @@ -1012,8 +1735,21 @@ namespace IO.Swagger.Api /// ID of pet to update /// Additional data to pass to server /// file to upload - /// - public async System.Threading.Tasks.Task UploadFileAsync (long? petId, string additionalMetadata, Stream file) + /// 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 + /// + /// 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"); @@ -1032,32 +1768,46 @@ namespace IO.Swagger.Api String[] http_header_accepts = new String[] { "application/json", "application/xml" }; - String http_header_accept = ApiClient.SelectHeaderAccept(http_header_accepts); + String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); if (http_header_accept != null) - headerParams.Add("Accept", ApiClient.SelectHeaderAccept(http_header_accepts)); + headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json pathParams.Add("format", "json"); - if (petId != null) pathParams.Add("petId", ApiClient.ParameterToString(petId)); // path parameter + if (petId != null) pathParams.Add("petId", Configuration.ApiClient.ParameterToString(petId)); // path parameter - if (additionalMetadata != null) formParams.Add("additionalMetadata", ApiClient.ParameterToString(additionalMetadata)); // form parameter - if (file != null) fileParams.Add("file", ApiClient.ParameterToFile("file", file)); + if (additionalMetadata != null) formParams.Add("additionalMetadata", Configuration.ApiClient.ParameterToString(additionalMetadata)); // form parameter + if (file != null) fileParams.Add("file", Configuration.ApiClient.ParameterToFile("file", file)); - - // authentication setting, if any - String[] authSettings = new String[] { "petstore_auth" }; - - // make the HTTP request - IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path_, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); - if (((int)response.StatusCode) >= 400) - throw new ApiException ((int)response.StatusCode, "Error calling UploadFile: " + response.Content, response.Content); - return; + // authentication (petstore_auth) required + + // oauth required + if (!String.IsNullOrEmpty(Configuration.AccessToken)) + { + headerParams["Authorization"] = "Bearer " + Configuration.AccessToken; + } + + + // make the HTTP request + IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + + int statusCode = (int) response.StatusCode; + + if (statusCode >= 400) + throw new ApiException (statusCode, "Error calling UploadFile: " + response.Content, response.Content); + else if (statusCode == 0) + throw new ApiException (statusCode, "Error calling UploadFile: " + response.ErrorMessage, response.ErrorMessage); + + + return new ApiResponse(statusCode, + response.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 b0a439ddf1a..a9e9d6e9b74 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 @@ -1,6 +1,7 @@ using System; using System.IO; using System.Collections.Generic; +using System.Linq; using RestSharp; using IO.Swagger.Client; using IO.Swagger.Model; @@ -20,7 +21,7 @@ namespace IO.Swagger.Api /// /// Returns a map of status codes to quantities /// - /// + /// Dictionary<string, int?> Dictionary GetInventory (); /// @@ -29,8 +30,26 @@ namespace IO.Swagger.Api /// /// Returns a map of status codes to quantities /// - /// + /// ApiResponse of Dictionary<string, int?> + ApiResponse> GetInventoryWithHttpInfo (); + + /// + /// Returns pet inventories by status + /// + /// + /// Returns a map of status codes to quantities + /// + /// Task of Dictionary<string, int?> System.Threading.Tasks.Task> GetInventoryAsync (); + + /// + /// Returns pet inventories by status + /// + /// + /// Returns a map of status codes to quantities + /// + /// Task of ApiResponse (Dictionary<string, int?>) + System.Threading.Tasks.Task>> GetInventoryAsyncWithHttpInfo (); /// /// Place an order for a pet @@ -40,7 +59,7 @@ namespace IO.Swagger.Api /// /// order placed for purchasing the pet /// Order - Order PlaceOrder (Order body); + Order PlaceOrder (Order body = null); /// /// Place an order for a pet @@ -49,8 +68,28 @@ namespace IO.Swagger.Api /// /// /// order placed for purchasing the pet - /// Order - System.Threading.Tasks.Task PlaceOrderAsync (Order body); + /// ApiResponse of Order + ApiResponse PlaceOrderWithHttpInfo (Order body = null); + + /// + /// Place an order for a pet + /// + /// + /// + /// + /// order placed for purchasing the pet + /// Task of Order + System.Threading.Tasks.Task PlaceOrderAsync (Order body = null); + + /// + /// Place an order for a pet + /// + /// + /// + /// + /// order placed for purchasing the pet + /// Task of ApiResponse (Order) + System.Threading.Tasks.Task> PlaceOrderAsyncWithHttpInfo (Order body = null); /// /// Find purchase order by ID @@ -69,8 +108,28 @@ namespace IO.Swagger.Api /// For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions /// /// ID of pet that needs to be fetched - /// Order + /// ApiResponse of Order + ApiResponse GetOrderByIdWithHttpInfo (string orderId); + + /// + /// Find purchase order by ID + /// + /// + /// For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + /// + /// 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 + /// + /// ID of pet that needs to be fetched + /// Task of ApiResponse (Order) + System.Threading.Tasks.Task> GetOrderByIdAsyncWithHttpInfo (string orderId); /// /// Delete purchase order by ID @@ -89,8 +148,28 @@ namespace IO.Swagger.Api /// For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors /// /// ID of the order that needs to be deleted - /// + /// ApiResponse of Object(void) + ApiResponse DeleteOrderWithHttpInfo (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 + /// + /// ID of the order that needs to be deleted + /// Task of void System.Threading.Tasks.Task DeleteOrderAsync (string orderId); + + /// + /// Delete purchase order by ID + /// + /// + /// For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + /// + /// ID of the order that needs to be deleted + /// Task of ApiResponse + System.Threading.Tasks.Task> DeleteOrderAsyncWithHttpInfo (string orderId); } @@ -99,59 +178,92 @@ namespace IO.Swagger.Api /// public class StoreApi : IStoreApi { - /// - /// Initializes a new instance of the class. - /// - /// an instance of ApiClient (optional) - /// - public StoreApi(ApiClient apiClient = null) - { - if (apiClient == null) // use the default one in Configuration - this.ApiClient = Configuration.DefaultApiClient; - else - this.ApiClient = apiClient; - } - /// /// Initializes a new instance of the class. /// /// public StoreApi(String basePath) { - this.ApiClient = new ApiClient(basePath); + this.Configuration = new Configuration(new ApiClient(basePath)); } /// - /// Sets the base path of the API client. + /// Initializes a new instance of the class + /// using Configuration object /// - /// The base path - /// The base path - public void SetBasePath(String basePath) + /// An instance of Configuration + /// + public StoreApi(Configuration configuration = null) { - this.ApiClient.BasePath = basePath; + if (configuration == null) // use the default one in Configuration + this.Configuration = Configuration.Default; + else + this.Configuration = configuration; } - + /// /// Gets the base path of the API client. /// /// The base path public String GetBasePath() { - return this.ApiClient.BasePath; + return this.Configuration.ApiClient.RestClient.BaseUrl.ToString(); + } + + /// + /// Sets the base path of the API client. + /// + /// The base path + [Obsolete("SetBasePath is deprecated, please do 'Configuraiton.ApiClient = new ApiClient(\"http://new-path\")' instead.")] + public void SetBasePath(String basePath) + { + // do nothing } /// - /// Gets or sets the API client. + /// Gets or sets the configuration object /// - /// An instance of the ApiClient - public ApiClient ApiClient {get; set;} - + /// An instance of the Configuration + public Configuration Configuration {get; set;} + + /// + /// Gets the default header. + /// + /// Dictionary of HTTP header + [Obsolete("DefaultHeader is deprecated, please use Configuration.DefaultHeader instead.")] + public Dictionary DefaultHeader() + { + return this.Configuration.DefaultHeader; + } + + /// + /// Add default header. + /// + /// Header field name. + /// Header field value. + /// + [Obsolete("AddDefaultHeader is deprecated, please use Configuration.AddDefaultHeader instead.")] + public void AddDefaultHeader(string key, string value) + { + this.Configuration.AddDefaultHeader(key, value); + } + /// /// Returns pet inventories by status Returns a map of status codes to quantities /// - /// + /// Dictionary<string, int?> public Dictionary GetInventory () + { + ApiResponse> response = GetInventoryWithHttpInfo(); + return response.Data; + } + + /// + /// Returns pet inventories by status Returns a map of status codes to quantities + /// + /// ApiResponse of Dictionary<string, int?> + public ApiResponse< Dictionary > GetInventoryWithHttpInfo () { @@ -159,7 +271,7 @@ namespace IO.Swagger.Api var pathParams = new Dictionary(); var queryParams = new Dictionary(); - var headerParams = new Dictionary(); + var headerParams = new Dictionary(Configuration.DefaultHeader); var formParams = new Dictionary(); var fileParams = new Dictionary(); String postBody = null; @@ -168,9 +280,9 @@ namespace IO.Swagger.Api String[] http_header_accepts = new String[] { "application/json", "application/xml" }; - String http_header_accept = ApiClient.SelectHeaderAccept(http_header_accepts); + String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); if (http_header_accept != null) - headerParams.Add("Accept", ApiClient.SelectHeaderAccept(http_header_accepts)); + headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json @@ -180,26 +292,49 @@ namespace IO.Swagger.Api - - // authentication setting, if any - String[] authSettings = new String[] { "api_key" }; + + + // authentication (api_key) required + + var apiKeyValue = Configuration.GetApiKeyWithPrefix("api_key"); + if (!String.IsNullOrEmpty(apiKeyValue)) + { + headerParams["api_key"] = apiKeyValue; + } + // make the HTTP request - IRestResponse response = (IRestResponse) ApiClient.CallApi(path_, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); + IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + + int statusCode = (int) response.StatusCode; - if (((int)response.StatusCode) >= 400) - throw new ApiException ((int)response.StatusCode, "Error calling GetInventory: " + response.Content, response.Content); - else if (((int)response.StatusCode) == 0) - throw new ApiException ((int)response.StatusCode, "Error calling GetInventory: " + response.ErrorMessage, response.ErrorMessage); + if (statusCode >= 400) + throw new ApiException (statusCode, "Error calling GetInventory: " + response.Content, response.Content); + else if (statusCode == 0) + throw new ApiException (statusCode, "Error calling GetInventory: " + response.ErrorMessage, response.ErrorMessage); - return (Dictionary) ApiClient.Deserialize(response, typeof(Dictionary)); + return new ApiResponse>(statusCode, + response.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), + (Dictionary) Configuration.ApiClient.Deserialize(response, typeof(Dictionary))); + } /// /// Returns pet inventories by status Returns a map of status codes to quantities /// - /// + /// Task of Dictionary<string, int?> public async System.Threading.Tasks.Task> GetInventoryAsync () + { + ApiResponse> response = await GetInventoryAsyncWithHttpInfo(); + return response.Data; + + } + + /// + /// Returns pet inventories by status Returns a map of status codes to quantities + /// + /// Task of ApiResponse (Dictionary<string, int?>) + public async System.Threading.Tasks.Task>> GetInventoryAsyncWithHttpInfo () { @@ -216,9 +351,9 @@ namespace IO.Swagger.Api String[] http_header_accepts = new String[] { "application/json", "application/xml" }; - String http_header_accept = ApiClient.SelectHeaderAccept(http_header_accepts); + String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); if (http_header_accept != null) - headerParams.Add("Accept", ApiClient.SelectHeaderAccept(http_header_accepts)); + headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json @@ -228,24 +363,50 @@ namespace IO.Swagger.Api - - // authentication setting, if any - String[] authSettings = new String[] { "api_key" }; - - // make the HTTP request - IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path_, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); - if (((int)response.StatusCode) >= 400) - throw new ApiException ((int)response.StatusCode, "Error calling GetInventory: " + response.Content, response.Content); - return (Dictionary) ApiClient.Deserialize(response, typeof(Dictionary)); + + // authentication (api_key) required + + var apiKeyValue = Configuration.GetApiKeyWithPrefix("api_key"); + if (!String.IsNullOrEmpty(apiKeyValue)) + { + headerParams["api_key"] = apiKeyValue; + } + + + // make the HTTP request + IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + + int statusCode = (int) response.StatusCode; + + if (statusCode >= 400) + throw new ApiException (statusCode, "Error calling GetInventory: " + response.Content, response.Content); + else if (statusCode == 0) + throw new ApiException (statusCode, "Error calling GetInventory: " + response.ErrorMessage, response.ErrorMessage); + + return new ApiResponse>(statusCode, + response.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), + (Dictionary) Configuration.ApiClient.Deserialize(response, typeof(Dictionary))); + } /// /// Place an order for a pet /// /// order placed for purchasing the pet - /// Order - public Order PlaceOrder (Order body) + /// Order + public Order PlaceOrder (Order body = null) + { + ApiResponse response = PlaceOrderWithHttpInfo(body); + return response.Data; + } + + /// + /// Place an order for a pet + /// + /// order placed for purchasing the pet + /// ApiResponse of Order + public ApiResponse< Order > PlaceOrderWithHttpInfo (Order body = null) { @@ -253,7 +414,7 @@ namespace IO.Swagger.Api var pathParams = new Dictionary(); var queryParams = new Dictionary(); - var headerParams = new Dictionary(); + var headerParams = new Dictionary(Configuration.DefaultHeader); var formParams = new Dictionary(); var fileParams = new Dictionary(); String postBody = null; @@ -262,9 +423,9 @@ namespace IO.Swagger.Api String[] http_header_accepts = new String[] { "application/json", "application/xml" }; - String http_header_accept = ApiClient.SelectHeaderAccept(http_header_accepts); + String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); if (http_header_accept != null) - headerParams.Add("Accept", ApiClient.SelectHeaderAccept(http_header_accepts)); + headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json @@ -273,29 +434,45 @@ namespace IO.Swagger.Api - postBody = ApiClient.Serialize(body); // http body (model) parameter + postBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter + + - // authentication setting, if any - String[] authSettings = new String[] { }; - // make the HTTP request - IRestResponse response = (IRestResponse) ApiClient.CallApi(path_, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); + IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + + int statusCode = (int) response.StatusCode; - if (((int)response.StatusCode) >= 400) - throw new ApiException ((int)response.StatusCode, "Error calling PlaceOrder: " + response.Content, response.Content); - else if (((int)response.StatusCode) == 0) - throw new ApiException ((int)response.StatusCode, "Error calling PlaceOrder: " + response.ErrorMessage, response.ErrorMessage); + if (statusCode >= 400) + throw new ApiException (statusCode, "Error calling PlaceOrder: " + response.Content, response.Content); + else if (statusCode == 0) + throw new ApiException (statusCode, "Error calling PlaceOrder: " + response.ErrorMessage, response.ErrorMessage); - return (Order) ApiClient.Deserialize(response, typeof(Order)); + return new ApiResponse(statusCode, + response.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), + (Order) Configuration.ApiClient.Deserialize(response, typeof(Order))); + } /// /// Place an order for a pet /// /// order placed for purchasing the pet - /// Order - public async System.Threading.Tasks.Task PlaceOrderAsync (Order body) + /// Task of Order + public async System.Threading.Tasks.Task PlaceOrderAsync (Order body = null) + { + ApiResponse response = await PlaceOrderAsyncWithHttpInfo(body); + return response.Data; + + } + + /// + /// Place an order for a pet + /// + /// order placed for purchasing the pet + /// Task of ApiResponse (Order) + public async System.Threading.Tasks.Task> PlaceOrderAsyncWithHttpInfo (Order body = null) { @@ -312,9 +489,9 @@ namespace IO.Swagger.Api String[] http_header_accepts = new String[] { "application/json", "application/xml" }; - String http_header_accept = ApiClient.SelectHeaderAccept(http_header_accepts); + String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); if (http_header_accept != null) - headerParams.Add("Accept", ApiClient.SelectHeaderAccept(http_header_accepts)); + headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json @@ -323,26 +500,44 @@ namespace IO.Swagger.Api - postBody = ApiClient.Serialize(body); // http body (model) parameter + postBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter - - // authentication setting, if any - String[] authSettings = new String[] { }; - - // make the HTTP request - IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path_, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); - if (((int)response.StatusCode) >= 400) - throw new ApiException ((int)response.StatusCode, "Error calling PlaceOrder: " + response.Content, response.Content); - return (Order) ApiClient.Deserialize(response, typeof(Order)); + + + // make the HTTP request + IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + + int statusCode = (int) response.StatusCode; + + if (statusCode >= 400) + throw new ApiException (statusCode, "Error calling PlaceOrder: " + response.Content, response.Content); + else if (statusCode == 0) + throw new ApiException (statusCode, "Error calling PlaceOrder: " + response.ErrorMessage, response.ErrorMessage); + + return new ApiResponse(statusCode, + response.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), + (Order) Configuration.ApiClient.Deserialize(response, typeof(Order))); + } /// /// Find purchase order by ID For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions /// /// ID of pet that needs to be fetched - /// Order + /// Order public Order GetOrderById (string orderId) + { + ApiResponse response = GetOrderByIdWithHttpInfo(orderId); + return response.Data; + } + + /// + /// Find purchase order by ID For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + /// + /// ID of pet that needs to be fetched + /// ApiResponse of Order + public ApiResponse< Order > GetOrderByIdWithHttpInfo (string orderId) { // verify the required parameter 'orderId' is set @@ -353,7 +548,7 @@ namespace IO.Swagger.Api var pathParams = new Dictionary(); var queryParams = new Dictionary(); - var headerParams = new Dictionary(); + var headerParams = new Dictionary(Configuration.DefaultHeader); var formParams = new Dictionary(); var fileParams = new Dictionary(); String postBody = null; @@ -362,40 +557,56 @@ namespace IO.Swagger.Api String[] http_header_accepts = new String[] { "application/json", "application/xml" }; - String http_header_accept = ApiClient.SelectHeaderAccept(http_header_accepts); + String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); if (http_header_accept != null) - headerParams.Add("Accept", ApiClient.SelectHeaderAccept(http_header_accepts)); + headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json pathParams.Add("format", "json"); - if (orderId != null) pathParams.Add("orderId", ApiClient.ParameterToString(orderId)); // path parameter + if (orderId != null) pathParams.Add("orderId", Configuration.ApiClient.ParameterToString(orderId)); // path parameter - - // authentication setting, if any - String[] authSettings = new String[] { }; + + // make the HTTP request - IRestResponse response = (IRestResponse) ApiClient.CallApi(path_, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); + IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + + int statusCode = (int) response.StatusCode; - if (((int)response.StatusCode) >= 400) - throw new ApiException ((int)response.StatusCode, "Error calling GetOrderById: " + response.Content, response.Content); - else if (((int)response.StatusCode) == 0) - throw new ApiException ((int)response.StatusCode, "Error calling GetOrderById: " + response.ErrorMessage, response.ErrorMessage); + if (statusCode >= 400) + throw new ApiException (statusCode, "Error calling GetOrderById: " + response.Content, response.Content); + else if (statusCode == 0) + throw new ApiException (statusCode, "Error calling GetOrderById: " + response.ErrorMessage, response.ErrorMessage); - return (Order) ApiClient.Deserialize(response, typeof(Order)); + return new ApiResponse(statusCode, + response.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), + (Order) Configuration.ApiClient.Deserialize(response, typeof(Order))); + } /// /// Find purchase order by ID For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions /// /// ID of pet that needs to be fetched - /// Order + /// Task of Order public async System.Threading.Tasks.Task GetOrderByIdAsync (string orderId) + { + ApiResponse response = await GetOrderByIdAsyncWithHttpInfo(orderId); + return response.Data; + + } + + /// + /// Find purchase order by ID For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + /// + /// 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"); @@ -414,37 +625,54 @@ namespace IO.Swagger.Api String[] http_header_accepts = new String[] { "application/json", "application/xml" }; - String http_header_accept = ApiClient.SelectHeaderAccept(http_header_accepts); + String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); if (http_header_accept != null) - headerParams.Add("Accept", ApiClient.SelectHeaderAccept(http_header_accepts)); + headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json pathParams.Add("format", "json"); - if (orderId != null) pathParams.Add("orderId", ApiClient.ParameterToString(orderId)); // path parameter + if (orderId != null) pathParams.Add("orderId", Configuration.ApiClient.ParameterToString(orderId)); // path parameter - - // authentication setting, if any - String[] authSettings = new String[] { }; - - // make the HTTP request - IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path_, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); - if (((int)response.StatusCode) >= 400) - throw new ApiException ((int)response.StatusCode, "Error calling GetOrderById: " + response.Content, response.Content); - return (Order) ApiClient.Deserialize(response, typeof(Order)); + + + // make the HTTP request + IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + + int statusCode = (int) response.StatusCode; + + if (statusCode >= 400) + throw new ApiException (statusCode, "Error calling GetOrderById: " + response.Content, response.Content); + else if (statusCode == 0) + throw new ApiException (statusCode, "Error calling GetOrderById: " + response.ErrorMessage, response.ErrorMessage); + + return new ApiResponse(statusCode, + response.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), + (Order) Configuration.ApiClient.Deserialize(response, 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 /// /// ID of the order that needs to be deleted - /// + /// public void DeleteOrder (string orderId) + { + DeleteOrderWithHttpInfo(orderId); + } + + /// + /// Delete purchase order by ID For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + /// + /// ID of the order that needs to be deleted + /// ApiResponse of Object(void) + public ApiResponse DeleteOrderWithHttpInfo (string orderId) { // verify the required parameter 'orderId' is set @@ -455,7 +683,7 @@ namespace IO.Swagger.Api var pathParams = new Dictionary(); var queryParams = new Dictionary(); - var headerParams = new Dictionary(); + var headerParams = new Dictionary(Configuration.DefaultHeader); var formParams = new Dictionary(); var fileParams = new Dictionary(); String postBody = null; @@ -464,40 +692,55 @@ namespace IO.Swagger.Api String[] http_header_accepts = new String[] { "application/json", "application/xml" }; - String http_header_accept = ApiClient.SelectHeaderAccept(http_header_accepts); + String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); if (http_header_accept != null) - headerParams.Add("Accept", ApiClient.SelectHeaderAccept(http_header_accepts)); + headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json pathParams.Add("format", "json"); - if (orderId != null) pathParams.Add("orderId", ApiClient.ParameterToString(orderId)); // path parameter + if (orderId != null) pathParams.Add("orderId", Configuration.ApiClient.ParameterToString(orderId)); // path parameter - - // authentication setting, if any - String[] authSettings = new String[] { }; + + // make the HTTP request - IRestResponse response = (IRestResponse) ApiClient.CallApi(path_, Method.DELETE, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); + IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, Method.DELETE, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + + int statusCode = (int) response.StatusCode; - if (((int)response.StatusCode) >= 400) - throw new ApiException ((int)response.StatusCode, "Error calling DeleteOrder: " + response.Content, response.Content); - else if (((int)response.StatusCode) == 0) - throw new ApiException ((int)response.StatusCode, "Error calling DeleteOrder: " + response.ErrorMessage, response.ErrorMessage); + if (statusCode >= 400) + throw new ApiException (statusCode, "Error calling DeleteOrder: " + response.Content, response.Content); + else if (statusCode == 0) + throw new ApiException (statusCode, "Error calling DeleteOrder: " + response.ErrorMessage, response.ErrorMessage); - return; + + return new ApiResponse(statusCode, + response.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 /// /// ID of the order that needs to be deleted - /// + /// Task of void public async System.Threading.Tasks.Task DeleteOrderAsync (string orderId) + { + await DeleteOrderAsyncWithHttpInfo(orderId); + + } + + /// + /// Delete purchase order by ID For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + /// + /// ID of the order that needs to be deleted + /// Task of ApiResponse + public async System.Threading.Tasks.Task> DeleteOrderAsyncWithHttpInfo (string orderId) { // verify the required parameter 'orderId' is set if (orderId == null) throw new ApiException(400, "Missing required parameter 'orderId' when calling DeleteOrder"); @@ -516,30 +759,36 @@ namespace IO.Swagger.Api String[] http_header_accepts = new String[] { "application/json", "application/xml" }; - String http_header_accept = ApiClient.SelectHeaderAccept(http_header_accepts); + String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); if (http_header_accept != null) - headerParams.Add("Accept", ApiClient.SelectHeaderAccept(http_header_accepts)); + headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json pathParams.Add("format", "json"); - if (orderId != null) pathParams.Add("orderId", ApiClient.ParameterToString(orderId)); // path parameter + if (orderId != null) pathParams.Add("orderId", Configuration.ApiClient.ParameterToString(orderId)); // path parameter - - // authentication setting, if any - String[] authSettings = new String[] { }; - - // make the HTTP request - IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path_, Method.DELETE, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); - if (((int)response.StatusCode) >= 400) - throw new ApiException ((int)response.StatusCode, "Error calling DeleteOrder: " + response.Content, response.Content); - return; + + // make the HTTP request + IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, Method.DELETE, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + + int statusCode = (int) response.StatusCode; + + if (statusCode >= 400) + throw new ApiException (statusCode, "Error calling DeleteOrder: " + response.Content, response.Content); + else if (statusCode == 0) + throw new ApiException (statusCode, "Error calling DeleteOrder: " + response.ErrorMessage, response.ErrorMessage); + + + return new ApiResponse(statusCode, + response.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/UserApi.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/UserApi.cs index b4c8d93c28c..5502fe15da1 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 @@ -1,6 +1,7 @@ using System; using System.IO; using System.Collections.Generic; +using System.Linq; using RestSharp; using IO.Swagger.Client; using IO.Swagger.Model; @@ -22,7 +23,7 @@ namespace IO.Swagger.Api /// /// Created user object /// - void CreateUser (User body); + void CreateUser (User body = null); /// /// Create user @@ -31,8 +32,28 @@ namespace IO.Swagger.Api /// This can only be done by the logged in user. /// /// Created user object - /// - System.Threading.Tasks.Task CreateUserAsync (User body); + /// ApiResponse of Object(void) + ApiResponse CreateUserWithHttpInfo (User body = null); + + /// + /// Create user + /// + /// + /// This can only be done by the logged in user. + /// + /// Created user object + /// Task of void + System.Threading.Tasks.Task CreateUserAsync (User body = null); + + /// + /// Create user + /// + /// + /// This can only be done by the logged in user. + /// + /// Created user object + /// Task of ApiResponse + System.Threading.Tasks.Task> CreateUserAsyncWithHttpInfo (User body = null); /// /// Creates list of users with given input array @@ -42,7 +63,7 @@ namespace IO.Swagger.Api /// /// List of user object /// - void CreateUsersWithArrayInput (List body); + void CreateUsersWithArrayInput (List body = null); /// /// Creates list of users with given input array @@ -51,8 +72,28 @@ namespace IO.Swagger.Api /// /// /// List of user object - /// - System.Threading.Tasks.Task CreateUsersWithArrayInputAsync (List body); + /// ApiResponse of Object(void) + ApiResponse CreateUsersWithArrayInputWithHttpInfo (List body = null); + + /// + /// Creates list of users with given input array + /// + /// + /// + /// + /// List of user object + /// Task of void + System.Threading.Tasks.Task CreateUsersWithArrayInputAsync (List body = null); + + /// + /// Creates list of users with given input array + /// + /// + /// + /// + /// List of user object + /// Task of ApiResponse + System.Threading.Tasks.Task> CreateUsersWithArrayInputAsyncWithHttpInfo (List body = null); /// /// Creates list of users with given input array @@ -62,7 +103,7 @@ namespace IO.Swagger.Api /// /// List of user object /// - void CreateUsersWithListInput (List body); + void CreateUsersWithListInput (List body = null); /// /// Creates list of users with given input array @@ -71,8 +112,28 @@ namespace IO.Swagger.Api /// /// /// List of user object - /// - System.Threading.Tasks.Task CreateUsersWithListInputAsync (List body); + /// ApiResponse of Object(void) + ApiResponse CreateUsersWithListInputWithHttpInfo (List body = null); + + /// + /// Creates list of users with given input array + /// + /// + /// + /// + /// List of user object + /// Task of void + System.Threading.Tasks.Task CreateUsersWithListInputAsync (List body = null); + + /// + /// Creates list of users with given input array + /// + /// + /// + /// + /// List of user object + /// Task of ApiResponse + System.Threading.Tasks.Task> CreateUsersWithListInputAsyncWithHttpInfo (List body = null); /// /// Logs user into the system @@ -83,7 +144,7 @@ namespace IO.Swagger.Api /// The user name for login /// The password for login in clear text /// string - string LoginUser (string username, string password); + string LoginUser (string username = null, string password = null); /// /// Logs user into the system @@ -93,8 +154,30 @@ namespace IO.Swagger.Api /// /// The user name for login /// The password for login in clear text - /// string - System.Threading.Tasks.Task LoginUserAsync (string username, string password); + /// ApiResponse of string + ApiResponse LoginUserWithHttpInfo (string username = null, string password = null); + + /// + /// Logs user into the system + /// + /// + /// + /// + /// 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 + /// + /// + /// + /// + /// 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 @@ -111,8 +194,26 @@ namespace IO.Swagger.Api /// /// /// - /// + /// ApiResponse of Object(void) + ApiResponse LogoutUserWithHttpInfo (); + + /// + /// Logs out current logged in user session + /// + /// + /// + /// + /// Task of void System.Threading.Tasks.Task LogoutUserAsync (); + + /// + /// Logs out current logged in user session + /// + /// + /// + /// + /// Task of ApiResponse + System.Threading.Tasks.Task> LogoutUserAsyncWithHttpInfo (); /// /// Get user by user name @@ -131,8 +232,28 @@ namespace IO.Swagger.Api /// /// /// The name that needs to be fetched. Use user1 for testing. - /// User + /// ApiResponse of User + ApiResponse GetUserByNameWithHttpInfo (string username); + + /// + /// Get user by user name + /// + /// + /// + /// + /// 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 + /// + /// + /// + /// + /// The name that needs to be fetched. Use user1 for testing. + /// Task of ApiResponse (User) + System.Threading.Tasks.Task> GetUserByNameAsyncWithHttpInfo (string username); /// /// Updated user @@ -143,7 +264,7 @@ namespace IO.Swagger.Api /// name that need to be deleted /// Updated user object /// - void UpdateUser (string username, User body); + void UpdateUser (string username, User body = null); /// /// Updated user @@ -153,8 +274,30 @@ namespace IO.Swagger.Api /// /// name that need to be deleted /// Updated user object - /// - System.Threading.Tasks.Task UpdateUserAsync (string username, User body); + /// ApiResponse of Object(void) + ApiResponse UpdateUserWithHttpInfo (string username, User body = null); + + /// + /// Updated user + /// + /// + /// This can only be done by the logged in user. + /// + /// 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. + /// + /// name that need to be deleted + /// Updated user object + /// Task of ApiResponse + System.Threading.Tasks.Task> UpdateUserAsyncWithHttpInfo (string username, User body = null); /// /// Delete user @@ -173,8 +316,28 @@ namespace IO.Swagger.Api /// This can only be done by the logged in user. /// /// The name that needs to be deleted - /// + /// ApiResponse of Object(void) + ApiResponse DeleteUserWithHttpInfo (string username); + + /// + /// Delete user + /// + /// + /// This can only be done by the logged in user. + /// + /// The name that needs to be deleted + /// Task of void System.Threading.Tasks.Task DeleteUserAsync (string username); + + /// + /// Delete user + /// + /// + /// This can only be done by the logged in user. + /// + /// The name that needs to be deleted + /// Task of ApiResponse + System.Threading.Tasks.Task> DeleteUserAsyncWithHttpInfo (string username); } @@ -183,60 +346,93 @@ namespace IO.Swagger.Api /// public class UserApi : IUserApi { - /// - /// Initializes a new instance of the class. - /// - /// an instance of ApiClient (optional) - /// - public UserApi(ApiClient apiClient = null) - { - if (apiClient == null) // use the default one in Configuration - this.ApiClient = Configuration.DefaultApiClient; - else - this.ApiClient = apiClient; - } - /// /// Initializes a new instance of the class. /// /// public UserApi(String basePath) { - this.ApiClient = new ApiClient(basePath); + this.Configuration = new Configuration(new ApiClient(basePath)); } /// - /// Sets the base path of the API client. + /// Initializes a new instance of the class + /// using Configuration object /// - /// The base path - /// The base path - public void SetBasePath(String basePath) + /// An instance of Configuration + /// + public UserApi(Configuration configuration = null) { - this.ApiClient.BasePath = basePath; + if (configuration == null) // use the default one in Configuration + this.Configuration = Configuration.Default; + else + this.Configuration = configuration; } - + /// /// Gets the base path of the API client. /// /// The base path public String GetBasePath() { - return this.ApiClient.BasePath; + return this.Configuration.ApiClient.RestClient.BaseUrl.ToString(); + } + + /// + /// Sets the base path of the API client. + /// + /// The base path + [Obsolete("SetBasePath is deprecated, please do 'Configuraiton.ApiClient = new ApiClient(\"http://new-path\")' instead.")] + public void SetBasePath(String basePath) + { + // do nothing } /// - /// Gets or sets the API client. + /// Gets or sets the configuration object /// - /// An instance of the ApiClient - public ApiClient ApiClient {get; set;} - + /// An instance of the Configuration + public Configuration Configuration {get; set;} + + /// + /// Gets the default header. + /// + /// Dictionary of HTTP header + [Obsolete("DefaultHeader is deprecated, please use Configuration.DefaultHeader instead.")] + public Dictionary DefaultHeader() + { + return this.Configuration.DefaultHeader; + } + + /// + /// Add default header. + /// + /// Header field name. + /// Header field value. + /// + [Obsolete("AddDefaultHeader is deprecated, please use Configuration.AddDefaultHeader instead.")] + public void AddDefaultHeader(string key, string value) + { + this.Configuration.AddDefaultHeader(key, value); + } + /// /// Create user This can only be done by the logged in user. /// /// Created user object - /// - public void CreateUser (User body) + /// + public void CreateUser (User body = null) + { + CreateUserWithHttpInfo(body); + } + + /// + /// Create user This can only be done by the logged in user. + /// + /// Created user object + /// ApiResponse of Object(void) + public ApiResponse CreateUserWithHttpInfo (User body = null) { @@ -244,7 +440,7 @@ namespace IO.Swagger.Api var pathParams = new Dictionary(); var queryParams = new Dictionary(); - var headerParams = new Dictionary(); + var headerParams = new Dictionary(Configuration.DefaultHeader); var formParams = new Dictionary(); var fileParams = new Dictionary(); String postBody = null; @@ -253,9 +449,9 @@ namespace IO.Swagger.Api String[] http_header_accepts = new String[] { "application/json", "application/xml" }; - String http_header_accept = ApiClient.SelectHeaderAccept(http_header_accepts); + String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); if (http_header_accept != null) - headerParams.Add("Accept", ApiClient.SelectHeaderAccept(http_header_accepts)); + headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json @@ -264,29 +460,44 @@ namespace IO.Swagger.Api - postBody = ApiClient.Serialize(body); // http body (model) parameter + postBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter + + - // authentication setting, if any - String[] authSettings = new String[] { }; - // make the HTTP request - IRestResponse response = (IRestResponse) ApiClient.CallApi(path_, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); + IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + + int statusCode = (int) response.StatusCode; - if (((int)response.StatusCode) >= 400) - throw new ApiException ((int)response.StatusCode, "Error calling CreateUser: " + response.Content, response.Content); - else if (((int)response.StatusCode) == 0) - throw new ApiException ((int)response.StatusCode, "Error calling CreateUser: " + response.ErrorMessage, response.ErrorMessage); + if (statusCode >= 400) + throw new ApiException (statusCode, "Error calling CreateUser: " + response.Content, response.Content); + else if (statusCode == 0) + throw new ApiException (statusCode, "Error calling CreateUser: " + response.ErrorMessage, response.ErrorMessage); - return; + + return new ApiResponse(statusCode, + response.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), + null); } /// /// Create user This can only be done by the logged in user. /// /// Created user object - /// - public async System.Threading.Tasks.Task CreateUserAsync (User body) + /// Task of void + public async System.Threading.Tasks.Task CreateUserAsync (User body = null) + { + await CreateUserAsyncWithHttpInfo(body); + + } + + /// + /// Create user This can only be done by the logged in user. + /// + /// Created user object + /// Task of ApiResponse + public async System.Threading.Tasks.Task> CreateUserAsyncWithHttpInfo (User body = null) { @@ -303,9 +514,9 @@ namespace IO.Swagger.Api String[] http_header_accepts = new String[] { "application/json", "application/xml" }; - String http_header_accept = ApiClient.SelectHeaderAccept(http_header_accepts); + String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); if (http_header_accept != null) - headerParams.Add("Accept", ApiClient.SelectHeaderAccept(http_header_accepts)); + headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json @@ -314,27 +525,108 @@ namespace IO.Swagger.Api - postBody = ApiClient.Serialize(body); // http body (model) parameter + postBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter - - // authentication setting, if any - String[] authSettings = new String[] { }; - - // make the HTTP request - IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path_, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); - if (((int)response.StatusCode) >= 400) - throw new ApiException ((int)response.StatusCode, "Error calling CreateUser: " + response.Content, response.Content); - return; + + // make the HTTP request + IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + + int statusCode = (int) response.StatusCode; + + if (statusCode >= 400) + throw new ApiException (statusCode, "Error calling CreateUser: " + response.Content, response.Content); + else if (statusCode == 0) + throw new ApiException (statusCode, "Error calling CreateUser: " + response.ErrorMessage, response.ErrorMessage); + + + return new ApiResponse(statusCode, + response.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), + null); } /// /// Creates list of users with given input array /// /// List of user object - /// - public void CreateUsersWithArrayInput (List body) + /// + public void CreateUsersWithArrayInput (List body = null) + { + CreateUsersWithArrayInputWithHttpInfo(body); + } + + /// + /// Creates list of users with given input array + /// + /// List of user object + /// ApiResponse of Object(void) + public ApiResponse CreateUsersWithArrayInputWithHttpInfo (List body = null) + { + + + var path_ = "/user/createWithArray"; + + var pathParams = new Dictionary(); + var queryParams = new Dictionary(); + var headerParams = new Dictionary(Configuration.DefaultHeader); + var formParams = new Dictionary(); + var fileParams = new Dictionary(); + String postBody = null; + + // to determine the Accept header + String[] http_header_accepts = new String[] { + "application/json", "application/xml" + }; + String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); + if (http_header_accept != null) + headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); + + // set "format" to json by default + // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json + pathParams.Add("format", "json"); + + + + + postBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter + + + + + // make the HTTP request + IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + + int statusCode = (int) response.StatusCode; + + if (statusCode >= 400) + throw new ApiException (statusCode, "Error calling CreateUsersWithArrayInput: " + response.Content, response.Content); + else if (statusCode == 0) + throw new ApiException (statusCode, "Error calling CreateUsersWithArrayInput: " + response.ErrorMessage, response.ErrorMessage); + + + return new ApiResponse(statusCode, + response.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), + null); + } + + /// + /// Creates list of users with given input array + /// + /// List of user object + /// Task of void + public async System.Threading.Tasks.Task CreateUsersWithArrayInputAsync (List body = null) + { + await CreateUsersWithArrayInputAsyncWithHttpInfo(body); + + } + + /// + /// Creates list of users with given input array + /// + /// List of user object + /// Task of ApiResponse + public async System.Threading.Tasks.Task> CreateUsersWithArrayInputAsyncWithHttpInfo (List body = null) { @@ -351,9 +643,9 @@ namespace IO.Swagger.Api String[] http_header_accepts = new String[] { "application/json", "application/xml" }; - String http_header_accept = ApiClient.SelectHeaderAccept(http_header_accepts); + String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); if (http_header_accept != null) - headerParams.Add("Accept", ApiClient.SelectHeaderAccept(http_header_accepts)); + headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json @@ -362,77 +654,43 @@ namespace IO.Swagger.Api - postBody = ApiClient.Serialize(body); // http body (model) parameter + postBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter - - // authentication setting, if any - String[] authSettings = new String[] { }; - + + + // make the HTTP request - IRestResponse response = (IRestResponse) ApiClient.CallApi(path_, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); - - if (((int)response.StatusCode) >= 400) - throw new ApiException ((int)response.StatusCode, "Error calling CreateUsersWithArrayInput: " + response.Content, response.Content); - else if (((int)response.StatusCode) == 0) - throw new ApiException ((int)response.StatusCode, "Error calling CreateUsersWithArrayInput: " + response.ErrorMessage, response.ErrorMessage); - - return; - } - - /// - /// Creates list of users with given input array - /// - /// List of user object - /// - public async System.Threading.Tasks.Task CreateUsersWithArrayInputAsync (List body) - { - - - var path_ = "/user/createWithArray"; - - var pathParams = new Dictionary(); - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); - var fileParams = new Dictionary(); - String postBody = null; + IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams); - // to determine the Accept header - String[] http_header_accepts = new String[] { - "application/json", "application/xml" - }; - String http_header_accept = ApiClient.SelectHeaderAccept(http_header_accepts); - if (http_header_accept != null) - headerParams.Add("Accept", ApiClient.SelectHeaderAccept(http_header_accepts)); - - // set "format" to json by default - // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json - pathParams.Add("format", "json"); - - - - - postBody = ApiClient.Serialize(body); // http body (model) parameter - - - // authentication setting, if any - String[] authSettings = new String[] { }; - - // make the HTTP request - IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path_, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); - if (((int)response.StatusCode) >= 400) - throw new ApiException ((int)response.StatusCode, "Error calling CreateUsersWithArrayInput: " + response.Content, response.Content); + int statusCode = (int) response.StatusCode; + + if (statusCode >= 400) + throw new ApiException (statusCode, "Error calling CreateUsersWithArrayInput: " + response.Content, response.Content); + else if (statusCode == 0) + throw new ApiException (statusCode, "Error calling CreateUsersWithArrayInput: " + response.ErrorMessage, response.ErrorMessage); - return; + return new ApiResponse(statusCode, + response.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), + null); } /// /// Creates list of users with given input array /// /// List of user object - /// - public void CreateUsersWithListInput (List body) + /// + public void CreateUsersWithListInput (List body = null) + { + CreateUsersWithListInputWithHttpInfo(body); + } + + /// + /// Creates list of users with given input array + /// + /// List of user object + /// ApiResponse of Object(void) + public ApiResponse CreateUsersWithListInputWithHttpInfo (List body = null) { @@ -440,7 +698,7 @@ namespace IO.Swagger.Api var pathParams = new Dictionary(); var queryParams = new Dictionary(); - var headerParams = new Dictionary(); + var headerParams = new Dictionary(Configuration.DefaultHeader); var formParams = new Dictionary(); var fileParams = new Dictionary(); String postBody = null; @@ -449,9 +707,9 @@ namespace IO.Swagger.Api String[] http_header_accepts = new String[] { "application/json", "application/xml" }; - String http_header_accept = ApiClient.SelectHeaderAccept(http_header_accepts); + String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); if (http_header_accept != null) - headerParams.Add("Accept", ApiClient.SelectHeaderAccept(http_header_accepts)); + headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json @@ -460,29 +718,44 @@ namespace IO.Swagger.Api - postBody = ApiClient.Serialize(body); // http body (model) parameter + postBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter + + - // authentication setting, if any - String[] authSettings = new String[] { }; - // make the HTTP request - IRestResponse response = (IRestResponse) ApiClient.CallApi(path_, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); + IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + + int statusCode = (int) response.StatusCode; - if (((int)response.StatusCode) >= 400) - throw new ApiException ((int)response.StatusCode, "Error calling CreateUsersWithListInput: " + response.Content, response.Content); - else if (((int)response.StatusCode) == 0) - throw new ApiException ((int)response.StatusCode, "Error calling CreateUsersWithListInput: " + response.ErrorMessage, response.ErrorMessage); + if (statusCode >= 400) + throw new ApiException (statusCode, "Error calling CreateUsersWithListInput: " + response.Content, response.Content); + else if (statusCode == 0) + throw new ApiException (statusCode, "Error calling CreateUsersWithListInput: " + response.ErrorMessage, response.ErrorMessage); - return; + + return new ApiResponse(statusCode, + response.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), + null); } /// /// Creates list of users with given input array /// /// List of user object - /// - public async System.Threading.Tasks.Task CreateUsersWithListInputAsync (List body) + /// Task of void + public async System.Threading.Tasks.Task CreateUsersWithListInputAsync (List body = null) + { + await CreateUsersWithListInputAsyncWithHttpInfo(body); + + } + + /// + /// Creates list of users with given input array + /// + /// List of user object + /// Task of ApiResponse + public async System.Threading.Tasks.Task> CreateUsersWithListInputAsyncWithHttpInfo (List body = null) { @@ -499,9 +772,9 @@ namespace IO.Swagger.Api String[] http_header_accepts = new String[] { "application/json", "application/xml" }; - String http_header_accept = ApiClient.SelectHeaderAccept(http_header_accepts); + String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); if (http_header_accept != null) - headerParams.Add("Accept", ApiClient.SelectHeaderAccept(http_header_accepts)); + headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json @@ -510,19 +783,25 @@ namespace IO.Swagger.Api - postBody = ApiClient.Serialize(body); // http body (model) parameter + postBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter - - // authentication setting, if any - String[] authSettings = new String[] { }; - - // make the HTTP request - IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path_, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); - if (((int)response.StatusCode) >= 400) - throw new ApiException ((int)response.StatusCode, "Error calling CreateUsersWithListInput: " + response.Content, response.Content); - return; + + // make the HTTP request + IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + + int statusCode = (int) response.StatusCode; + + if (statusCode >= 400) + throw new ApiException (statusCode, "Error calling CreateUsersWithListInput: " + response.Content, response.Content); + else if (statusCode == 0) + throw new ApiException (statusCode, "Error calling CreateUsersWithListInput: " + response.ErrorMessage, response.ErrorMessage); + + + return new ApiResponse(statusCode, + response.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), + null); } /// @@ -530,8 +809,20 @@ namespace IO.Swagger.Api /// /// The user name for login /// The password for login in clear text - /// string - public string LoginUser (string username, string password) + /// string + public string LoginUser (string username = null, string password = null) + { + ApiResponse response = LoginUserWithHttpInfo(username, password); + return response.Data; + } + + /// + /// Logs user into the system + /// + /// 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) { @@ -539,7 +830,7 @@ namespace IO.Swagger.Api var pathParams = new Dictionary(); var queryParams = new Dictionary(); - var headerParams = new Dictionary(); + var headerParams = new Dictionary(Configuration.DefaultHeader); var formParams = new Dictionary(); var fileParams = new Dictionary(); String postBody = null; @@ -548,33 +839,37 @@ namespace IO.Swagger.Api String[] http_header_accepts = new String[] { "application/json", "application/xml" }; - String http_header_accept = ApiClient.SelectHeaderAccept(http_header_accepts); + String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); if (http_header_accept != null) - headerParams.Add("Accept", ApiClient.SelectHeaderAccept(http_header_accepts)); + headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json pathParams.Add("format", "json"); - if (username != null) queryParams.Add("username", ApiClient.ParameterToString(username)); // query parameter - if (password != null) queryParams.Add("password", ApiClient.ParameterToString(password)); // query parameter + if (username != null) queryParams.Add("username", Configuration.ApiClient.ParameterToString(username)); // query parameter + if (password != null) queryParams.Add("password", Configuration.ApiClient.ParameterToString(password)); // query parameter - - // authentication setting, if any - String[] authSettings = new String[] { }; + + // make the HTTP request - IRestResponse response = (IRestResponse) ApiClient.CallApi(path_, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); + IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + + int statusCode = (int) response.StatusCode; - if (((int)response.StatusCode) >= 400) - throw new ApiException ((int)response.StatusCode, "Error calling LoginUser: " + response.Content, response.Content); - else if (((int)response.StatusCode) == 0) - throw new ApiException ((int)response.StatusCode, "Error calling LoginUser: " + response.ErrorMessage, response.ErrorMessage); + if (statusCode >= 400) + throw new ApiException (statusCode, "Error calling LoginUser: " + response.Content, response.Content); + else if (statusCode == 0) + throw new ApiException (statusCode, "Error calling LoginUser: " + response.ErrorMessage, response.ErrorMessage); - return (string) ApiClient.Deserialize(response, typeof(string)); + return new ApiResponse(statusCode, + response.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), + (string) Configuration.ApiClient.Deserialize(response, typeof(string))); + } /// @@ -582,8 +877,21 @@ namespace IO.Swagger.Api /// /// The user name for login /// The password for login in clear text - /// string - public async System.Threading.Tasks.Task LoginUserAsync (string username, string password) + /// Task of string + public async System.Threading.Tasks.Task LoginUserAsync (string username = null, string password = null) + { + ApiResponse response = await LoginUserAsyncWithHttpInfo(username, password); + return response.Data; + + } + + /// + /// Logs user into the system + /// + /// 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) { @@ -600,37 +908,53 @@ namespace IO.Swagger.Api String[] http_header_accepts = new String[] { "application/json", "application/xml" }; - String http_header_accept = ApiClient.SelectHeaderAccept(http_header_accepts); + String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); if (http_header_accept != null) - headerParams.Add("Accept", ApiClient.SelectHeaderAccept(http_header_accepts)); + headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json pathParams.Add("format", "json"); - if (username != null) queryParams.Add("username", ApiClient.ParameterToString(username)); // query parameter - if (password != null) queryParams.Add("password", ApiClient.ParameterToString(password)); // query parameter + if (username != null) queryParams.Add("username", Configuration.ApiClient.ParameterToString(username)); // query parameter + if (password != null) queryParams.Add("password", Configuration.ApiClient.ParameterToString(password)); // query parameter - - // authentication setting, if any - String[] authSettings = new String[] { }; - - // make the HTTP request - IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path_, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); - if (((int)response.StatusCode) >= 400) - throw new ApiException ((int)response.StatusCode, "Error calling LoginUser: " + response.Content, response.Content); - return (string) ApiClient.Deserialize(response, typeof(string)); + + + // make the HTTP request + IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + + int statusCode = (int) response.StatusCode; + + if (statusCode >= 400) + throw new ApiException (statusCode, "Error calling LoginUser: " + response.Content, response.Content); + else if (statusCode == 0) + throw new ApiException (statusCode, "Error calling LoginUser: " + response.ErrorMessage, response.ErrorMessage); + + return new ApiResponse(statusCode, + response.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), + (string) Configuration.ApiClient.Deserialize(response, typeof(string))); + } /// /// Logs out current logged in user session /// - /// + /// public void LogoutUser () + { + LogoutUserWithHttpInfo(); + } + + /// + /// Logs out current logged in user session + /// + /// ApiResponse of Object(void) + public ApiResponse LogoutUserWithHttpInfo () { @@ -638,7 +962,7 @@ namespace IO.Swagger.Api var pathParams = new Dictionary(); var queryParams = new Dictionary(); - var headerParams = new Dictionary(); + var headerParams = new Dictionary(Configuration.DefaultHeader); var formParams = new Dictionary(); var fileParams = new Dictionary(); String postBody = null; @@ -647,9 +971,9 @@ namespace IO.Swagger.Api String[] http_header_accepts = new String[] { "application/json", "application/xml" }; - String http_header_accept = ApiClient.SelectHeaderAccept(http_header_accepts); + String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); if (http_header_accept != null) - headerParams.Add("Accept", ApiClient.SelectHeaderAccept(http_header_accepts)); + headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json @@ -659,26 +983,40 @@ namespace IO.Swagger.Api - - // authentication setting, if any - String[] authSettings = new String[] { }; + + // make the HTTP request - IRestResponse response = (IRestResponse) ApiClient.CallApi(path_, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); + IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + + int statusCode = (int) response.StatusCode; - if (((int)response.StatusCode) >= 400) - throw new ApiException ((int)response.StatusCode, "Error calling LogoutUser: " + response.Content, response.Content); - else if (((int)response.StatusCode) == 0) - throw new ApiException ((int)response.StatusCode, "Error calling LogoutUser: " + response.ErrorMessage, response.ErrorMessage); + if (statusCode >= 400) + throw new ApiException (statusCode, "Error calling LogoutUser: " + response.Content, response.Content); + else if (statusCode == 0) + throw new ApiException (statusCode, "Error calling LogoutUser: " + response.ErrorMessage, response.ErrorMessage); - return; + + return new ApiResponse(statusCode, + response.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), + null); } /// /// Logs out current logged in user session /// - /// + /// Task of void public async System.Threading.Tasks.Task LogoutUserAsync () + { + await LogoutUserAsyncWithHttpInfo(); + + } + + /// + /// Logs out current logged in user session + /// + /// Task of ApiResponse + public async System.Threading.Tasks.Task> LogoutUserAsyncWithHttpInfo () { @@ -695,9 +1033,9 @@ namespace IO.Swagger.Api String[] http_header_accepts = new String[] { "application/json", "application/xml" }; - String http_header_accept = ApiClient.SelectHeaderAccept(http_header_accepts); + String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); if (http_header_accept != null) - headerParams.Add("Accept", ApiClient.SelectHeaderAccept(http_header_accepts)); + headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json @@ -707,25 +1045,42 @@ namespace IO.Swagger.Api - - // authentication setting, if any - String[] authSettings = new String[] { }; - - // make the HTTP request - IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path_, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); - if (((int)response.StatusCode) >= 400) - throw new ApiException ((int)response.StatusCode, "Error calling LogoutUser: " + response.Content, response.Content); - return; + + // make the HTTP request + IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + + int statusCode = (int) response.StatusCode; + + if (statusCode >= 400) + throw new ApiException (statusCode, "Error calling LogoutUser: " + response.Content, response.Content); + else if (statusCode == 0) + throw new ApiException (statusCode, "Error calling LogoutUser: " + response.ErrorMessage, response.ErrorMessage); + + + return new ApiResponse(statusCode, + response.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), + null); } /// /// Get user by user name /// /// The name that needs to be fetched. Use user1 for testing. - /// User + /// User public User GetUserByName (string username) + { + ApiResponse response = GetUserByNameWithHttpInfo(username); + return response.Data; + } + + /// + /// Get user by user name + /// + /// 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 @@ -736,7 +1091,7 @@ namespace IO.Swagger.Api var pathParams = new Dictionary(); var queryParams = new Dictionary(); - var headerParams = new Dictionary(); + var headerParams = new Dictionary(Configuration.DefaultHeader); var formParams = new Dictionary(); var fileParams = new Dictionary(); String postBody = null; @@ -745,40 +1100,56 @@ namespace IO.Swagger.Api String[] http_header_accepts = new String[] { "application/json", "application/xml" }; - String http_header_accept = ApiClient.SelectHeaderAccept(http_header_accepts); + String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); if (http_header_accept != null) - headerParams.Add("Accept", ApiClient.SelectHeaderAccept(http_header_accepts)); + headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json pathParams.Add("format", "json"); - if (username != null) pathParams.Add("username", ApiClient.ParameterToString(username)); // path parameter + if (username != null) pathParams.Add("username", Configuration.ApiClient.ParameterToString(username)); // path parameter - - // authentication setting, if any - String[] authSettings = new String[] { }; + + // make the HTTP request - IRestResponse response = (IRestResponse) ApiClient.CallApi(path_, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); + IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + + int statusCode = (int) response.StatusCode; - if (((int)response.StatusCode) >= 400) - throw new ApiException ((int)response.StatusCode, "Error calling GetUserByName: " + response.Content, response.Content); - else if (((int)response.StatusCode) == 0) - throw new ApiException ((int)response.StatusCode, "Error calling GetUserByName: " + response.ErrorMessage, response.ErrorMessage); + if (statusCode >= 400) + throw new ApiException (statusCode, "Error calling GetUserByName: " + response.Content, response.Content); + else if (statusCode == 0) + throw new ApiException (statusCode, "Error calling GetUserByName: " + response.ErrorMessage, response.ErrorMessage); - return (User) ApiClient.Deserialize(response, typeof(User)); + return new ApiResponse(statusCode, + response.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), + (User) Configuration.ApiClient.Deserialize(response, typeof(User))); + } /// /// Get user by user name /// /// The name that needs to be fetched. Use user1 for testing. - /// User + /// Task of User public async System.Threading.Tasks.Task GetUserByNameAsync (string username) + { + ApiResponse response = await GetUserByNameAsyncWithHttpInfo(username); + return response.Data; + + } + + /// + /// Get user by user name + /// + /// 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"); @@ -797,29 +1168,36 @@ namespace IO.Swagger.Api String[] http_header_accepts = new String[] { "application/json", "application/xml" }; - String http_header_accept = ApiClient.SelectHeaderAccept(http_header_accepts); + String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); if (http_header_accept != null) - headerParams.Add("Accept", ApiClient.SelectHeaderAccept(http_header_accepts)); + headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json pathParams.Add("format", "json"); - if (username != null) pathParams.Add("username", ApiClient.ParameterToString(username)); // path parameter + if (username != null) pathParams.Add("username", Configuration.ApiClient.ParameterToString(username)); // path parameter - - // authentication setting, if any - String[] authSettings = new String[] { }; - - // make the HTTP request - IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path_, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); - if (((int)response.StatusCode) >= 400) - throw new ApiException ((int)response.StatusCode, "Error calling GetUserByName: " + response.Content, response.Content); - return (User) ApiClient.Deserialize(response, typeof(User)); + + + // make the HTTP request + IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + + int statusCode = (int) response.StatusCode; + + if (statusCode >= 400) + throw new ApiException (statusCode, "Error calling GetUserByName: " + response.Content, response.Content); + else if (statusCode == 0) + throw new ApiException (statusCode, "Error calling GetUserByName: " + response.ErrorMessage, response.ErrorMessage); + + return new ApiResponse(statusCode, + response.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), + (User) Configuration.ApiClient.Deserialize(response, typeof(User))); + } /// @@ -827,8 +1205,19 @@ namespace IO.Swagger.Api /// /// name that need to be deleted /// Updated user object - /// - public void UpdateUser (string username, User body) + /// + public void UpdateUser (string username, User body = null) + { + UpdateUserWithHttpInfo(username, body); + } + + /// + /// Updated user This can only be done by the logged in user. + /// + /// 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 @@ -839,7 +1228,7 @@ namespace IO.Swagger.Api var pathParams = new Dictionary(); var queryParams = new Dictionary(); - var headerParams = new Dictionary(); + var headerParams = new Dictionary(Configuration.DefaultHeader); var formParams = new Dictionary(); var fileParams = new Dictionary(); String postBody = null; @@ -848,33 +1237,37 @@ namespace IO.Swagger.Api String[] http_header_accepts = new String[] { "application/json", "application/xml" }; - String http_header_accept = ApiClient.SelectHeaderAccept(http_header_accepts); + String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); if (http_header_accept != null) - headerParams.Add("Accept", ApiClient.SelectHeaderAccept(http_header_accepts)); + headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json pathParams.Add("format", "json"); - if (username != null) pathParams.Add("username", ApiClient.ParameterToString(username)); // path parameter + if (username != null) pathParams.Add("username", Configuration.ApiClient.ParameterToString(username)); // path parameter - postBody = ApiClient.Serialize(body); // http body (model) parameter + postBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter + + - - // authentication setting, if any - String[] authSettings = new String[] { }; // make the HTTP request - IRestResponse response = (IRestResponse) ApiClient.CallApi(path_, Method.PUT, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); + IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, Method.PUT, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + + int statusCode = (int) response.StatusCode; - if (((int)response.StatusCode) >= 400) - throw new ApiException ((int)response.StatusCode, "Error calling UpdateUser: " + response.Content, response.Content); - else if (((int)response.StatusCode) == 0) - throw new ApiException ((int)response.StatusCode, "Error calling UpdateUser: " + response.ErrorMessage, response.ErrorMessage); + if (statusCode >= 400) + throw new ApiException (statusCode, "Error calling UpdateUser: " + response.Content, response.Content); + else if (statusCode == 0) + throw new ApiException (statusCode, "Error calling UpdateUser: " + response.ErrorMessage, response.ErrorMessage); - return; + + return new ApiResponse(statusCode, + response.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), + null); } /// @@ -882,8 +1275,20 @@ namespace IO.Swagger.Api /// /// name that need to be deleted /// Updated user object - /// - public async System.Threading.Tasks.Task UpdateUserAsync (string username, User body) + /// 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. + /// + /// 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"); @@ -902,39 +1307,55 @@ namespace IO.Swagger.Api String[] http_header_accepts = new String[] { "application/json", "application/xml" }; - String http_header_accept = ApiClient.SelectHeaderAccept(http_header_accepts); + String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); if (http_header_accept != null) - headerParams.Add("Accept", ApiClient.SelectHeaderAccept(http_header_accepts)); + headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json pathParams.Add("format", "json"); - if (username != null) pathParams.Add("username", ApiClient.ParameterToString(username)); // path parameter + if (username != null) pathParams.Add("username", Configuration.ApiClient.ParameterToString(username)); // path parameter - postBody = ApiClient.Serialize(body); // http body (model) parameter + postBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter - - // authentication setting, if any - String[] authSettings = new String[] { }; - - // make the HTTP request - IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path_, Method.PUT, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); - if (((int)response.StatusCode) >= 400) - throw new ApiException ((int)response.StatusCode, "Error calling UpdateUser: " + response.Content, response.Content); - return; + + // make the HTTP request + IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, Method.PUT, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + + int statusCode = (int) response.StatusCode; + + if (statusCode >= 400) + throw new ApiException (statusCode, "Error calling UpdateUser: " + response.Content, response.Content); + else if (statusCode == 0) + throw new ApiException (statusCode, "Error calling UpdateUser: " + response.ErrorMessage, response.ErrorMessage); + + + return new ApiResponse(statusCode, + response.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), + null); } /// /// Delete user This can only be done by the logged in user. /// /// The name that needs to be deleted - /// + /// public void DeleteUser (string username) + { + DeleteUserWithHttpInfo(username); + } + + /// + /// Delete user This can only be done by the logged in user. + /// + /// The name that needs to be deleted + /// ApiResponse of Object(void) + public ApiResponse DeleteUserWithHttpInfo (string username) { // verify the required parameter 'username' is set @@ -945,7 +1366,7 @@ namespace IO.Swagger.Api var pathParams = new Dictionary(); var queryParams = new Dictionary(); - var headerParams = new Dictionary(); + var headerParams = new Dictionary(Configuration.DefaultHeader); var formParams = new Dictionary(); var fileParams = new Dictionary(); String postBody = null; @@ -954,40 +1375,55 @@ namespace IO.Swagger.Api String[] http_header_accepts = new String[] { "application/json", "application/xml" }; - String http_header_accept = ApiClient.SelectHeaderAccept(http_header_accepts); + String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); if (http_header_accept != null) - headerParams.Add("Accept", ApiClient.SelectHeaderAccept(http_header_accepts)); + headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json pathParams.Add("format", "json"); - if (username != null) pathParams.Add("username", ApiClient.ParameterToString(username)); // path parameter + if (username != null) pathParams.Add("username", Configuration.ApiClient.ParameterToString(username)); // path parameter - - // authentication setting, if any - String[] authSettings = new String[] { }; + + // make the HTTP request - IRestResponse response = (IRestResponse) ApiClient.CallApi(path_, Method.DELETE, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); + IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, Method.DELETE, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + + int statusCode = (int) response.StatusCode; - if (((int)response.StatusCode) >= 400) - throw new ApiException ((int)response.StatusCode, "Error calling DeleteUser: " + response.Content, response.Content); - else if (((int)response.StatusCode) == 0) - throw new ApiException ((int)response.StatusCode, "Error calling DeleteUser: " + response.ErrorMessage, response.ErrorMessage); + if (statusCode >= 400) + throw new ApiException (statusCode, "Error calling DeleteUser: " + response.Content, response.Content); + else if (statusCode == 0) + throw new ApiException (statusCode, "Error calling DeleteUser: " + response.ErrorMessage, response.ErrorMessage); - return; + + return new ApiResponse(statusCode, + response.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), + null); } /// /// Delete user This can only be done by the logged in user. /// /// The name that needs to be deleted - /// + /// Task of void public async System.Threading.Tasks.Task DeleteUserAsync (string username) + { + await DeleteUserAsyncWithHttpInfo(username); + + } + + /// + /// Delete user This can only be done by the logged in user. + /// + /// The name that needs to be deleted + /// Task of ApiResponse + public async System.Threading.Tasks.Task> DeleteUserAsyncWithHttpInfo (string username) { // verify the required parameter 'username' is set if (username == null) throw new ApiException(400, "Missing required parameter 'username' when calling DeleteUser"); @@ -1006,30 +1442,36 @@ namespace IO.Swagger.Api String[] http_header_accepts = new String[] { "application/json", "application/xml" }; - String http_header_accept = ApiClient.SelectHeaderAccept(http_header_accepts); + String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); if (http_header_accept != null) - headerParams.Add("Accept", ApiClient.SelectHeaderAccept(http_header_accepts)); + headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json pathParams.Add("format", "json"); - if (username != null) pathParams.Add("username", ApiClient.ParameterToString(username)); // path parameter + if (username != null) pathParams.Add("username", Configuration.ApiClient.ParameterToString(username)); // path parameter - - // authentication setting, if any - String[] authSettings = new String[] { }; - - // make the HTTP request - IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path_, Method.DELETE, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); - if (((int)response.StatusCode) >= 400) - throw new ApiException ((int)response.StatusCode, "Error calling DeleteUser: " + response.Content, response.Content); - return; + + // make the HTTP request + IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, Method.DELETE, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + + int statusCode = (int) response.StatusCode; + + if (statusCode >= 400) + throw new ApiException (statusCode, "Error calling DeleteUser: " + response.Content, response.Content); + else if (statusCode == 0) + throw new ApiException (statusCode, "Error calling DeleteUser: " + response.ErrorMessage, response.ErrorMessage); + + + return new ApiResponse(statusCode, + response.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 67f66d3487c..7e6807f16a4 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 @@ -18,62 +18,71 @@ namespace IO.Swagger.Client /// public class ApiClient { - private readonly Dictionary _defaultHeaderMap = new Dictionary(); - /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class + /// with default configuration and base path (http://petstore.swagger.io/v2). + /// + public ApiClient() + { + Configuration = Configuration.Default; + RestClient = new RestClient("http://petstore.swagger.io/v2"); + } + + /// + /// Initializes a new instance of the class + /// with default base path (http://petstore.swagger.io/v2). + /// + /// An instance of Configuration. + public ApiClient(Configuration config = null) + { + if (config == null) + Configuration = Configuration.Default; + else + Configuration = config; + + RestClient = new RestClient("http://petstore.swagger.io/v2"); + } + + /// + /// Initializes a new instance of the class + /// with default configuration. /// /// The base path. - public ApiClient(String basePath="http://petstore.swagger.io/v2") + public ApiClient(String basePath = "http://petstore.swagger.io/v2") { - BasePath = basePath; - RestClient = new RestClient(BasePath); + if (String.IsNullOrEmpty(basePath)) + throw new ArgumentException("basePath cannot be empty"); + + RestClient = new RestClient(basePath); + Configuration = Configuration.Default; } + + /// + /// Gets or sets the default API client for making HTTP calls. + /// + /// The default API client. + public static ApiClient Default = new ApiClient(Configuration.Default); /// - /// Gets or sets the base path. + /// Gets or sets the Configuration. /// - /// The base path - public string BasePath { get; set; } - + /// An instance of the Configuration. + public Configuration Configuration { get; set; } + /// /// Gets or sets the RestClient. /// /// An instance of the RestClient public RestClient RestClient { get; set; } - /// - /// Gets the default header. - /// - public Dictionary DefaultHeader - { - get { return _defaultHeaderMap; } - } - - /// - /// Gets the status code of the previous request - /// - public int StatusCode { get; private set; } - - /// - /// Gets the response headers of the previous request - /// - public Dictionary ResponseHeaders { get; private set; } - // Creates and sets up a RestRequest prior to a call. private RestRequest PrepareRequest( String path, RestSharp.Method method, Dictionary queryParams, String postBody, Dictionary headerParams, Dictionary formParams, - Dictionary fileParams, Dictionary pathParams, String[] authSettings) + Dictionary fileParams, Dictionary pathParams) { var request = new RestRequest(path, method); - UpdateParamsForAuth(queryParams, headerParams, authSettings); - - // add default header, if any - foreach(var defaultHeader in _defaultHeaderMap) - request.AddHeader(defaultHeader.Key, defaultHeader.Value); - // add path parameter, if any foreach(var param in pathParams) request.AddParameter(param.Key, param.Value, ParameterType.UrlSegment); @@ -111,18 +120,15 @@ namespace IO.Swagger.Client /// Form parameters. /// File parameters. /// Path parameters. - /// Authentication settings. /// Object public Object CallApi( String path, RestSharp.Method method, Dictionary queryParams, String postBody, Dictionary headerParams, Dictionary formParams, - Dictionary fileParams, Dictionary pathParams, String[] authSettings) + Dictionary fileParams, Dictionary pathParams) { var request = PrepareRequest( - path, method, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); + path, method, queryParams, postBody, headerParams, formParams, fileParams, pathParams); var response = RestClient.Execute(request); - StatusCode = (int) response.StatusCode; - ResponseHeaders = response.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()); return (Object) response; } @@ -137,32 +143,18 @@ namespace IO.Swagger.Client /// Form parameters. /// File parameters. /// Path parameters. - /// Authentication settings. /// The Task instance. public async System.Threading.Tasks.Task CallApiAsync( String path, RestSharp.Method method, Dictionary queryParams, String postBody, Dictionary headerParams, Dictionary formParams, - Dictionary fileParams, Dictionary pathParams, String[] authSettings) + Dictionary fileParams, Dictionary pathParams) { var request = PrepareRequest( - path, method, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); + path, method, queryParams, postBody, headerParams, formParams, fileParams, pathParams); var response = await RestClient.ExecuteTaskAsync(request); - StatusCode = (int)response.StatusCode; - ResponseHeaders = response.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()); return (Object)response; } - /// - /// Add default header. - /// - /// Header field name. - /// Header field value. - /// - public void AddDefaultHeader(string key, string value) - { - _defaultHeaderMap.Add(key, value); - } - /// /// Escape string (url-encoded). /// @@ -188,7 +180,7 @@ namespace IO.Swagger.Client } /// - /// If parameter is DateTime, output in ISO8601 format. + /// If parameter is DateTime, output in a formatted string (default ISO 8601), customizable with Configuration.DateTime. /// If parameter is a list, join the list with ",". /// Otherwise just return the string. /// @@ -197,14 +189,21 @@ namespace IO.Swagger.Client public string ParameterToString(object obj) { if (obj is DateTime) - return ((DateTime)obj).ToString ("u"); - else if (obj is IList) { - string flattenString = ""; - string separator = ","; - foreach (var param in (IList)obj) { - flattenString += param.ToString() + separator; + // Return a formatted date string - Can be customized with Configuration.DateTimeFormat + // Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o") + // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 + // For example: 2009-06-15T13:45:30.0000000 + return ((DateTime)obj).ToString (Configuration.DateTimeFormat); + else if (obj is IList) + { + var flattenedString = new StringBuilder(); + foreach (var param in (IList)obj) + { + if (flattenedString.Length > 0) + flattenedString.Append(","); + flattenedString.Append(param); } - return flattenString.Remove(flattenString.Length - 1);; + return flattenedString.ToString(); } else return Convert.ToString (obj); @@ -233,13 +232,16 @@ namespace IO.Swagger.Client var filePath = String.IsNullOrEmpty(Configuration.TempFolderPath) ? Path.GetTempPath() : Configuration.TempFolderPath; - var regex = new Regex(@"Content-Disposition:.*filename=['""]?([^'""\s]+)['""]?$"); - var match = regex.Match(headers.ToString()); - if (match.Success) + var regex = new Regex(@"Content-Disposition=.*filename=['""]?([^'""\s]+)['""]?$"); + foreach (var header in headers) { - string fileName = filePath + match.Value.Replace("\"", "").Replace("'", ""); - File.WriteAllBytes(fileName, data); - return new FileStream(fileName, FileMode.Open); + var match = regex.Match(header.ToString()); + if (match.Success) + { + string fileName = filePath + match.Groups[1].Value.Replace("\"", "").Replace("'", ""); + File.WriteAllBytes(fileName, data); + return new FileStream(fileName, FileMode.Open); + } } } var stream = new MemoryStream(data); @@ -284,54 +286,6 @@ namespace IO.Swagger.Client } } - /// - /// Get the API key with prefix. - /// - /// API key identifier (authentication scheme). - /// API key with prefix. - public string GetApiKeyWithPrefix (string apiKeyIdentifier) - { - var apiKeyValue = ""; - Configuration.ApiKey.TryGetValue (apiKeyIdentifier, out apiKeyValue); - var apiKeyPrefix = ""; - if (Configuration.ApiKeyPrefix.TryGetValue (apiKeyIdentifier, out apiKeyPrefix)) - return apiKeyPrefix + " " + apiKeyValue; - else - return apiKeyValue; - } - - /// - /// Update parameters based on authentication. - /// - /// Query parameters. - /// Header parameters. - /// Authentication settings. - public void UpdateParamsForAuth(Dictionary queryParams, Dictionary headerParams, string[] authSettings) - { - if (authSettings == null || authSettings.Length == 0) - return; - - foreach (string auth in authSettings) - { - // determine which one to use - switch(auth) - { - - case "petstore_auth": - headerParams["Authorization"] = "Bearer " + Configuration.AccessToken; - break; - - case "api_key": - headerParams["api_key"] = GetApiKeyWithPrefix("api_key"); - break; - - default: - //TODO show warning about security definition not found - break; - } - } - } - /// /// Select the Accept header's value from the given accepts array: /// if JSON exists in the given array, use it; @@ -339,11 +293,14 @@ namespace IO.Swagger.Client /// /// The accepts array to select from. /// The Accept header to use. - public String SelectHeaderAccept(String[] accepts) { + public String SelectHeaderAccept(String[] accepts) + { if (accepts.Length == 0) return null; + if (accepts.Contains("application/json", StringComparer.OrdinalIgnoreCase)) return "application/json"; + return String.Join(",", accepts); } @@ -354,8 +311,7 @@ namespace IO.Swagger.Client /// Encoded string. public static string Base64Encode(string text) { - var textByte = System.Text.Encoding.UTF8.GetBytes(text); - return System.Convert.ToBase64String(textByte); + return System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(text)); } /// @@ -365,7 +321,8 @@ namespace IO.Swagger.Client /// Object to be casted /// Target type /// Casted object - public static dynamic ConvertType(dynamic source, Type dest) { + public static dynamic ConvertType(dynamic source, Type dest) + { return Convert.ChangeType(source, dest); } 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 addfc839716..2410626602c 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 @@ -1,47 +1,50 @@ using System; -namespace IO.Swagger.Client { - /// - /// API Exception - /// - public class ApiException : Exception { - /// - /// Gets or sets the error code (HTTP status code) - /// - /// The error code (HTTP status code). - public int ErrorCode { get; set; } - - /// - /// Gets or sets the error content (body json object) - /// - /// The error content (Http response body). - public dynamic ErrorContent { get; private set; } - - /// - /// Initializes a new instance of the class. - /// - public ApiException() {} - - /// - /// Initializes a new instance of the class. - /// - /// HTTP status code. - /// Error message. - public ApiException(int errorCode, string message) : base(message) { - this.ErrorCode = errorCode; - } - - /// - /// Initializes a new instance of the class. - /// - /// HTTP status code. - /// Error message. - /// Error content. - public ApiException(int errorCode, string message, dynamic errorContent = null) : base(message) { - this.ErrorCode = errorCode; - this.ErrorContent = errorContent; - } - - } - +namespace IO.Swagger.Client +{ + /// + /// API Exception + /// + public class ApiException : Exception + { + /// + /// Gets or sets the error code (HTTP status code) + /// + /// The error code (HTTP status code). + public int ErrorCode { get; set; } + + /// + /// Gets or sets the error content (body json object) + /// + /// The error content (Http response body). + public dynamic ErrorContent { get; private set; } + + /// + /// Initializes a new instance of the class. + /// + public ApiException() {} + + /// + /// Initializes a new instance of the class. + /// + /// HTTP status code. + /// Error message. + public ApiException(int errorCode, string message) : base(message) + { + this.ErrorCode = errorCode; + } + + /// + /// Initializes a new instance of the class. + /// + /// HTTP status code. + /// Error message. + /// Error content. + public ApiException(int errorCode, string message, dynamic errorContent = null) : base(message) + { + this.ErrorCode = errorCode; + this.ErrorContent = errorContent; + } + } + } diff --git a/samples/client/petstore/csharp/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 new file mode 100644 index 00000000000..15735711656 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Client/ApiResponse.cs @@ -0,0 +1,44 @@ +using System; +using System.Collections.Generic; + +namespace IO.Swagger.Client +{ + /// + /// API Response + /// + public class ApiResponse + { + /// + /// Gets or sets the status code (HTTP status code) + /// + /// The status code. + public int StatusCode { get; private set; } + + /// + /// Gets or sets the HTTP headers + /// + /// HTTP headers + public IDictionary Headers { get; private set; } + + /// + /// Gets or sets the data (parsed HTTP body) + /// + /// The data. + public T Data { get; private set; } + + /// + /// Initializes a new instance of the class. + /// + /// HTTP status code. + /// Error message. + /// Data (parsed HTTP body) + public ApiResponse(int statusCode, IDictionary headers, T data) + { + this.StatusCode= statusCode; + this.Headers = headers; + this.Data = data; + } + + } + +} diff --git a/samples/client/petstore/csharp/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 4168d69a2ea..000b8893cdf 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 @@ -12,6 +12,62 @@ namespace IO.Swagger.Client /// public class Configuration { + /// + /// Initializes a new instance of the Configuration class with different settings + /// + /// Api client + /// Dictionary of default HTTP header + /// Username + /// Password + /// accessToken + /// Dictionary of API key + /// Dictionary of API key prefix + /// Temp folder path + /// DateTime format string + public Configuration(ApiClient apiClient = null, + Dictionary defaultHeader = null, + string username = null, + string password = null, + string accessToken = null, + Dictionary apiKey = null, + Dictionary apiKeyPrefix = null, + string tempFolderPath = null, + string dateTimeFormat = null, + int timeout = 100000 + ) + { + if (apiClient == null) + ApiClient = ApiClient.Default; + else + ApiClient = apiClient; + + Username = username; + Password = password; + AccessToken = accessToken; + + if (defaultHeader != null) + DefaultHeader = defaultHeader; + if (apiKey != null) + ApiKey = apiKey; + if (apiKeyPrefix != null) + ApiKeyPrefix = apiKeyPrefix; + + TempFolderPath = tempFolderPath; + DateTimeFormat = dateTimeFormat; + Timeout = timeout; + } + + /// + /// Initializes a new instance of the Configuration class. + /// + /// Api client. + public Configuration(ApiClient apiClient) + { + if (apiClient == null) + ApiClient = ApiClient.Default; + else + ApiClient = apiClient; + } /// /// Version of the package. @@ -19,49 +75,111 @@ namespace IO.Swagger.Client /// Version of the package. public const string Version = "1.0.0"; + /// + /// Gets or sets the default Configuration. + /// + /// Configuration. + public static Configuration Default = new Configuration(); + + /// + /// Gets or sets the HTTP timeout (milliseconds) of ApiClient. Default to 100000 milliseconds. + /// + /// Timeout. + public int Timeout + { + get { return ApiClient.RestClient.Timeout; } + + set + { + ApiClient.RestClient.Timeout = value; + } + } + /// /// Gets or sets the default API client for making HTTP calls. /// /// The API client. - public static ApiClient DefaultApiClient = new ApiClient(); - + public ApiClient ApiClient; + + private Dictionary _defaultHeaderMap = new Dictionary(); + + /// + /// Gets or sets the default header. + /// + public Dictionary DefaultHeader + { + get { return _defaultHeaderMap; } + + set + { + _defaultHeaderMap = value; + } + } + + /// + /// Add default header. + /// + /// Header field name. + /// Header field value. + /// + public void AddDefaultHeader(string key, string value) + { + _defaultHeaderMap.Add(key, value); + } + /// /// Gets or sets the username (HTTP basic authentication). /// /// The username. - public static String Username { get; set; } + public String Username { get; set; } /// /// Gets or sets the password (HTTP basic authentication). /// /// The password. - public static String Password { get; set; } + public String Password { get; set; } /// /// Gets or sets the access token for OAuth2 authentication. /// /// The access token. - public static String AccessToken { get; set; } + public String AccessToken { get; set; } /// /// Gets or sets the API key based on the authentication name. /// /// The API key. - public static Dictionary ApiKey = new Dictionary(); + public Dictionary ApiKey = new Dictionary(); /// /// Gets or sets the prefix (e.g. Token) of the API key based on the authentication name. /// /// The prefix of the API key. - public static Dictionary ApiKeyPrefix = new Dictionary(); + public Dictionary ApiKeyPrefix = new Dictionary(); + + /// + /// Get the API key with prefix. + /// + /// API key identifier (authentication scheme). + /// API key with prefix. + public string GetApiKeyWithPrefix (string apiKeyIdentifier) + { + var apiKeyValue = ""; + ApiKey.TryGetValue (apiKeyIdentifier, out apiKeyValue); + var apiKeyPrefix = ""; + if (ApiKeyPrefix.TryGetValue (apiKeyIdentifier, out apiKeyPrefix)) + return apiKeyPrefix + " " + apiKeyValue; + else + return apiKeyValue; + } - private static string _tempFolderPath = Path.GetTempPath(); + private string _tempFolderPath = Path.GetTempPath(); /// /// Gets or sets the temporary folder path to store the files downloaded from the server. /// /// Folder path. - public static String TempFolderPath + public String TempFolderPath { get { return _tempFolderPath; } @@ -84,7 +202,40 @@ namespace IO.Swagger.Client _tempFolderPath = value + Path.DirectorySeparatorChar; } } - + + private const string ISO8601_DATETIME_FORMAT = "o"; + + private string _dateTimeFormat = ISO8601_DATETIME_FORMAT; + + /// + /// Gets or sets the the date time format used when serializing in the ApiClient + /// By default, it's set to ISO 8601 - "o", for others see: + /// https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx + /// and https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx + /// No validation is done to ensure that the string you're providing is valid + /// + /// The DateTimeFormat string + public String DateTimeFormat + { + get + { + return _dateTimeFormat; + } + set + { + if (string.IsNullOrEmpty(value)) + { + // Never allow a blank or null string, go back to the default + _dateTimeFormat = ISO8601_DATETIME_FORMAT; + return; + } + + // Caution, no validation when you choose date time format other than ISO 8601 + // Take a look at the above links + _dateTimeFormat = value; + } + } + /// /// Returns a string with essential information for debugging. /// 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 29e4208fb75..472c30a9226 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 @@ -44,6 +44,21 @@ namespace IO.Swagger.Model return sb.ToString(); } + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + var sb = new StringBuilder(); + sb.Append("class Category {\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + + sb.Append("}\n"); + return sb.ToString(); + } + /// /// Returns the JSON string presentation of the object /// 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 47494e8f029..bd4dd0988c1 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 @@ -85,6 +85,25 @@ namespace IO.Swagger.Model return sb.ToString(); } + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + var sb = new StringBuilder(); + sb.Append("class Order {\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" PetId: ").Append(PetId).Append("\n"); + sb.Append(" Quantity: ").Append(Quantity).Append("\n"); + sb.Append(" ShipDate: ").Append(ShipDate).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append(" Complete: ").Append(Complete).Append("\n"); + + sb.Append("}\n"); + return sb.ToString(); + } + /// /// Returns the JSON string presentation of the object /// 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 8daa0687386..3913d011167 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 @@ -85,6 +85,25 @@ namespace IO.Swagger.Model return sb.ToString(); } + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + var sb = new StringBuilder(); + sb.Append("class Pet {\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Category: ").Append(Category).Append("\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append(" PhotoUrls: ").Append(PhotoUrls).Append("\n"); + sb.Append(" Tags: ").Append(Tags).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + + sb.Append("}\n"); + return sb.ToString(); + } + /// /// Returns the JSON string presentation of the object /// 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 566b9230334..5a33cb8348b 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 @@ -44,6 +44,21 @@ namespace IO.Swagger.Model return sb.ToString(); } + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + var sb = new StringBuilder(); + sb.Append("class Tag {\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + + sb.Append("}\n"); + return sb.ToString(); + } + /// /// Returns the JSON string presentation of the object /// 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 cc4d969d78c..63f6911a778 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 @@ -87,6 +87,27 @@ namespace IO.Swagger.Model return sb.ToString(); } + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + var sb = new StringBuilder(); + sb.Append("class User {\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Username: ").Append(Username).Append("\n"); + sb.Append(" FirstName: ").Append(FirstName).Append("\n"); + sb.Append(" LastName: ").Append(LastName).Append("\n"); + sb.Append(" Email: ").Append(Email).Append("\n"); + sb.Append(" Password: ").Append(Password).Append("\n"); + sb.Append(" Phone: ").Append(Phone).Append("\n"); + sb.Append(" UserStatus: ").Append(UserStatus).Append("\n"); + + sb.Append("}\n"); + return sb.ToString(); + } + /// /// Returns the JSON string presentation of the object /// diff --git a/samples/client/petstore/csharp/SwaggerClientTest/SwaggerClientTest.csproj b/samples/client/petstore/csharp/SwaggerClientTest/SwaggerClientTest.csproj index 00467e845ea..5556641ea1f 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/SwaggerClientTest.csproj +++ b/samples/client/petstore/csharp/SwaggerClientTest/SwaggerClientTest.csproj @@ -1,4 +1,4 @@ - + Debug @@ -56,6 +56,8 @@ + + @@ -67,5 +69,9 @@ + + + + \ No newline at end of file diff --git a/samples/client/petstore/csharp/SwaggerClientTest/SwaggerClientTest.userprefs b/samples/client/petstore/csharp/SwaggerClientTest/SwaggerClientTest.userprefs index 05585bff932..3b6f6c505af 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/SwaggerClientTest.userprefs +++ b/samples/client/petstore/csharp/SwaggerClientTest/SwaggerClientTest.userprefs @@ -1,8 +1,10 @@ - + - + - + + + diff --git a/samples/client/petstore/csharp/SwaggerClientTest/TestApiClient.cs b/samples/client/petstore/csharp/SwaggerClientTest/TestApiClient.cs index 42cea3120fe..f0232c330f0 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/TestApiClient.cs +++ b/samples/client/petstore/csharp/SwaggerClientTest/TestApiClient.cs @@ -3,11 +3,18 @@ using System; using System.Collections.Generic; using IO.Swagger.Client; -namespace SwaggerClient.TestApiClient +namespace SwaggerClientTest.TestApiClient { public class TestApiClient { - [Test ()] + [TearDown()] + public void TearDown() + { + // Reset to default, just in case + Configuration.Default.DateTimeFormat = "o"; + } + + [Test ()] public void TestParameterToString () { ApiClient api = new ApiClient (); @@ -21,6 +28,53 @@ namespace SwaggerClient.TestApiClient Assert.AreEqual("1,37", api.ParameterToString (numList)); } - } + [Test ()] + public void TestParameterToStringForDateTime () + { + ApiClient api = new ApiClient (); + + // test datetime + DateTime dateUtc = DateTime.Parse ("2008-04-10T13:30:00.0000000z", null, System.Globalization.DateTimeStyles.RoundtripKind); + Assert.AreEqual ("2008-04-10T13:30:00.0000000Z", api.ParameterToString (dateUtc)); + + // test datetime with no timezone + DateTime dateWithNoTz = DateTime.Parse ("2008-04-10T13:30:00.000", null, System.Globalization.DateTimeStyles.RoundtripKind); + Assert.AreEqual ("2008-04-10T13:30:00.0000000", api.ParameterToString (dateWithNoTz)); + } + + // The test below only passes when running at -04:00 timezone + [Ignore ()] + public void TestParameterToStringWithTimeZoneForDateTime () + { + ApiClient api = new ApiClient (); + // test datetime with a time zone + DateTime dateWithTz = DateTime.Parse("2008-04-10T13:30:00.0000000-04:00", null, System.Globalization.DateTimeStyles.RoundtripKind); + Assert.AreEqual("2008-04-10T13:30:00.0000000-04:00", api.ParameterToString(dateWithTz)); + } + + [Test ()] + public void TestParameterToStringForDateTimeWithUFormat () + { + // Setup the DateTimeFormat across all of the calls + Configuration.Default.DateTimeFormat = "u"; + ApiClient api = new ApiClient(); + + // test datetime + DateTime dateUtc = DateTime.Parse("2009-06-15 20:45:30Z", null, System.Globalization.DateTimeStyles.RoundtripKind); + Assert.AreEqual("2009-06-15 20:45:30Z", api.ParameterToString(dateUtc)); + } + + [Test ()] + public void TestParameterToStringForDateTimeWithCustomFormat () + { + // Setup the DateTimeFormat across all of the calls + Configuration.Default.DateTimeFormat = "dd/MM/yy HH:mm:ss"; + ApiClient api = new ApiClient(); + + // test datetime + DateTime dateUtc = DateTime.Parse("2009-06-15 20:45:30Z", null, System.Globalization.DateTimeStyles.RoundtripKind); + Assert.AreEqual("15/06/09 20:45:30", api.ParameterToString(dateUtc)); + } + } } diff --git a/samples/client/petstore/csharp/SwaggerClientTest/TestConfiguration.cs b/samples/client/petstore/csharp/SwaggerClientTest/TestConfiguration.cs new file mode 100644 index 00000000000..140fd269834 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientTest/TestConfiguration.cs @@ -0,0 +1,123 @@ +using NUnit.Framework; +using System; +using System.Collections.Generic; +using IO.Swagger.Client; +using IO.Swagger.Api; +using IO.Swagger.Model; + +namespace SwaggerClientTest.TestConfiguration +{ + public class TestConfiguration + { + [TearDown ()] + public void TearDown () + { + // Reset to default, just in case + Configuration.Default.DateTimeFormat = "o"; + } + + [Test ()] + public void TestAuthentication () + { + Configuration c = new Configuration (); + c.Username = "test_username"; + c.Password = "test_password"; + + c.ApiKey ["api_key_identifier"] = "1233456778889900"; + c.ApiKeyPrefix ["api_key_identifier"] = "PREFIX"; + Assert.AreEqual (c.GetApiKeyWithPrefix("api_key_identifier"), "PREFIX 1233456778889900"); + + } + + [Test ()] + public void TestBasePath () + { + PetApi p = new PetApi ("http://new-basepath.com"); + Assert.AreEqual (p.Configuration.ApiClient.RestClient.BaseUrl, "http://new-basepath.com"); + // Given that PetApi is initailized with a base path, a new configuration (with a new ApiClient) + // is created by default + Assert.AreNotSame (p.Configuration, Configuration.Default); + } + + [Test ()] + public void TestDateTimeFormat_Default () + { + // Should default to the Round-trip Format Specifier - "o" + // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 + Assert.AreEqual("o", Configuration.Default.DateTimeFormat); + } + + [Test ()] + public void TestDateTimeFormat_UType() + { + Configuration.Default.DateTimeFormat = "u"; + + Assert.AreEqual("u", Configuration.Default.DateTimeFormat); + } + + [Test ()] + public void TestConstructor() + { + Configuration c = new Configuration (username: "test username", password: "test password"); + Assert.AreEqual (c.Username, "test username"); + Assert.AreEqual (c.Password, "test password"); + + } + + [Test ()] + public void TestDefautlConfiguration () + { + PetApi p1 = new PetApi (); + PetApi p2 = new PetApi (); + Assert.AreSame (p1.Configuration, p2.Configuration); + // same as the default + Assert.AreSame (p1.Configuration, Configuration.Default); + + Configuration c = new Configuration (); + Assert.AreNotSame (c, p1.Configuration); + + PetApi p3 = new PetApi (c); + // same as c + Assert.AreSame (p3.Configuration, c); + // not same as default + Assert.AreNotSame (p3.Configuration, p1.Configuration); + + } + + [Test ()] + public void TestUsage () + { + // basic use case using default base URL + PetApi p1 = new PetApi (); + Assert.AreSame (p1.Configuration, Configuration.Default, "PetApi should use default configuration"); + + // using a different base URL + PetApi p2 = new PetApi ("http://new-base-url.com/"); + Assert.AreEqual (p2.Configuration.ApiClient.RestClient.BaseUrl.ToString(), "http://new-base-url.com/"); + + // using a different configuration + Configuration c1 = new Configuration (); + PetApi p3 = new PetApi (c1); + Assert.AreSame (p3.Configuration, c1); + + // using a different base URL via a new ApiClient + ApiClient a1 = new ApiClient ("http://new-api-client.com"); + Configuration c2 = new Configuration (a1); + PetApi p4 = new PetApi (c2); + Assert.AreSame (p4.Configuration.ApiClient, a1); + } + + [Test ()] + public void TestTimeout () + { + Configuration c1 = new Configuration(); + Assert.AreEqual(100000, c1.Timeout); // default vaue + + c1.Timeout = 50000; + Assert.AreEqual(50000, c1.Timeout); + + Configuration c2 = new Configuration(timeout: 20000); + Assert.AreEqual(20000, c2.Timeout); + } + } +} \ No newline at end of file diff --git a/samples/client/petstore/csharp/SwaggerClientTest/TestPet.cs b/samples/client/petstore/csharp/SwaggerClientTest/TestPet.cs index 0227a2d9113..10324a2fae7 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/TestPet.cs +++ b/samples/client/petstore/csharp/SwaggerClientTest/TestPet.cs @@ -1,4 +1,4 @@ -using NUnit.Framework; +using NUnit.Framework; using System; using System.Linq; using System.IO; @@ -6,9 +6,9 @@ using System.Collections.Generic; using IO.Swagger.Api; using IO.Swagger.Model; using IO.Swagger.Client; +using System.Reflection; - -namespace SwaggerClient.TestPet +namespace SwaggerClientTest.TestPet { [TestFixture ()] public class TestPet @@ -49,7 +49,9 @@ namespace SwaggerClient.TestPet petApi.DeletePet(petId, "test key"); } - + /// + /// Test GetPetByIdAsync + /// [Test ()] public void TestGetPetByIdAsync () { @@ -74,10 +76,48 @@ namespace SwaggerClient.TestPet } + /// + /// Test GetPetByIdAsyncWithHttpInfo + /// + [Test ()] + public void TestGetPetByIdAsyncWithHttpInfo () + { + PetApi petApi = new PetApi (); + var task = petApi.GetPetByIdAsyncWithHttpInfo (petId); + + Assert.AreEqual (200, task.Result.StatusCode); + Assert.IsTrue (task.Result.Headers.ContainsKey("Content-Type")); + Assert.AreEqual (task.Result.Headers["Content-Type"], "application/json"); + + Pet response = task.Result.Data; + Assert.IsInstanceOf (response, "Response is a Pet"); + + Assert.AreEqual ("Csharp test", response.Name); + Assert.AreEqual ("available", response.Status); + + Assert.IsInstanceOf> (response.Tags, "Response.Tags is a Array"); + Assert.AreEqual (petId, response.Tags [0].Id); + Assert.AreEqual ("sample tag name1", response.Tags [0].Name); + + Assert.IsInstanceOf> (response.PhotoUrls, "Response.PhotoUrls is a Array"); + Assert.AreEqual ("sample photoUrls", response.PhotoUrls [0]); + + Assert.IsInstanceOf (response.Category, "Response.Category is a Category"); + Assert.AreEqual (56, response.Category.Id); + Assert.AreEqual ("sample category name2", response.Category.Name); + + } + + /// + /// Test GetPetById + /// [Test ()] public void TestGetPetById () { - PetApi petApi = new PetApi (); + // set timeout to 10 seconds + Configuration c1 = new Configuration (timeout: 10000); + + PetApi petApi = new PetApi (c1); Pet response = petApi.GetPetById (petId); Assert.IsInstanceOf (response, "Response is a Pet"); @@ -97,6 +137,9 @@ namespace SwaggerClient.TestPet } + /// + /// Test UpdatePetWithForm + /// [Test ()] public void TestUpdatePetWithForm () { @@ -113,23 +156,34 @@ namespace SwaggerClient.TestPet Assert.AreEqual (petId, response.Tags [0].Id); Assert.AreEqual (56, response.Category.Id); + + // test optional parameter + petApi.UpdatePetWithForm (petId.ToString(), "new form name2"); + Pet response2 = petApi.GetPetById (petId); + Assert.AreEqual ("new form name2", response2.Name); } + /// + /// Test UploadFile + /// [Test ()] public void TestUploadFile () { - PetApi petApi = new PetApi (); - //NOTE: please provide a valid file (full path) - FileStream fileStream = new FileStream("/var/tmp/small.gif", FileMode.Open); + Assembly _assembly = Assembly.GetExecutingAssembly(); + Stream _imageStream = _assembly.GetManifestResourceStream("SwaggerClientTest.swagger-logo.png"); + PetApi petApi = new PetApi (); // test file upload with form parameters - petApi.UploadFile(petId, "new form name", fileStream); + petApi.UploadFile(petId, "new form name", _imageStream); // test file upload without any form parameters - petApi.UploadFile(petId, null, fileStream); + // using optional parameter syntax introduced at .net 4.0 + petApi.UploadFile(petId: petId, file: _imageStream); } - + /// + /// Test FindPetByStatus + /// [Test ()] public void TestFindPetByStatus () { @@ -145,6 +199,9 @@ namespace SwaggerClient.TestPet } + /// + /// Test Equal + /// [Test ()] public void TestEqual() { @@ -207,6 +264,32 @@ namespace SwaggerClient.TestPet } + /// + /// Test status code + /// + [Test ()] + public void TestStatusCodeAndHeader () + { + PetApi petApi = new PetApi (); + var response = petApi.GetPetByIdWithHttpInfo (petId); + Assert.AreEqual (response.StatusCode, 200); + Assert.IsTrue (response.Headers.ContainsKey("Content-Type")); + Assert.AreEqual (response.Headers["Content-Type"], "application/json"); + } + + /// + /// Test default header (should be deprecated + /// + [Test ()] + public void TestDefaultHeader () + { + PetApi petApi = new PetApi (); + // there should be a warning for using AddDefaultHeader (deprecated) below + petApi.AddDefaultHeader ("header_key", "header_value"); + // the following should be used instead as suggested in the doc + petApi.Configuration.AddDefaultHeader ("header_key2", "header_value2"); + + } } } diff --git a/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/SwaggerClientTest.dll b/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/SwaggerClientTest.dll index 924934c4623..b0a59cff946 100755 Binary files a/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/SwaggerClientTest.dll and b/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/SwaggerClientTest.dll differ diff --git a/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/SwaggerClientTest.dll.mdb b/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/SwaggerClientTest.dll.mdb index d0d7f1b3ccf..25bc7b803d9 100644 Binary files a/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/SwaggerClientTest.dll.mdb and b/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/SwaggerClientTest.dll.mdb differ 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 b46eed9f9d6..f115c595d6a 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 @@ -1,4 +1,5 @@ /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 diff --git a/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.dll b/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.dll index 924934c4623..b0a59cff946 100755 Binary files a/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.dll and b/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.dll differ diff --git a/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.dll.mdb b/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.dll.mdb index d0d7f1b3ccf..25bc7b803d9 100644 Binary files a/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.dll.mdb and b/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.dll.mdb differ diff --git a/samples/client/petstore/csharp/SwaggerClientTest/swagger-logo.png b/samples/client/petstore/csharp/SwaggerClientTest/swagger-logo.png new file mode 100644 index 00000000000..7671d64c7da Binary files /dev/null and b/samples/client/petstore/csharp/SwaggerClientTest/swagger-logo.png differ diff --git a/samples/client/petstore/java/default/pom.xml b/samples/client/petstore/java/default/pom.xml index 8a939b9dc34..e35e30af583 100644 --- a/samples/client/petstore/java/default/pom.xml +++ b/samples/client/petstore/java/default/pom.xml @@ -137,6 +137,11 @@ jackson-databind ${jackson-version} + + com.fasterxml.jackson.jaxrs + jackson-jaxrs-json-provider + ${jackson-version} + com.fasterxml.jackson.datatype jackson-datatype-joda 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 386f10bde24..3c6aff9cecf 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 @@ -1,8 +1,13 @@ package io.swagger.client; +import com.fasterxml.jackson.annotation.*; +import com.fasterxml.jackson.databind.*; +import com.fasterxml.jackson.datatype.joda.*; +import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider; + import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.ClientResponse; -import com.sun.jersey.api.client.config.ClientConfig; +import com.sun.jersey.api.client.GenericType; import com.sun.jersey.api.client.config.DefaultClientConfig; import com.sun.jersey.api.client.filter.LoggingFilter; import com.sun.jersey.api.client.WebResource.Builder; @@ -25,27 +30,24 @@ import java.util.TimeZone; import java.net.URLEncoder; -import java.io.IOException; import java.io.File; import java.io.UnsupportedEncodingException; -import java.io.DataInputStream; import java.text.DateFormat; import java.text.SimpleDateFormat; -import java.text.ParseException; import io.swagger.client.auth.Authentication; 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 = "2015-11-19T13:52:16.052+01:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-12-22T10:21:47.360+01:00") public class ApiClient { private Map hostMap = new HashMap(); private Map defaultHeaderMap = new HashMap(); private boolean debugging = false; private String basePath = "http://petstore.swagger.io/v2"; - private JSON json = new JSON(); + private ObjectMapper mapper; private Map authentications; @@ -55,6 +57,14 @@ public class ApiClient { private DateFormat dateFormat; public ApiClient() { + mapper = new ObjectMapper(); + mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); + mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING); + mapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING); + mapper.registerModule(new JodaModule()); + // Use RFC3339 format for date and datetime. // See http://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14 this.dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); @@ -62,7 +72,7 @@ public class ApiClient { // Use UTC as the default time zone. this.dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); - this.json.setDateFormat((DateFormat) dateFormat.clone()); + this.mapper.setDateFormat((DateFormat) dateFormat.clone()); // Set default User-Agent. setUserAgent("Java-Swagger"); @@ -75,13 +85,6 @@ public class ApiClient { authentications = Collections.unmodifiableMap(authentications); } - /** - * Gets the JSON instance to do JSON serialization and deserialization. - */ - public JSON getJSON() { - return json; - } - public String getBasePath() { return basePath; } @@ -236,7 +239,7 @@ public class ApiClient { public ApiClient setDateFormat(DateFormat dateFormat) { this.dateFormat = dateFormat; // also set the date format for model (de)serialization with Date properties - this.json.setDateFormat((DateFormat) dateFormat.clone()); + this.mapper.setDateFormat((DateFormat) dateFormat.clone()); return this; } @@ -268,7 +271,7 @@ public class ApiClient { return formatDate((Date) param); } else if (param instanceof Collection) { StringBuilder b = new StringBuilder(); - for(Object o : (Collection)param) { + for(Object o : (Collection)param) { if(b.length() > 0) { b.append(","); } @@ -289,9 +292,9 @@ public class ApiClient { // preconditions if (name == null || name.isEmpty() || value == null) return params; - Collection valueCollection = null; - if (value instanceof Collection) { - valueCollection = (Collection) value; + Collection valueCollection = null; + if (value instanceof Collection) { + valueCollection = (Collection) value; } else { params.add(new Pair(name, parameterToString(value))); return params; @@ -336,6 +339,17 @@ public class ApiClient { return params; } + /** + * Check if the given MIME is a JSON MIME. + * JSON MIME examples: + * application/json + * application/json; charset=UTF8 + * APPLICATION/JSON + */ + public boolean isJsonMime(String mime) { + return mime != null && mime.matches("(?i)application\\/json(;.*)?"); + } + /** * Select the Accept header's value from the given accepts array: * if JSON exists in the given array, use it; @@ -346,8 +360,14 @@ public class ApiClient { * null will be returned (not to set the Accept header explicitly). */ public String selectHeaderAccept(String[] accepts) { - if (accepts.length == 0) return null; - if (StringUtil.containsIgnoreCase(accepts, "application/json")) return "application/json"; + if (accepts.length == 0) { + return null; + } + for (String accept : accepts) { + if (isJsonMime(accept)) { + return accept; + } + } return StringUtil.join(accepts, ","); } @@ -361,8 +381,14 @@ public class ApiClient { * JSON will be used. */ public String selectHeaderContentType(String[] contentTypes) { - if (contentTypes.length == 0) return "application/json"; - if (StringUtil.containsIgnoreCase(contentTypes, "application/json")) return "application/json"; + if (contentTypes.length == 0) { + return "application/json"; + } + for (String contentType : contentTypes) { + if (isJsonMime(contentType)) { + return contentType; + } + } return contentTypes[0]; } @@ -381,49 +407,30 @@ public class ApiClient { * Serialize the given Java object into string according the given * Content-Type (only JSON is supported for now). */ - public String serialize(Object obj, String contentType) throws ApiException { - if (contentType.startsWith("application/json")) { - return json.serialize(obj); + public Object serialize(Object obj, String contentType, Map formParams) throws ApiException { + if (contentType.startsWith("multipart/form-data")) { + FormDataMultiPart mp = new FormDataMultiPart(); + for (Entry param: formParams.entrySet()) { + if (param.getValue() instanceof File) { + File file = (File) param.getValue(); + mp.bodyPart(new FileDataBodyPart(param.getKey(), file, MediaType.MULTIPART_FORM_DATA_TYPE)); + } else { + mp.field(param.getKey(), parameterToString(param.getValue()), MediaType.MULTIPART_FORM_DATA_TYPE); + } + } + return mp; + } else if (contentType.startsWith("application/x-www-form-urlencoded")) { + return this.getXWWWFormUrlencodedParams(formParams); } else { - throw new ApiException(400, "can not serialize object into Content-Type: " + contentType); + // We let Jersey attempt to serialize the body + return obj; } } - /** - * Deserialize response body to Java object according to the Content-Type. - */ - public T deserialize(ClientResponse response, TypeRef returnType) throws ApiException { - String contentType = null; - List contentTypes = response.getHeaders().get("Content-Type"); - if (contentTypes != null && !contentTypes.isEmpty()) - contentType = contentTypes.get(0); - if (contentType == null) - throw new ApiException(500, "missing Content-Type in response"); + private ClientResponse getAPIResponse(String path, String method, List queryParams, Object body, Map headerParams, Map formParams, String accept, String contentType, String[] authNames) throws ApiException { - String body; - if (response.hasEntity()) - body = (String) response.getEntity(String.class); - else - body = ""; - - if (contentType.startsWith("application/json")) { - return json.deserialize(body, returnType); - } else if (returnType.getType().equals(String.class)) { - // Expecting string, return the raw response body. - return (T) body; - } else { - throw new ApiException( - 500, - "Content type \"" + contentType + "\" is not supported for type: " - + returnType.getType() - ); - } - } - - private ClientResponse getAPIResponse(String path, String method, List queryParams, Object body, byte[] binaryBody, Map headerParams, Map formParams, String accept, String contentType, String[] authNames) throws ApiException { - - if (body != null && binaryBody != null){ - throw new ApiException(500, "either body or binaryBody must be null"); + if (body != null && !formParams.isEmpty()){ + throw new ApiException(500, "Cannot have body and form params"); } updateParamsForAuth(authNames, queryParams, headerParams); @@ -460,62 +467,16 @@ public class ApiClient { } } - String encodedFormParams = null; - if (contentType.startsWith("multipart/form-data")) { - FormDataMultiPart mp = new FormDataMultiPart(); - for (Entry param: formParams.entrySet()) { - if (param.getValue() instanceof File) { - File file = (File) param.getValue(); - mp.field(param.getKey(), file.getName()); - mp.bodyPart(new FileDataBodyPart(param.getKey(), file, MediaType.MULTIPART_FORM_DATA_TYPE)); - } else { - mp.field(param.getKey(), parameterToString(param.getValue()), MediaType.MULTIPART_FORM_DATA_TYPE); - } - } - body = mp; - } else if (contentType.startsWith("application/x-www-form-urlencoded")) { - encodedFormParams = this.getXWWWFormUrlencodedParams(formParams); - } - ClientResponse response = null; if ("GET".equals(method)) { response = (ClientResponse) builder.get(ClientResponse.class); } else if ("POST".equals(method)) { - if (encodedFormParams != null) { - response = builder.type(contentType).post(ClientResponse.class, encodedFormParams); - } else if (body == null) { - if(binaryBody == null) - response = builder.post(ClientResponse.class, null); - else - response = builder.type(contentType).post(ClientResponse.class, binaryBody); - } else if (body instanceof FormDataMultiPart) { - response = builder.type(contentType).post(ClientResponse.class, body); - } else { - response = builder.type(contentType).post(ClientResponse.class, serialize(body, contentType)); - } + response = builder.type(contentType).post(ClientResponse.class, serialize(body, contentType, formParams)); } else if ("PUT".equals(method)) { - if (encodedFormParams != null) { - response = builder.type(contentType).put(ClientResponse.class, encodedFormParams); - } else if(body == null) { - if(binaryBody == null) - response = builder.put(ClientResponse.class, null); - else - response = builder.type(contentType).put(ClientResponse.class, binaryBody); - } else { - response = builder.type(contentType).put(ClientResponse.class, serialize(body, contentType)); - } + response = builder.type(contentType).put(ClientResponse.class, serialize(body, contentType, formParams)); } else if ("DELETE".equals(method)) { - if (encodedFormParams != null) { - response = builder.type(contentType).delete(ClientResponse.class, encodedFormParams); - } else if(body == null) { - if(binaryBody == null) - response = builder.delete(ClientResponse.class); - else - response = builder.type(contentType).delete(ClientResponse.class, binaryBody); - } else { - response = builder.type(contentType).delete(ClientResponse.class, serialize(body, contentType)); - } + response = builder.type(contentType).delete(ClientResponse.class, serialize(body, contentType, formParams)); } else { throw new ApiException(500, "unknown method type " + method); } @@ -529,7 +490,6 @@ public class ApiClient { * @param method The request method, one of "GET", "POST", "PUT", and "DELETE" * @param queryParams The query parameters * @param body The request body object - if it is not binary, otherwise null - * @param binaryBody The request body object - if it is binary, otherwise null * @param headerParams The header parameters * @param formParams The form parameters * @param accept The request's Accept header @@ -537,9 +497,9 @@ public class ApiClient { * @param authNames The authentications to apply * @return The response body in type of string */ - public T invokeAPI(String path, String method, List queryParams, Object body, byte[] binaryBody, Map headerParams, Map formParams, String accept, String contentType, String[] authNames, TypeRef returnType) throws ApiException { + public T invokeAPI(String path, String method, List queryParams, Object body, Map headerParams, Map formParams, String accept, String contentType, String[] authNames, GenericType returnType) throws ApiException { - ClientResponse response = getAPIResponse(path, method, queryParams, body, binaryBody, headerParams, formParams, accept, contentType, authNames); + ClientResponse response = getAPIResponse(path, method, queryParams, body, headerParams, formParams, accept, contentType, authNames); statusCode = response.getStatusInfo().getStatusCode(); responseHeaders = response.getHeaders(); @@ -550,13 +510,13 @@ public class ApiClient { if (returnType == null) return null; else - return deserialize(response, returnType); + return response.getEntity(returnType); } else { String message = "error"; String respBody = null; if (response.hasEntity()) { try { - respBody = String.valueOf(response.getEntity(String.class)); + respBody = response.getEntity(String.class); message = respBody; } catch (RuntimeException e) { // e.printStackTrace(); @@ -569,58 +529,6 @@ public class ApiClient { respBody); } } - /** - * Invoke API by sending HTTP request with the given options - return binary result - * - * @param path The sub-path of the HTTP URL - * @param method The request method, one of "GET", "POST", "PUT", and "DELETE" - * @param queryParams The query parameters - * @param body The request body object - if it is not binary, otherwise null - * @param binaryBody The request body object - if it is binary, otherwise null - * @param headerParams The header parameters - * @param formParams The form parameters - * @param accept The request's Accept header - * @param contentType The request's Content-Type header - * @param authNames The authentications to apply - * @return The response body in type of string - */ - public byte[] invokeBinaryAPI(String path, String method, List queryParams, Object body, byte[] binaryBody, Map headerParams, Map formParams, String accept, String contentType, String[]authNames) throws ApiException { - - ClientResponse response = getAPIResponse(path, method, queryParams, body, binaryBody, headerParams, formParams, accept, contentType, authNames); - - if(response.getStatusInfo() == ClientResponse.Status.NO_CONTENT) { - return null; - } - else if(response.getStatusInfo().getFamily() == Family.SUCCESSFUL) { - if(response.hasEntity()) { - DataInputStream stream = new DataInputStream(response.getEntityInputStream()); - byte[] data = new byte[response.getLength()]; - try { - stream.readFully(data); - } catch (IOException ex) { - throw new ApiException(500, "Error obtaining binary response data"); - } - return data; - } - else { - return new byte[0]; - } - } - else { - String message = "error"; - if(response.hasEntity()) { - try{ - message = String.valueOf(response.getEntity(String.class)); - } - catch (RuntimeException e) { - // e.printStackTrace(); - } - } - throw new ApiException( - response.getStatusInfo().getStatusCode(), - message); - } - } /** * Update query and header parameters based on authentication settings. @@ -642,7 +550,6 @@ public class ApiClient { StringBuilder formParamBuilder = new StringBuilder(); for (Entry param : formParams.entrySet()) { - String keyStr = param.getKey(); String valueStr = parameterToString(param.getValue()); try { formParamBuilder.append(URLEncoder.encode(param.getKey(), "utf8")) @@ -667,7 +574,11 @@ public class ApiClient { */ private Client getClient() { if(!hostMap.containsKey(basePath)) { - Client client = Client.create(); + // Add the JSON serialization support to Jersey + JacksonJsonProvider jsonProvider = new JacksonJsonProvider(mapper); + DefaultClientConfig conf = new DefaultClientConfig(); + conf.getSingletons().add(jsonProvider); + Client client = Client.create(conf); if (debugging) client.addFilter(new LoggingFilter()); hostMap.put(basePath, client); 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 666dbc842b2..bc873b56b80 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 = "2015-11-19T13:52:16.052+01:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-12-22T10:21:47.360+01: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 88e67771ede..04d62c45a8f 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 = "2015-11-19T13:52:16.052+01:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-12-22T10:21:47.360+01:00") public class Configuration { private static ApiClient defaultApiClient = new ApiClient(); diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/JSON.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/JSON.java deleted file mode 100644 index b7da2974d26..00000000000 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/JSON.java +++ /dev/null @@ -1,64 +0,0 @@ -package io.swagger.client; - -import com.fasterxml.jackson.annotation.*; -import com.fasterxml.jackson.databind.*; -import com.fasterxml.jackson.datatype.joda.*; - -import java.text.DateFormat; - -import java.io.IOException; - -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-11-19T13:52:16.052+01:00") -public class JSON { - private ObjectMapper mapper; - - public JSON() { - mapper = new ObjectMapper(); - mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); - mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING); - mapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING); - mapper.registerModule(new JodaModule()); - } - - /** - * Set the date format for JSON (de)serialization with Date properties. - */ - public void setDateFormat(DateFormat dateFormat) { - mapper.setDateFormat(dateFormat); - } - - /** - * Serialize the given Java object into JSON string. - */ - public String serialize(Object obj) throws ApiException { - try { - if (obj != null) - return mapper.writeValueAsString(obj); - else - return null; - } catch (Exception e) { - throw new ApiException(400, e.getMessage()); - } - } - - /** - * Deserialize the given JSON string to Java object. - * - * @param body The JSON string - * @param returnType The type to deserialize inot - * @return The deserialized Java object - */ - public T deserialize(String body, TypeRef returnType) throws ApiException { - JavaType javaType = mapper.constructType(returnType.getType()); - try { - return mapper.readValue(body, javaType); - } catch (IOException e) { - if (returnType.getType().equals(String.class)) - return (T) body; - else - throw new ApiException(500, e.getMessage(), null, body); - } - } -} 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 8f77fa48cfe..dabe2000bb8 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 = "2015-11-19T13:52:16.052+01:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-12-22T10:21:47.360+01: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 858bf7ace19..8c5f7f9c27b 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 = "2015-11-19T13:52:16.052+01:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-12-22T10:21:47.360+01: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/TypeRef.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/TypeRef.java deleted file mode 100644 index 5a45bac9ad4..00000000000 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/TypeRef.java +++ /dev/null @@ -1,26 +0,0 @@ -package io.swagger.client; - -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.Type; - -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-11-19T13:52:16.052+01:00") -public class TypeRef { - private final Type type; - - public TypeRef() { - this.type = getGenericType(getClass()); - } - - private static Type getGenericType(Class klass) { - Type superclass = klass.getGenericSuperclass(); - if (superclass instanceof Class) { - throw new RuntimeException("No type parameter provided"); - } - ParameterizedType parameterized = (ParameterizedType) superclass; - return parameterized.getActualTypeArguments()[0]; - } - - public Type getType() { - return type; - } -} 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 8cf9c31f0e6..d504bcbf3dc 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 @@ -1,17 +1,18 @@ package io.swagger.client.api; +import com.sun.jersey.api.client.GenericType; + import io.swagger.client.ApiException; import io.swagger.client.ApiClient; import io.swagger.client.Configuration; import io.swagger.client.Pair; -import io.swagger.client.TypeRef; import io.swagger.client.model.Pet; import java.io.File; import java.util.*; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-11-19T13:52:16.052+01:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-12-22T10:21:47.360+01:00") public class PetApi { private ApiClient apiClient; @@ -38,9 +39,8 @@ public class PetApi { * @param body Pet object that needs to be added to the store * @return void */ - public void updatePet (Pet body) throws ApiException { + public void updatePet(Pet body) throws ApiException { Object postBody = body; - byte[] postBinaryBody = null; // create path and map variables String path = "/pet".replaceAll("\\{format\\}","json"); @@ -69,14 +69,8 @@ public class PetApi { String[] authNames = new String[] { "petstore_auth" }; - + apiClient.invokeAPI(path, "PUT", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); - - apiClient.invokeAPI(path, "PUT", queryParams, postBody, postBinaryBody, headerParams, formParams, accept, contentType, authNames, null); - - - - } /** @@ -85,9 +79,8 @@ public class PetApi { * @param body Pet object that needs to be added to the store * @return void */ - public void addPet (Pet body) throws ApiException { + public void addPet(Pet body) throws ApiException { Object postBody = body; - byte[] postBinaryBody = null; // create path and map variables String path = "/pet".replaceAll("\\{format\\}","json"); @@ -116,14 +109,8 @@ public class PetApi { String[] authNames = new String[] { "petstore_auth" }; - + apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); - - apiClient.invokeAPI(path, "POST", queryParams, postBody, postBinaryBody, headerParams, formParams, accept, contentType, authNames, null); - - - - } /** @@ -132,9 +119,8 @@ public class PetApi { * @param status Status values that need to be considered for filter * @return List */ - public List findPetsByStatus (List status) throws ApiException { + public List findPetsByStatus(List status) throws ApiException { Object postBody = null; - byte[] postBinaryBody = null; // create path and map variables String path = "/pet/findByStatus".replaceAll("\\{format\\}","json"); @@ -165,15 +151,9 @@ public class PetApi { String[] authNames = new String[] { "petstore_auth" }; - + GenericType> returnType = new GenericType>() {}; + return apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); - - TypeRef returnType = new TypeRef>() {}; - return apiClient.invokeAPI(path, "GET", queryParams, postBody, postBinaryBody, headerParams, formParams, accept, contentType, authNames, returnType); - - - - } /** @@ -182,9 +162,8 @@ public class PetApi { * @param tags Tags to filter by * @return List */ - public List findPetsByTags (List tags) throws ApiException { + public List findPetsByTags(List tags) throws ApiException { Object postBody = null; - byte[] postBinaryBody = null; // create path and map variables String path = "/pet/findByTags".replaceAll("\\{format\\}","json"); @@ -215,15 +194,9 @@ public class PetApi { String[] authNames = new String[] { "petstore_auth" }; - + GenericType> returnType = new GenericType>() {}; + return apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); - - TypeRef returnType = new TypeRef>() {}; - return apiClient.invokeAPI(path, "GET", queryParams, postBody, postBinaryBody, headerParams, formParams, accept, contentType, authNames, returnType); - - - - } /** @@ -232,9 +205,8 @@ public class PetApi { * @param petId ID of pet that needs to be fetched * @return Pet */ - public Pet getPetById (Long petId) throws ApiException { + public Pet getPetById(Long petId) throws ApiException { Object postBody = null; - byte[] postBinaryBody = null; // verify the required parameter 'petId' is set if (petId == null) { @@ -269,15 +241,9 @@ public class PetApi { String[] authNames = new String[] { "api_key" }; - + GenericType returnType = new GenericType() {}; + return apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); - - TypeRef returnType = new TypeRef() {}; - return apiClient.invokeAPI(path, "GET", queryParams, postBody, postBinaryBody, headerParams, formParams, accept, contentType, authNames, returnType); - - - - } /** @@ -288,9 +254,8 @@ public class PetApi { * @param status Updated status of the pet * @return void */ - public void updatePetWithForm (String petId, String name, String status) throws ApiException { + public void updatePetWithForm(String petId, String name, String status) throws ApiException { Object postBody = null; - byte[] postBinaryBody = null; // verify the required parameter 'petId' is set if (petId == null) { @@ -329,14 +294,8 @@ public class PetApi { String[] authNames = new String[] { "petstore_auth" }; - + apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); - - apiClient.invokeAPI(path, "POST", queryParams, postBody, postBinaryBody, headerParams, formParams, accept, contentType, authNames, null); - - - - } /** @@ -346,9 +305,8 @@ public class PetApi { * @param apiKey * @return void */ - public void deletePet (Long petId, String apiKey) throws ApiException { + public void deletePet(Long petId, String apiKey) throws ApiException { Object postBody = null; - byte[] postBinaryBody = null; // verify the required parameter 'petId' is set if (petId == null) { @@ -385,14 +343,48 @@ public class PetApi { String[] authNames = new String[] { "petstore_auth" }; + apiClient.invokeAPI(path, "DELETE", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); + + } + + /** + * downloads an image + * + * @return File + */ + public File downloadFile() throws ApiException { + Object postBody = null; + + // create path and map variables + String path = "/pet/{petId}/downloadImage".replaceAll("\\{format\\}","json"); + + // query params + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); - - apiClient.invokeAPI(path, "DELETE", queryParams, postBody, postBinaryBody, headerParams, formParams, accept, contentType, authNames, null); - + + + final String[] accepts = { + "application/octet-stream" + }; + final String accept = apiClient.selectHeaderAccept(accepts); + + final String[] contentTypes = { + + }; + final String contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { }; + + + GenericType returnType = new GenericType() {}; + return apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); + } /** @@ -403,9 +395,8 @@ public class PetApi { * @param file file to upload * @return void */ - public void uploadFile (Long petId, String additionalMetadata, File file) throws ApiException { + public void uploadFile(Long petId, String additionalMetadata, File file) throws ApiException { Object postBody = null; - byte[] postBinaryBody = null; // verify the required parameter 'petId' is set if (petId == null) { @@ -444,14 +435,8 @@ public class PetApi { String[] authNames = new String[] { "petstore_auth" }; - + apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); - - apiClient.invokeAPI(path, "POST", queryParams, postBody, postBinaryBody, headerParams, formParams, accept, contentType, authNames, 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 6fe8a357ca8..29e54429b2e 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 @@ -1,17 +1,18 @@ package io.swagger.client.api; +import com.sun.jersey.api.client.GenericType; + import io.swagger.client.ApiException; import io.swagger.client.ApiClient; import io.swagger.client.Configuration; import io.swagger.client.Pair; -import io.swagger.client.TypeRef; import java.util.Map; import io.swagger.client.model.Order; import java.util.*; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-11-19T13:52:16.052+01:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-12-22T10:21:47.360+01:00") public class StoreApi { private ApiClient apiClient; @@ -37,9 +38,8 @@ public class StoreApi { * Returns a map of status codes to quantities * @return Map */ - public Map getInventory () throws ApiException { + public Map getInventory() throws ApiException { Object postBody = null; - byte[] postBinaryBody = null; // create path and map variables String path = "/store/inventory".replaceAll("\\{format\\}","json"); @@ -68,15 +68,9 @@ public class StoreApi { String[] authNames = new String[] { "api_key" }; - + GenericType> returnType = new GenericType>() {}; + return apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); - - TypeRef returnType = new TypeRef>() {}; - return apiClient.invokeAPI(path, "GET", queryParams, postBody, postBinaryBody, headerParams, formParams, accept, contentType, authNames, returnType); - - - - } /** @@ -85,9 +79,8 @@ public class StoreApi { * @param body order placed for purchasing the pet * @return Order */ - public Order placeOrder (Order body) throws ApiException { + public Order placeOrder(Order body) throws ApiException { Object postBody = body; - byte[] postBinaryBody = null; // create path and map variables String path = "/store/order".replaceAll("\\{format\\}","json"); @@ -116,15 +109,9 @@ public class StoreApi { String[] authNames = new String[] { }; - + GenericType returnType = new GenericType() {}; + return apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); - - TypeRef returnType = new TypeRef() {}; - return apiClient.invokeAPI(path, "POST", queryParams, postBody, postBinaryBody, headerParams, formParams, accept, contentType, authNames, returnType); - - - - } /** @@ -133,9 +120,8 @@ public class StoreApi { * @param orderId ID of pet that needs to be fetched * @return Order */ - public Order getOrderById (String orderId) throws ApiException { + public Order getOrderById(String orderId) throws ApiException { Object postBody = null; - byte[] postBinaryBody = null; // verify the required parameter 'orderId' is set if (orderId == null) { @@ -170,15 +156,9 @@ public class StoreApi { String[] authNames = new String[] { }; - + GenericType returnType = new GenericType() {}; + return apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); - - TypeRef returnType = new TypeRef() {}; - return apiClient.invokeAPI(path, "GET", queryParams, postBody, postBinaryBody, headerParams, formParams, accept, contentType, authNames, returnType); - - - - } /** @@ -187,9 +167,8 @@ public class StoreApi { * @param orderId ID of the order that needs to be deleted * @return void */ - public void deleteOrder (String orderId) throws ApiException { + public void deleteOrder(String orderId) throws ApiException { Object postBody = null; - byte[] postBinaryBody = null; // verify the required parameter 'orderId' is set if (orderId == null) { @@ -224,14 +203,8 @@ public class StoreApi { String[] authNames = new String[] { }; - + apiClient.invokeAPI(path, "DELETE", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); - - apiClient.invokeAPI(path, "DELETE", queryParams, postBody, postBinaryBody, headerParams, formParams, accept, contentType, authNames, 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 3309549f218..1aa0a28c713 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 @@ -1,17 +1,18 @@ package io.swagger.client.api; +import com.sun.jersey.api.client.GenericType; + import io.swagger.client.ApiException; import io.swagger.client.ApiClient; import io.swagger.client.Configuration; import io.swagger.client.Pair; -import io.swagger.client.TypeRef; import io.swagger.client.model.User; import java.util.*; import java.util.*; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-11-19T13:52:16.052+01:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-12-22T10:21:47.360+01:00") public class UserApi { private ApiClient apiClient; @@ -38,9 +39,8 @@ public class UserApi { * @param body Created user object * @return void */ - public void createUser (User body) throws ApiException { + public void createUser(User body) throws ApiException { Object postBody = body; - byte[] postBinaryBody = null; // create path and map variables String path = "/user".replaceAll("\\{format\\}","json"); @@ -69,14 +69,8 @@ public class UserApi { String[] authNames = new String[] { }; - + apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); - - apiClient.invokeAPI(path, "POST", queryParams, postBody, postBinaryBody, headerParams, formParams, accept, contentType, authNames, null); - - - - } /** @@ -85,9 +79,8 @@ public class UserApi { * @param body List of user object * @return void */ - public void createUsersWithArrayInput (List body) throws ApiException { + public void createUsersWithArrayInput(List body) throws ApiException { Object postBody = body; - byte[] postBinaryBody = null; // create path and map variables String path = "/user/createWithArray".replaceAll("\\{format\\}","json"); @@ -116,14 +109,8 @@ public class UserApi { String[] authNames = new String[] { }; - + apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); - - apiClient.invokeAPI(path, "POST", queryParams, postBody, postBinaryBody, headerParams, formParams, accept, contentType, authNames, null); - - - - } /** @@ -132,9 +119,8 @@ public class UserApi { * @param body List of user object * @return void */ - public void createUsersWithListInput (List body) throws ApiException { + public void createUsersWithListInput(List body) throws ApiException { Object postBody = body; - byte[] postBinaryBody = null; // create path and map variables String path = "/user/createWithList".replaceAll("\\{format\\}","json"); @@ -163,14 +149,8 @@ public class UserApi { String[] authNames = new String[] { }; - + apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); - - apiClient.invokeAPI(path, "POST", queryParams, postBody, postBinaryBody, headerParams, formParams, accept, contentType, authNames, null); - - - - } /** @@ -180,9 +160,8 @@ public class UserApi { * @param password The password for login in clear text * @return String */ - public String loginUser (String username, String password) throws ApiException { + public String loginUser(String username, String password) throws ApiException { Object postBody = null; - byte[] postBinaryBody = null; // create path and map variables String path = "/user/login".replaceAll("\\{format\\}","json"); @@ -215,15 +194,9 @@ public class UserApi { String[] authNames = new String[] { }; - + GenericType returnType = new GenericType() {}; + return apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); - - TypeRef returnType = new TypeRef() {}; - return apiClient.invokeAPI(path, "GET", queryParams, postBody, postBinaryBody, headerParams, formParams, accept, contentType, authNames, returnType); - - - - } /** @@ -231,9 +204,8 @@ public class UserApi { * * @return void */ - public void logoutUser () throws ApiException { + public void logoutUser() throws ApiException { Object postBody = null; - byte[] postBinaryBody = null; // create path and map variables String path = "/user/logout".replaceAll("\\{format\\}","json"); @@ -262,14 +234,8 @@ public class UserApi { String[] authNames = new String[] { }; - + apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); - - apiClient.invokeAPI(path, "GET", queryParams, postBody, postBinaryBody, headerParams, formParams, accept, contentType, authNames, null); - - - - } /** @@ -278,9 +244,8 @@ public class UserApi { * @param username The name that needs to be fetched. Use user1 for testing. * @return User */ - public User getUserByName (String username) throws ApiException { + public User getUserByName(String username) throws ApiException { Object postBody = null; - byte[] postBinaryBody = null; // verify the required parameter 'username' is set if (username == null) { @@ -315,15 +280,9 @@ public class UserApi { String[] authNames = new String[] { }; - + GenericType returnType = new GenericType() {}; + return apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); - - TypeRef returnType = new TypeRef() {}; - return apiClient.invokeAPI(path, "GET", queryParams, postBody, postBinaryBody, headerParams, formParams, accept, contentType, authNames, returnType); - - - - } /** @@ -333,9 +292,8 @@ public class UserApi { * @param body Updated user object * @return void */ - public void updateUser (String username, User body) throws ApiException { + public void updateUser(String username, User body) throws ApiException { Object postBody = body; - byte[] postBinaryBody = null; // verify the required parameter 'username' is set if (username == null) { @@ -370,14 +328,8 @@ public class UserApi { String[] authNames = new String[] { }; - + apiClient.invokeAPI(path, "PUT", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); - - apiClient.invokeAPI(path, "PUT", queryParams, postBody, postBinaryBody, headerParams, formParams, accept, contentType, authNames, null); - - - - } /** @@ -386,9 +338,8 @@ public class UserApi { * @param username The name that needs to be deleted * @return void */ - public void deleteUser (String username) throws ApiException { + public void deleteUser(String username) throws ApiException { Object postBody = null; - byte[] postBinaryBody = null; // verify the required parameter 'username' is set if (username == null) { @@ -423,14 +374,8 @@ public class UserApi { String[] authNames = new String[] { }; - + apiClient.invokeAPI(path, "DELETE", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); - - apiClient.invokeAPI(path, "DELETE", queryParams, postBody, postBinaryBody, headerParams, formParams, accept, contentType, authNames, 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 0011210c8cc..7cbfe2c5672 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 = "2015-11-20T17:28:23.285+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-12-22T10:21:47.360+01: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/Authentication.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/Authentication.java index b25870f479c..d1d9bd05a1e 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/Authentication.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/Authentication.java @@ -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 = "2015-11-19T13:52:16.052+01:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-12-22T10:21:47.360+01:00") public interface Authentication { /** Apply authentication settings to header and query params. */ void applyToParams(List queryParams, Map headerParams); diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/HttpBasicAuth.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/HttpBasicAuth.java index 8c2aa444678..f8ef24718ac 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 = "2015-11-22T13:15:32.345+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-12-22T10:21:47.360+01: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 86ce7da14ee..5e0afc9ba05 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 = "2015-11-19T13:52:16.052+01:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-12-22T10:21:47.360+01: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 0b52b76bfe2..19514335442 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 @@ -3,13 +3,15 @@ package io.swagger.client.model; import io.swagger.client.StringUtil; +import java.util.Objects; import io.swagger.annotations.*; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.*; + @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-11-19T13:52:16.052+01:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-12-22T10:21:47.360+01:00") public class Category { private Long id = null; @@ -41,6 +43,24 @@ public class Category { + @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(); 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 8643d22f36d..de92dddc13f 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 @@ -4,13 +4,15 @@ import io.swagger.client.StringUtil; import java.util.Date; +import java.util.Objects; import io.swagger.annotations.*; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.*; + @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-11-19T13:52:16.052+01:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-12-22T10:21:47.360+01:00") public class Order { private Long id = null; @@ -18,6 +20,7 @@ public class Order { private Integer quantity = null; private Date shipDate = null; + public enum StatusEnum { PLACED("placed"), APPROVED("approved"), @@ -30,6 +33,7 @@ public enum StatusEnum { } @Override + @JsonValue public String toString() { return value; } @@ -113,6 +117,28 @@ public enum StatusEnum { + @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(); 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 d2647630d4d..9450e25332b 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 @@ -6,13 +6,15 @@ import java.util.*; import io.swagger.client.model.Tag; +import java.util.Objects; import io.swagger.annotations.*; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.*; + @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-11-19T13:52:16.052+01:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-12-22T10:21:47.360+01:00") public class Pet { private Long id = null; @@ -21,6 +23,7 @@ public class Pet { private List photoUrls = new ArrayList(); private List tags = new ArrayList(); + public enum StatusEnum { AVAILABLE("available"), PENDING("pending"), @@ -33,6 +36,7 @@ public enum StatusEnum { } @Override + @JsonValue public String toString() { return value; } @@ -115,6 +119,28 @@ public enum StatusEnum { + @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(); 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 3db8a70749a..bcb1223d98e 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 @@ -3,13 +3,15 @@ package io.swagger.client.model; import io.swagger.client.StringUtil; +import java.util.Objects; import io.swagger.annotations.*; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.*; + @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-11-19T13:52:16.052+01:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-12-22T10:21:47.360+01:00") public class Tag { private Long id = null; @@ -41,6 +43,24 @@ public class Tag { + @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(); 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 a8c9b8d4bcc..9aa1e8bd517 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 @@ -3,13 +3,15 @@ package io.swagger.client.model; import io.swagger.client.StringUtil; +import java.util.Objects; import io.swagger.annotations.*; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.*; + @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-11-19T13:52:16.052+01:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-12-22T10:21:47.360+01:00") public class User { private Long id = null; @@ -120,6 +122,30 @@ public class User { + @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(); 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 3d57f3fa84c..29eae3d017e 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 @@ -38,16 +38,29 @@ public class ApiClientTest { assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T13:49:09+10:00"))); } + @Test + public void testIsJsonMime() { + assertFalse(apiClient.isJsonMime(null)); + assertFalse(apiClient.isJsonMime("")); + assertFalse(apiClient.isJsonMime("text/plain")); + assertFalse(apiClient.isJsonMime("application/xml")); + assertFalse(apiClient.isJsonMime("application/jsonp")); + + assertTrue(apiClient.isJsonMime("application/json")); + assertTrue(apiClient.isJsonMime("application/json; charset=UTF8")); + assertTrue(apiClient.isJsonMime("APPLICATION/JSON")); + } + @Test public void testSelectHeaderAccept() { - String[] accepts = {"APPLICATION/JSON", "APPLICATION/XML"}; + String[] accepts = {"application/json", "application/xml"}; assertEquals("application/json", apiClient.selectHeaderAccept(accepts)); - accepts = new String[]{"application/json", "application/xml"}; - assertEquals("application/json", apiClient.selectHeaderAccept(accepts)); + accepts = new String[]{"APPLICATION/XML", "APPLICATION/JSON"}; + assertEquals("APPLICATION/JSON", apiClient.selectHeaderAccept(accepts)); - accepts = new String[]{"application/xml", "application/json"}; - assertEquals("application/json", apiClient.selectHeaderAccept(accepts)); + accepts = new String[]{"application/xml", "application/json; charset=UTF8"}; + assertEquals("application/json; charset=UTF8", apiClient.selectHeaderAccept(accepts)); accepts = new String[]{"text/plain", "application/xml"}; assertEquals("text/plain,application/xml", apiClient.selectHeaderAccept(accepts)); @@ -58,14 +71,14 @@ public class ApiClientTest { @Test public void testSelectHeaderContentType() { - String[] contentTypes = {"APPLICATION/JSON", "APPLICATION/XML"}; + String[] contentTypes = {"application/json", "application/xml"}; assertEquals("application/json", apiClient.selectHeaderContentType(contentTypes)); - contentTypes = new String[]{"application/json", "application/xml"}; - assertEquals("application/json", apiClient.selectHeaderContentType(contentTypes)); + contentTypes = new String[]{"APPLICATION/JSON", "APPLICATION/XML"}; + assertEquals("APPLICATION/JSON", apiClient.selectHeaderContentType(contentTypes)); - contentTypes = new String[]{"application/xml", "application/json"}; - assertEquals("application/json", apiClient.selectHeaderContentType(contentTypes)); + contentTypes = new String[]{"application/xml", "application/json; charset=UTF8"}; + assertEquals("application/json; charset=UTF8", apiClient.selectHeaderContentType(contentTypes)); contentTypes = new String[]{"text/plain", "application/xml"}; assertEquals("text/plain", apiClient.selectHeaderContentType(contentTypes)); diff --git a/samples/client/petstore/java/default/src/test/java/io/swagger/client/JSONTest.java b/samples/client/petstore/java/default/src/test/java/io/swagger/client/JSONTest.java deleted file mode 100644 index 1250a135078..00000000000 --- a/samples/client/petstore/java/default/src/test/java/io/swagger/client/JSONTest.java +++ /dev/null @@ -1,52 +0,0 @@ -package io.swagger.client; - -import io.swagger.client.model.Order; - -import java.lang.Exception; -import java.text.DateFormat; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.*; -import java.util.TimeZone; - -import org.junit.*; -import static org.junit.Assert.*; - - -public class JSONTest { - JSON json = null; - Order order = null; - - @Before - public void setup() { - json = new JSON(); - order = new Order(); - } - - @Test - public void testDefaultDate() throws Exception { - final DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); - dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); - final String dateStr = "2015-11-07T14:11:05.267Z"; - order.setShipDate(dateFormat.parse(dateStr)); - - String str = json.serialize(order); - TypeRef typeRef = new TypeRef() { }; - Order o = json.deserialize(str, typeRef); - assertEquals(dateStr, dateFormat.format(o.getShipDate())); - } - - @Test - public void testCustomDate() throws Exception { - final DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX"); - dateFormat.setTimeZone(TimeZone.getTimeZone("GMT-2")); - final String dateStr = "2015-11-07T14:11:05-02:00"; - order.setShipDate(dateFormat.parse(dateStr)); - - json.setDateFormat(dateFormat); - String str = json.serialize(order); - TypeRef typeRef = new TypeRef() { }; - Order o = json.deserialize(str, typeRef); - assertEquals(dateStr, dateFormat.format(o.getShipDate())); - } -} \ No newline at end of file diff --git a/samples/client/petstore/java/default/src/test/java/io/swagger/petstore/test/PetApiTest.java b/samples/client/petstore/java/default/src/test/java/io/swagger/petstore/test/PetApiTest.java index 0a8f8a1665d..c0bee9328d5 100644 --- a/samples/client/petstore/java/default/src/test/java/io/swagger/petstore/test/PetApiTest.java +++ b/samples/client/petstore/java/default/src/test/java/io/swagger/petstore/test/PetApiTest.java @@ -174,6 +174,33 @@ public class PetApiTest { api.uploadFile(pet.getId(), "a test file", new File(file.getAbsolutePath())); } + @Test + public void testEqualsAndHashCode() { + Pet pet1 = new Pet(); + Pet pet2 = new Pet(); + assertTrue(pet1.equals(pet2)); + assertTrue(pet2.equals(pet1)); + assertTrue(pet1.hashCode() == pet2.hashCode()); + assertTrue(pet1.equals(pet1)); + assertTrue(pet1.hashCode() == pet1.hashCode()); + + pet2.setName("really-happy"); + pet2.setPhotoUrls(Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"})); + assertFalse(pet1.equals(pet2)); + assertFalse(pet2.equals(pet1)); + assertFalse(pet1.hashCode() == (pet2.hashCode())); + assertTrue(pet2.equals(pet2)); + assertTrue(pet2.hashCode() == pet2.hashCode()); + + pet1.setName("really-happy"); + pet1.setPhotoUrls(Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"})); + assertTrue(pet1.equals(pet2)); + assertTrue(pet2.equals(pet1)); + assertTrue(pet1.hashCode() == pet2.hashCode()); + assertTrue(pet1.equals(pet1)); + assertTrue(pet1.hashCode() == pet1.hashCode()); + } + private Pet createRandomPet() { Pet pet = new Pet(); pet.setId(System.currentTimeMillis()); diff --git a/samples/client/petstore/java/feign/README.md b/samples/client/petstore/java/feign/README.md new file mode 100644 index 00000000000..3ca7abfb557 --- /dev/null +++ b/samples/client/petstore/java/feign/README.md @@ -0,0 +1,43 @@ +# swagger-petstore-feign + +## Requirements + +Building the API client library requires [Maven](https://maven.apache.org/) to be installed. + +## Installation & Usage + +To install the API client library to your local Maven repository, simply execute: + +```shell +mvn install +``` + +To deploy it to a remote Maven repository instead, configure the settings of the repository and execute: + +```shell +mvn deploy +``` + +Refer to the [official documentation](https://maven.apache.org/plugins/maven-deploy-plugin/usage.html) for more information. + +After the client libarary is installed/deployed, you can use it in your Maven project by adding the following to your *pom.xml*: + +```xml + + io.swagger + swagger-petstore-feign + 1.0.0 + compile + + +``` + +## Recommendation + +It's recommended to create an instance of `ApiClient` per thread in a multithreaded environment to avoid any potential issue. + +## Author + +apiteam@swagger.io + + diff --git a/samples/client/petstore/java/feign/build.gradle b/samples/client/petstore/java/feign/build.gradle new file mode 100644 index 00000000000..0bfcfbec71f --- /dev/null +++ b/samples/client/petstore/java/feign/build.gradle @@ -0,0 +1,113 @@ +group = 'io.swagger' +version = '1.0.0' + +buildscript { + repositories { + jcenter() + } + dependencies { + classpath 'com.android.tools.build:gradle:1.2.2' + classpath 'com.github.dcendents:android-maven-plugin:1.2' + } +} + +repositories { + jcenter() +} + + +if(hasProperty('target') && target == 'android') { + + apply plugin: 'com.android.library' + apply plugin: 'com.github.dcendents.android-maven' + + android { + compileSdkVersion 22 + buildToolsVersion '22.0.0' + defaultConfig { + minSdkVersion 14 + targetSdkVersion 22 + } + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_7 + targetCompatibility JavaVersion.VERSION_1_7 + } + + // Rename the aar correctly + libraryVariants.all { variant -> + variant.outputs.each { output -> + def outputFile = output.outputFile + if (outputFile != null && outputFile.name.endsWith('.aar')) { + def fileName = "${project.name}-${variant.baseName}-${version}.aar" + output.outputFile = new File(outputFile.parent, fileName) + } + } + } + + dependencies { + provided 'javax.annotation:jsr250-api:1.0' + } + } + + afterEvaluate { + android.libraryVariants.all { variant -> + def task = project.tasks.create "jar${variant.name.capitalize()}", Jar + task.description = "Create jar artifact for ${variant.name}" + task.dependsOn variant.javaCompile + task.from variant.javaCompile.destinationDir + task.destinationDir = project.file("${project.buildDir}/outputs/jar") + task.archiveName = "${project.name}-${variant.baseName}-${version}.jar" + artifacts.add('archives', task); + } + } + + task sourcesJar(type: Jar) { + from android.sourceSets.main.java.srcDirs + classifier = 'sources' + } + + artifacts { + archives sourcesJar + } + +} else { + + apply plugin: 'java' + apply plugin: 'maven' + + sourceCompatibility = JavaVersion.VERSION_1_7 + targetCompatibility = JavaVersion.VERSION_1_7 + + install { + repositories.mavenInstaller { + pom.artifactId = 'swagger-petstore-feign' + } + } + + task execute(type:JavaExec) { + main = System.getProperty('mainClass') + classpath = sourceSets.main.runtimeClasspath + } +} + +ext { + swagger_annotations_version = "1.5.0" + jackson_version = "2.6.3" + feign_version = "8.1.1" + jodatime_version = "2.5" + junit_version = "4.12" +} + +dependencies { + compile "io.swagger:swagger-annotations:$swagger_annotations_version" + compile "com.netflix.feign:feign-core:$feign_version" + compile "com.netflix.feign:feign-jackson:$feign_version" + compile "com.netflix.feign:feign-slf4j:$feign_version" + compile "com.fasterxml.jackson.core:jackson-core:$jackson_version" + compile "com.fasterxml.jackson.core:jackson-annotations:$jackson_version" + compile "com.fasterxml.jackson.core:jackson-databind:$jackson_version" + compile "com.fasterxml.jackson.datatype:jackson-datatype-joda:2.1.5" + compile "joda-time:joda-time:$jodatime_version" + compile "com.brsanthu:migbase64:2.2" + testCompile "junit:junit:$junit_version" +} diff --git a/samples/client/petstore/java/feign/gradle.properties b/samples/client/petstore/java/feign/gradle.properties new file mode 100644 index 00000000000..05644f0754a --- /dev/null +++ b/samples/client/petstore/java/feign/gradle.properties @@ -0,0 +1,2 @@ +# Uncomment to build for Android +#target = android \ No newline at end of file diff --git a/samples/client/petstore/java/feign/pom.xml b/samples/client/petstore/java/feign/pom.xml new file mode 100644 index 00000000000..5f7e9551862 --- /dev/null +++ b/samples/client/petstore/java/feign/pom.xml @@ -0,0 +1,183 @@ + + 4.0.0 + io.swagger + swagger-petstore-feign + jar + swagger-petstore-feign + 1.0.0 + + scm:git:git@github.com:swagger-api/swagger-mustache.git + scm:git:git@github.com:swagger-api/swagger-codegen.git + https://github.com/swagger-api/swagger-codegen + + + 2.2.0 + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.12 + + + + loggerPath + conf/log4j.properties + + + -Xms512m -Xmx1500m + methods + pertest + + + + maven-dependency-plugin + + + package + + copy-dependencies + + + ${project.build.directory}/lib + + + + + + + + org.apache.maven.plugins + maven-jar-plugin + 2.2 + + + + jar + test-jar + + + + + + + + + org.codehaus.mojo + build-helper-maven-plugin + + + add_sources + generate-sources + + add-source + + + + src/main/java + + + + + add_test_sources + generate-test-sources + + add-test-source + + + + src/test/java + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 2.3.2 + + 1.6 + 1.6 + + + + + + + io.swagger + swagger-annotations + ${swagger-annotations-version} + + + + + com.netflix.feign + feign-core + ${feign-version} + + + com.netflix.feign + feign-jackson + ${feign-version} + + + com.netflix.feign + feign-slf4j + ${feign-version} + + + + + com.fasterxml.jackson.core + jackson-core + ${jackson-version} + + + com.fasterxml.jackson.core + jackson-annotations + ${jackson-version} + + + com.fasterxml.jackson.core + jackson-databind + ${jackson-version} + + + com.fasterxml.jackson.datatype + jackson-datatype-joda + 2.1.5 + + + joda-time + joda-time + ${jodatime-version} + + + + + com.brsanthu + migbase64 + 2.2 + + + + + junit + junit + ${junit-version} + test + + + + 1.5.0 + 8.1.1 + 2.6.3 + 2.5 + 4.12 + 1.0.0 + + diff --git a/samples/client/petstore/java/feign/settings.gradle b/samples/client/petstore/java/feign/settings.gradle new file mode 100644 index 00000000000..a25109c126e --- /dev/null +++ b/samples/client/petstore/java/feign/settings.gradle @@ -0,0 +1 @@ +rootProject.name = "swagger-petstore-feign" \ No newline at end of file diff --git a/samples/client/petstore/java/feign/src/main/AndroidManifest.xml b/samples/client/petstore/java/feign/src/main/AndroidManifest.xml new file mode 100644 index 00000000000..465dcb520c4 --- /dev/null +++ b/samples/client/petstore/java/feign/src/main/AndroidManifest.xml @@ -0,0 +1,3 @@ + + + diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/ApiClient.java new file mode 100644 index 00000000000..fae831971e9 --- /dev/null +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/ApiClient.java @@ -0,0 +1,86 @@ +package io.swagger.client; + +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; +import feign.Feign; +import feign.jackson.JacksonDecoder; +import feign.jackson.JacksonEncoder; +import feign.slf4j.Slf4jLogger; + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-12-10T16:26:30.730+08:00") +public class ApiClient { + public interface Api {} + + private ObjectMapper objectMapper; + private String basePath = "http://petstore.swagger.io/v2"; + + public ApiClient() { + objectMapper = createObjectMapper(); + } + + public String getBasePath() { + return basePath; + } + + public ApiClient setBasePath(String basePath) { + this.basePath = basePath; + return this; + } + + private ObjectMapper createObjectMapper() { + ObjectMapper objectMapper = new ObjectMapper(); + objectMapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING); + objectMapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING); + return objectMapper; + } + + /** + * Creates a feign client for given API interface. + * + * Usage: + * ApiClient apiClient = new ApiClient(); + * apiClient.setBasePath("http://localhost:8080"); + * XYZApi api = apiClient.buildClient(XYZApi.class); + * XYZResponse response = api.someMethod(...); + */ + public T buildClient(Class clientClass) { + return Feign.builder() + .encoder(new FormAwareEncoder(new JacksonEncoder(objectMapper))) + .decoder(new JacksonDecoder(objectMapper)) +// enable for basic auth: +// .requestInterceptor(new feign.auth.BasicAuthRequestInterceptor(username, password)) + .logger(new Slf4jLogger()) + .target(clientClass, basePath); + } + + /** + * Select the Accept header's value from the given accepts array: + * if JSON exists in the given array, use it; + * otherwise use all of them (joining into a string) + * + * @param accepts The accepts array to select from + * @return The Accept header to use. If the given array is empty, + * null will be returned (not to set the Accept header explicitly). + */ + public String selectHeaderAccept(String[] accepts) { + if (accepts.length == 0) return null; + if (StringUtil.containsIgnoreCase(accepts, "application/json")) return "application/json"; + return StringUtil.join(accepts, ","); + } + + /** + * Select the Content-Type header's value from the given array: + * if JSON exists in the given array, use it; + * otherwise use the first one of the array. + * + * @param contentTypes The Content-Type array to select from + * @return The Content-Type header to use. If the given array is empty, + * JSON will be used. + */ + public String selectHeaderContentType(String[] contentTypes) { + if (contentTypes.length == 0) return "application/json"; + if (StringUtil.containsIgnoreCase(contentTypes, "application/json")) return "application/json"; + return contentTypes[0]; + } +} 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 new file mode 100644 index 00000000000..e9ee05b16a4 --- /dev/null +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/FormAwareEncoder.java @@ -0,0 +1,197 @@ +package io.swagger.client; + +import java.io.*; +import java.lang.reflect.Type; +import java.net.URLEncoder; +import java.net.URLConnection; +import java.nio.charset.Charset; +import java.util.*; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; + +import feign.codec.EncodeException; +import feign.codec.Encoder; +import feign.RequestTemplate; + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-12-10T16:26:30.730+08:00") +public class FormAwareEncoder implements Encoder { + public static final String UTF_8 = "utf-8"; + private static final String LINE_FEED = "\r\n"; + private static final String TWO_DASH = "--"; + private static final String BOUNDARY = "----------------314159265358979323846"; + + private byte[] lineFeedBytes; + private byte[] boundaryBytes; + private byte[] twoDashBytes; + private byte[] atBytes; + private byte[] eqBytes; + + private final Encoder delegate; + private final DateFormat dateFormat; + + public FormAwareEncoder(Encoder delegate) { + this.delegate = delegate; + // Use RFC3339 format for date and datetime. + // See http://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14 + this.dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); + + // Use UTC as the default time zone. + this.dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); + try { + this.lineFeedBytes = LINE_FEED.getBytes(UTF_8); + this.boundaryBytes = BOUNDARY.getBytes(UTF_8); + this.twoDashBytes = TWO_DASH.getBytes(UTF_8); + this.atBytes = "&".getBytes(UTF_8); + this.eqBytes = "=".getBytes(UTF_8); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + } + } + + public void encode(Object object, Type bodyType, RequestTemplate template) throws EncodeException { + if (object instanceof Map) { + try { + encodeFormParams(template, (Map) object); + } catch (IOException e) { + throw new EncodeException("Failed to create request", e); + } + } else { + delegate.encode(object, bodyType, template); + } + } + + private void encodeFormParams(RequestTemplate template, Map formParams) throws IOException { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + + boolean isMultiPart = isMultiPart(formParams); + boolean isFirstField = true; + for (Map.Entry param : formParams.entrySet()) { + String keyStr = param.getKey(); + if (param.getValue() instanceof File) { + addFilePart(baos, keyStr, (File) param.getValue()); + } else { + String valueStr = parameterToString(param.getValue()); + if (isMultiPart) { + addMultiPartFormField(baos, keyStr, valueStr); + } else { + addEncodedFormField(baos, keyStr, valueStr, isFirstField); + isFirstField = false; + } + } + } + + if (isMultiPart) { + baos.write(lineFeedBytes); + baos.write(twoDashBytes); + baos.write(boundaryBytes); + baos.write(twoDashBytes); + baos.write(lineFeedBytes); + } + + String contentType = isMultiPart ? "multipart/form-data; boundary=" + BOUNDARY : "application/x-www-form-urlencoded"; + template.header("Content-type"); + template.header("Content-type", contentType); + template.header("MIME-Version", "1.0"); + template.body(baos.toByteArray(), Charset.forName(UTF_8)); + } + + /* + * Currently only supports text files + */ + private void addFilePart(ByteArrayOutputStream baos, String fieldName, File uploadFile) throws IOException { + String fileName = uploadFile.getName(); + baos.write(twoDashBytes); + baos.write(boundaryBytes); + baos.write(lineFeedBytes); + + String contentDisposition = "Content-Disposition: form-data; name=\"" + fieldName + + "\"; filename=\"" + fileName + "\""; + baos.write(contentDisposition.getBytes(UTF_8)); + baos.write(lineFeedBytes); + String contentType = "Content-Type: " + URLConnection.guessContentTypeFromName(fileName); + baos.write(contentType.getBytes(UTF_8)); + baos.write(lineFeedBytes); + baos.write(lineFeedBytes); + + BufferedReader reader = new BufferedReader(new FileReader(uploadFile)); + InputStream input = new FileInputStream(uploadFile); + byte[] bytes = new byte[4096]; + int len = bytes.length; + while ((len = input.read(bytes)) != -1) { + baos.write(bytes, 0, len); + baos.write(lineFeedBytes); + } + + baos.write(lineFeedBytes); + } + + private void addEncodedFormField(ByteArrayOutputStream baos, String name, String value, boolean isFirstField) throws IOException { + if (!isFirstField) { + baos.write(atBytes); + } + + String encodedName = URLEncoder.encode(name, UTF_8); + String encodedValue = URLEncoder.encode(value, UTF_8); + baos.write(encodedName.getBytes(UTF_8)); + baos.write("=".getBytes(UTF_8)); + baos.write(encodedValue.getBytes(UTF_8)); + } + + private void addMultiPartFormField(ByteArrayOutputStream baos, String name, String value) throws IOException { + baos.write(twoDashBytes); + baos.write(boundaryBytes); + baos.write(lineFeedBytes); + + String contentDisposition = "Content-Disposition: form-data; name=\"" + name + "\""; + String contentType = "Content-Type: text/plain; charset=utf-8"; + + baos.write(contentDisposition.getBytes(UTF_8)); + baos.write(lineFeedBytes); + baos.write(contentType.getBytes(UTF_8)); + baos.write(lineFeedBytes); + baos.write(lineFeedBytes); + baos.write(value.getBytes(UTF_8)); + baos.write(lineFeedBytes); + } + + private boolean isMultiPart(Map formParams) { + boolean isMultiPart = false; + for (Map.Entry entry : formParams.entrySet()) { + if (entry.getValue() instanceof File) { + isMultiPart = true; + break; + } + } + return isMultiPart; + } + + /** + * Format the given parameter object into string. + */ + public String parameterToString(Object param) { + if (param == null) { + return ""; + } else if (param instanceof Date) { + return formatDate((Date) param); + } else if (param instanceof Collection) { + StringBuilder b = new StringBuilder(); + for(Object o : (Collection)param) { + if(b.length() > 0) { + b.append(","); + } + b.append(String.valueOf(o)); + } + return b.toString(); + } else { + return String.valueOf(param); + } + } + + /** + * Format the given Date object into string. + */ + public String formatDate(Date date) { + return dateFormat.format(date); + } +} 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 new file mode 100644 index 00000000000..c843634389d --- /dev/null +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/StringUtil.java @@ -0,0 +1,51 @@ +package io.swagger.client; + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-12-10T16:26:30.730+08:00") +public class StringUtil { + /** + * Check if the given array contains the given value (with case-insensitive comparison). + * + * @param array The array + * @param value The value to search + * @return true if the array contains the value + */ + public static boolean containsIgnoreCase(String[] array, String value) { + for (String str : array) { + if (value == null && str == null) return true; + if (value != null && value.equalsIgnoreCase(str)) return true; + } + return false; + } + + /** + * Join an array of strings with the given separator. + *

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

+ * + * @param array The array of strings + * @param separator The separator + * @return the resulting string + */ + public static String join(String[] array, String separator) { + int len = array.length; + if (len == 0) return ""; + + StringBuilder out = new StringBuilder(); + out.append(array[0]); + for (int i = 1; i < len; i++) { + out.append(separator).append(array[i]); + } + return out.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + public static String toIndentedString(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/api/PetApi.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/PetApi.java new file mode 100644 index 00000000000..cdf1c4d75d3 --- /dev/null +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/PetApi.java @@ -0,0 +1,125 @@ +package io.swagger.client.api; + +import io.swagger.client.ApiClient; + +import io.swagger.client.model.Pet; +import java.io.File; + +import java.util.*; +import feign.*; + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-12-10T16:26:30.730+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 + * @return void + */ + @RequestLine("POST /pet") + @Headers({ + "Content-type: application/json", + "Accepts: application/json", + }) + void addPet(Pet body); + + /** + * 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 + * @return List + */ + @RequestLine("GET /pet/findByStatus?status={status}") + @Headers({ + "Content-type: application/json", + "Accepts: application/json", + }) + List findPetsByStatus(@Param("status") List status); + + /** + * 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 + */ + @RequestLine("GET /pet/findByTags?tags={tags}") + @Headers({ + "Content-type: application/json", + "Accepts: application/json", + }) + List findPetsByTags(@Param("tags") List tags); + + /** + * 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 + */ + @RequestLine("GET /pet/{petId}") + @Headers({ + "Content-type: application/json", + "Accepts: application/json", + }) + 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); + +} 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 new file mode 100644 index 00000000000..3983ee7d046 --- /dev/null +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/StoreApi.java @@ -0,0 +1,66 @@ +package io.swagger.client.api; + +import io.swagger.client.ApiClient; + +import java.util.Map; +import io.swagger.client.model.Order; + +import java.util.*; +import feign.*; + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-12-10T16:26:30.730+08:00") +public interface StoreApi extends ApiClient.Api { + + + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + * @return Map + */ + @RequestLine("GET /store/inventory") + @Headers({ + "Content-type: application/json", + "Accepts: application/json", + }) + Map getInventory(); + + /** + * 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 + * @return Order + */ + @RequestLine("GET /store/order/{orderId}") + @Headers({ + "Content-type: application/json", + "Accepts: application/json", + }) + 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 + */ + @RequestLine("DELETE /store/order/{orderId}") + @Headers({ + "Content-type: application/json", + "Accepts: application/json", + }) + void deleteOrder(@Param("orderId") String orderId); + +} 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 new file mode 100644 index 00000000000..95d4ade78d6 --- /dev/null +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/UserApi.java @@ -0,0 +1,120 @@ +package io.swagger.client.api; + +import io.swagger.client.ApiClient; + +import io.swagger.client.model.User; +import java.util.*; + +import java.util.*; +import feign.*; + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-12-10T16:26:30.730+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 + * @return void + */ + @RequestLine("POST /user") + @Headers({ + "Content-type: application/json", + "Accepts: application/json", + }) + void createUser(User body); + + /** + * Creates list of users with given input array + * + * @param body List of user object + * @return void + */ + @RequestLine("POST /user/createWithArray") + @Headers({ + "Content-type: application/json", + "Accepts: application/json", + }) + void createUsersWithArrayInput(List body); + + /** + * Creates list of users with given input array + * + * @param body List of user object + * @return void + */ + @RequestLine("POST /user/createWithList") + @Headers({ + "Content-type: application/json", + "Accepts: application/json", + }) + void createUsersWithListInput(List body); + + /** + * Logs user into the system + * + * @param username The user name for login + * @param password The password for login in clear text + * @return String + */ + @RequestLine("GET /user/login?username={username}&password={password}") + @Headers({ + "Content-type: application/json", + "Accepts: application/json", + }) + String loginUser(@Param("username") String username, @Param("password") String password); + + /** + * Logs out current logged in user session + * + * @return void + */ + @RequestLine("GET /user/logout") + @Headers({ + "Content-type: application/json", + "Accepts: application/json", + }) + 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 + * @return void + */ + @RequestLine("PUT /user/{username}") + @Headers({ + "Content-type: application/json", + "Accepts: application/json", + }) + 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/ApiResponse.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ApiResponse.java new file mode 100644 index 00000000000..ab98bf61e89 --- /dev/null +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ApiResponse.java @@ -0,0 +1,92 @@ +package io.swagger.client.model; + +import io.swagger.client.StringUtil; + + + +import java.util.Objects; + +import io.swagger.annotations.*; +import com.fasterxml.jackson.annotation.JsonProperty; + + + +@ApiModel(description = "") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-12-09T22:59:22.180-05:00") +public class ApiResponse { + + private Integer code = null; + private String type = null; + private String message = null; + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("code") + public Integer getCode() { + return code; + } + public void setCode(Integer code) { + this.code = code; + } + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("type") + public String getType() { + return type; + } + public void setType(String type) { + this.type = type; + } + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("message") + public String getMessage() { + return message; + } + public void setMessage(String message) { + this.message = message; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + 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(StringUtil.toIndentedString(code)).append("\n"); + sb.append(" type: ").append(StringUtil.toIndentedString(type)).append("\n"); + sb.append(" message: ").append(StringUtil.toIndentedString(message)).append("\n"); + sb.append("}"); + return sb.toString(); + } +} + + diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Category.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Category.java new file mode 100644 index 00000000000..463da28c638 --- /dev/null +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Category.java @@ -0,0 +1,73 @@ +package io.swagger.client.model; + +import io.swagger.client.StringUtil; + + +import java.util.Objects; + +import io.swagger.annotations.*; +import com.fasterxml.jackson.annotation.*; + + +@ApiModel(description = "") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-12-10T16:26:30.730+08:00") +public class Category { + + private Long id = null; + private String name = null; + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("id") + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("name") + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Category category = (Category) o; + return Objects.equals(id, category.id) && + Objects.equals(name, category.name); + } + + @Override + public int hashCode() { + return Objects.hash(id, name); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Category {\n"); + + sb.append(" id: ").append(StringUtil.toIndentedString(id)).append("\n"); + sb.append(" name: ").append(StringUtil.toIndentedString(name)).append("\n"); + sb.append("}"); + return sb.toString(); + } +} diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Order.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Order.java new file mode 100644 index 00000000000..9b490767759 --- /dev/null +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Order.java @@ -0,0 +1,155 @@ +package io.swagger.client.model; + +import io.swagger.client.StringUtil; +import java.util.Date; + + +import java.util.Objects; + +import io.swagger.annotations.*; +import com.fasterxml.jackson.annotation.*; + + +@ApiModel(description = "") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-12-10T16:26:30.730+08:00") +public class Order { + + private Long id = null; + private Long petId = null; + private Integer quantity = null; + private Date shipDate = null; + + +public enum StatusEnum { + PLACED("placed"), + APPROVED("approved"), + DELIVERED("delivered"); + + private String value; + + StatusEnum(String value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return value; + } +} + + private StatusEnum status = null; + private Boolean complete = null; + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("id") + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("petId") + public Long getPetId() { + return petId; + } + public void setPetId(Long petId) { + this.petId = petId; + } + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("quantity") + public Integer getQuantity() { + return quantity; + } + public void setQuantity(Integer quantity) { + this.quantity = quantity; + } + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("shipDate") + public Date getShipDate() { + return shipDate; + } + public void setShipDate(Date shipDate) { + this.shipDate = shipDate; + } + + + /** + * Order Status + **/ + @ApiModelProperty(value = "Order Status") + @JsonProperty("status") + public StatusEnum getStatus() { + return status; + } + public void setStatus(StatusEnum status) { + this.status = status; + } + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("complete") + public Boolean getComplete() { + return complete; + } + public void setComplete(Boolean complete) { + this.complete = complete; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Order order = (Order) o; + return Objects.equals(id, order.id) && + Objects.equals(petId, order.petId) && + Objects.equals(quantity, order.quantity) && + Objects.equals(shipDate, order.shipDate) && + Objects.equals(status, order.status) && + Objects.equals(complete, order.complete); + } + + @Override + public int hashCode() { + return Objects.hash(id, petId, quantity, shipDate, status, complete); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Order {\n"); + + sb.append(" id: ").append(StringUtil.toIndentedString(id)).append("\n"); + sb.append(" petId: ").append(StringUtil.toIndentedString(petId)).append("\n"); + sb.append(" quantity: ").append(StringUtil.toIndentedString(quantity)).append("\n"); + sb.append(" shipDate: ").append(StringUtil.toIndentedString(shipDate)).append("\n"); + sb.append(" status: ").append(StringUtil.toIndentedString(status)).append("\n"); + sb.append(" complete: ").append(StringUtil.toIndentedString(complete)).append("\n"); + sb.append("}"); + return sb.toString(); + } +} 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 new file mode 100644 index 00000000000..471bbe34b00 --- /dev/null +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Pet.java @@ -0,0 +1,157 @@ +package io.swagger.client.model; + +import io.swagger.client.StringUtil; +import io.swagger.client.model.Category; +import io.swagger.client.model.Tag; +import java.util.*; + + +import java.util.Objects; + +import io.swagger.annotations.*; +import com.fasterxml.jackson.annotation.*; + + +@ApiModel(description = "") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-12-10T16:26:30.730+08:00") +public class Pet { + + private Long id = null; + private Category category = null; + private String name = null; + private List photoUrls = new ArrayList(); + private List tags = new ArrayList(); + + +public enum StatusEnum { + AVAILABLE("available"), + PENDING("pending"), + SOLD("sold"); + + private String value; + + StatusEnum(String value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return value; + } +} + + private StatusEnum status = null; + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("id") + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("category") + public Category getCategory() { + return category; + } + public void setCategory(Category category) { + this.category = category; + } + + + /** + **/ + @ApiModelProperty(required = true, value = "") + @JsonProperty("name") + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + + + /** + **/ + @ApiModelProperty(required = true, value = "") + @JsonProperty("photoUrls") + public List getPhotoUrls() { + return photoUrls; + } + public void setPhotoUrls(List photoUrls) { + this.photoUrls = photoUrls; + } + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("tags") + public List getTags() { + return tags; + } + public void setTags(List tags) { + this.tags = tags; + } + + + /** + * pet status in the store + **/ + @ApiModelProperty(value = "pet status in the store") + @JsonProperty("status") + public StatusEnum getStatus() { + return status; + } + public void setStatus(StatusEnum status) { + this.status = status; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Pet pet = (Pet) o; + return Objects.equals(id, pet.id) && + Objects.equals(category, pet.category) && + Objects.equals(name, pet.name) && + Objects.equals(photoUrls, pet.photoUrls) && + Objects.equals(tags, pet.tags) && + Objects.equals(status, pet.status); + } + + @Override + public int hashCode() { + return Objects.hash(id, category, name, photoUrls, tags, status); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Pet {\n"); + + sb.append(" id: ").append(StringUtil.toIndentedString(id)).append("\n"); + sb.append(" category: ").append(StringUtil.toIndentedString(category)).append("\n"); + sb.append(" name: ").append(StringUtil.toIndentedString(name)).append("\n"); + sb.append(" photoUrls: ").append(StringUtil.toIndentedString(photoUrls)).append("\n"); + sb.append(" tags: ").append(StringUtil.toIndentedString(tags)).append("\n"); + sb.append(" status: ").append(StringUtil.toIndentedString(status)).append("\n"); + sb.append("}"); + return sb.toString(); + } +} 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 new file mode 100644 index 00000000000..02b5b85be40 --- /dev/null +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Tag.java @@ -0,0 +1,73 @@ +package io.swagger.client.model; + +import io.swagger.client.StringUtil; + + +import java.util.Objects; + +import io.swagger.annotations.*; +import com.fasterxml.jackson.annotation.*; + + +@ApiModel(description = "") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-12-10T16:26:30.730+08:00") +public class Tag { + + private Long id = null; + private String name = null; + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("id") + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("name") + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Tag tag = (Tag) o; + return Objects.equals(id, tag.id) && + Objects.equals(name, tag.name); + } + + @Override + public int hashCode() { + return Objects.hash(id, name); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Tag {\n"); + + sb.append(" id: ").append(StringUtil.toIndentedString(id)).append("\n"); + sb.append(" name: ").append(StringUtil.toIndentedString(name)).append("\n"); + sb.append("}"); + return sb.toString(); + } +} 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 new file mode 100644 index 00000000000..4d072f67d47 --- /dev/null +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/User.java @@ -0,0 +1,164 @@ +package io.swagger.client.model; + +import io.swagger.client.StringUtil; + + +import java.util.Objects; + +import io.swagger.annotations.*; +import com.fasterxml.jackson.annotation.*; + + +@ApiModel(description = "") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-12-10T16:26:30.730+08:00") +public class User { + + private Long id = null; + private String username = null; + private String firstName = null; + private String lastName = null; + private String email = null; + private String password = null; + private String phone = null; + private Integer userStatus = null; + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("id") + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("username") + public String getUsername() { + return username; + } + public void setUsername(String username) { + this.username = username; + } + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("firstName") + public String getFirstName() { + return firstName; + } + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("lastName") + public String getLastName() { + return lastName; + } + public void setLastName(String lastName) { + this.lastName = lastName; + } + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("email") + public String getEmail() { + return email; + } + public void setEmail(String email) { + this.email = email; + } + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("password") + public String getPassword() { + return password; + } + public void setPassword(String password) { + this.password = password; + } + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("phone") + public String getPhone() { + return phone; + } + public void setPhone(String phone) { + this.phone = phone; + } + + + /** + * User Status + **/ + @ApiModelProperty(value = "User Status") + @JsonProperty("userStatus") + public Integer getUserStatus() { + return userStatus; + } + public void setUserStatus(Integer userStatus) { + this.userStatus = userStatus; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + User user = (User) o; + return Objects.equals(id, user.id) && + Objects.equals(username, user.username) && + Objects.equals(firstName, user.firstName) && + Objects.equals(lastName, user.lastName) && + Objects.equals(email, user.email) && + Objects.equals(password, user.password) && + Objects.equals(phone, user.phone) && + Objects.equals(userStatus, user.userStatus); + } + + @Override + public int hashCode() { + return Objects.hash(id, username, firstName, lastName, email, password, phone, userStatus); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class User {\n"); + + sb.append(" id: ").append(StringUtil.toIndentedString(id)).append("\n"); + sb.append(" username: ").append(StringUtil.toIndentedString(username)).append("\n"); + sb.append(" firstName: ").append(StringUtil.toIndentedString(firstName)).append("\n"); + sb.append(" lastName: ").append(StringUtil.toIndentedString(lastName)).append("\n"); + sb.append(" email: ").append(StringUtil.toIndentedString(email)).append("\n"); + sb.append(" password: ").append(StringUtil.toIndentedString(password)).append("\n"); + sb.append(" phone: ").append(StringUtil.toIndentedString(phone)).append("\n"); + sb.append(" userStatus: ").append(StringUtil.toIndentedString(userStatus)).append("\n"); + sb.append("}"); + return sb.toString(); + } +} diff --git a/samples/client/petstore/java/feign/src/test/java/io/swagger/client/StringUtilTest.java b/samples/client/petstore/java/feign/src/test/java/io/swagger/client/StringUtilTest.java new file mode 100644 index 00000000000..c93908b8482 --- /dev/null +++ b/samples/client/petstore/java/feign/src/test/java/io/swagger/client/StringUtilTest.java @@ -0,0 +1,32 @@ +package io.swagger.client; + +import org.junit.*; +import static org.junit.Assert.*; + +public class StringUtilTest { + @Test + public void testContainsIgnoreCase() { + assertTrue(StringUtil.containsIgnoreCase(new String[]{"abc"}, "abc")); + assertTrue(StringUtil.containsIgnoreCase(new String[]{"abc"}, "ABC")); + assertTrue(StringUtil.containsIgnoreCase(new String[]{"ABC"}, "abc")); + assertTrue(StringUtil.containsIgnoreCase(new String[]{null, "abc"}, "ABC")); + assertTrue(StringUtil.containsIgnoreCase(new String[]{null, "abc"}, null)); + + assertFalse(StringUtil.containsIgnoreCase(new String[]{"abc"}, "def")); + assertFalse(StringUtil.containsIgnoreCase(new String[]{}, "ABC")); + assertFalse(StringUtil.containsIgnoreCase(new String[]{}, null)); + } + + @Test + public void testJoin() { + String[] array = {"aa", "bb", "cc"}; + assertEquals("aa,bb,cc", StringUtil.join(array, ",")); + assertEquals("aa, bb, cc", StringUtil.join(array, ", ")); + assertEquals("aabbcc", StringUtil.join(array, "")); + assertEquals("aa bb cc", StringUtil.join(array, " ")); + assertEquals("aa\nbb\ncc", StringUtil.join(array, "\n")); + + assertEquals("", StringUtil.join(new String[]{}, ",")); + assertEquals("abc", StringUtil.join(new String[]{"abc"}, ",")); + } +} \ No newline at end of file diff --git a/samples/client/petstore/java/feign/src/test/java/io/swagger/petstore/test/PetApiTest.java b/samples/client/petstore/java/feign/src/test/java/io/swagger/petstore/test/PetApiTest.java new file mode 100644 index 00000000000..aef8ab25610 --- /dev/null +++ b/samples/client/petstore/java/feign/src/test/java/io/swagger/petstore/test/PetApiTest.java @@ -0,0 +1,199 @@ +package io.swagger.petstore.test; + +import io.swagger.client.ApiClient; + +import io.swagger.client.api.*; +import io.swagger.client.model.*; + +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileWriter; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import org.junit.*; +import static org.junit.Assert.*; + +public class PetApiTest { + ApiClient apiClient; + PetApi api; + + @Before + public void setup() { + apiClient = new ApiClient(); + api = apiClient.buildClient(PetApi.class); + } + + @Test + public void testApiClient() { + // the default api client is used + assertEquals("http://petstore.swagger.io/v2", apiClient.getBasePath()); + + ApiClient newClient = new ApiClient(); + newClient.setBasePath("http://example.com"); + + assertEquals("http://example.com", newClient.getBasePath()); + } + + @Test + public void testCreateAndGetPet() throws Exception { + Pet pet = createRandomPet(); + api.addPet(pet); + + Pet fetched = api.getPetById(pet.getId()); + assertNotNull(fetched); + assertEquals(pet.getId(), fetched.getId()); + assertNotNull(fetched.getCategory()); + assertEquals(fetched.getCategory().getName(), pet.getCategory().getName()); + } + + @Test + public void testUpdatePet() throws Exception { + Pet pet = createRandomPet(); + pet.setName("programmer"); + + api.updatePet(pet); + + Pet fetched = api.getPetById(pet.getId()); + assertNotNull(fetched); + assertEquals(pet.getId(), fetched.getId()); + assertNotNull(fetched.getCategory()); + assertEquals(fetched.getCategory().getName(), pet.getCategory().getName()); + } + + @Test + public void testFindPetsByStatus() throws Exception { + Pet pet = createRandomPet(); + pet.setName("programmer"); + pet.setStatus(Pet.StatusEnum.AVAILABLE); + + api.updatePet(pet); + + List pets = api.findPetsByStatus(Arrays.asList(new String[]{"available"})); + assertNotNull(pets); + + boolean found = false; + for (Pet fetched : pets) { + if (fetched.getId().equals(pet.getId())) { + found = true; + break; + } + } + + assertTrue(found); + } + + @Test + public void testFindPetsByTags() throws Exception { + Pet pet = createRandomPet(); + pet.setName("monster"); + pet.setStatus(Pet.StatusEnum.AVAILABLE); + + List tags = new ArrayList(); + Tag tag1 = new Tag(); + tag1.setName("friendly"); + tags.add(tag1); + pet.setTags(tags); + + api.updatePet(pet); + + List pets = api.findPetsByTags(Arrays.asList(new String[]{"friendly"})); + assertNotNull(pets); + + boolean found = false; + for (Pet fetched : pets) { + if (fetched.getId().equals(pet.getId())) { + found = true; + break; + } + } + assertTrue(found); + } + + @Test + public void testUpdatePetWithForm() throws Exception { + Pet pet = createRandomPet(); + pet.setName("frank"); + api.addPet(pet); + + Pet fetched = api.getPetById(pet.getId()); + + api.updatePetWithForm(fetched.getId().toString(), "furt", null); + Pet updated = api.getPetById(fetched.getId()); + + assertEquals(updated.getName(), "furt"); + } + + @Test + public void testDeletePet() throws Exception { + Pet pet = createRandomPet(); + api.addPet(pet); + + Pet fetched = api.getPetById(pet.getId()); + api.deletePet(fetched.getId(), null); + + try { + fetched = api.getPetById(fetched.getId()); + fail("expected an error"); + } catch (Exception e) { +// assertEquals(404, e.getCode()); + } + } + + @Test + public void testUploadFile() throws Exception { + Pet pet = createRandomPet(); + api.addPet(pet); + + File file = new File("hello.txt"); + BufferedWriter writer = new BufferedWriter(new FileWriter(file)); + writer.write("Hello world!"); + writer.close(); + + api.uploadFile(pet.getId(), "a test file", new File(file.getAbsolutePath())); + } + + @Test + public void testEqualsAndHashCode() { + Pet pet1 = new Pet(); + Pet pet2 = new Pet(); + assertTrue(pet1.equals(pet2)); + assertTrue(pet2.equals(pet1)); + assertTrue(pet1.hashCode() == pet2.hashCode()); + assertTrue(pet1.equals(pet1)); + assertTrue(pet1.hashCode() == pet1.hashCode()); + + pet2.setName("really-happy"); + pet2.setPhotoUrls(Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"})); + assertFalse(pet1.equals(pet2)); + assertFalse(pet2.equals(pet1)); + assertFalse(pet1.hashCode() == (pet2.hashCode())); + assertTrue(pet2.equals(pet2)); + assertTrue(pet2.hashCode() == pet2.hashCode()); + + pet1.setName("really-happy"); + pet1.setPhotoUrls(Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"})); + assertTrue(pet1.equals(pet2)); + assertTrue(pet2.equals(pet1)); + assertTrue(pet1.hashCode() == pet2.hashCode()); + assertTrue(pet1.equals(pet1)); + assertTrue(pet1.hashCode() == pet1.hashCode()); + } + + private Pet createRandomPet() { + Pet pet = new Pet(); + pet.setId(System.currentTimeMillis()); + pet.setName("gorilla"); + + Category category = new Category(); + category.setName("really-happy"); + + pet.setCategory(category); + pet.setStatus(Pet.StatusEnum.AVAILABLE); + List photos = Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"}); + pet.setPhotoUrls(photos); + + return pet; + } +} diff --git a/samples/client/petstore/java/feign/src/test/java/io/swagger/petstore/test/StoreApiTest.java b/samples/client/petstore/java/feign/src/test/java/io/swagger/petstore/test/StoreApiTest.java new file mode 100644 index 00000000000..dd5bf4e71f4 --- /dev/null +++ b/samples/client/petstore/java/feign/src/test/java/io/swagger/petstore/test/StoreApiTest.java @@ -0,0 +1,64 @@ +package io.swagger.petstore.test; + +import io.swagger.client.*; +import io.swagger.client.api.*; +import io.swagger.client.model.*; + +import java.util.Map; + +import org.junit.*; +import static org.junit.Assert.*; + +public class StoreApiTest { + ApiClient apiClient; + StoreApi api; + + @Before + public void setup() { + apiClient = new ApiClient(); + api = apiClient.buildClient(StoreApi.class); + } + + @Test + public void testGetInventory() throws Exception { + Map inventory = api.getInventory(); + assertTrue(inventory.keySet().size() > 0); + } + + @Test + public void testPlaceOrder() throws Exception { + Order order = createOrder(); + api.placeOrder(order); + + Order fetched = api.getOrderById(order.getId().toString()); + assertEquals(order.getId(), fetched.getId()); + assertEquals(order.getPetId(), fetched.getPetId()); + assertEquals(order.getQuantity(), fetched.getQuantity()); + } + + @Test + public void testDeleteOrder() throws Exception { + Order order = createOrder(); + api.placeOrder(order); + + Order fetched = api.getOrderById(order.getId().toString()); + assertEquals(fetched.getId(), order.getId()); + + api.deleteOrder(String.valueOf(order.getId())); + + api.getOrderById(order.getId().toString()); +// fail("expected an error"); + } + + private Order createOrder() { + Order order = new Order(); + order.setId(new Long(System.currentTimeMillis())); + order.setPetId(new Long(200)); + order.setQuantity(new Integer(13)); + order.setShipDate(new java.util.Date()); + order.setStatus(Order.StatusEnum.PLACED); + order.setComplete(true); + + return order; + } +} diff --git a/samples/client/petstore/java/feign/src/test/java/io/swagger/petstore/test/UserApiTest.java b/samples/client/petstore/java/feign/src/test/java/io/swagger/petstore/test/UserApiTest.java new file mode 100644 index 00000000000..1615dbf1dce --- /dev/null +++ b/samples/client/petstore/java/feign/src/test/java/io/swagger/petstore/test/UserApiTest.java @@ -0,0 +1,87 @@ +package io.swagger.petstore.test; + +import io.swagger.client.ApiClient; +import io.swagger.client.api.*; +import io.swagger.client.model.*; + +import java.util.Arrays; + +import org.junit.*; +import static org.junit.Assert.*; + +public class UserApiTest { + ApiClient apiClient; + UserApi api; + + @Before + public void setup() { + apiClient = new ApiClient(); + api = apiClient.buildClient(UserApi.class); + } + + @Test + public void testCreateUser() throws Exception { + User user = createUser(); + + api.createUser(user); + + User fetched = api.getUserByName(user.getUsername()); + assertEquals(user.getId(), fetched.getId()); + } + + @Test + public void testCreateUsersWithArray() throws Exception { + User user1 = createUser(); + user1.setUsername("abc123"); + User user2 = createUser(); + user2.setUsername("123abc"); + + api.createUsersWithArrayInput(Arrays.asList(new User[]{user1, user2})); + + User fetched = api.getUserByName(user1.getUsername()); + assertEquals(user1.getId(), fetched.getId()); + } + + @Test + public void testCreateUsersWithList() throws Exception { + User user1 = createUser(); + user1.setUsername("abc123"); + User user2 = createUser(); + user2.setUsername("123abc"); + + api.createUsersWithListInput(Arrays.asList(new User[]{user1, user2})); + + User fetched = api.getUserByName(user1.getUsername()); + assertEquals(user1.getId(), fetched.getId()); + } + + // ignore for the time being, please refer to the following for more info: + // https://github.com/swagger-api/swagger-codegen/issues/1660 + @Ignore @Test + public void testLoginUser() throws Exception { + User user = createUser(); + api.createUser(user); + + String token = api.loginUser(user.getUsername(), user.getPassword()); + assertTrue(token.startsWith("logged in user session:")); + } + + @Test + public void logoutUser() throws Exception { + api.logoutUser(); + } + + private User createUser() { + User user = new User(); + user.setId(System.currentTimeMillis()); + user.setUsername("fred" + user.getId()); + user.setFirstName("Fred"); + user.setLastName("Meyer"); + user.setEmail("fred@fredmeyer.com"); + user.setPassword("xxXXxx"); + user.setPhone("408-867-5309"); + user.setUserStatus(123); + + return user; + } +} diff --git a/samples/client/petstore/java/jersey2/pom.xml b/samples/client/petstore/java/jersey2/pom.xml index 0881cc29374..6b0ba2cba08 100644 --- a/samples/client/petstore/java/jersey2/pom.xml +++ b/samples/client/petstore/java/jersey2/pom.xml @@ -124,7 +124,12 @@ jersey-media-multipart ${jersey-version}
- + + org.glassfish.jersey.media + jersey-media-json-jackson + 2.22.1 + + com.fasterxml.jackson.core 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 c74c6e6ba29..4ca24fbabb0 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 @@ -6,6 +6,7 @@ import javax.ws.rs.client.Entity; import javax.ws.rs.client.Invocation; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.Form; +import javax.ws.rs.core.GenericType; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; @@ -13,10 +14,9 @@ import javax.ws.rs.core.Response.Status; import org.glassfish.jersey.client.ClientConfig; import org.glassfish.jersey.filter.LoggingFilter; import org.glassfish.jersey.media.multipart.FormDataBodyPart; -import org.glassfish.jersey.media.multipart.FormDataMultiPart; +import org.glassfish.jersey.media.multipart.FormDataContentDisposition; import org.glassfish.jersey.media.multipart.MultiPart; import org.glassfish.jersey.media.multipart.MultiPartFeature; -import org.glassfish.jersey.media.multipart.file.FileDataBodyPart; import java.util.Collection; import java.util.Collections; @@ -30,20 +30,18 @@ import java.util.TimeZone; import java.net.URLEncoder; -import java.io.IOException; import java.io.File; import java.io.UnsupportedEncodingException; import java.text.DateFormat; import java.text.SimpleDateFormat; -import java.text.ParseException; import io.swagger.client.auth.Authentication; 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 = "2015-11-17T11:17:50.535-05:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-12-09T12:31:44.572-05:00") public class ApiClient { private Client client; private Map hostMap = new HashMap(); @@ -344,6 +342,17 @@ public class ApiClient { return params; } + /** + * Check if the given MIME is a JSON MIME. + * JSON MIME examples: + * application/json + * application/json; charset=UTF8 + * APPLICATION/JSON + */ + public boolean isJsonMime(String mime) { + return mime != null && mime.matches("(?i)application\\/json(;.*)?"); + } + /** * Select the Accept header's value from the given accepts array: * if JSON exists in the given array, use it; @@ -354,8 +363,14 @@ public class ApiClient { * null will be returned (not to set the Accept header explicitly). */ public String selectHeaderAccept(String[] accepts) { - if (accepts.length == 0) return null; - if (StringUtil.containsIgnoreCase(accepts, "application/json")) return "application/json"; + if (accepts.length == 0) { + return null; + } + for (String accept : accepts) { + if (isJsonMime(accept)) { + return accept; + } + } return StringUtil.join(accepts, ","); } @@ -369,8 +384,14 @@ public class ApiClient { * JSON will be used. */ public String selectHeaderContentType(String[] contentTypes) { - if (contentTypes.length == 0) return "application/json"; - if (StringUtil.containsIgnoreCase(contentTypes, "application/json")) return "application/json"; + if (contentTypes.length == 0) { + return "application/json"; + } + for (String contentType : contentTypes) { + if (isJsonMime(contentType)) { + return contentType; + } + } return contentTypes[0]; } @@ -389,18 +410,39 @@ public class ApiClient { * Serialize the given Java object into string entity according the given * Content-Type (only JSON is supported for now). */ - public Entity serialize(Object obj, String contentType) throws ApiException { - if (contentType.startsWith("application/json")) { - return Entity.json(json.serialize(obj)); + public Entity serialize(Object obj, Map formParams, String contentType) throws ApiException { + Entity entity = null; + if (contentType.startsWith("multipart/form-data")) { + MultiPart multiPart = new MultiPart(); + for (Entry param: formParams.entrySet()) { + if (param.getValue() instanceof File) { + File file = (File) param.getValue(); + FormDataContentDisposition contentDisp = FormDataContentDisposition.name(param.getKey()) + .fileName(file.getName()).size(file.length()).build(); + multiPart.bodyPart(new FormDataBodyPart(contentDisp, file, MediaType.APPLICATION_OCTET_STREAM_TYPE)); + } else { + FormDataContentDisposition contentDisp = FormDataContentDisposition.name(param.getKey()).build(); + multiPart.bodyPart(new FormDataBodyPart(contentDisp, parameterToString(param.getValue()))); + } + } + entity = Entity.entity(multiPart, MediaType.MULTIPART_FORM_DATA_TYPE); + } else if (contentType.startsWith("application/x-www-form-urlencoded")) { + Form form = new Form(); + for (Entry param: formParams.entrySet()) { + form.param(param.getKey(), parameterToString(param.getValue())); + } + entity = Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE); } else { - throw new ApiException(400, "can not serialize object into Content-Type: " + contentType); + // We let jersey handle the serialization + entity = Entity.entity(obj, contentType); } + return entity; } /** * Deserialize response body to Java object according to the Content-Type. */ - public T deserialize(Response response, TypeRef returnType) throws ApiException { + public T deserialize(Response response, GenericType returnType) throws ApiException { String contentType = null; List contentTypes = response.getHeaders().get("Content-Type"); if (contentTypes != null && !contentTypes.isEmpty()) @@ -408,24 +450,7 @@ public class ApiClient { if (contentType == null) throw new ApiException(500, "missing Content-Type in response"); - String body; - if (response.hasEntity()) - body = (String) response.readEntity(String.class); - else - body = ""; - - if (contentType.startsWith("application/json")) { - return json.deserialize(body, returnType); - } else if (returnType.getType().equals(String.class)) { - // Expecting string, return the raw response body. - return (T) body; - } else { - throw new ApiException( - 500, - "Content type \"" + contentType + "\" is not supported for type: " - + returnType.getType() - ); - } + return response.readEntity(returnType); } /** @@ -443,7 +468,7 @@ public class ApiClient { * @param returnType The return type into which to deserialize the response * @return The response body in type of string */ - public T invokeAPI(String path, String method, List queryParams, Object body, Map headerParams, Map formParams, String accept, String contentType, String[] authNames, TypeRef returnType) throws ApiException { + public T invokeAPI(String path, String method, List queryParams, Object body, Map headerParams, Map formParams, String accept, String contentType, String[] authNames, GenericType returnType) throws ApiException { updateParamsForAuth(authNames, queryParams, headerParams); WebTarget target = client.target(this.basePath).path(path); @@ -474,54 +499,16 @@ public class ApiClient { } } - Entity formEntity = null; - - if (contentType.startsWith("multipart/form-data")) { - MultiPart multipart = new MultiPart(); - for (Entry param: formParams.entrySet()) { - if (param.getValue() instanceof File) { - File file = (File) param.getValue(); - - FormDataMultiPart mp = new FormDataMultiPart(); - mp.bodyPart(new FormDataBodyPart(param.getKey(), file.getName())); - multipart.bodyPart(mp, MediaType.MULTIPART_FORM_DATA_TYPE); - - multipart.bodyPart(new FileDataBodyPart(param.getKey(), file, MediaType.APPLICATION_OCTET_STREAM_TYPE)); - } else { - FormDataMultiPart mp = new FormDataMultiPart(); - mp.bodyPart(new FormDataBodyPart(param.getKey(), parameterToString(param.getValue()))); - multipart.bodyPart(mp, MediaType.MULTIPART_FORM_DATA_TYPE); - } - } - formEntity = Entity.entity(multipart, MediaType.MULTIPART_FORM_DATA_TYPE); - } else if (contentType.startsWith("application/x-www-form-urlencoded")) { - Form form = new Form(); - for (Entry param: formParams.entrySet()) { - form.param(param.getKey(), parameterToString(param.getValue())); - } - formEntity = Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE); - } + Entity entity = serialize(body, formParams, contentType); Response response = null; if ("GET".equals(method)) { response = invocationBuilder.get(); } else if ("POST".equals(method)) { - if (formEntity != null) { - response = invocationBuilder.post(formEntity); - } else if (body == null) { - response = invocationBuilder.post(null); - } else { - response = invocationBuilder.post(serialize(body, contentType)); - } + response = invocationBuilder.post(entity); } else if ("PUT".equals(method)) { - if (formEntity != null) { - response = invocationBuilder.put(formEntity); - } else if (body == null) { - response = invocationBuilder.put(null); - } else { - response = invocationBuilder.put(serialize(body, contentType)); - } + response = invocationBuilder.put(entity); } else if ("DELETE".equals(method)) { response = invocationBuilder.delete(); } else { @@ -560,6 +547,8 @@ public class ApiClient { private void buildClient() { final ClientConfig clientConfig = new ClientConfig(); clientConfig.register(MultiPartFeature.class); + clientConfig.register(json); + clientConfig.register(org.glassfish.jersey.jackson.JacksonFeature.class); if (debugging) { clientConfig.register(LoggingFilter.class); } 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 80bf3d260ca..0e36184742a 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 = "2015-11-17T11:17:50.535-05:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-11-29T00:18:01.946+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 82b8e0459bc..2967d84c190 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 = "2015-11-17T11:17:50.535-05:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-11-29T00:18:01.946+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 a05975c0e59..aab2d27e463 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 @@ -6,10 +6,10 @@ import com.fasterxml.jackson.datatype.joda.*; import java.text.DateFormat; -import java.io.IOException; +import javax.ws.rs.ext.ContextResolver; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-11-17T11:17:50.535-05:00") -public class JSON { +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-12-09T12:31:44.572-05:00") +public class JSON implements ContextResolver { private ObjectMapper mapper; public JSON() { @@ -29,36 +29,8 @@ public class JSON { mapper.setDateFormat(dateFormat); } - /** - * Serialize the given Java object into JSON string. - */ - public String serialize(Object obj) throws ApiException { - try { - if (obj != null) - return mapper.writeValueAsString(obj); - else - return null; - } catch (Exception e) { - throw new ApiException(400, e.getMessage()); - } - } - - /** - * Deserialize the given JSON string to Java object. - * - * @param body The JSON string - * @param returnType The type to deserialize inot - * @return The deserialized Java object - */ - public T deserialize(String body, TypeRef returnType) throws ApiException { - JavaType javaType = mapper.constructType(returnType.getType()); - try { - return mapper.readValue(body, javaType); - } catch (IOException e) { - if (returnType.getType().equals(String.class)) - return (T) body; - else - throw new ApiException(500, e.getMessage(), null, body); - } + @Override + public ObjectMapper getContext(Class type) { + return 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 aae34092fc2..995677baaf5 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 = "2015-11-17T11:17:50.535-05:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-11-29T00:18:01.946+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 02e52457fef..e9cc1341e04 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 = "2015-11-17T11:17:50.535-05:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-11-29T00:18:01.946+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/TypeRef.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/TypeRef.java deleted file mode 100644 index 0452e40e0c4..00000000000 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/TypeRef.java +++ /dev/null @@ -1,26 +0,0 @@ -package io.swagger.client; - -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.Type; - -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-11-17T11:17:50.535-05:00") -public class TypeRef { - private final Type type; - - public TypeRef() { - this.type = getGenericType(getClass()); - } - - private static Type getGenericType(Class klass) { - Type superclass = klass.getGenericSuperclass(); - if (superclass instanceof Class) { - throw new RuntimeException("No type parameter provided"); - } - ParameterizedType parameterized = (ParameterizedType) superclass; - return parameterized.getActualTypeArguments()[0]; - } - - public Type getType() { - return type; - } -} 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 10134d4f3ea..ab33fca7c79 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 @@ -4,14 +4,15 @@ import io.swagger.client.ApiException; import io.swagger.client.ApiClient; import io.swagger.client.Configuration; import io.swagger.client.Pair; -import io.swagger.client.TypeRef; + +import javax.ws.rs.core.GenericType; import io.swagger.client.model.Pet; import java.io.File; import java.util.*; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-11-17T11:17:50.535-05:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-12-09T12:31:44.572-05:00") public class PetApi { private ApiClient apiClient; @@ -38,7 +39,7 @@ public class PetApi { * @param body Pet object that needs to be added to the store * @return void */ - public void updatePet (Pet body) throws ApiException { + public void updatePet(Pet body) throws ApiException { Object postBody = body; // create path and map variables @@ -78,7 +79,7 @@ public class PetApi { * @param body Pet object that needs to be added to the store * @return void */ - public void addPet (Pet body) throws ApiException { + public void addPet(Pet body) throws ApiException { Object postBody = body; // create path and map variables @@ -118,7 +119,7 @@ public class PetApi { * @param status Status values that need to be considered for filter * @return List */ - public List findPetsByStatus (List status) throws ApiException { + public List findPetsByStatus(List status) throws ApiException { Object postBody = null; // create path and map variables @@ -150,7 +151,7 @@ public class PetApi { String[] authNames = new String[] { "petstore_auth" }; - TypeRef returnType = new TypeRef>() {}; + GenericType> returnType = new GenericType>() {}; return apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); } @@ -161,7 +162,7 @@ public class PetApi { * @param tags Tags to filter by * @return List */ - public List findPetsByTags (List tags) throws ApiException { + public List findPetsByTags(List tags) throws ApiException { Object postBody = null; // create path and map variables @@ -193,7 +194,7 @@ public class PetApi { String[] authNames = new String[] { "petstore_auth" }; - TypeRef returnType = new TypeRef>() {}; + GenericType> returnType = new GenericType>() {}; return apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); } @@ -204,7 +205,7 @@ public class PetApi { * @param petId ID of pet that needs to be fetched * @return Pet */ - public Pet getPetById (Long petId) throws ApiException { + public Pet getPetById(Long petId) throws ApiException { Object postBody = null; // verify the required parameter 'petId' is set @@ -240,7 +241,7 @@ public class PetApi { String[] authNames = new String[] { "api_key" }; - TypeRef returnType = new TypeRef() {}; + GenericType returnType = new GenericType() {}; return apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); } @@ -253,7 +254,7 @@ public class PetApi { * @param status Updated status of the pet * @return void */ - public void updatePetWithForm (String petId, String name, String status) throws ApiException { + public void updatePetWithForm(String petId, String name, String status) throws ApiException { Object postBody = null; // verify the required parameter 'petId' is set @@ -304,7 +305,7 @@ public class PetApi { * @param apiKey * @return void */ - public void deletePet (Long petId, String apiKey) throws ApiException { + public void deletePet(Long petId, String apiKey) throws ApiException { Object postBody = null; // verify the required parameter 'petId' is set @@ -354,7 +355,7 @@ public class PetApi { * @param file file to upload * @return void */ - public void uploadFile (Long petId, String additionalMetadata, File file) throws ApiException { + public void uploadFile(Long petId, String additionalMetadata, File file) throws ApiException { Object postBody = null; // verify the required parameter 'petId' is set 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 d7e30dd2b0e..5dfdbcc3e62 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 @@ -4,14 +4,15 @@ import io.swagger.client.ApiException; import io.swagger.client.ApiClient; import io.swagger.client.Configuration; import io.swagger.client.Pair; -import io.swagger.client.TypeRef; + +import javax.ws.rs.core.GenericType; import java.util.Map; import io.swagger.client.model.Order; import java.util.*; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-11-17T11:17:50.535-05:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-12-09T12:31:44.572-05:00") public class StoreApi { private ApiClient apiClient; @@ -37,7 +38,7 @@ public class StoreApi { * Returns a map of status codes to quantities * @return Map */ - public Map getInventory () throws ApiException { + public Map getInventory() throws ApiException { Object postBody = null; // create path and map variables @@ -67,7 +68,7 @@ public class StoreApi { String[] authNames = new String[] { "api_key" }; - TypeRef returnType = new TypeRef>() {}; + GenericType> returnType = new GenericType>() {}; return apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); } @@ -78,7 +79,7 @@ public class StoreApi { * @param body order placed for purchasing the pet * @return Order */ - public Order placeOrder (Order body) throws ApiException { + public Order placeOrder(Order body) throws ApiException { Object postBody = body; // create path and map variables @@ -108,7 +109,7 @@ public class StoreApi { String[] authNames = new String[] { }; - TypeRef returnType = new TypeRef() {}; + GenericType returnType = new GenericType() {}; return apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); } @@ -119,7 +120,7 @@ public class StoreApi { * @param orderId ID of pet that needs to be fetched * @return Order */ - public Order getOrderById (String orderId) throws ApiException { + public Order getOrderById(String orderId) throws ApiException { Object postBody = null; // verify the required parameter 'orderId' is set @@ -155,7 +156,7 @@ public class StoreApi { String[] authNames = new String[] { }; - TypeRef returnType = new TypeRef() {}; + GenericType returnType = new GenericType() {}; return apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); } @@ -166,7 +167,7 @@ public class StoreApi { * @param orderId ID of the order that needs to be deleted * @return void */ - public void deleteOrder (String orderId) throws ApiException { + public void deleteOrder(String orderId) throws ApiException { Object postBody = null; // verify the required parameter 'orderId' is set 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 db04594b56b..0424382e7c3 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 @@ -4,14 +4,15 @@ import io.swagger.client.ApiException; import io.swagger.client.ApiClient; import io.swagger.client.Configuration; import io.swagger.client.Pair; -import io.swagger.client.TypeRef; + +import javax.ws.rs.core.GenericType; import io.swagger.client.model.User; import java.util.*; import java.util.*; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-11-17T11:17:50.535-05:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-12-09T12:31:44.572-05:00") public class UserApi { private ApiClient apiClient; @@ -38,7 +39,7 @@ public class UserApi { * @param body Created user object * @return void */ - public void createUser (User body) throws ApiException { + public void createUser(User body) throws ApiException { Object postBody = body; // create path and map variables @@ -78,7 +79,7 @@ public class UserApi { * @param body List of user object * @return void */ - public void createUsersWithArrayInput (List body) throws ApiException { + public void createUsersWithArrayInput(List body) throws ApiException { Object postBody = body; // create path and map variables @@ -118,7 +119,7 @@ public class UserApi { * @param body List of user object * @return void */ - public void createUsersWithListInput (List body) throws ApiException { + public void createUsersWithListInput(List body) throws ApiException { Object postBody = body; // create path and map variables @@ -159,7 +160,7 @@ public class UserApi { * @param password The password for login in clear text * @return String */ - public String loginUser (String username, String password) throws ApiException { + public String loginUser(String username, String password) throws ApiException { Object postBody = null; // create path and map variables @@ -193,7 +194,7 @@ public class UserApi { String[] authNames = new String[] { }; - TypeRef returnType = new TypeRef() {}; + GenericType returnType = new GenericType() {}; return apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); } @@ -203,7 +204,7 @@ public class UserApi { * * @return void */ - public void logoutUser () throws ApiException { + public void logoutUser() throws ApiException { Object postBody = null; // create path and map variables @@ -243,7 +244,7 @@ public class UserApi { * @param username The name that needs to be fetched. Use user1 for testing. * @return User */ - public User getUserByName (String username) throws ApiException { + public User getUserByName(String username) throws ApiException { Object postBody = null; // verify the required parameter 'username' is set @@ -279,7 +280,7 @@ public class UserApi { String[] authNames = new String[] { }; - TypeRef returnType = new TypeRef() {}; + GenericType returnType = new GenericType() {}; return apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); } @@ -291,7 +292,7 @@ public class UserApi { * @param body Updated user object * @return void */ - public void updateUser (String username, User body) throws ApiException { + public void updateUser(String username, User body) throws ApiException { Object postBody = body; // verify the required parameter 'username' is set @@ -337,7 +338,7 @@ public class UserApi { * @param username The name that needs to be deleted * @return void */ - public void deleteUser (String username) throws ApiException { + public void deleteUser(String username) throws ApiException { Object postBody = null; // verify the required parameter 'username' is set diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/Authentication.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/Authentication.java index 0861802a7d3..939e4d10db7 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/Authentication.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/Authentication.java @@ -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 = "2015-11-17T11:17:50.535-05:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-11-29T00:18:01.946+08:00") public interface Authentication { /** Apply authentication settings to header and query params. */ void applyToParams(List queryParams, Map headerParams); 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 144d4c9681f..b7d6be76237 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 = "2015-11-17T11:17:50.535-05:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-11-29T00:18:01.946+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 26e1b89bba7..abe1bb895d3 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 @@ -3,13 +3,14 @@ package io.swagger.client.model; import io.swagger.client.StringUtil; +import java.util.Objects; import io.swagger.annotations.*; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.*; @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-11-17T11:17:50.535-05:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-11-29T00:18:01.946+08:00") public class Category { private Long id = null; @@ -41,6 +42,24 @@ public class Category { + @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(); 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 6efc0786703..6c90b3eca40 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 @@ -4,13 +4,14 @@ import io.swagger.client.StringUtil; import java.util.Date; +import java.util.Objects; import io.swagger.annotations.*; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.*; @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-11-17T11:17:50.535-05:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-11-29T00:18:01.946+08:00") public class Order { private Long id = null; @@ -18,6 +19,7 @@ public class Order { private Integer quantity = null; private Date shipDate = null; + public enum StatusEnum { PLACED("placed"), APPROVED("approved"), @@ -30,6 +32,7 @@ public enum StatusEnum { } @Override + @JsonValue public String toString() { return value; } @@ -113,6 +116,28 @@ public enum StatusEnum { + @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(); 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 02f0b88d6f5..28343f0fc44 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 @@ -2,17 +2,18 @@ package io.swagger.client.model; import io.swagger.client.StringUtil; import io.swagger.client.model.Category; -import java.util.*; import io.swagger.client.model.Tag; +import java.util.*; +import java.util.Objects; import io.swagger.annotations.*; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.*; @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-11-17T11:17:50.535-05:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-11-29T00:18:01.946+08:00") public class Pet { private Long id = null; @@ -21,6 +22,7 @@ public class Pet { private List photoUrls = new ArrayList(); private List tags = new ArrayList(); + public enum StatusEnum { AVAILABLE("available"), PENDING("pending"), @@ -33,6 +35,7 @@ public enum StatusEnum { } @Override + @JsonValue public String toString() { return value; } @@ -115,6 +118,28 @@ public enum StatusEnum { + @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(); 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 9dc8e017f9f..a7ee39070c8 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 @@ -3,13 +3,14 @@ package io.swagger.client.model; import io.swagger.client.StringUtil; +import java.util.Objects; import io.swagger.annotations.*; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.*; @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-11-17T11:17:50.535-05:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-11-29T00:18:01.946+08:00") public class Tag { private Long id = null; @@ -41,6 +42,24 @@ public class Tag { + @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(); 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 8ad399fcc6b..5bfea7707f4 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 @@ -3,13 +3,14 @@ package io.swagger.client.model; import io.swagger.client.StringUtil; +import java.util.Objects; import io.swagger.annotations.*; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.*; @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-11-17T11:17:50.535-05:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-11-29T00:18:01.946+08:00") public class User { private Long id = null; @@ -120,6 +121,30 @@ public class User { + @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(); 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 3d57f3fa84c..29eae3d017e 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 @@ -38,16 +38,29 @@ public class ApiClientTest { assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T13:49:09+10:00"))); } + @Test + public void testIsJsonMime() { + assertFalse(apiClient.isJsonMime(null)); + assertFalse(apiClient.isJsonMime("")); + assertFalse(apiClient.isJsonMime("text/plain")); + assertFalse(apiClient.isJsonMime("application/xml")); + assertFalse(apiClient.isJsonMime("application/jsonp")); + + assertTrue(apiClient.isJsonMime("application/json")); + assertTrue(apiClient.isJsonMime("application/json; charset=UTF8")); + assertTrue(apiClient.isJsonMime("APPLICATION/JSON")); + } + @Test public void testSelectHeaderAccept() { - String[] accepts = {"APPLICATION/JSON", "APPLICATION/XML"}; + String[] accepts = {"application/json", "application/xml"}; assertEquals("application/json", apiClient.selectHeaderAccept(accepts)); - accepts = new String[]{"application/json", "application/xml"}; - assertEquals("application/json", apiClient.selectHeaderAccept(accepts)); + accepts = new String[]{"APPLICATION/XML", "APPLICATION/JSON"}; + assertEquals("APPLICATION/JSON", apiClient.selectHeaderAccept(accepts)); - accepts = new String[]{"application/xml", "application/json"}; - assertEquals("application/json", apiClient.selectHeaderAccept(accepts)); + accepts = new String[]{"application/xml", "application/json; charset=UTF8"}; + assertEquals("application/json; charset=UTF8", apiClient.selectHeaderAccept(accepts)); accepts = new String[]{"text/plain", "application/xml"}; assertEquals("text/plain,application/xml", apiClient.selectHeaderAccept(accepts)); @@ -58,14 +71,14 @@ public class ApiClientTest { @Test public void testSelectHeaderContentType() { - String[] contentTypes = {"APPLICATION/JSON", "APPLICATION/XML"}; + String[] contentTypes = {"application/json", "application/xml"}; assertEquals("application/json", apiClient.selectHeaderContentType(contentTypes)); - contentTypes = new String[]{"application/json", "application/xml"}; - assertEquals("application/json", apiClient.selectHeaderContentType(contentTypes)); + contentTypes = new String[]{"APPLICATION/JSON", "APPLICATION/XML"}; + assertEquals("APPLICATION/JSON", apiClient.selectHeaderContentType(contentTypes)); - contentTypes = new String[]{"application/xml", "application/json"}; - assertEquals("application/json", apiClient.selectHeaderContentType(contentTypes)); + contentTypes = new String[]{"application/xml", "application/json; charset=UTF8"}; + assertEquals("application/json; charset=UTF8", apiClient.selectHeaderContentType(contentTypes)); contentTypes = new String[]{"text/plain", "application/xml"}; assertEquals("text/plain", apiClient.selectHeaderContentType(contentTypes)); diff --git a/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/JSONTest.java b/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/JSONTest.java index 1250a135078..f10909ab9e7 100644 --- a/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/JSONTest.java +++ b/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/JSONTest.java @@ -4,9 +4,7 @@ import io.swagger.client.model.Order; import java.lang.Exception; import java.text.DateFormat; -import java.text.ParseException; import java.text.SimpleDateFormat; -import java.util.*; import java.util.TimeZone; import org.junit.*; @@ -30,9 +28,8 @@ public class JSONTest { final String dateStr = "2015-11-07T14:11:05.267Z"; order.setShipDate(dateFormat.parse(dateStr)); - String str = json.serialize(order); - TypeRef typeRef = new TypeRef() { }; - Order o = json.deserialize(str, typeRef); + String str = json.getContext(null).writeValueAsString(order); + Order o = json.getContext(null).readValue(str, Order.class); assertEquals(dateStr, dateFormat.format(o.getShipDate())); } @@ -44,9 +41,8 @@ public class JSONTest { order.setShipDate(dateFormat.parse(dateStr)); json.setDateFormat(dateFormat); - String str = json.serialize(order); - TypeRef typeRef = new TypeRef() { }; - Order o = json.deserialize(str, typeRef); + String str = json.getContext(null).writeValueAsString(order); + Order o = json.getContext(null).readValue(str, Order.class); assertEquals(dateStr, dateFormat.format(o.getShipDate())); } } \ No newline at end of file diff --git a/samples/client/petstore/java/jersey2/src/test/java/io/swagger/petstore/test/PetApiTest.java b/samples/client/petstore/java/jersey2/src/test/java/io/swagger/petstore/test/PetApiTest.java index 0a8f8a1665d..c0bee9328d5 100644 --- a/samples/client/petstore/java/jersey2/src/test/java/io/swagger/petstore/test/PetApiTest.java +++ b/samples/client/petstore/java/jersey2/src/test/java/io/swagger/petstore/test/PetApiTest.java @@ -174,6 +174,33 @@ public class PetApiTest { api.uploadFile(pet.getId(), "a test file", new File(file.getAbsolutePath())); } + @Test + public void testEqualsAndHashCode() { + Pet pet1 = new Pet(); + Pet pet2 = new Pet(); + assertTrue(pet1.equals(pet2)); + assertTrue(pet2.equals(pet1)); + assertTrue(pet1.hashCode() == pet2.hashCode()); + assertTrue(pet1.equals(pet1)); + assertTrue(pet1.hashCode() == pet1.hashCode()); + + pet2.setName("really-happy"); + pet2.setPhotoUrls(Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"})); + assertFalse(pet1.equals(pet2)); + assertFalse(pet2.equals(pet1)); + assertFalse(pet1.hashCode() == (pet2.hashCode())); + assertTrue(pet2.equals(pet2)); + assertTrue(pet2.hashCode() == pet2.hashCode()); + + pet1.setName("really-happy"); + pet1.setPhotoUrls(Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"})); + assertTrue(pet1.equals(pet2)); + assertTrue(pet2.equals(pet1)); + assertTrue(pet1.hashCode() == pet2.hashCode()); + assertTrue(pet1.equals(pet1)); + assertTrue(pet1.hashCode() == pet1.hashCode()); + } + private Pet createRandomPet() { Pet pet = new Pet(); pet.setId(System.currentTimeMillis()); diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiCallback.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiCallback.java index d75713c9a01..fcf2d289fbf 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiCallback.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiCallback.java @@ -28,4 +28,22 @@ public interface ApiCallback { * @param responseHeaders Headers of the response */ void onSuccess(T result, int statusCode, Map> responseHeaders); + + /** + * This is called when the API upload processing. + * + * @param bytesWritten bytes Written + * @param contentLength content length of request body + * @param done write end + */ + void onUploadProgress(long bytesWritten, long contentLength, boolean done); + + /** + * This is called when the API downlond processing. + * + * @param bytesRead bytes Read + * @param contentLength content lenngth of the response + * @param done Read end + */ + void onDownloadProgress(long bytesRead, long contentLength, boolean done); } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiClient.java index 6e4e299ad3a..19cb83d620c 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 @@ -104,9 +104,6 @@ public class ApiClient { private Map authentications; - private int statusCode; - private Map> responseHeaders; - private DateFormat dateFormat; private DateFormat datetimeFormat; private boolean lenientDatetimeFormat; @@ -176,24 +173,6 @@ public class ApiClient { return this; } - /** - * Gets the status code of the previous request. - * NOTE: Status code of last async response is not recorded here, it is - * passed to the callback methods instead. - */ - public int getStatusCode() { - return statusCode; - } - - /** - * Gets the response headers of the previous request. - * NOTE: Headers of last async response is not recorded here, it is passed - * to callback methods instead. - */ - public Map> getResponseHeaders() { - return responseHeaders; - } - public boolean isVerifyingSsl() { return verifyingSsl; } @@ -569,6 +548,17 @@ public class ApiClient { return params; } + /** + * Check if the given MIME is a JSON MIME. + * JSON MIME examples: + * application/json + * application/json; charset=UTF8 + * APPLICATION/JSON + */ + public boolean isJsonMime(String mime) { + return mime != null && mime.matches("(?i)application\\/json(;.*)?"); + } + /** * Select the Accept header's value from the given accepts array: * if JSON exists in the given array, use it; @@ -579,8 +569,14 @@ public class ApiClient { * null will be returned (not to set the Accept header explicitly). */ public String selectHeaderAccept(String[] accepts) { - if (accepts.length == 0) return null; - if (StringUtil.containsIgnoreCase(accepts, "application/json")) return "application/json"; + if (accepts.length == 0) { + return null; + } + for (String accept : accepts) { + if (isJsonMime(accept)) { + return accept; + } + } return StringUtil.join(accepts, ","); } @@ -594,8 +590,14 @@ public class ApiClient { * JSON will be used. */ public String selectHeaderContentType(String[] contentTypes) { - if (contentTypes.length == 0) return "application/json"; - if (StringUtil.containsIgnoreCase(contentTypes, "application/json")) return "application/json"; + if (contentTypes.length == 0) { + return "application/json"; + } + for (String contentType : contentTypes) { + if (isJsonMime(contentType)) { + return contentType; + } + } return contentTypes[0]; } @@ -617,6 +619,8 @@ public class ApiClient { * @param response HTTP response * @param returnType The type of the Java object * @return The deserialized Java object + * @throws ApiException If fail to deserialize response body, i.e. cannot read response body + * or the Content-Type of the response is not supported. */ public T deserialize(Response response, Type returnType) throws ApiException { if (response == null || returnType == null) @@ -644,7 +648,7 @@ public class ApiClient { // ensuring a default content type contentType = "application/json"; } - if (contentType.startsWith("application/json")) { + if (isJsonMime(contentType)) { return json.deserialize(respBody, returnType); } else if (returnType.equals(String.class)) { // Expecting string, return the raw response body. @@ -665,9 +669,10 @@ public class ApiClient { * @param obj The Java object * @param contentType The request Content-Type * @return The serialized string + * @throws ApiException If fail to serialize the given object */ public String serialize(Object obj, String contentType) throws ApiException { - if (contentType.startsWith("application/json")) { + if (isJsonMime(contentType)) { if (obj != null) return json.serialize(obj); else @@ -679,6 +684,7 @@ public class ApiClient { /** * Download file from the given response. + * @throws ApiException If fail to read file content from response and write to disk */ public File downloadFileFromResponse(Response response) throws ApiException { try { @@ -730,7 +736,7 @@ public class ApiClient { /** * @see #execute(Call, Type) */ - public T execute(Call call) throws ApiException { + public ApiResponse execute(Call call) throws ApiException { return execute(call, null); } @@ -739,14 +745,16 @@ public class ApiClient { * * @param returnType The return type used to deserialize HTTP response body * @param The return type corresponding to (same with) returnType - * @return The Java object deserialized from response body. Returns null if returnType is null. + * @return ApiResponse object containing response status, headers and + * data, which is a Java object deserialized from response body and would be null + * when returnType is null. + * @throws ApiException If fail to execute the call */ - public T execute(Call call, Type returnType) throws ApiException { + public ApiResponse execute(Call call, Type returnType) throws ApiException { try { Response response = call.execute(); - this.statusCode = response.code(); - this.responseHeaders = response.headers().toMultimap(); - return handleResponse(response, returnType); + T data = handleResponse(response, returnType); + return new ApiResponse(response.code(), response.headers().toMultimap(), data); } catch (IOException e) { throw new ApiException(e); } @@ -755,7 +763,7 @@ public class ApiClient { /** * #see executeAsync(Call, Type, ApiCallback) */ - public void executeAsync(Call call, ApiCallback callback) throws ApiException { + public void executeAsync(Call call, ApiCallback callback) { executeAsync(call, null, callback); } @@ -786,6 +794,12 @@ public class ApiClient { }); } + /** + * Handle the given response, return the deserialized object when the response is successful. + * + * @throws ApiException If the response has a unsuccessful status code or + * fail to deserialize the response body + */ public T handleResponse(Response response, Type returnType) throws ApiException { if (response.isSuccessful()) { if (returnType == null || response.code() == 204) { @@ -819,8 +833,9 @@ public class ApiClient { * @param formParams The form parameters * @param authNames The authentications to apply * @return The HTTP call + * @throws ApiException If fail to serialize the request body object */ - public Call buildCall(String path, String method, List queryParams, Object body, Map headerParams, Map formParams, String[] authNames) throws ApiException { + public Call buildCall(String path, String method, List queryParams, Object body, Map headerParams, Map formParams, String[] authNames, ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { updateParamsForAuth(authNames, queryParams, headerParams); final String url = buildUrl(path, queryParams); @@ -829,7 +844,9 @@ public class ApiClient { String contentType = (String) headerParams.get("Content-Type"); // ensuring a default content type - if (contentType == null) contentType = "application/json"; + if (contentType == null) { + contentType = "application/json"; + } RequestBody reqBody; if (!HttpMethod.permitsRequestBody(method)) { @@ -850,7 +867,15 @@ public class ApiClient { reqBody = RequestBody.create(MediaType.parse(contentType), serialize(body, contentType)); } - Request request = reqBuilder.method(method, reqBody).build(); + Request request = null; + + if(progressRequestListener != null && reqBody != null) { + ProgressRequestBody progressRequestBody = new ProgressRequestBody(reqBody, progressRequestListener); + request = reqBuilder.method(method, progressRequestBody).build(); + } else { + request = reqBuilder.method(method, reqBody).build(); + } + return httpClient.newCall(request); } 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 0bdd5bd17c6..bf096d22a5c 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 = "2015-10-20T11:42:25.339-07:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-12-07T12:21:33.403+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/ApiResponse.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiResponse.java new file mode 100644 index 00000000000..0a33f09e64e --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiResponse.java @@ -0,0 +1,46 @@ +package io.swagger.client; + +import java.util.List; +import java.util.Map; + +/** + * API response returned by API call. + * + * @param T The type of data that is deserialized from response body + */ +public class ApiResponse { + final private int statusCode; + final private Map> headers; + final private T data; + + /** + * @param statusCode The status code of HTTP response + * @param headers The headers of HTTP response + */ + public ApiResponse(int statusCode, Map> headers) { + this(statusCode, headers, null); + } + + /** + * @param statusCode The status code of HTTP response + * @param headers The headers of HTTP response + * @param data The object deserialized from response bod + */ + public ApiResponse(int statusCode, Map> headers, T data) { + this.statusCode = statusCode; + this.headers = headers; + this.data = data; + } + + public int getStatusCode() { + return statusCode; + } + + public Map> getHeaders() { + return headers; + } + + public T getData() { + return data; + } +} diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/Configuration.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/Configuration.java index a63382fc05b..e996b89ef77 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 = "2015-10-20T11:42:25.339-07:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-12-07T12:21:33.403+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 533d318cb5c..ef80752c495 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 = "2015-10-20T11:42:25.339-07:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-12-07T12:21:33.403+08:00") public class Pair { private String name = ""; private String value = ""; diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ProgressRequestBody.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ProgressRequestBody.java new file mode 100644 index 00000000000..71f34ed1140 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ProgressRequestBody.java @@ -0,0 +1,70 @@ +package io.swagger.client; + +import com.squareup.okhttp.MediaType; +import com.squareup.okhttp.RequestBody; + +import java.io.IOException; + +import okio.Buffer; +import okio.BufferedSink; +import okio.ForwardingSink; +import okio.Okio; +import okio.Sink; + +public class ProgressRequestBody extends RequestBody { + + public interface ProgressRequestListener { + void onRequestProgress(long bytesWritten, long contentLength, boolean done); + } + + private final RequestBody requestBody; + + private final ProgressRequestListener progressListener; + + private BufferedSink bufferedSink; + + public ProgressRequestBody(RequestBody requestBody, ProgressRequestListener progressListener) { + this.requestBody = requestBody; + this.progressListener = progressListener; + } + + @Override + public MediaType contentType() { + return requestBody.contentType(); + } + + @Override + public long contentLength() throws IOException { + return requestBody.contentLength(); + } + + @Override + public void writeTo(BufferedSink sink) throws IOException { + if (bufferedSink == null) { + bufferedSink = Okio.buffer(sink(sink)); + } + + requestBody.writeTo(bufferedSink); + bufferedSink.flush(); + + } + + private Sink sink(Sink sink) { + return new ForwardingSink(sink) { + + long bytesWritten = 0L; + long contentLength = 0L; + + @Override + public void write(Buffer source, long byteCount) throws IOException { + super.write(source, byteCount); + if (contentLength == 0) { + contentLength = contentLength(); + } + + bytesWritten += byteCount; + progressListener.onRequestProgress(bytesWritten, contentLength, bytesWritten == contentLength); + } + }; + } +} diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ProgressResponseBody.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ProgressResponseBody.java new file mode 100644 index 00000000000..138da3f2106 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ProgressResponseBody.java @@ -0,0 +1,63 @@ +package io.swagger.client; + +import com.squareup.okhttp.MediaType; +import com.squareup.okhttp.ResponseBody; + +import java.io.IOException; + +import okio.Buffer; +import okio.BufferedSource; +import okio.ForwardingSource; +import okio.Okio; +import okio.Source; + +public class ProgressResponseBody extends ResponseBody { + + public interface ProgressListener { + void update(long bytesRead, long contentLength, boolean done); + } + + private final ResponseBody responseBody; + private final ProgressListener progressListener; + private BufferedSource bufferedSource; + + public ProgressResponseBody(ResponseBody responseBody, ProgressListener progressListener) { + this.responseBody = responseBody; + this.progressListener = progressListener; + } + + @Override + public MediaType contentType() { + return responseBody.contentType(); + } + + @Override + public long contentLength() throws IOException { + return responseBody.contentLength(); + } + + @Override + public BufferedSource source() throws IOException { + if (bufferedSource == null) { + bufferedSource = Okio.buffer(source(responseBody.source())); + } + return bufferedSource; + } + + private Source source(Source source) { + return new ForwardingSource(source) { + long totalBytesRead = 0L; + + @Override + public long read(Buffer sink, long byteCount) throws IOException { + long bytesRead = super.read(sink, byteCount); + // read() returns the number of bytes read, or -1 if this source is exhausted. + totalBytesRead += bytesRead != -1 ? bytesRead : 0; + progressListener.update(totalBytesRead, responseBody.contentLength(), bytesRead == -1); + return bytesRead; + } + }; + } +} + + diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/StringUtil.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/StringUtil.java index 42d453c31ef..3a105a258e4 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 = "2015-10-20T11:42:25.339-07:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-12-07T12:21:33.403+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 39154cf855e..460cd0f4c4d 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 @@ -3,12 +3,19 @@ package io.swagger.client.api; import io.swagger.client.ApiCallback; import io.swagger.client.ApiClient; import io.swagger.client.ApiException; +import io.swagger.client.ApiResponse; import io.swagger.client.Configuration; import io.swagger.client.Pair; +import io.swagger.client.ProgressRequestBody; +import io.swagger.client.ProgressResponseBody; import com.google.gson.reflect.TypeToken; import com.squareup.okhttp.Call; +import com.squareup.okhttp.Interceptor; +import com.squareup.okhttp.Response; + +import java.io.IOException; import io.swagger.client.model.Pet; import java.io.File; @@ -37,7 +44,7 @@ public class PetApi { /* Build call for updatePet */ - private Call updatePetCall(Pet body) throws ApiException { + private Call updatePetCall(Pet body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object postBody = body; @@ -62,18 +69,42 @@ public class PetApi { final String contentType = apiClient.selectHeaderContentType(contentTypes); headerParams.put("Content-Type", contentType); + 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[] authNames = new String[] { "petstore_auth" }; - return apiClient.buildCall(path, "PUT", queryParams, postBody, headerParams, formParams, authNames); + return apiClient.buildCall(path, "PUT", queryParams, postBody, headerParams, formParams, authNames, 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 { - Call call = updatePetCall(body); - apiClient.execute(call); + 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); } /** @@ -82,15 +113,36 @@ public class PetApi { * @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, ApiCallback callback) throws ApiException { - Call call = updatePetCall(body); + 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) throws ApiException { + private Call addPetCall(Pet body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object postBody = body; @@ -115,18 +167,42 @@ public class PetApi { final String contentType = apiClient.selectHeaderContentType(contentTypes); headerParams.put("Content-Type", contentType); + 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[] authNames = new String[] { "petstore_auth" }; - return apiClient.buildCall(path, "POST", queryParams, postBody, headerParams, formParams, authNames); + return apiClient.buildCall(path, "POST", queryParams, postBody, headerParams, formParams, authNames, progressRequestListener); } /** * Add a new pet to the store * * @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 addPet(Pet body) throws ApiException { - Call call = addPetCall(body); - apiClient.execute(call); + addPetWithHttpInfo(body); + } + + /** + * Add a new pet to the store + * + * @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 addPetWithHttpInfo(Pet body) throws ApiException { + Call call = addPetCall(body, null, null); + return apiClient.execute(call); } /** @@ -135,15 +211,36 @@ public class PetApi { * @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 addPetAsync(Pet body, ApiCallback callback) throws ApiException { - Call call = addPetCall(body); + public Call addPetAsync(Pet body, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + Call call = addPetCall(body, progressListener, progressRequestListener); apiClient.executeAsync(call, callback); return call; } /* Build call for findPetsByStatus */ - private Call findPetsByStatusCall(List status) throws ApiException { + private Call findPetsByStatusCall(List status, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object postBody = null; @@ -170,8 +267,20 @@ public class PetApi { final String contentType = apiClient.selectHeaderContentType(contentTypes); headerParams.put("Content-Type", contentType); + 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[] authNames = new String[] { "petstore_auth" }; - return apiClient.buildCall(path, "GET", queryParams, postBody, headerParams, formParams, authNames); + return apiClient.buildCall(path, "GET", queryParams, postBody, headerParams, formParams, authNames, progressRequestListener); } /** @@ -179,9 +288,22 @@ public class PetApi { * Multiple status values can be provided with comma seperated strings * @param status Status values that need to be considered for filter * @return List + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ public List findPetsByStatus(List status) throws ApiException { - Call call = findPetsByStatusCall(status); + ApiResponse> resp = findPetsByStatusWithHttpInfo(status); + return resp.getData(); + } + + /** + * 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 + * @return ApiResponse> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse> findPetsByStatusWithHttpInfo(List status) throws ApiException { + Call call = findPetsByStatusCall(status, null, null); Type returnType = new TypeToken>(){}.getType(); return apiClient.execute(call, returnType); } @@ -192,16 +314,37 @@ public class PetApi { * @param status Status values that need to be considered for filter * @param callback The callback to be executed when the API call finishes * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object */ - public Call findPetsByStatusAsync(List status, ApiCallback> callback) throws ApiException { - Call call = findPetsByStatusCall(status); + public Call findPetsByStatusAsync(List status, final ApiCallback> callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + Call call = findPetsByStatusCall(status, progressListener, progressRequestListener); Type returnType = new TypeToken>(){}.getType(); apiClient.executeAsync(call, returnType, callback); return call; } /* Build call for findPetsByTags */ - private Call findPetsByTagsCall(List tags) throws ApiException { + private Call findPetsByTagsCall(List tags, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object postBody = null; @@ -228,8 +371,20 @@ public class PetApi { final String contentType = apiClient.selectHeaderContentType(contentTypes); headerParams.put("Content-Type", contentType); + 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[] authNames = new String[] { "petstore_auth" }; - return apiClient.buildCall(path, "GET", queryParams, postBody, headerParams, formParams, authNames); + return apiClient.buildCall(path, "GET", queryParams, postBody, headerParams, formParams, authNames, progressRequestListener); } /** @@ -237,9 +392,22 @@ public class PetApi { * 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 fail to call the API, e.g. server error or cannot deserialize the response body */ public List findPetsByTags(List tags) throws ApiException { - Call call = findPetsByTagsCall(tags); + ApiResponse> resp = findPetsByTagsWithHttpInfo(tags); + return resp.getData(); + } + + /** + * 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 ApiResponse> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse> findPetsByTagsWithHttpInfo(List tags) throws ApiException { + Call call = findPetsByTagsCall(tags, null, null); Type returnType = new TypeToken>(){}.getType(); return apiClient.execute(call, returnType); } @@ -250,16 +418,37 @@ public class PetApi { * @param tags Tags to filter by * @param callback The callback to be executed when the API call finishes * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object */ - public Call findPetsByTagsAsync(List tags, ApiCallback> callback) throws ApiException { - Call call = findPetsByTagsCall(tags); + public Call findPetsByTagsAsync(List tags, final ApiCallback> callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + Call call = findPetsByTagsCall(tags, progressListener, progressRequestListener); Type returnType = new TypeToken>(){}.getType(); apiClient.executeAsync(call, returnType, callback); return call; } /* Build call for getPetById */ - private Call getPetByIdCall(Long petId) throws ApiException { + private Call getPetByIdCall(Long petId, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object postBody = null; // verify the required parameter 'petId' is set @@ -290,8 +479,20 @@ public class PetApi { final String contentType = apiClient.selectHeaderContentType(contentTypes); headerParams.put("Content-Type", contentType); + 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[] authNames = new String[] { "api_key" }; - return apiClient.buildCall(path, "GET", queryParams, postBody, headerParams, formParams, authNames); + return apiClient.buildCall(path, "GET", queryParams, postBody, headerParams, formParams, authNames, progressRequestListener); } /** @@ -299,9 +500,22 @@ public class PetApi { * 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 fail to call the API, e.g. server error or cannot deserialize the response body */ public Pet getPetById(Long petId) throws ApiException { - Call call = getPetByIdCall(petId); + ApiResponse resp = getPetByIdWithHttpInfo(petId); + return resp.getData(); + } + + /** + * 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 ApiResponse + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse getPetByIdWithHttpInfo(Long petId) throws ApiException { + Call call = getPetByIdCall(petId, null, null); Type returnType = new TypeToken(){}.getType(); return apiClient.execute(call, returnType); } @@ -312,16 +526,37 @@ public class PetApi { * @param petId ID of pet that needs to be fetched * @param callback The callback to be executed when the API call finishes * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object */ - public Call getPetByIdAsync(Long petId, ApiCallback callback) throws ApiException { - Call call = getPetByIdCall(petId); + public Call getPetByIdAsync(Long petId, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + Call call = getPetByIdCall(petId, progressListener, progressRequestListener); Type returnType = new TypeToken(){}.getType(); apiClient.executeAsync(call, returnType, callback); return call; } /* Build call for updatePetWithForm */ - private Call updatePetWithFormCall(String petId, String name, String status) throws ApiException { + private Call updatePetWithFormCall(String petId, String name, String status, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object postBody = null; // verify the required parameter 'petId' is set @@ -356,8 +591,20 @@ public class PetApi { final String contentType = apiClient.selectHeaderContentType(contentTypes); headerParams.put("Content-Type", contentType); + 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[] authNames = new String[] { "petstore_auth" }; - return apiClient.buildCall(path, "POST", queryParams, postBody, headerParams, formParams, authNames); + return apiClient.buildCall(path, "POST", queryParams, postBody, headerParams, formParams, authNames, progressRequestListener); } /** @@ -366,10 +613,24 @@ public class PetApi { * @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 { - Call call = updatePetWithFormCall(petId, name, status); - apiClient.execute(call); + 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); } /** @@ -380,15 +641,36 @@ public class PetApi { * @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, ApiCallback callback) throws ApiException { - Call call = updatePetWithFormCall(petId, name, status); + 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) throws ApiException { + private Call deletePetCall(Long petId, String apiKey, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object postBody = null; // verify the required parameter 'petId' is set @@ -421,8 +703,20 @@ public class PetApi { final String contentType = apiClient.selectHeaderContentType(contentTypes); headerParams.put("Content-Type", contentType); + 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[] authNames = new String[] { "petstore_auth" }; - return apiClient.buildCall(path, "DELETE", queryParams, postBody, headerParams, formParams, authNames); + return apiClient.buildCall(path, "DELETE", queryParams, postBody, headerParams, formParams, authNames, progressRequestListener); } /** @@ -430,10 +724,23 @@ public class PetApi { * * @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 { - Call call = deletePetCall(petId, apiKey); - apiClient.execute(call); + 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); } /** @@ -443,15 +750,36 @@ public class PetApi { * @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, ApiCallback callback) throws ApiException { - Call call = deletePetCall(petId, apiKey); + 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) throws ApiException { + private Call uploadFileCall(Long petId, String additionalMetadata, File file, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object postBody = null; // verify the required parameter 'petId' is set @@ -486,8 +814,20 @@ public class PetApi { final String contentType = apiClient.selectHeaderContentType(contentTypes); headerParams.put("Content-Type", contentType); + 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[] authNames = new String[] { "petstore_auth" }; - return apiClient.buildCall(path, "POST", queryParams, postBody, headerParams, formParams, authNames); + return apiClient.buildCall(path, "POST", queryParams, postBody, headerParams, formParams, authNames, progressRequestListener); } /** @@ -496,10 +836,24 @@ public class PetApi { * @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 { - Call call = uploadFileCall(petId, additionalMetadata, file); - apiClient.execute(call); + 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); } /** @@ -510,9 +864,30 @@ public class PetApi { * @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, ApiCallback callback) throws ApiException { - Call call = uploadFileCall(petId, additionalMetadata, file); + 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 cb780538e18..5e6c7c48c6b 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 @@ -3,12 +3,19 @@ package io.swagger.client.api; import io.swagger.client.ApiCallback; import io.swagger.client.ApiClient; import io.swagger.client.ApiException; +import io.swagger.client.ApiResponse; import io.swagger.client.Configuration; import io.swagger.client.Pair; +import io.swagger.client.ProgressRequestBody; +import io.swagger.client.ProgressResponseBody; import com.google.gson.reflect.TypeToken; import com.squareup.okhttp.Call; +import com.squareup.okhttp.Interceptor; +import com.squareup.okhttp.Response; + +import java.io.IOException; import java.util.Map; import io.swagger.client.model.Order; @@ -37,7 +44,7 @@ public class StoreApi { /* Build call for getInventory */ - private Call getInventoryCall() throws ApiException { + private Call getInventoryCall(final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object postBody = null; @@ -62,17 +69,41 @@ public class StoreApi { final String contentType = apiClient.selectHeaderContentType(contentTypes); headerParams.put("Content-Type", contentType); + 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[] authNames = new String[] { "api_key" }; - return apiClient.buildCall(path, "GET", queryParams, postBody, headerParams, formParams, authNames); + return apiClient.buildCall(path, "GET", queryParams, postBody, headerParams, formParams, authNames, progressRequestListener); } /** * Returns pet inventories by status * Returns a map of status codes to quantities * @return Map + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ public Map getInventory() throws ApiException { - Call call = getInventoryCall(); + ApiResponse> resp = getInventoryWithHttpInfo(); + return resp.getData(); + } + + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + * @return ApiResponse> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse> getInventoryWithHttpInfo() throws ApiException { + Call call = getInventoryCall(null, null); Type returnType = new TypeToken>(){}.getType(); return apiClient.execute(call, returnType); } @@ -82,16 +113,37 @@ public class StoreApi { * Returns a map of status codes to quantities * @param callback The callback to be executed when the API call finishes * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object */ - public Call getInventoryAsync(ApiCallback> callback) throws ApiException { - Call call = getInventoryCall(); + public Call getInventoryAsync(final ApiCallback> callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + Call call = getInventoryCall(progressListener, progressRequestListener); Type returnType = new TypeToken>(){}.getType(); apiClient.executeAsync(call, returnType, callback); return call; } /* Build call for placeOrder */ - private Call placeOrderCall(Order body) throws ApiException { + private Call placeOrderCall(Order body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object postBody = body; @@ -116,8 +168,20 @@ public class StoreApi { final String contentType = apiClient.selectHeaderContentType(contentTypes); headerParams.put("Content-Type", contentType); + 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[] authNames = new String[] { }; - return apiClient.buildCall(path, "POST", queryParams, postBody, headerParams, formParams, authNames); + return apiClient.buildCall(path, "POST", queryParams, postBody, headerParams, formParams, authNames, progressRequestListener); } /** @@ -125,9 +189,22 @@ public class StoreApi { * * @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 { - Call call = placeOrderCall(body); + 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 returnType = new TypeToken(){}.getType(); return apiClient.execute(call, returnType); } @@ -138,16 +215,37 @@ public class StoreApi { * @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, ApiCallback callback) throws ApiException { - Call call = placeOrderCall(body); + 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 returnType = new TypeToken(){}.getType(); apiClient.executeAsync(call, returnType, callback); return call; } /* Build call for getOrderById */ - private Call getOrderByIdCall(String orderId) throws ApiException { + private Call getOrderByIdCall(String orderId, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object postBody = null; // verify the required parameter 'orderId' is set @@ -178,8 +276,20 @@ public class StoreApi { final String contentType = apiClient.selectHeaderContentType(contentTypes); headerParams.put("Content-Type", contentType); + 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[] authNames = new String[] { }; - return apiClient.buildCall(path, "GET", queryParams, postBody, headerParams, formParams, authNames); + return apiClient.buildCall(path, "GET", queryParams, postBody, headerParams, formParams, authNames, progressRequestListener); } /** @@ -187,9 +297,22 @@ public class StoreApi { * 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 fail to call the API, e.g. server error or cannot deserialize the response body */ public Order getOrderById(String orderId) throws ApiException { - Call call = getOrderByIdCall(orderId); + ApiResponse resp = getOrderByIdWithHttpInfo(orderId); + return resp.getData(); + } + + /** + * Find purchase order by ID + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * @param orderId ID of pet that needs to be fetched + * @return ApiResponse + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse getOrderByIdWithHttpInfo(String orderId) throws ApiException { + Call call = getOrderByIdCall(orderId, null, null); Type returnType = new TypeToken(){}.getType(); return apiClient.execute(call, returnType); } @@ -200,16 +323,37 @@ public class StoreApi { * @param orderId ID of pet that needs to be fetched * @param callback The callback to be executed when the API call finishes * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object */ - public Call getOrderByIdAsync(String orderId, ApiCallback callback) throws ApiException { - Call call = getOrderByIdCall(orderId); + public Call getOrderByIdAsync(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 = getOrderByIdCall(orderId, progressListener, progressRequestListener); Type returnType = new TypeToken(){}.getType(); apiClient.executeAsync(call, returnType, callback); return call; } /* Build call for deleteOrder */ - private Call deleteOrderCall(String orderId) throws ApiException { + private Call deleteOrderCall(String orderId, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object postBody = null; // verify the required parameter 'orderId' is set @@ -240,18 +384,42 @@ public class StoreApi { final String contentType = apiClient.selectHeaderContentType(contentTypes); headerParams.put("Content-Type", contentType); + 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[] authNames = new String[] { }; - return apiClient.buildCall(path, "DELETE", queryParams, postBody, headerParams, formParams, authNames); + return apiClient.buildCall(path, "DELETE", queryParams, postBody, headerParams, formParams, authNames, 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 + * @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 { - Call call = deleteOrderCall(orderId); - apiClient.execute(call); + 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 + * @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); } /** @@ -260,9 +428,30 @@ public class StoreApi { * @param orderId ID of the order 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 deleteOrderAsync(String orderId, ApiCallback callback) throws ApiException { - Call call = deleteOrderCall(orderId); + 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; } 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 a04470b3b40..ab043bdbe3b 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 @@ -3,12 +3,19 @@ package io.swagger.client.api; import io.swagger.client.ApiCallback; import io.swagger.client.ApiClient; import io.swagger.client.ApiException; +import io.swagger.client.ApiResponse; import io.swagger.client.Configuration; import io.swagger.client.Pair; +import io.swagger.client.ProgressRequestBody; +import io.swagger.client.ProgressResponseBody; import com.google.gson.reflect.TypeToken; import com.squareup.okhttp.Call; +import com.squareup.okhttp.Interceptor; +import com.squareup.okhttp.Response; + +import java.io.IOException; import io.swagger.client.model.User; import java.util.*; @@ -37,7 +44,7 @@ public class UserApi { /* Build call for createUser */ - private Call createUserCall(User body) throws ApiException { + private Call createUserCall(User body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object postBody = body; @@ -62,18 +69,42 @@ public class UserApi { final String contentType = apiClient.selectHeaderContentType(contentTypes); headerParams.put("Content-Type", contentType); + 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[] authNames = new String[] { }; - return apiClient.buildCall(path, "POST", queryParams, postBody, headerParams, formParams, authNames); + return apiClient.buildCall(path, "POST", queryParams, postBody, headerParams, formParams, authNames, progressRequestListener); } /** * Create user * This can only be done by the logged in user. * @param body Created user object + * @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 { - Call call = createUserCall(body); - apiClient.execute(call); + createUserWithHttpInfo(body); + } + + /** + * Create user + * This can only be done by the logged in user. + * @param body Created user object + * @return ApiResponse + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse createUserWithHttpInfo(User body) throws ApiException { + Call call = createUserCall(body, null, null); + return apiClient.execute(call); } /** @@ -82,15 +113,36 @@ public class UserApi { * @param body Created user object * @param callback The callback to be executed when the API call finishes * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object */ - public Call createUserAsync(User body, ApiCallback callback) throws ApiException { - Call call = createUserCall(body); + public Call createUserAsync(User body, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + Call call = createUserCall(body, progressListener, progressRequestListener); apiClient.executeAsync(call, callback); return call; } /* Build call for createUsersWithArrayInput */ - private Call createUsersWithArrayInputCall(List body) throws ApiException { + private Call createUsersWithArrayInputCall(List body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object postBody = body; @@ -115,18 +167,42 @@ public class UserApi { final String contentType = apiClient.selectHeaderContentType(contentTypes); headerParams.put("Content-Type", contentType); + 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[] authNames = new String[] { }; - return apiClient.buildCall(path, "POST", queryParams, postBody, headerParams, formParams, authNames); + return apiClient.buildCall(path, "POST", queryParams, postBody, headerParams, formParams, authNames, progressRequestListener); } /** * Creates list of users with given input array * * @param body List of user object + * @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 { - Call call = createUsersWithArrayInputCall(body); - apiClient.execute(call); + createUsersWithArrayInputWithHttpInfo(body); + } + + /** + * Creates list of users with given input array + * + * @param body List of user object + * @return ApiResponse + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse createUsersWithArrayInputWithHttpInfo(List body) throws ApiException { + Call call = createUsersWithArrayInputCall(body, null, null); + return apiClient.execute(call); } /** @@ -135,15 +211,36 @@ public class UserApi { * @param body List of user object * @param callback The callback to be executed when the API call finishes * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object */ - public Call createUsersWithArrayInputAsync(List body, ApiCallback callback) throws ApiException { - Call call = createUsersWithArrayInputCall(body); + public Call createUsersWithArrayInputAsync(List body, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + Call call = createUsersWithArrayInputCall(body, progressListener, progressRequestListener); apiClient.executeAsync(call, callback); return call; } /* Build call for createUsersWithListInput */ - private Call createUsersWithListInputCall(List body) throws ApiException { + private Call createUsersWithListInputCall(List body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object postBody = body; @@ -168,18 +265,42 @@ public class UserApi { final String contentType = apiClient.selectHeaderContentType(contentTypes); headerParams.put("Content-Type", contentType); + 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[] authNames = new String[] { }; - return apiClient.buildCall(path, "POST", queryParams, postBody, headerParams, formParams, authNames); + return apiClient.buildCall(path, "POST", queryParams, postBody, headerParams, formParams, authNames, progressRequestListener); } /** * Creates list of users with given input array * * @param body List of user object + * @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 { - Call call = createUsersWithListInputCall(body); - apiClient.execute(call); + createUsersWithListInputWithHttpInfo(body); + } + + /** + * Creates list of users with given input array + * + * @param body List of user object + * @return ApiResponse + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse createUsersWithListInputWithHttpInfo(List body) throws ApiException { + Call call = createUsersWithListInputCall(body, null, null); + return apiClient.execute(call); } /** @@ -188,15 +309,36 @@ public class UserApi { * @param body List of user object * @param callback The callback to be executed when the API call finishes * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object */ - public Call createUsersWithListInputAsync(List body, ApiCallback callback) throws ApiException { - Call call = createUsersWithListInputCall(body); + public Call createUsersWithListInputAsync(List body, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + Call call = createUsersWithListInputCall(body, progressListener, progressRequestListener); apiClient.executeAsync(call, callback); return call; } /* Build call for loginUser */ - private Call loginUserCall(String username, String password) throws ApiException { + private Call loginUserCall(String username, String password, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object postBody = null; @@ -225,8 +367,20 @@ public class UserApi { final String contentType = apiClient.selectHeaderContentType(contentTypes); headerParams.put("Content-Type", contentType); + 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[] authNames = new String[] { }; - return apiClient.buildCall(path, "GET", queryParams, postBody, headerParams, formParams, authNames); + return apiClient.buildCall(path, "GET", queryParams, postBody, headerParams, formParams, authNames, progressRequestListener); } /** @@ -235,9 +389,23 @@ public class UserApi { * @param username The user name for login * @param password The password for login in clear text * @return String + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ public String loginUser(String username, String password) throws ApiException { - Call call = loginUserCall(username, password); + ApiResponse resp = loginUserWithHttpInfo(username, password); + return resp.getData(); + } + + /** + * Logs user into the system + * + * @param username The user name for login + * @param password The password for login in clear text + * @return ApiResponse + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse loginUserWithHttpInfo(String username, String password) throws ApiException { + Call call = loginUserCall(username, password, null, null); Type returnType = new TypeToken(){}.getType(); return apiClient.execute(call, returnType); } @@ -249,16 +417,37 @@ public class UserApi { * @param password The password for login in clear text * @param callback The callback to be executed when the API call finishes * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object */ - public Call loginUserAsync(String username, String password, ApiCallback callback) throws ApiException { - Call call = loginUserCall(username, password); + public Call loginUserAsync(String username, String password, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + Call call = loginUserCall(username, password, progressListener, progressRequestListener); Type returnType = new TypeToken(){}.getType(); apiClient.executeAsync(call, returnType, callback); return call; } /* Build call for logoutUser */ - private Call logoutUserCall() throws ApiException { + private Call logoutUserCall(final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object postBody = null; @@ -283,17 +472,40 @@ public class UserApi { final String contentType = apiClient.selectHeaderContentType(contentTypes); headerParams.put("Content-Type", contentType); + 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[] authNames = new String[] { }; - return apiClient.buildCall(path, "GET", queryParams, postBody, headerParams, formParams, authNames); + return apiClient.buildCall(path, "GET", queryParams, postBody, headerParams, formParams, authNames, progressRequestListener); } /** * Logs out current logged in user session * + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ public void logoutUser() throws ApiException { - Call call = logoutUserCall(); - apiClient.execute(call); + logoutUserWithHttpInfo(); + } + + /** + * Logs out current logged in user session + * + * @return ApiResponse + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse logoutUserWithHttpInfo() throws ApiException { + Call call = logoutUserCall(null, null); + return apiClient.execute(call); } /** @@ -301,15 +513,36 @@ public class UserApi { * * @param callback The callback to be executed when the API call finishes * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object */ - public Call logoutUserAsync(ApiCallback callback) throws ApiException { - Call call = logoutUserCall(); + public Call logoutUserAsync(final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + Call call = logoutUserCall(progressListener, progressRequestListener); apiClient.executeAsync(call, callback); return call; } /* Build call for getUserByName */ - private Call getUserByNameCall(String username) throws ApiException { + private Call getUserByNameCall(String username, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object postBody = null; // verify the required parameter 'username' is set @@ -340,8 +573,20 @@ public class UserApi { final String contentType = apiClient.selectHeaderContentType(contentTypes); headerParams.put("Content-Type", contentType); + 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[] authNames = new String[] { }; - return apiClient.buildCall(path, "GET", queryParams, postBody, headerParams, formParams, authNames); + return apiClient.buildCall(path, "GET", queryParams, postBody, headerParams, formParams, authNames, progressRequestListener); } /** @@ -349,9 +594,22 @@ public class UserApi { * * @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 { - Call call = getUserByNameCall(username); + 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 returnType = new TypeToken(){}.getType(); return apiClient.execute(call, returnType); } @@ -362,16 +620,37 @@ public class UserApi { * @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, ApiCallback callback) throws ApiException { - Call call = getUserByNameCall(username); + 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 returnType = new TypeToken(){}.getType(); apiClient.executeAsync(call, returnType, callback); return call; } /* Build call for updateUser */ - private Call updateUserCall(String username, User body) throws ApiException { + private Call updateUserCall(String username, User body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object postBody = body; // verify the required parameter 'username' is set @@ -402,8 +681,20 @@ public class UserApi { final String contentType = apiClient.selectHeaderContentType(contentTypes); headerParams.put("Content-Type", contentType); + 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[] authNames = new String[] { }; - return apiClient.buildCall(path, "PUT", queryParams, postBody, headerParams, formParams, authNames); + return apiClient.buildCall(path, "PUT", queryParams, postBody, headerParams, formParams, authNames, progressRequestListener); } /** @@ -411,10 +702,23 @@ public class UserApi { * This can only be done by the logged in user. * @param username name that need to be deleted * @param body Updated user object + * @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 { - Call call = updateUserCall(username, body); - apiClient.execute(call); + updateUserWithHttpInfo(username, body); + } + + /** + * 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 + * @return ApiResponse + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse updateUserWithHttpInfo(String username, User body) throws ApiException { + Call call = updateUserCall(username, body, null, null); + return apiClient.execute(call); } /** @@ -424,15 +728,36 @@ public class UserApi { * @param body Updated user object * @param callback The callback to be executed when the API call finishes * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object */ - public Call updateUserAsync(String username, User body, ApiCallback callback) throws ApiException { - Call call = updateUserCall(username, body); + public Call updateUserAsync(String username, User body, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + Call call = updateUserCall(username, body, progressListener, progressRequestListener); apiClient.executeAsync(call, callback); return call; } /* Build call for deleteUser */ - private Call deleteUserCall(String username) throws ApiException { + private Call deleteUserCall(String username, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object postBody = null; // verify the required parameter 'username' is set @@ -463,18 +788,42 @@ public class UserApi { final String contentType = apiClient.selectHeaderContentType(contentTypes); headerParams.put("Content-Type", contentType); + 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[] authNames = new String[] { }; - return apiClient.buildCall(path, "DELETE", queryParams, postBody, headerParams, formParams, authNames); + return apiClient.buildCall(path, "DELETE", queryParams, postBody, headerParams, formParams, authNames, 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 { - Call call = deleteUserCall(username); - apiClient.execute(call); + 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); } /** @@ -483,9 +832,30 @@ public class UserApi { * @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, ApiCallback callback) throws ApiException { - Call call = deleteUserCall(username); + 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/Authentication.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/Authentication.java index 18ca4080c2e..6817892cce9 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/Authentication.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/Authentication.java @@ -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 = "2015-10-20T11:42:25.339-07:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-12-07T12:21:33.403+08:00") public interface Authentication { /** Apply authentication settings to header and query params. */ void applyToParams(List queryParams, Map headerParams); 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 bc6473d110f..d0b457bacd8 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 = "2015-11-02T22:14:00.422+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-12-07T12:21:33.403+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 0a7023ac7a5..4f15da15c65 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 @@ -5,6 +5,7 @@ import io.swagger.client.StringUtil; import com.google.gson.annotations.SerializedName; +import java.util.Objects; import io.swagger.annotations.*; @@ -44,6 +45,24 @@ public class Category { + @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(); 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 df8e77b6fb3..18c51201ad4 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 @@ -6,6 +6,7 @@ import java.util.Date; import com.google.gson.annotations.SerializedName; +import java.util.Objects; import io.swagger.annotations.*; @@ -125,6 +126,28 @@ public enum StatusEnum { + @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(); 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 d1310e10ded..7e771866b39 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 @@ -2,12 +2,13 @@ package io.swagger.client.model; import io.swagger.client.StringUtil; import io.swagger.client.model.Category; -import io.swagger.client.model.Tag; import java.util.*; +import io.swagger.client.model.Tag; import com.google.gson.annotations.SerializedName; +import java.util.Objects; import io.swagger.annotations.*; @@ -127,6 +128,28 @@ public enum StatusEnum { + @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(); 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 9935b744f2d..474904011f7 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 @@ -5,6 +5,7 @@ import io.swagger.client.StringUtil; import com.google.gson.annotations.SerializedName; +import java.util.Objects; import io.swagger.annotations.*; @@ -44,6 +45,24 @@ public class Tag { + @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(); 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 cba6abef8dd..82f1a0822db 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 @@ -5,6 +5,7 @@ import io.swagger.client.StringUtil; import com.google.gson.annotations.SerializedName; +import java.util.Objects; import io.swagger.annotations.*; @@ -129,6 +130,30 @@ public class User { + @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(); 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 aaf4f33c49e..9b5c6805744 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 @@ -77,16 +77,29 @@ public class ApiClientTest { assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11"))); } + @Test + public void testIsJsonMime() { + assertFalse(apiClient.isJsonMime(null)); + assertFalse(apiClient.isJsonMime("")); + assertFalse(apiClient.isJsonMime("text/plain")); + assertFalse(apiClient.isJsonMime("application/xml")); + assertFalse(apiClient.isJsonMime("application/jsonp")); + + assertTrue(apiClient.isJsonMime("application/json")); + assertTrue(apiClient.isJsonMime("application/json; charset=UTF8")); + assertTrue(apiClient.isJsonMime("APPLICATION/JSON")); + } + @Test public void testSelectHeaderAccept() { - String[] accepts = {"APPLICATION/JSON", "APPLICATION/XML"}; + String[] accepts = {"application/json", "application/xml"}; assertEquals("application/json", apiClient.selectHeaderAccept(accepts)); - accepts = new String[]{"application/json", "application/xml"}; - assertEquals("application/json", apiClient.selectHeaderAccept(accepts)); + accepts = new String[]{"APPLICATION/XML", "APPLICATION/JSON"}; + assertEquals("APPLICATION/JSON", apiClient.selectHeaderAccept(accepts)); - accepts = new String[]{"application/xml", "application/json"}; - assertEquals("application/json", apiClient.selectHeaderAccept(accepts)); + accepts = new String[]{"application/xml", "application/json; charset=UTF8"}; + assertEquals("application/json; charset=UTF8", apiClient.selectHeaderAccept(accepts)); accepts = new String[]{"text/plain", "application/xml"}; assertEquals("text/plain,application/xml", apiClient.selectHeaderAccept(accepts)); @@ -97,14 +110,14 @@ public class ApiClientTest { @Test public void testSelectHeaderContentType() { - String[] contentTypes = {"APPLICATION/JSON", "APPLICATION/XML"}; + String[] contentTypes = {"application/json", "application/xml"}; assertEquals("application/json", apiClient.selectHeaderContentType(contentTypes)); - contentTypes = new String[]{"application/json", "application/xml"}; - assertEquals("application/json", apiClient.selectHeaderContentType(contentTypes)); + contentTypes = new String[]{"APPLICATION/JSON", "APPLICATION/XML"}; + assertEquals("APPLICATION/JSON", apiClient.selectHeaderContentType(contentTypes)); - contentTypes = new String[]{"application/xml", "application/json"}; - assertEquals("application/json", apiClient.selectHeaderContentType(contentTypes)); + contentTypes = new String[]{"application/xml", "application/json; charset=UTF8"}; + assertEquals("application/json; charset=UTF8", apiClient.selectHeaderContentType(contentTypes)); contentTypes = new String[]{"text/plain", "application/xml"}; assertEquals("text/plain", apiClient.selectHeaderContentType(contentTypes)); diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/petstore/test/PetApiTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/petstore/test/PetApiTest.java index c9586343025..56cc8073984 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/petstore/test/PetApiTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/petstore/test/PetApiTest.java @@ -1,10 +1,6 @@ package io.swagger.petstore.test; -import io.swagger.client.ApiClient; -import io.swagger.client.ApiException; -import io.swagger.client.Configuration; - -import io.swagger.client.ApiCallback; +import io.swagger.client.*; import io.swagger.client.api.*; import io.swagger.client.auth.*; import io.swagger.client.model.*; @@ -71,6 +67,21 @@ public class PetApiTest { assertEquals(fetched.getCategory().getName(), pet.getCategory().getName()); } + @Test + public void testCreateAndGetPetWithHttpInfo() throws Exception { + Pet pet = createRandomPet(); + api.addPetWithHttpInfo(pet); + + ApiResponse resp = api.getPetByIdWithHttpInfo(pet.getId()); + assertEquals(200, resp.getStatusCode()); + assertEquals("application/json", resp.getHeaders().get("Content-Type").get(0)); + Pet fetched = resp.getData(); + assertNotNull(fetched); + assertEquals(pet.getId(), fetched.getId()); + assertNotNull(fetched.getCategory()); + assertEquals(fetched.getCategory().getName(), pet.getCategory().getName()); + } + @Test public void testCreateAndGetPetAsync() throws Exception { Pet pet = createRandomPet(); @@ -88,6 +99,16 @@ public class PetApiTest { public void onSuccess(Pet pet, int statusCode, Map> responseHeaders) { result.put("pet", pet); } + + @Override + public void onUploadProgress(long bytesWritten, long contentLength, boolean done) { + //empty + } + + @Override + public void onDownloadProgress(long bytesRead, long contentLength, boolean done) { + //empty + } }); // the API call should be executed asynchronously, so result should be empty at the moment assertTrue(result.isEmpty()); @@ -123,6 +144,16 @@ public class PetApiTest { public void onSuccess(Pet pet, int statusCode, Map> responseHeaders) { result.put("pet", pet); } + + @Override + public void onUploadProgress(long bytesWritten, long contentLength, boolean done) { + //empty + } + + @Override + public void onDownloadProgress(long bytesRead, long contentLength, boolean done) { + //empty + } }); // the API call should be executed asynchronously, so result should be empty at the moment assertTrue(result.isEmpty()); @@ -252,6 +283,33 @@ public class PetApiTest { api.uploadFile(pet.getId(), "a test file", new File(file.getAbsolutePath())); } + @Test + public void testEqualsAndHashCode() { + Pet pet1 = new Pet(); + Pet pet2 = new Pet(); + assertTrue(pet1.equals(pet2)); + assertTrue(pet2.equals(pet1)); + assertTrue(pet1.hashCode() == pet2.hashCode()); + assertTrue(pet1.equals(pet1)); + assertTrue(pet1.hashCode() == pet1.hashCode()); + + pet2.setName("really-happy"); + pet2.setPhotoUrls(Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"})); + assertFalse(pet1.equals(pet2)); + assertFalse(pet2.equals(pet1)); + assertFalse(pet1.hashCode() == (pet2.hashCode())); + assertTrue(pet2.equals(pet2)); + assertTrue(pet2.hashCode() == pet2.hashCode()); + + pet1.setName("really-happy"); + pet1.setPhotoUrls(Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"})); + assertTrue(pet1.equals(pet2)); + assertTrue(pet2.equals(pet1)); + assertTrue(pet1.hashCode() == pet2.hashCode()); + assertTrue(pet1.equals(pet1)); + assertTrue(pet1.hashCode() == pet1.hashCode()); + } + private Pet createRandomPet() { Pet pet = new Pet(); pet.setId(System.currentTimeMillis()); diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/ApiClient.java index 6540997c319..ed1ff85acab 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/ApiClient.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/ApiClient.java @@ -47,10 +47,10 @@ public class ApiClient { this(); for(String authName : authNames) { Interceptor auth; - if (authName == "petstore_auth") { - auth = new OAuth(OAuthFlow.implicit, "http://petstore.swagger.io/api/oauth/dialog", "", "write:pets, read:pets"); - } else if (authName == "api_key") { + if (authName == "api_key") { auth = new ApiKeyAuth("header", "api_key"); + } else if (authName == "petstore_auth") { + auth = new OAuth(OAuthFlow.implicit, "http://petstore.swagger.io/api/oauth/dialog", "", "write:pets, read:pets"); } else { throw new RuntimeException("auth name \"" + authName + "\" not found in available auth names"); } 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 2f6d6fed42c..fa3abdc9c78 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 = "2015-10-20T11:42:31.307-07:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-11-29T00:18:14.988+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 cd4dbe866a5..1746009aa77 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 @@ -1,15 +1,16 @@ package io.swagger.client.api; -import io.swagger.client.model.*; +import io.swagger.client.CollectionFormats.*; import retrofit.Callback; import retrofit.http.*; import retrofit.mime.*; -import java.util.*; import io.swagger.client.model.Pet; import java.io.File; +import java.util.*; + public interface PetApi { /** @@ -20,7 +21,7 @@ public interface PetApi { * @return Void */ - @PUT("/pet") + @PUT("/pet") Void updatePet( @Body Pet body ); @@ -29,14 +30,14 @@ public interface PetApi { * Update an existing pet * Async method * @param body Pet object that needs to be added to the store - * @param cb callback method + * @param cb callback method * @return void */ - @PUT("/pet") + @PUT("/pet") void updatePet( @Body Pet body, Callback cb - ); + ); /** * Add a new pet to the store @@ -46,7 +47,7 @@ public interface PetApi { * @return Void */ - @POST("/pet") + @POST("/pet") Void addPet( @Body Pet body ); @@ -55,14 +56,14 @@ 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 cb callback method + * @param cb callback method * @return void */ - @POST("/pet") + @POST("/pet") void addPet( @Body Pet body, Callback cb - ); + ); /** * Finds Pets by status @@ -72,7 +73,7 @@ public interface PetApi { * @return List */ - @GET("/pet/findByStatus") + @GET("/pet/findByStatus") List findPetsByStatus( @Query("status") List status ); @@ -81,14 +82,14 @@ public interface PetApi { * Finds Pets by status * Async method * @param status Status values that need to be considered for filter - * @param cb callback method + * @param cb callback method * @return void */ - @GET("/pet/findByStatus") + @GET("/pet/findByStatus") void findPetsByStatus( @Query("status") List status, Callback> cb - ); + ); /** * Finds Pets by tags @@ -98,7 +99,7 @@ public interface PetApi { * @return List */ - @GET("/pet/findByTags") + @GET("/pet/findByTags") List findPetsByTags( @Query("tags") List tags ); @@ -107,14 +108,14 @@ public interface PetApi { * Finds Pets by tags * Async method * @param tags Tags to filter by - * @param cb callback method + * @param cb callback method * @return void */ - @GET("/pet/findByTags") + @GET("/pet/findByTags") void findPetsByTags( @Query("tags") List tags, Callback> cb - ); + ); /** * Find pet by ID @@ -124,7 +125,7 @@ public interface PetApi { * @return Pet */ - @GET("/pet/{petId}") + @GET("/pet/{petId}") Pet getPetById( @Path("petId") Long petId ); @@ -133,14 +134,14 @@ public interface PetApi { * Find pet by ID * Async method * @param petId ID of pet that needs to be fetched - * @param cb callback method + * @param cb callback method * @return void */ - @GET("/pet/{petId}") + @GET("/pet/{petId}") void getPetById( @Path("petId") Long petId, Callback cb - ); + ); /** * Updates a pet in the store with form data @@ -153,7 +154,7 @@ public interface PetApi { */ @FormUrlEncoded - @POST("/pet/{petId}") + @POST("/pet/{petId}") Void updatePetWithForm( @Path("petId") String petId, @Field("name") String name, @Field("status") String status ); @@ -164,15 +165,15 @@ public interface PetApi { * @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 + * @param cb callback method * @return void */ @FormUrlEncoded - @POST("/pet/{petId}") + @POST("/pet/{petId}") void updatePetWithForm( @Path("petId") String petId, @Field("name") String name, @Field("status") String status, Callback cb - ); + ); /** * Deletes a pet @@ -183,7 +184,7 @@ public interface PetApi { * @return Void */ - @DELETE("/pet/{petId}") + @DELETE("/pet/{petId}") Void deletePet( @Path("petId") Long petId, @Header("api_key") String apiKey ); @@ -193,14 +194,14 @@ public interface PetApi { * Async method * @param petId Pet id to delete * @param apiKey - * @param cb callback method + * @param cb callback method * @return void */ - @DELETE("/pet/{petId}") + @DELETE("/pet/{petId}") void deletePet( @Path("petId") Long petId, @Header("api_key") String apiKey, Callback cb - ); + ); /** * uploads an image @@ -213,7 +214,7 @@ public interface PetApi { */ @Multipart - @POST("/pet/{petId}/uploadImage") + @POST("/pet/{petId}/uploadImage") Void uploadFile( @Path("petId") Long petId, @Part("additionalMetadata") String additionalMetadata, @Part("file") TypedFile file ); @@ -224,14 +225,14 @@ public interface PetApi { * @param petId ID of pet to update * @param additionalMetadata Additional data to pass to server * @param file file to upload - * @param cb callback method + * @param cb callback method * @return void */ @Multipart - @POST("/pet/{petId}/uploadImage") + @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 1c0a8291d02..4d6d3aa7c00 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 @@ -1,15 +1,16 @@ package io.swagger.client.api; -import io.swagger.client.model.*; +import io.swagger.client.CollectionFormats.*; import retrofit.Callback; import retrofit.http.*; import retrofit.mime.*; -import java.util.*; import java.util.Map; import io.swagger.client.model.Order; +import java.util.*; + public interface StoreApi { /** @@ -19,21 +20,21 @@ public interface StoreApi { * @return Map */ - @GET("/store/inventory") + @GET("/store/inventory") Map getInventory(); /** * Returns pet inventories by status * Async method - * @param cb callback method + * @param cb callback method * @return void */ - @GET("/store/inventory") + @GET("/store/inventory") void getInventory( Callback> cb - ); + ); /** * Place an order for a pet @@ -43,7 +44,7 @@ public interface StoreApi { * @return Order */ - @POST("/store/order") + @POST("/store/order") Order placeOrder( @Body Order body ); @@ -52,14 +53,14 @@ public interface StoreApi { * Place an order for a pet * Async method * @param body order placed for purchasing the pet - * @param cb callback method + * @param cb callback method * @return void */ - @POST("/store/order") + @POST("/store/order") void placeOrder( @Body Order body, Callback cb - ); + ); /** * Find purchase order by ID @@ -69,7 +70,7 @@ public interface StoreApi { * @return Order */ - @GET("/store/order/{orderId}") + @GET("/store/order/{orderId}") Order getOrderById( @Path("orderId") String orderId ); @@ -78,14 +79,14 @@ public interface StoreApi { * Find purchase order by ID * Async method * @param orderId ID of pet that needs to be fetched - * @param cb callback method + * @param cb callback method * @return void */ - @GET("/store/order/{orderId}") + @GET("/store/order/{orderId}") void getOrderById( @Path("orderId") String orderId, Callback cb - ); + ); /** * Delete purchase order by ID @@ -95,7 +96,7 @@ public interface StoreApi { * @return Void */ - @DELETE("/store/order/{orderId}") + @DELETE("/store/order/{orderId}") Void deleteOrder( @Path("orderId") String orderId ); @@ -104,13 +105,13 @@ public interface StoreApi { * Delete purchase order by ID * Async method * @param orderId ID of the order that needs to be deleted - * @param cb callback method + * @param cb callback method * @return void */ - @DELETE("/store/order/{orderId}") + @DELETE("/store/order/{orderId}") void deleteOrder( @Path("orderId") String orderId, 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 162222bc0f1..ff4b4562977 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 @@ -1,15 +1,16 @@ package io.swagger.client.api; -import io.swagger.client.model.*; +import io.swagger.client.CollectionFormats.*; import retrofit.Callback; import retrofit.http.*; import retrofit.mime.*; -import java.util.*; import io.swagger.client.model.User; import java.util.*; +import java.util.*; + public interface UserApi { /** @@ -20,7 +21,7 @@ public interface UserApi { * @return Void */ - @POST("/user") + @POST("/user") Void createUser( @Body User body ); @@ -29,14 +30,14 @@ public interface UserApi { * Create user * Async method * @param body Created user object - * @param cb callback method + * @param cb callback method * @return void */ - @POST("/user") + @POST("/user") void createUser( @Body User body, Callback cb - ); + ); /** * Creates list of users with given input array @@ -46,7 +47,7 @@ public interface UserApi { * @return Void */ - @POST("/user/createWithArray") + @POST("/user/createWithArray") Void createUsersWithArrayInput( @Body List body ); @@ -55,14 +56,14 @@ public interface UserApi { * Creates list of users with given input array * Async method * @param body List of user object - * @param cb callback method + * @param cb callback method * @return void */ - @POST("/user/createWithArray") + @POST("/user/createWithArray") void createUsersWithArrayInput( @Body List body, Callback cb - ); + ); /** * Creates list of users with given input array @@ -72,7 +73,7 @@ public interface UserApi { * @return Void */ - @POST("/user/createWithList") + @POST("/user/createWithList") Void createUsersWithListInput( @Body List body ); @@ -81,14 +82,14 @@ public interface UserApi { * Creates list of users with given input array * Async method * @param body List of user object - * @param cb callback method + * @param cb callback method * @return void */ - @POST("/user/createWithList") + @POST("/user/createWithList") void createUsersWithListInput( @Body List body, Callback cb - ); + ); /** * Logs user into the system @@ -99,7 +100,7 @@ public interface UserApi { * @return String */ - @GET("/user/login") + @GET("/user/login") String loginUser( @Query("username") String username, @Query("password") String password ); @@ -109,14 +110,14 @@ public interface UserApi { * Async method * @param username The user name for login * @param password The password for login in clear text - * @param cb callback method + * @param cb callback method * @return void */ - @GET("/user/login") + @GET("/user/login") void loginUser( @Query("username") String username, @Query("password") String password, Callback cb - ); + ); /** * Logs out current logged in user session @@ -125,21 +126,21 @@ public interface UserApi { * @return Void */ - @GET("/user/logout") + @GET("/user/logout") Void logoutUser(); /** * Logs out current logged in user session * Async method - * @param cb callback method + * @param cb callback method * @return void */ - @GET("/user/logout") + @GET("/user/logout") void logoutUser( Callback cb - ); + ); /** * Get user by user name @@ -149,7 +150,7 @@ public interface UserApi { * @return User */ - @GET("/user/{username}") + @GET("/user/{username}") User getUserByName( @Path("username") String username ); @@ -158,14 +159,14 @@ public interface UserApi { * Get user by user name * Async method * @param username The name that needs to be fetched. Use user1 for testing. - * @param cb callback method + * @param cb callback method * @return void */ - @GET("/user/{username}") + @GET("/user/{username}") void getUserByName( @Path("username") String username, Callback cb - ); + ); /** * Updated user @@ -176,7 +177,7 @@ public interface UserApi { * @return Void */ - @PUT("/user/{username}") + @PUT("/user/{username}") Void updateUser( @Path("username") String username, @Body User body ); @@ -186,14 +187,14 @@ public interface UserApi { * Async method * @param username name that need to be deleted * @param body Updated user object - * @param cb callback method + * @param cb callback method * @return void */ - @PUT("/user/{username}") + @PUT("/user/{username}") void updateUser( @Path("username") String username, @Body User body, Callback cb - ); + ); /** * Delete user @@ -203,7 +204,7 @@ public interface UserApi { * @return Void */ - @DELETE("/user/{username}") + @DELETE("/user/{username}") Void deleteUser( @Path("username") String username ); @@ -212,13 +213,13 @@ public interface UserApi { * Delete user * Async method * @param username The name that needs to be deleted - * @param cb callback method + * @param cb callback method * @return void */ - @DELETE("/user/{username}") + @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/auth/OAuth.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/auth/OAuth.java index 80614f0f56a..b725e019aff 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/auth/OAuth.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/auth/OAuth.java @@ -1,6 +1,7 @@ package io.swagger.client.auth; import static java.net.HttpURLConnection.HTTP_UNAUTHORIZED; +import static java.net.HttpURLConnection.HTTP_FORBIDDEN; import java.io.IOException; import java.util.Map; @@ -85,42 +86,55 @@ public class OAuth implements Interceptor { updateAccessToken(null); } - // Build the request - Builder rb = request.newBuilder(); - - String requestAccessToken = new String(getAccessToken()); - try { - oAuthRequest = new OAuthBearerClientRequest(request.urlString()) - .setAccessToken(requestAccessToken) - .buildHeaderMessage(); - } catch (OAuthSystemException e) { - throw new IOException(e); + if (getAccessToken() != null) { + // Build the request + Builder rb = request.newBuilder(); + + String requestAccessToken = new String(getAccessToken()); + try { + oAuthRequest = new OAuthBearerClientRequest(request.urlString()) + .setAccessToken(requestAccessToken) + .buildHeaderMessage(); + } catch (OAuthSystemException e) { + throw new IOException(e); + } + + for ( Map.Entry header : oAuthRequest.getHeaders().entrySet() ) { + rb.addHeader(header.getKey(), header.getValue()); + } + rb.url( oAuthRequest.getLocationUri()); + + //Execute the request + Response response = chain.proceed(rb.build()); + + // 401 most likely indicates that access token has expired. + // Time to refresh and resend the request + if ( response != null && (response.code() == HTTP_UNAUTHORIZED | response.code() == HTTP_FORBIDDEN) ) { + if (updateAccessToken(requestAccessToken)) { + return intercept( chain ); + } + } + return response; + } else { + return chain.proceed(chain.request()); } - - for ( Map.Entry header : oAuthRequest.getHeaders().entrySet() ) { - rb.addHeader(header.getKey(), header.getValue()); - } - rb.url( oAuthRequest.getLocationUri()); - - //Execute the request - Response response = chain.proceed(rb.build()); - - // 401 most likely indicates that access token has expired. - // Time to refresh and resend the request - if ( response.code() == HTTP_UNAUTHORIZED ) { - updateAccessToken(requestAccessToken); - return intercept( chain ); - } - return response; } - public synchronized void updateAccessToken(String requestAccessToken) throws IOException { + /* + * Returns true if the access token has been updated + */ + public synchronized boolean updateAccessToken(String requestAccessToken) throws IOException { if (getAccessToken() == null || getAccessToken().equals(requestAccessToken)) { try { OAuthJSONAccessTokenResponse accessTokenResponse = oauthClient.accessToken(this.tokenRequestBuilder.buildBodyMessage()); - setAccessToken(accessTokenResponse.getAccessToken()); - if (accessTokenListener != null) { - accessTokenListener.notify((BasicOAuthToken) accessTokenResponse.getOAuthToken()); + if (accessTokenResponse != null && accessTokenResponse.getAccessToken() != null) { + setAccessToken(accessTokenResponse.getAccessToken()); + if (accessTokenListener != null) { + accessTokenListener.notify((BasicOAuthToken) accessTokenResponse.getOAuthToken()); + } + return getAccessToken().equals(requestAccessToken); + } else { + return false; } } catch (OAuthSystemException e) { throw new IOException(e); @@ -128,6 +142,7 @@ public class OAuth implements Interceptor { throw new IOException(e); } } + return true; } public void registerAccessTokenListener(AccessTokenListener accessTokenListener) { diff --git a/samples/client/petstore/java/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 0a7023ac7a5..4f15da15c65 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 @@ -5,6 +5,7 @@ import io.swagger.client.StringUtil; import com.google.gson.annotations.SerializedName; +import java.util.Objects; import io.swagger.annotations.*; @@ -44,6 +45,24 @@ public class Category { + @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(); 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 df8e77b6fb3..18c51201ad4 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 @@ -6,6 +6,7 @@ import java.util.Date; import com.google.gson.annotations.SerializedName; +import java.util.Objects; import io.swagger.annotations.*; @@ -125,6 +126,28 @@ public enum StatusEnum { + @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(); 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 d1310e10ded..bc3b80370b0 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,6 +8,7 @@ import java.util.*; import com.google.gson.annotations.SerializedName; +import java.util.Objects; import io.swagger.annotations.*; @@ -127,6 +128,28 @@ public enum StatusEnum { + @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(); 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 9935b744f2d..474904011f7 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 @@ -5,6 +5,7 @@ import io.swagger.client.StringUtil; import com.google.gson.annotations.SerializedName; +import java.util.Objects; import io.swagger.annotations.*; @@ -44,6 +45,24 @@ public class Tag { + @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(); 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 cba6abef8dd..82f1a0822db 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 @@ -5,6 +5,7 @@ import io.swagger.client.StringUtil; import com.google.gson.annotations.SerializedName; +import java.util.Objects; import io.swagger.annotations.*; @@ -129,6 +130,30 @@ public class User { + @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(); diff --git a/samples/client/petstore/java/retrofit/src/test/java/io/swagger/petstore/test/PetApiTest.java b/samples/client/petstore/java/retrofit/src/test/java/io/swagger/petstore/test/PetApiTest.java index ec93912b1f6..1ff1dbb10e2 100644 --- a/samples/client/petstore/java/retrofit/src/test/java/io/swagger/petstore/test/PetApiTest.java +++ b/samples/client/petstore/java/retrofit/src/test/java/io/swagger/petstore/test/PetApiTest.java @@ -143,6 +143,33 @@ public class PetApiTest { api.uploadFile(pet.getId(), "a test file", new TypedFile("text/plain", file)); } + @Test + public void testEqualsAndHashCode() { + Pet pet1 = new Pet(); + Pet pet2 = new Pet(); + assertTrue(pet1.equals(pet2)); + assertTrue(pet2.equals(pet1)); + assertTrue(pet1.hashCode() == pet2.hashCode()); + assertTrue(pet1.equals(pet1)); + assertTrue(pet1.hashCode() == pet1.hashCode()); + + pet2.setName("really-happy"); + pet2.setPhotoUrls(Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"})); + assertFalse(pet1.equals(pet2)); + assertFalse(pet2.equals(pet1)); + assertFalse(pet1.hashCode() == (pet2.hashCode())); + assertTrue(pet2.equals(pet2)); + assertTrue(pet2.hashCode() == pet2.hashCode()); + + pet1.setName("really-happy"); + pet1.setPhotoUrls(Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"})); + assertTrue(pet1.equals(pet2)); + assertTrue(pet2.equals(pet1)); + assertTrue(pet1.hashCode() == pet2.hashCode()); + assertTrue(pet1.equals(pet1)); + assertTrue(pet1.hashCode() == pet1.hashCode()); + } + private Pet createRandomPet() { Pet pet = new Pet(); pet.setId(System.currentTimeMillis()); diff --git a/samples/client/petstore/java/retrofit2/build.gradle b/samples/client/petstore/java/retrofit2/build.gradle index 0deeeea2e37..29e1737f3b3 100644 --- a/samples/client/petstore/java/retrofit2/build.gradle +++ b/samples/client/petstore/java/retrofit2/build.gradle @@ -98,8 +98,8 @@ ext { dependencies { compile "com.squareup.okhttp:okhttp:$okhttp_version" compile "com.squareup.retrofit:retrofit:$retrofit_version" - compile 'com.google.code.gson:gson:$gson_version' - compile 'com.squareup.retrofit:converter-gson:$retrofit_version' + compile "com.google.code.gson:gson:$gson_version" + compile "com.squareup.retrofit:converter-gson:$retrofit_version" compile "io.swagger:swagger-annotations:$swagger_annotations_version" compile "org.apache.oltu.oauth2:org.apache.oltu.oauth2.client:$oltu_version" testCompile "junit:junit:$junit_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 2138c3a172b..75e641c689c 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 @@ -44,10 +44,10 @@ public class ApiClient { this(); for(String authName : authNames) { Interceptor auth; - if (authName == "petstore_auth") { - auth = new OAuth(OAuthFlow.implicit, "http://petstore.swagger.io/api/oauth/dialog", "", "write:pets, read:pets"); - } else if (authName == "api_key") { + if (authName == "api_key") { auth = new ApiKeyAuth("header", "api_key"); + } else if (authName == "petstore_auth") { + auth = new OAuth(OAuthFlow.implicit, "http://petstore.swagger.io/api/oauth/dialog", "", "write:pets, read:pets"); } else { throw new RuntimeException("auth name \"" + authName + "\" not found in available auth names"); } 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 5125ae3e55b..47f9908c4de 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 = "2015-11-10T12:25:26.227+01:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-11-28T16:01:49.902+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/model/Category.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Category.java index 0a7023ac7a5..4f15da15c65 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 @@ -5,6 +5,7 @@ import io.swagger.client.StringUtil; import com.google.gson.annotations.SerializedName; +import java.util.Objects; import io.swagger.annotations.*; @@ -44,6 +45,24 @@ public class Category { + @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(); 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 df8e77b6fb3..18c51201ad4 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 @@ -6,6 +6,7 @@ import java.util.Date; import com.google.gson.annotations.SerializedName; +import java.util.Objects; import io.swagger.annotations.*; @@ -125,6 +126,28 @@ public enum StatusEnum { + @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(); 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 9ab5457e26a..bc3b80370b0 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 @@ -2,12 +2,13 @@ package io.swagger.client.model; import io.swagger.client.StringUtil; import io.swagger.client.model.Category; -import java.util.*; import io.swagger.client.model.Tag; +import java.util.*; import com.google.gson.annotations.SerializedName; +import java.util.Objects; import io.swagger.annotations.*; @@ -127,6 +128,28 @@ public enum StatusEnum { + @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(); 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 9935b744f2d..474904011f7 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 @@ -5,6 +5,7 @@ import io.swagger.client.StringUtil; import com.google.gson.annotations.SerializedName; +import java.util.Objects; import io.swagger.annotations.*; @@ -44,6 +45,24 @@ public class Tag { + @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(); 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 cba6abef8dd..82f1a0822db 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 @@ -5,6 +5,7 @@ import io.swagger.client.StringUtil; import com.google.gson.annotations.SerializedName; +import java.util.Objects; import io.swagger.annotations.*; @@ -129,6 +130,30 @@ public class User { + @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(); diff --git a/samples/client/petstore/java/retrofit2/src/test/java/io/swagger/petstore/test/PetApiTest.java b/samples/client/petstore/java/retrofit2/src/test/java/io/swagger/petstore/test/PetApiTest.java index 8522c4f30ad..8506fc08f5c 100644 --- a/samples/client/petstore/java/retrofit2/src/test/java/io/swagger/petstore/test/PetApiTest.java +++ b/samples/client/petstore/java/retrofit2/src/test/java/io/swagger/petstore/test/PetApiTest.java @@ -142,6 +142,33 @@ public class PetApiTest { api.uploadFile(pet.getId(), "a test file", RequestBody.create(MediaType.parse("text/plain"), file)).execute(); } + @Test + public void testEqualsAndHashCode() { + Pet pet1 = new Pet(); + Pet pet2 = new Pet(); + assertTrue(pet1.equals(pet2)); + assertTrue(pet2.equals(pet1)); + assertTrue(pet1.hashCode() == pet2.hashCode()); + assertTrue(pet1.equals(pet1)); + assertTrue(pet1.hashCode() == pet1.hashCode()); + + pet2.setName("really-happy"); + pet2.setPhotoUrls(Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"})); + assertFalse(pet1.equals(pet2)); + assertFalse(pet2.equals(pet1)); + assertFalse(pet1.hashCode() == (pet2.hashCode())); + assertTrue(pet2.equals(pet2)); + assertTrue(pet2.hashCode() == pet2.hashCode()); + + pet1.setName("really-happy"); + pet1.setPhotoUrls(Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"})); + assertTrue(pet1.equals(pet2)); + assertTrue(pet2.equals(pet1)); + assertTrue(pet1.hashCode() == pet2.hashCode()); + assertTrue(pet1.equals(pet1)); + assertTrue(pet1.hashCode() == pet1.hashCode()); + } + private Pet createRandomPet() { Pet pet = new Pet(); pet.setId(System.currentTimeMillis()); diff --git a/samples/client/petstore/javascript/.gitignore b/samples/client/petstore/javascript/.gitignore new file mode 100644 index 00000000000..2ccbe4656c6 --- /dev/null +++ b/samples/client/petstore/javascript/.gitignore @@ -0,0 +1 @@ +/node_modules/ diff --git a/samples/client/petstore/javascript/package.json b/samples/client/petstore/javascript/package.json new file mode 100644 index 00000000000..6810fd633de --- /dev/null +++ b/samples/client/petstore/javascript/package.json @@ -0,0 +1,20 @@ +{ + "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", + "license": "Apache 2.0", + "main": "src/index.js", + "scripts": { + "test": "./node_modules/mocha/bin/mocha --recursive" + }, + "dependencies": { + "jquery": "~2.1.4" + }, + "devDependencies": { + "mocha": "~2.3.4", + "expect.js": "~0.3.1", + "mockrequire": "~0.0.5", + "domino": "~1.0.20", + "xmlhttprequest": "~1.8.0" + } +} diff --git a/samples/client/petstore/javascript/pom.xml b/samples/client/petstore/javascript/pom.xml new file mode 100644 index 00000000000..b7a17c92b79 --- /dev/null +++ b/samples/client/petstore/javascript/pom.xml @@ -0,0 +1,45 @@ + + 4.0.0 + io.swagger + swagger-petstore-javascript + pom + 1.0-SNAPSHOT + Swagger Petstore - Javascript Client + + + + org.codehaus.mojo + exec-maven-plugin + 1.2.1 + + + npm-install + pre-integration-test + + exec + + + npm + + install + + + + + mocha + integration-test + + exec + + + npm + + test + + + + + + + + diff --git a/samples/client/petstore/javascript/src/api/PetApi.js b/samples/client/petstore/javascript/src/api/PetApi.js new file mode 100644 index 00000000000..3b6d9c5b4c6 --- /dev/null +++ b/samples/client/petstore/javascript/src/api/PetApi.js @@ -0,0 +1,527 @@ +// require files in Node.js environment +var $, Pet; +if (typeof module === 'object' && module.exports) { + $ = require('jquery'); + Pet = require('../model/Pet.js'); +} + +// export module for AMD +if ( typeof define === "function" && define.amd ) { + define(['jquery', 'Pet'], function($, Pet) { + return PetApi; + }); +} + +var PetApi = function PetApi() { + var self = this; + + + /** + * Update an existing pet + * + * @param {Pet} body Pet object that needs to be added to the store + * @param {function} callback the callback function + * @return void + */ + self.updatePet = function(body, callback) { + var postBody = JSON.stringify(body); + var postBinaryBody = null; + + // create path and map variables + var basePath = 'http://petstore.swagger.io/v2'; + // if basePath ends with a /, remove it as path starts with a leading / + if (basePath.substring(basePath.length-1, basePath.length)=='/') { + basePath = basePath.substring(0, basePath.length-1); + } + + var path = basePath + replaceAll(replaceAll("/pet", "\\{format\\}","json")); + + var queryParams = {}; + var headerParams = {}; + var formParams = {}; + + + + + + path += createQueryString(queryParams); + + var options = {type: "PUT", async: true, contentType: "application/json", dataType: "json", data: postBody}; + var request = $.ajax(path, options); + + request.fail(function(jqXHR, textStatus, errorThrown){ + if (callback) { + var error = errorThrown || textStatus || jqXHR.statusText || 'error'; + callback(null, textStatus, jqXHR, error); + } + }); + + request.done(function(response, textStatus, jqXHR){ + + if (callback) { + callback(response, textStatus, jqXHR); + } + + }); + + return request; + } + + /** + * Add a new pet to the store + * + * @param {Pet} body Pet object that needs to be added to the store + * @param {function} callback the callback function + * @return void + */ + self.addPet = function(body, callback) { + var postBody = JSON.stringify(body); + var postBinaryBody = null; + + // create path and map variables + var basePath = 'http://petstore.swagger.io/v2'; + // if basePath ends with a /, remove it as path starts with a leading / + if (basePath.substring(basePath.length-1, basePath.length)=='/') { + basePath = basePath.substring(0, basePath.length-1); + } + + var path = basePath + replaceAll(replaceAll("/pet", "\\{format\\}","json")); + + var queryParams = {}; + var headerParams = {}; + var formParams = {}; + + + + + + path += createQueryString(queryParams); + + var options = {type: "POST", async: true, contentType: "application/json", dataType: "json", data: postBody}; + var request = $.ajax(path, options); + + request.fail(function(jqXHR, textStatus, errorThrown){ + if (callback) { + var error = errorThrown || textStatus || jqXHR.statusText || 'error'; + callback(null, textStatus, jqXHR, error); + } + }); + + request.done(function(response, textStatus, jqXHR){ + + if (callback) { + callback(response, textStatus, jqXHR); + } + + }); + + return request; + } + + /** + * Finds Pets by status + * Multiple status values can be provided with comma seperated strings + * @param {Array} status Status values that need to be considered for filter + * @param {function} callback the callback function + * @return Array + */ + self.findPetsByStatus = function(status, callback) { + var postBody = null; + var postBinaryBody = null; + + // create path and map variables + var basePath = 'http://petstore.swagger.io/v2'; + // if basePath ends with a /, remove it as path starts with a leading / + if (basePath.substring(basePath.length-1, basePath.length)=='/') { + basePath = basePath.substring(0, basePath.length-1); + } + + var path = basePath + replaceAll(replaceAll("/pet/findByStatus", "\\{format\\}","json")); + + var queryParams = {}; + var headerParams = {}; + var formParams = {}; + + + queryParams.status = status; + + + + + path += createQueryString(queryParams); + + var options = {type: "GET", async: true, contentType: "application/json", dataType: "json", data: postBody}; + var request = $.ajax(path, options); + + request.fail(function(jqXHR, textStatus, errorThrown){ + if (callback) { + var error = errorThrown || textStatus || jqXHR.statusText || 'error'; + callback(null, textStatus, jqXHR, error); + } + }); + + request.done(function(response, textStatus, jqXHR){ + + /** + * @returns Array + */ + + var myResponse = new Array(); + myResponse.constructFromObject(response); + if (callback) { + callback(myResponse, textStatus, jqXHR); + } + + }); + + return request; + } + + /** + * Finds Pets by tags + * Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + * @param {Array} tags Tags to filter by + * @param {function} callback the callback function + * @return Array + */ + self.findPetsByTags = function(tags, callback) { + var postBody = null; + var postBinaryBody = null; + + // create path and map variables + var basePath = 'http://petstore.swagger.io/v2'; + // if basePath ends with a /, remove it as path starts with a leading / + if (basePath.substring(basePath.length-1, basePath.length)=='/') { + basePath = basePath.substring(0, basePath.length-1); + } + + var path = basePath + replaceAll(replaceAll("/pet/findByTags", "\\{format\\}","json")); + + var queryParams = {}; + var headerParams = {}; + var formParams = {}; + + + queryParams.tags = tags; + + + + + path += createQueryString(queryParams); + + var options = {type: "GET", async: true, contentType: "application/json", dataType: "json", data: postBody}; + var request = $.ajax(path, options); + + request.fail(function(jqXHR, textStatus, errorThrown){ + if (callback) { + var error = errorThrown || textStatus || jqXHR.statusText || 'error'; + callback(null, textStatus, jqXHR, error); + } + }); + + request.done(function(response, textStatus, jqXHR){ + + /** + * @returns Array + */ + + var myResponse = new Array(); + myResponse.constructFromObject(response); + if (callback) { + callback(myResponse, textStatus, jqXHR); + } + + }); + + return request; + } + + /** + * 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 + * @return Pet + */ + self.getPetById = function(petId, callback) { + var postBody = null; + var postBinaryBody = null; + + // verify the required parameter 'petId' is set + if (petId == null) { + //throw new ApiException(400, "Missing the required parameter 'petId' when calling getPetById"); + var errorRequiredMsg = "Missing the required parameter 'petId' when calling getPetById"; + throw errorRequiredMsg; + } + + // create path and map variables + var basePath = 'http://petstore.swagger.io/v2'; + // if basePath ends with a /, remove it as path starts with a leading / + if (basePath.substring(basePath.length-1, basePath.length)=='/') { + basePath = basePath.substring(0, basePath.length-1); + } + + var path = basePath + replaceAll(replaceAll("/pet/{petId}", "\\{format\\}","json") +, "\\{" + "petId" + "\\}", encodeURIComponent(petId.toString())); + + var queryParams = {}; + var headerParams = {}; + var formParams = {}; + + + + + + path += createQueryString(queryParams); + + var options = {type: "GET", async: true, contentType: "application/json", dataType: "json", data: postBody}; + var request = $.ajax(path, options); + + request.fail(function(jqXHR, textStatus, errorThrown){ + if (callback) { + var error = errorThrown || textStatus || jqXHR.statusText || 'error'; + callback(null, textStatus, jqXHR, error); + } + }); + + request.done(function(response, textStatus, jqXHR){ + + /** + * @returns Pet + */ + + var myResponse = new Pet(); + myResponse.constructFromObject(response); + if (callback) { + callback(myResponse, textStatus, jqXHR); + } + + }); + + return request; + } + + /** + * Updates a pet in the store with form data + * + * @param {String} petId ID of pet that needs to be updated + * @param {String} name Updated name of the pet + * @param {String} status Updated status of the pet + * @param {function} callback the callback function + * @return void + */ + self.updatePetWithForm = function(petId, name, status, callback) { + var postBody = null; + var postBinaryBody = null; + + // verify the required parameter 'petId' is set + if (petId == null) { + //throw new ApiException(400, "Missing the required parameter 'petId' when calling updatePetWithForm"); + var errorRequiredMsg = "Missing the required parameter 'petId' when calling updatePetWithForm"; + throw errorRequiredMsg; + } + + // create path and map variables + var basePath = 'http://petstore.swagger.io/v2'; + // if basePath ends with a /, remove it as path starts with a leading / + if (basePath.substring(basePath.length-1, basePath.length)=='/') { + basePath = basePath.substring(0, basePath.length-1); + } + + var path = basePath + replaceAll(replaceAll("/pet/{petId}", "\\{format\\}","json") +, "\\{" + "petId" + "\\}", encodeURIComponent(petId.toString())); + + var queryParams = {}; + var headerParams = {}; + var formParams = {}; + + + + if (name != null) + formParams.put("name", name); + if (status != null) + formParams.put("status", status); + + + path += createQueryString(queryParams); + + var options = {type: "POST", async: true, contentType: "application/json", dataType: "json", data: postBody}; + var request = $.ajax(path, options); + + request.fail(function(jqXHR, textStatus, errorThrown){ + if (callback) { + var error = errorThrown || textStatus || jqXHR.statusText || 'error'; + callback(null, textStatus, jqXHR, error); + } + }); + + request.done(function(response, textStatus, jqXHR){ + + if (callback) { + callback(response, textStatus, jqXHR); + } + + }); + + return request; + } + + /** + * Deletes a pet + * + * @param {Integer} petId Pet id to delete + * @param {String} apiKey + * @param {function} callback the callback function + * @return void + */ + self.deletePet = function(petId, apiKey, callback) { + var postBody = null; + var postBinaryBody = null; + + // verify the required parameter 'petId' is set + if (petId == null) { + //throw new ApiException(400, "Missing the required parameter 'petId' when calling deletePet"); + var errorRequiredMsg = "Missing the required parameter 'petId' when calling deletePet"; + throw errorRequiredMsg; + } + + // create path and map variables + var basePath = 'http://petstore.swagger.io/v2'; + // if basePath ends with a /, remove it as path starts with a leading / + if (basePath.substring(basePath.length-1, basePath.length)=='/') { + basePath = basePath.substring(0, basePath.length-1); + } + + var path = basePath + replaceAll(replaceAll("/pet/{petId}", "\\{format\\}","json") +, "\\{" + "petId" + "\\}", encodeURIComponent(petId.toString())); + + var queryParams = {}; + var headerParams = {}; + var formParams = {}; + + + if (apiKey != null) + headerParams.put("api_key", apiKey); + + + + path += createQueryString(queryParams); + + var options = {type: "DELETE", async: true, contentType: "application/json", dataType: "json", data: postBody}; + var request = $.ajax(path, options); + + request.fail(function(jqXHR, textStatus, errorThrown){ + if (callback) { + var error = errorThrown || textStatus || jqXHR.statusText || 'error'; + callback(null, textStatus, jqXHR, error); + } + }); + + request.done(function(response, textStatus, jqXHR){ + + if (callback) { + callback(response, textStatus, jqXHR); + } + + }); + + return request; + } + + /** + * uploads an image + * + * @param {Integer} petId ID of pet to update + * @param {String} additionalMetadata Additional data to pass to server + * @param {File} file file to upload + * @param {function} callback the callback function + * @return void + */ + self.uploadFile = function(petId, additionalMetadata, file, callback) { + var postBody = null; + var postBinaryBody = null; + + // verify the required parameter 'petId' is set + if (petId == null) { + //throw new ApiException(400, "Missing the required parameter 'petId' when calling uploadFile"); + var errorRequiredMsg = "Missing the required parameter 'petId' when calling uploadFile"; + throw errorRequiredMsg; + } + + // create path and map variables + var basePath = 'http://petstore.swagger.io/v2'; + // if basePath ends with a /, remove it as path starts with a leading / + if (basePath.substring(basePath.length-1, basePath.length)=='/') { + basePath = basePath.substring(0, basePath.length-1); + } + + var path = basePath + replaceAll(replaceAll("/pet/{petId}/uploadImage", "\\{format\\}","json") +, "\\{" + "petId" + "\\}", encodeURIComponent(petId.toString())); + + var queryParams = {}; + var headerParams = {}; + var formParams = {}; + + + + if (additionalMetadata != null) + formParams.put("additionalMetadata", additionalMetadata); + if (file != null) + formParams.put("file", file); + + + path += createQueryString(queryParams); + + var options = {type: "POST", async: true, contentType: "application/json", dataType: "json", data: postBody}; + var request = $.ajax(path, options); + + request.fail(function(jqXHR, textStatus, errorThrown){ + if (callback) { + var error = errorThrown || textStatus || jqXHR.statusText || 'error'; + callback(null, textStatus, jqXHR, error); + } + }); + + request.done(function(response, textStatus, jqXHR){ + + if (callback) { + callback(response, textStatus, jqXHR); + } + + }); + + return request; + } + + + + function replaceAll (haystack, needle, replace) { + var result= haystack; + if (needle !=null && replace!=null) { + result= haystack.replace(new RegExp(needle, 'g'), replace); + } + return result; + } + + function createQueryString (queryParams) { + var queryString =''; + var i = 0; + for (var queryParamName in queryParams) { + if (i==0) { + queryString += '?' ; + } else { + queryString += '&' ; + } + + queryString += queryParamName + '=' + encodeURIComponent(queryParams[queryParamName]); + i++; + } + + return queryString; + } +} + +// export module for Node.js +if (typeof module === 'object' && module.exports) { + module.exports = PetApi; +} diff --git a/samples/client/petstore/javascript/src/api/StoreApi.js b/samples/client/petstore/javascript/src/api/StoreApi.js new file mode 100644 index 00000000000..e52a3105964 --- /dev/null +++ b/samples/client/petstore/javascript/src/api/StoreApi.js @@ -0,0 +1,286 @@ +// require files in Node.js environment +var $, Order; +if (typeof module === 'object' && module.exports) { + $ = require('jquery'); + Order = require('../model/Order.js'); +} + +// export module for AMD +if ( typeof define === "function" && define.amd ) { + define(['jquery', 'Order'], function($, Order) { + return StoreApi; + }); +} + +var StoreApi = function StoreApi() { + var self = this; + + + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + * @param {function} callback the callback function + * @return Object + */ + self.getInventory = function(callback) { + var postBody = null; + var postBinaryBody = null; + + // create path and map variables + var basePath = 'http://petstore.swagger.io/v2'; + // if basePath ends with a /, remove it as path starts with a leading / + if (basePath.substring(basePath.length-1, basePath.length)=='/') { + basePath = basePath.substring(0, basePath.length-1); + } + + var path = basePath + replaceAll(replaceAll("/store/inventory", "\\{format\\}","json")); + + var queryParams = {}; + var headerParams = {}; + var formParams = {}; + + + + + + path += createQueryString(queryParams); + + var options = {type: "GET", async: true, contentType: "application/json", dataType: "json", data: postBody}; + var request = $.ajax(path, options); + + request.fail(function(jqXHR, textStatus, errorThrown){ + if (callback) { + var error = errorThrown || textStatus || jqXHR.statusText || 'error'; + callback(null, textStatus, jqXHR, error); + } + }); + + request.done(function(response, textStatus, jqXHR){ + + /** + * @returns Object + */ + var myResponse = response; + + if (callback) { + callback(myResponse, textStatus, jqXHR); + } + + }); + + return request; + } + + /** + * Place an order for a pet + * + * @param {Order} body order placed for purchasing the pet + * @param {function} callback the callback function + * @return Order + */ + self.placeOrder = function(body, callback) { + var postBody = JSON.stringify(body); + var postBinaryBody = null; + + // create path and map variables + var basePath = 'http://petstore.swagger.io/v2'; + // if basePath ends with a /, remove it as path starts with a leading / + if (basePath.substring(basePath.length-1, basePath.length)=='/') { + basePath = basePath.substring(0, basePath.length-1); + } + + var path = basePath + replaceAll(replaceAll("/store/order", "\\{format\\}","json")); + + var queryParams = {}; + var headerParams = {}; + var formParams = {}; + + + + + + path += createQueryString(queryParams); + + var options = {type: "POST", async: true, contentType: "application/json", dataType: "json", data: postBody}; + var request = $.ajax(path, options); + + request.fail(function(jqXHR, textStatus, errorThrown){ + if (callback) { + var error = errorThrown || textStatus || jqXHR.statusText || 'error'; + callback(null, textStatus, jqXHR, error); + } + }); + + request.done(function(response, textStatus, jqXHR){ + + /** + * @returns Order + */ + + var myResponse = new Order(); + myResponse.constructFromObject(response); + if (callback) { + callback(myResponse, textStatus, jqXHR); + } + + }); + + return request; + } + + /** + * 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 + * @return Order + */ + self.getOrderById = function(orderId, callback) { + var postBody = null; + var postBinaryBody = null; + + // verify the required parameter 'orderId' is set + if (orderId == null) { + //throw new ApiException(400, "Missing the required parameter 'orderId' when calling getOrderById"); + var errorRequiredMsg = "Missing the required parameter 'orderId' when calling getOrderById"; + throw errorRequiredMsg; + } + + // create path and map variables + var basePath = 'http://petstore.swagger.io/v2'; + // if basePath ends with a /, remove it as path starts with a leading / + if (basePath.substring(basePath.length-1, basePath.length)=='/') { + basePath = basePath.substring(0, basePath.length-1); + } + + var path = basePath + replaceAll(replaceAll("/store/order/{orderId}", "\\{format\\}","json") +, "\\{" + "orderId" + "\\}", encodeURIComponent(orderId.toString())); + + var queryParams = {}; + var headerParams = {}; + var formParams = {}; + + + + + + path += createQueryString(queryParams); + + var options = {type: "GET", async: true, contentType: "application/json", dataType: "json", data: postBody}; + var request = $.ajax(path, options); + + request.fail(function(jqXHR, textStatus, errorThrown){ + if (callback) { + var error = errorThrown || textStatus || jqXHR.statusText || 'error'; + callback(null, textStatus, jqXHR, error); + } + }); + + request.done(function(response, textStatus, jqXHR){ + + /** + * @returns Order + */ + + var myResponse = new Order(); + myResponse.constructFromObject(response); + if (callback) { + callback(myResponse, textStatus, jqXHR); + } + + }); + + return request; + } + + /** + * 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 + * @return void + */ + self.deleteOrder = function(orderId, callback) { + var postBody = null; + var postBinaryBody = null; + + // verify the required parameter 'orderId' is set + if (orderId == null) { + //throw new ApiException(400, "Missing the required parameter 'orderId' when calling deleteOrder"); + var errorRequiredMsg = "Missing the required parameter 'orderId' when calling deleteOrder"; + throw errorRequiredMsg; + } + + // create path and map variables + var basePath = 'http://petstore.swagger.io/v2'; + // if basePath ends with a /, remove it as path starts with a leading / + if (basePath.substring(basePath.length-1, basePath.length)=='/') { + basePath = basePath.substring(0, basePath.length-1); + } + + var path = basePath + replaceAll(replaceAll("/store/order/{orderId}", "\\{format\\}","json") +, "\\{" + "orderId" + "\\}", encodeURIComponent(orderId.toString())); + + var queryParams = {}; + var headerParams = {}; + var formParams = {}; + + + + + + path += createQueryString(queryParams); + + var options = {type: "DELETE", async: true, contentType: "application/json", dataType: "json", data: postBody}; + var request = $.ajax(path, options); + + request.fail(function(jqXHR, textStatus, errorThrown){ + if (callback) { + var error = errorThrown || textStatus || jqXHR.statusText || 'error'; + callback(null, textStatus, jqXHR, error); + } + }); + + request.done(function(response, textStatus, jqXHR){ + + if (callback) { + callback(response, textStatus, jqXHR); + } + + }); + + return request; + } + + + + function replaceAll (haystack, needle, replace) { + var result= haystack; + if (needle !=null && replace!=null) { + result= haystack.replace(new RegExp(needle, 'g'), replace); + } + return result; + } + + function createQueryString (queryParams) { + var queryString =''; + var i = 0; + for (var queryParamName in queryParams) { + if (i==0) { + queryString += '?' ; + } else { + queryString += '&' ; + } + + queryString += queryParamName + '=' + encodeURIComponent(queryParams[queryParamName]); + i++; + } + + return queryString; + } +} + +// export module for Node.js +if (typeof module === 'object' && module.exports) { + module.exports = StoreApi; +} diff --git a/samples/client/petstore/javascript/src/api/UserApi.js b/samples/client/petstore/javascript/src/api/UserApi.js new file mode 100644 index 00000000000..148e6171ed4 --- /dev/null +++ b/samples/client/petstore/javascript/src/api/UserApi.js @@ -0,0 +1,498 @@ +// require files in Node.js environment +var $, User; +if (typeof module === 'object' && module.exports) { + $ = require('jquery'); + User = require('../model/User.js'); +} + +// export module for AMD +if ( typeof define === "function" && define.amd ) { + define(['jquery', 'User'], function($, User) { + return UserApi; + }); +} + +var UserApi = function UserApi() { + var self = this; + + + /** + * Create user + * This can only be done by the logged in user. + * @param {User} body Created user object + * @param {function} callback the callback function + * @return void + */ + self.createUser = function(body, callback) { + var postBody = JSON.stringify(body); + var postBinaryBody = null; + + // create path and map variables + var basePath = 'http://petstore.swagger.io/v2'; + // if basePath ends with a /, remove it as path starts with a leading / + if (basePath.substring(basePath.length-1, basePath.length)=='/') { + basePath = basePath.substring(0, basePath.length-1); + } + + var path = basePath + replaceAll(replaceAll("/user", "\\{format\\}","json")); + + var queryParams = {}; + var headerParams = {}; + var formParams = {}; + + + + + + path += createQueryString(queryParams); + + var options = {type: "POST", async: true, contentType: "application/json", dataType: "json", data: postBody}; + var request = $.ajax(path, options); + + request.fail(function(jqXHR, textStatus, errorThrown){ + if (callback) { + var error = errorThrown || textStatus || jqXHR.statusText || 'error'; + callback(null, textStatus, jqXHR, error); + } + }); + + request.done(function(response, textStatus, jqXHR){ + + if (callback) { + callback(response, textStatus, jqXHR); + } + + }); + + return request; + } + + /** + * Creates list of users with given input array + * + * @param {Array} body List of user object + * @param {function} callback the callback function + * @return void + */ + self.createUsersWithArrayInput = function(body, callback) { + var postBody = JSON.stringify(body); + var postBinaryBody = null; + + // create path and map variables + var basePath = 'http://petstore.swagger.io/v2'; + // if basePath ends with a /, remove it as path starts with a leading / + if (basePath.substring(basePath.length-1, basePath.length)=='/') { + basePath = basePath.substring(0, basePath.length-1); + } + + var path = basePath + replaceAll(replaceAll("/user/createWithArray", "\\{format\\}","json")); + + var queryParams = {}; + var headerParams = {}; + var formParams = {}; + + + + + + path += createQueryString(queryParams); + + var options = {type: "POST", async: true, contentType: "application/json", dataType: "json", data: postBody}; + var request = $.ajax(path, options); + + request.fail(function(jqXHR, textStatus, errorThrown){ + if (callback) { + var error = errorThrown || textStatus || jqXHR.statusText || 'error'; + callback(null, textStatus, jqXHR, error); + } + }); + + request.done(function(response, textStatus, jqXHR){ + + if (callback) { + callback(response, textStatus, jqXHR); + } + + }); + + return request; + } + + /** + * Creates list of users with given input array + * + * @param {Array} body List of user object + * @param {function} callback the callback function + * @return void + */ + self.createUsersWithListInput = function(body, callback) { + var postBody = JSON.stringify(body); + var postBinaryBody = null; + + // create path and map variables + var basePath = 'http://petstore.swagger.io/v2'; + // if basePath ends with a /, remove it as path starts with a leading / + if (basePath.substring(basePath.length-1, basePath.length)=='/') { + basePath = basePath.substring(0, basePath.length-1); + } + + var path = basePath + replaceAll(replaceAll("/user/createWithList", "\\{format\\}","json")); + + var queryParams = {}; + var headerParams = {}; + var formParams = {}; + + + + + + path += createQueryString(queryParams); + + var options = {type: "POST", async: true, contentType: "application/json", dataType: "json", data: postBody}; + var request = $.ajax(path, options); + + request.fail(function(jqXHR, textStatus, errorThrown){ + if (callback) { + var error = errorThrown || textStatus || jqXHR.statusText || 'error'; + callback(null, textStatus, jqXHR, error); + } + }); + + request.done(function(response, textStatus, jqXHR){ + + if (callback) { + callback(response, textStatus, jqXHR); + } + + }); + + return request; + } + + /** + * Logs user into the system + * + * @param {String} username The user name for login + * @param {String} password The password for login in clear text + * @param {function} callback the callback function + * @return String + */ + self.loginUser = function(username, password, callback) { + var postBody = null; + var postBinaryBody = null; + + // create path and map variables + var basePath = 'http://petstore.swagger.io/v2'; + // if basePath ends with a /, remove it as path starts with a leading / + if (basePath.substring(basePath.length-1, basePath.length)=='/') { + basePath = basePath.substring(0, basePath.length-1); + } + + var path = basePath + replaceAll(replaceAll("/user/login", "\\{format\\}","json")); + + var queryParams = {}; + var headerParams = {}; + var formParams = {}; + + + queryParams.username = username; + + queryParams.password = password; + + + + + path += createQueryString(queryParams); + + var options = {type: "GET", async: true, contentType: "application/json", dataType: "json", data: postBody}; + var request = $.ajax(path, options); + + request.fail(function(jqXHR, textStatus, errorThrown){ + if (callback) { + var error = errorThrown || textStatus || jqXHR.statusText || 'error'; + callback(null, textStatus, jqXHR, error); + } + }); + + request.done(function(response, textStatus, jqXHR){ + + /** + * @returns String + */ + var myResponse = response; + + if (callback) { + callback(myResponse, textStatus, jqXHR); + } + + }); + + return request; + } + + /** + * Logs out current logged in user session + * + * @param {function} callback the callback function + * @return void + */ + self.logoutUser = function(callback) { + var postBody = null; + var postBinaryBody = null; + + // create path and map variables + var basePath = 'http://petstore.swagger.io/v2'; + // if basePath ends with a /, remove it as path starts with a leading / + if (basePath.substring(basePath.length-1, basePath.length)=='/') { + basePath = basePath.substring(0, basePath.length-1); + } + + var path = basePath + replaceAll(replaceAll("/user/logout", "\\{format\\}","json")); + + var queryParams = {}; + var headerParams = {}; + var formParams = {}; + + + + + + path += createQueryString(queryParams); + + var options = {type: "GET", async: true, contentType: "application/json", dataType: "json", data: postBody}; + var request = $.ajax(path, options); + + request.fail(function(jqXHR, textStatus, errorThrown){ + if (callback) { + var error = errorThrown || textStatus || jqXHR.statusText || 'error'; + callback(null, textStatus, jqXHR, error); + } + }); + + request.done(function(response, textStatus, jqXHR){ + + if (callback) { + callback(response, textStatus, jqXHR); + } + + }); + + return request; + } + + /** + * 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 + * @return User + */ + self.getUserByName = function(username, callback) { + var postBody = null; + var postBinaryBody = null; + + // verify the required parameter 'username' is set + if (username == null) { + //throw new ApiException(400, "Missing the required parameter 'username' when calling getUserByName"); + var errorRequiredMsg = "Missing the required parameter 'username' when calling getUserByName"; + throw errorRequiredMsg; + } + + // create path and map variables + var basePath = 'http://petstore.swagger.io/v2'; + // if basePath ends with a /, remove it as path starts with a leading / + if (basePath.substring(basePath.length-1, basePath.length)=='/') { + basePath = basePath.substring(0, basePath.length-1); + } + + var path = basePath + replaceAll(replaceAll("/user/{username}", "\\{format\\}","json") +, "\\{" + "username" + "\\}", encodeURIComponent(username.toString())); + + var queryParams = {}; + var headerParams = {}; + var formParams = {}; + + + + + + path += createQueryString(queryParams); + + var options = {type: "GET", async: true, contentType: "application/json", dataType: "json", data: postBody}; + var request = $.ajax(path, options); + + request.fail(function(jqXHR, textStatus, errorThrown){ + if (callback) { + var error = errorThrown || textStatus || jqXHR.statusText || 'error'; + callback(null, textStatus, jqXHR, error); + } + }); + + request.done(function(response, textStatus, jqXHR){ + + /** + * @returns User + */ + + var myResponse = new User(); + myResponse.constructFromObject(response); + if (callback) { + callback(myResponse, textStatus, jqXHR); + } + + }); + + return request; + } + + /** + * Updated user + * This can only be done by the logged in user. + * @param {String} username name that need to be deleted + * @param {User} body Updated user object + * @param {function} callback the callback function + * @return void + */ + self.updateUser = function(username, body, callback) { + var postBody = JSON.stringify(body); + var postBinaryBody = null; + + // verify the required parameter 'username' is set + if (username == null) { + //throw new ApiException(400, "Missing the required parameter 'username' when calling updateUser"); + var errorRequiredMsg = "Missing the required parameter 'username' when calling updateUser"; + throw errorRequiredMsg; + } + + // create path and map variables + var basePath = 'http://petstore.swagger.io/v2'; + // if basePath ends with a /, remove it as path starts with a leading / + if (basePath.substring(basePath.length-1, basePath.length)=='/') { + basePath = basePath.substring(0, basePath.length-1); + } + + var path = basePath + replaceAll(replaceAll("/user/{username}", "\\{format\\}","json") +, "\\{" + "username" + "\\}", encodeURIComponent(username.toString())); + + var queryParams = {}; + var headerParams = {}; + var formParams = {}; + + + + + + path += createQueryString(queryParams); + + var options = {type: "PUT", async: true, contentType: "application/json", dataType: "json", data: postBody}; + var request = $.ajax(path, options); + + request.fail(function(jqXHR, textStatus, errorThrown){ + if (callback) { + var error = errorThrown || textStatus || jqXHR.statusText || 'error'; + callback(null, textStatus, jqXHR, error); + } + }); + + request.done(function(response, textStatus, jqXHR){ + + if (callback) { + callback(response, textStatus, jqXHR); + } + + }); + + return request; + } + + /** + * 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 + * @return void + */ + self.deleteUser = function(username, callback) { + var postBody = null; + var postBinaryBody = null; + + // verify the required parameter 'username' is set + if (username == null) { + //throw new ApiException(400, "Missing the required parameter 'username' when calling deleteUser"); + var errorRequiredMsg = "Missing the required parameter 'username' when calling deleteUser"; + throw errorRequiredMsg; + } + + // create path and map variables + var basePath = 'http://petstore.swagger.io/v2'; + // if basePath ends with a /, remove it as path starts with a leading / + if (basePath.substring(basePath.length-1, basePath.length)=='/') { + basePath = basePath.substring(0, basePath.length-1); + } + + var path = basePath + replaceAll(replaceAll("/user/{username}", "\\{format\\}","json") +, "\\{" + "username" + "\\}", encodeURIComponent(username.toString())); + + var queryParams = {}; + var headerParams = {}; + var formParams = {}; + + + + + + path += createQueryString(queryParams); + + var options = {type: "DELETE", async: true, contentType: "application/json", dataType: "json", data: postBody}; + var request = $.ajax(path, options); + + request.fail(function(jqXHR, textStatus, errorThrown){ + if (callback) { + var error = errorThrown || textStatus || jqXHR.statusText || 'error'; + callback(null, textStatus, jqXHR, error); + } + }); + + request.done(function(response, textStatus, jqXHR){ + + if (callback) { + callback(response, textStatus, jqXHR); + } + + }); + + return request; + } + + + + function replaceAll (haystack, needle, replace) { + var result= haystack; + if (needle !=null && replace!=null) { + result= haystack.replace(new RegExp(needle, 'g'), replace); + } + return result; + } + + function createQueryString (queryParams) { + var queryString =''; + var i = 0; + for (var queryParamName in queryParams) { + if (i==0) { + queryString += '?' ; + } else { + queryString += '&' ; + } + + queryString += queryParamName + '=' + encodeURIComponent(queryParams[queryParamName]); + i++; + } + + return queryString; + } +} + +// export module for Node.js +if (typeof module === 'object' && module.exports) { + module.exports = UserApi; +} diff --git a/samples/client/petstore/javascript/src/index.js b/samples/client/petstore/javascript/src/index.js new file mode 100644 index 00000000000..b772f6024dc --- /dev/null +++ b/samples/client/petstore/javascript/src/index.js @@ -0,0 +1,22 @@ +if (typeof module === 'object' && module.exports) { + var SwaggerPetstore = {}; + + SwaggerPetstore.User = require('./model/User.js'); + + SwaggerPetstore.Category = require('./model/Category.js'); + + SwaggerPetstore.Pet = require('./model/Pet.js'); + + SwaggerPetstore.Tag = require('./model/Tag.js'); + + SwaggerPetstore.Order = require('./model/Order.js'); + + + SwaggerPetstore.UserApi = require('./api/UserApi.js'); + + SwaggerPetstore.StoreApi = require('./api/StoreApi.js'); + + SwaggerPetstore.PetApi = require('./api/PetApi.js'); + + module.exports = SwaggerPetstore; +} \ No newline at end of file diff --git a/samples/client/petstore/javascript/src/model/Category.js b/samples/client/petstore/javascript/src/model/Category.js new file mode 100644 index 00000000000..ff40497a61a --- /dev/null +++ b/samples/client/petstore/javascript/src/model/Category.js @@ -0,0 +1,81 @@ +// require files in Node.js environment + +if (typeof module === 'object' && module.exports) { + +} + + + + +//export module +if ( typeof define === "function" && define.amd ) { + define('Category', ['jquery'], + function($) { + return Category; + }); +} + + +var Category = function Category() { + var self = this; + + /** + * datatype: Integer + **/ + self.id = null; + + /** + * datatype: String + **/ + self.name = null; + + + self.constructFromObject = function(data) { + if (!data) { + return; + } + + self.id = data.id; + + self.name = data.name; + + } + + + /** + * @return {Integer} + **/ + self.getId = function() { + return self.id; + } + + /** + * @param {Integer} id + **/ + self.setId = function (id) { + self.id = id; + } + + /** + * @return {String} + **/ + self.getName = function() { + return self.name; + } + + /** + * @param {String} name + **/ + self.setName = function (name) { + self.name = name; + } + + + self.toJson = function () { + return JSON.stringify(self); + } +} + +if (typeof module === 'object' && module.exports) { + module.exports = Category; +} diff --git a/samples/client/petstore/javascript/src/model/Order.js b/samples/client/petstore/javascript/src/model/Order.js new file mode 100644 index 00000000000..3cf2335b535 --- /dev/null +++ b/samples/client/petstore/javascript/src/model/Order.js @@ -0,0 +1,196 @@ +// require files in Node.js environment + +if (typeof module === 'object' && module.exports) { + +} + + + +//export module +if ( typeof define === "function" && define.amd ) { + define('StatusEnum', ['jquery'], function($) { + return StatusEnum; + }); +} + +var StatusEnum = function StatusEnum() { + var self = this; + + + /** + * @const + */ + self.PLACED = "placed", + + /** + * @const + */ + self.APPROVED = "approved", + + /** + * @const + */ + self.DELIVERED = "delivered"; + +} + + +//export module +if ( typeof define === "function" && define.amd ) { + define('Order', ['jquery'], + function($) { + return Order; + }); +} + + +var Order = function Order() { + var self = this; + + /** + * datatype: Integer + **/ + self.id = null; + + /** + * datatype: Integer + **/ + self.petId = null; + + /** + * datatype: Integer + **/ + self.quantity = null; + + /** + * datatype: Date + **/ + self.shipDate = null; + + /** + * Order Status + * datatype: StatusEnum + **/ + self.status = null; + + /** + * datatype: Boolean + **/ + self.complete = null; + + + self.constructFromObject = function(data) { + if (!data) { + return; + } + + self.id = data.id; + + self.petId = data.petId; + + self.quantity = data.quantity; + + self.shipDate = data.shipDate; + + self.status = data.status; + + self.complete = data.complete; + + } + + + /** + * @return {Integer} + **/ + self.getId = function() { + return self.id; + } + + /** + * @param {Integer} id + **/ + self.setId = function (id) { + self.id = id; + } + + /** + * @return {Integer} + **/ + self.getPetId = function() { + return self.petId; + } + + /** + * @param {Integer} petId + **/ + self.setPetId = function (petId) { + self.petId = petId; + } + + /** + * @return {Integer} + **/ + self.getQuantity = function() { + return self.quantity; + } + + /** + * @param {Integer} quantity + **/ + self.setQuantity = function (quantity) { + self.quantity = quantity; + } + + /** + * @return {Date} + **/ + self.getShipDate = function() { + return self.shipDate; + } + + /** + * @param {Date} shipDate + **/ + self.setShipDate = function (shipDate) { + self.shipDate = shipDate; + } + + /** + * get Order Status + * @return {StatusEnum} + **/ + self.getStatus = function() { + return self.status; + } + + /** + * set Order Status + * @param {StatusEnum} status + **/ + self.setStatus = function (status) { + self.status = status; + } + + /** + * @return {Boolean} + **/ + self.getComplete = function() { + return self.complete; + } + + /** + * @param {Boolean} complete + **/ + self.setComplete = function (complete) { + self.complete = complete; + } + + + self.toJson = function () { + return JSON.stringify(self); + } +} + +if (typeof module === 'object' && module.exports) { + module.exports = Order; +} diff --git a/samples/client/petstore/javascript/src/model/Pet.js b/samples/client/petstore/javascript/src/model/Pet.js new file mode 100644 index 00000000000..25ae2e951c8 --- /dev/null +++ b/samples/client/petstore/javascript/src/model/Pet.js @@ -0,0 +1,200 @@ +// require files in Node.js environment +var Category;var Tag; +if (typeof module === 'object' && module.exports) { + + Category = require('./Category.js'); + Tag = require('./Tag.js'); +} + + + +//export module +if ( typeof define === "function" && define.amd ) { + define('StatusEnum', ['jquery'], function($) { + return StatusEnum; + }); +} + +var StatusEnum = function StatusEnum() { + var self = this; + + + /** + * @const + */ + self.AVAILABLE = "available", + + /** + * @const + */ + self.PENDING = "pending", + + /** + * @const + */ + self.SOLD = "sold"; + +} + + +//export module +if ( typeof define === "function" && define.amd ) { + define('Pet', ['jquery', 'Category', 'Array'], + function($, Category, Array) { + return Pet; + }); +} + + +var Pet = function Pet(photoUrls, name) { + var self = this; + + /** + * datatype: Integer + **/ + self.id = null; + + /** + * datatype: Category + **/ + self.category = new Category(); + + /** + * datatype: String + * required + **/ + self.name = name; + + /** + * datatype: Array + * required + **/ + self.photoUrls = photoUrls; + + /** + * datatype: Array + **/ + self.tags = []; + + /** + * pet status in the store + * datatype: StatusEnum + **/ + self.status = null; + + + self.constructFromObject = function(data) { + if (!data) { + return; + } + + self.id = data.id; + + self.category.constructFromObject(data.category); + + self.name = data.name; + + self.photoUrls = new Array(); + + self.tags = new Array(); + + self.status = data.status; + + } + + + /** + * @return {Integer} + **/ + self.getId = function() { + return self.id; + } + + /** + * @param {Integer} id + **/ + self.setId = function (id) { + self.id = id; + } + + /** + * @return {Category} + **/ + self.getCategory = function() { + return self.category; + } + + /** + * @param {Category} category + **/ + self.setCategory = function (category) { + self.category = category; + } + + /** + * @return {String} + **/ + self.getName = function() { + return self.name; + } + + /** + * @param {String} name + **/ + self.setName = function (name) { + self.name = name; + } + + /** + * @return {Array} + **/ + self.getPhotoUrls = function() { + return self.photoUrls; + } + + /** + * @param {Array} photoUrls + **/ + self.setPhotoUrls = function (photoUrls) { + self.photoUrls = photoUrls; + } + + /** + * @return {Array} + **/ + self.getTags = function() { + return self.tags; + } + + /** + * @param {Array} tags + **/ + self.setTags = function (tags) { + self.tags = tags; + } + + /** + * get pet status in the store + * @return {StatusEnum} + **/ + self.getStatus = function() { + return self.status; + } + + /** + * set pet status in the store + * @param {StatusEnum} status + **/ + self.setStatus = function (status) { + self.status = status; + } + + + self.toJson = function () { + return JSON.stringify(self); + } +} + +if (typeof module === 'object' && module.exports) { + module.exports = Pet; +} diff --git a/samples/client/petstore/javascript/src/model/Tag.js b/samples/client/petstore/javascript/src/model/Tag.js new file mode 100644 index 00000000000..0fa97bd8c78 --- /dev/null +++ b/samples/client/petstore/javascript/src/model/Tag.js @@ -0,0 +1,81 @@ +// require files in Node.js environment + +if (typeof module === 'object' && module.exports) { + +} + + + + +//export module +if ( typeof define === "function" && define.amd ) { + define('Tag', ['jquery'], + function($) { + return Tag; + }); +} + + +var Tag = function Tag() { + var self = this; + + /** + * datatype: Integer + **/ + self.id = null; + + /** + * datatype: String + **/ + self.name = null; + + + self.constructFromObject = function(data) { + if (!data) { + return; + } + + self.id = data.id; + + self.name = data.name; + + } + + + /** + * @return {Integer} + **/ + self.getId = function() { + return self.id; + } + + /** + * @param {Integer} id + **/ + self.setId = function (id) { + self.id = id; + } + + /** + * @return {String} + **/ + self.getName = function() { + return self.name; + } + + /** + * @param {String} name + **/ + self.setName = function (name) { + self.name = name; + } + + + self.toJson = function () { + return JSON.stringify(self); + } +} + +if (typeof module === 'object' && module.exports) { + module.exports = Tag; +} diff --git a/samples/client/petstore/javascript/src/model/User.js b/samples/client/petstore/javascript/src/model/User.js new file mode 100644 index 00000000000..632208a523c --- /dev/null +++ b/samples/client/petstore/javascript/src/model/User.js @@ -0,0 +1,210 @@ +// require files in Node.js environment + +if (typeof module === 'object' && module.exports) { + +} + + + + +//export module +if ( typeof define === "function" && define.amd ) { + define('User', ['jquery'], + function($) { + return User; + }); +} + + +var User = function User() { + var self = this; + + /** + * datatype: Integer + **/ + self.id = null; + + /** + * datatype: String + **/ + self.username = null; + + /** + * datatype: String + **/ + self.firstName = null; + + /** + * datatype: String + **/ + self.lastName = null; + + /** + * datatype: String + **/ + self.email = null; + + /** + * datatype: String + **/ + self.password = null; + + /** + * datatype: String + **/ + self.phone = null; + + /** + * User Status + * datatype: Integer + **/ + self.userStatus = null; + + + self.constructFromObject = function(data) { + if (!data) { + return; + } + + self.id = data.id; + + self.username = data.username; + + self.firstName = data.firstName; + + self.lastName = data.lastName; + + self.email = data.email; + + self.password = data.password; + + self.phone = data.phone; + + self.userStatus = data.userStatus; + + } + + + /** + * @return {Integer} + **/ + self.getId = function() { + return self.id; + } + + /** + * @param {Integer} id + **/ + self.setId = function (id) { + self.id = id; + } + + /** + * @return {String} + **/ + self.getUsername = function() { + return self.username; + } + + /** + * @param {String} username + **/ + self.setUsername = function (username) { + self.username = username; + } + + /** + * @return {String} + **/ + self.getFirstName = function() { + return self.firstName; + } + + /** + * @param {String} firstName + **/ + self.setFirstName = function (firstName) { + self.firstName = firstName; + } + + /** + * @return {String} + **/ + self.getLastName = function() { + return self.lastName; + } + + /** + * @param {String} lastName + **/ + self.setLastName = function (lastName) { + self.lastName = lastName; + } + + /** + * @return {String} + **/ + self.getEmail = function() { + return self.email; + } + + /** + * @param {String} email + **/ + self.setEmail = function (email) { + self.email = email; + } + + /** + * @return {String} + **/ + self.getPassword = function() { + return self.password; + } + + /** + * @param {String} password + **/ + self.setPassword = function (password) { + self.password = password; + } + + /** + * @return {String} + **/ + self.getPhone = function() { + return self.phone; + } + + /** + * @param {String} phone + **/ + self.setPhone = function (phone) { + self.phone = phone; + } + + /** + * get User Status + * @return {Integer} + **/ + self.getUserStatus = function() { + return self.userStatus; + } + + /** + * set User Status + * @param {Integer} userStatus + **/ + self.setUserStatus = function (userStatus) { + self.userStatus = userStatus; + } + + + self.toJson = function () { + return JSON.stringify(self); + } +} + +if (typeof module === 'object' && module.exports) { + module.exports = User; +} diff --git a/samples/client/petstore/javascript/test/api/PetApiTest.js b/samples/client/petstore/javascript/test/api/PetApiTest.js new file mode 100644 index 00000000000..325cc16b616 --- /dev/null +++ b/samples/client/petstore/javascript/test/api/PetApiTest.js @@ -0,0 +1,189 @@ +if (typeof module === 'object' && module.exports) { + var expect = require('expect.js'); + var requireApiWithMocks = require('../helper.js').requireApiWithMocks; + var PetApi = requireApiWithMocks('PetApi'); + var Pet = require('../../src/model/Pet'); + var Category = require('../../src/model/Category'); + var Tag = require('../../src/model/Tag'); +} + +var api; + +beforeEach(function() { + api = new PetApi(); +}); + +var createRandomPet = function() { + var id = new Date().getTime(); + var pet = new Pet(); + pet.setId(id); + pet.setName("gorilla" + id); + + var category = new Category(); + category.setName("really-happy"); + pet.setCategory(category); + + pet.setStatus('available'); + var photos = ["http://foo.bar.com/1", "http://foo.bar.com/2"]; + pet.setPhotoUrls(photos); + + return pet; +}; + +describe('PetApi', function() { + it('should create and get pet', function (done) { + var pet = createRandomPet(); + api.addPet(pet).then(function() { + api.getPetById(pet.id, function(fetched, textStatus, jqXHR, error) { + if (error) throw error; + + expect(textStatus).to.be('success'); + expect(fetched).to.be.ok(); + expect(fetched.id).to.be(pet.id); + expect(fetched.getCategory()).to.be.ok(); + expect(fetched.getCategory().getName()).to.be(pet.getCategory().getName()); + + api.deletePet(pet.id); + done(); + }); + }, function(jqXHR, textStatus, errorThrown) { + throw errorThrown || textStatus; + }); + }); +}); + +/* + @Test + public void testUpdatePet() throws Exception { + Pet pet = createRandomPet(); + pet.setName("programmer"); + + api.updatePet(pet); + + Pet fetched = api.getPetById(pet.getId()); + assertNotNull(fetched); + assertEquals(pet.getId(), fetched.getId()); + assertNotNull(fetched.getCategory()); + assertEquals(fetched.getCategory().getName(), pet.getCategory().getName()); + } + + @Test + public void testFindPetsByStatus() throws Exception { + Pet pet = createRandomPet(); + pet.setName("programmer"); + pet.setStatus(Pet.StatusEnum.AVAILABLE); + + api.updatePet(pet); + + List pets = api.findPetsByStatus(Arrays.asList(new String[]{"available"})); + assertNotNull(pets); + + boolean found = false; + for (Pet fetched : pets) { + if (fetched.getId().equals(pet.getId())) { + found = true; + break; + } + } + + assertTrue(found); + } + + @Test + public void testFindPetsByTags() throws Exception { + Pet pet = createRandomPet(); + pet.setName("monster"); + pet.setStatus(Pet.StatusEnum.AVAILABLE); + + List tags = new ArrayList(); + Tag tag1 = new Tag(); + tag1.setName("friendly"); + tags.add(tag1); + pet.setTags(tags); + + api.updatePet(pet); + + List pets = api.findPetsByTags(Arrays.asList(new String[]{"friendly"})); + assertNotNull(pets); + + boolean found = false; + for (Pet fetched : pets) { + if (fetched.getId().equals(pet.getId())) { + found = true; + break; + } + } + assertTrue(found); + } + + @Test + public void testUpdatePetWithForm() throws Exception { + Pet pet = createRandomPet(); + pet.setName("frank"); + api.addPet(pet); + + Pet fetched = api.getPetById(pet.getId()); + + api.updatePetWithForm(String.valueOf(fetched.getId()), "furt", null); + Pet updated = api.getPetById(fetched.getId()); + + assertEquals(updated.getName(), "furt"); + } + + @Test + public void testDeletePet() throws Exception { + Pet pet = createRandomPet(); + api.addPet(pet); + + Pet fetched = api.getPetById(pet.getId()); + api.deletePet(fetched.getId(), null); + + try { + fetched = api.getPetById(fetched.getId()); + fail("expected an error"); + } catch (ApiException e) { + assertEquals(404, e.getCode()); + } + } + + @Test + public void testUploadFile() throws Exception { + Pet pet = createRandomPet(); + api.addPet(pet); + + File file = new File("hello.txt"); + BufferedWriter writer = new BufferedWriter(new FileWriter(file)); + writer.write("Hello world!"); + writer.close(); + + api.uploadFile(pet.getId(), "a test file", new File(file.getAbsolutePath())); + } + + @Test + public void testEqualsAndHashCode() { + Pet pet1 = new Pet(); + Pet pet2 = new Pet(); + assertTrue(pet1.equals(pet2)); + assertTrue(pet2.equals(pet1)); + assertTrue(pet1.hashCode() == pet2.hashCode()); + assertTrue(pet1.equals(pet1)); + assertTrue(pet1.hashCode() == pet1.hashCode()); + + pet2.setName("really-happy"); + pet2.setPhotoUrls(Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"})); + assertFalse(pet1.equals(pet2)); + assertFalse(pet2.equals(pet1)); + assertFalse(pet1.hashCode() == (pet2.hashCode())); + assertTrue(pet2.equals(pet2)); + assertTrue(pet2.hashCode() == pet2.hashCode()); + + pet1.setName("really-happy"); + pet1.setPhotoUrls(Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"})); + assertTrue(pet1.equals(pet2)); + assertTrue(pet2.equals(pet1)); + assertTrue(pet1.hashCode() == pet2.hashCode()); + assertTrue(pet1.equals(pet1)); + assertTrue(pet1.hashCode() == pet1.hashCode()); + } +} +*/ diff --git a/samples/client/petstore/javascript/test/api/StoreApiTest.java b/samples/client/petstore/javascript/test/api/StoreApiTest.java new file mode 100644 index 00000000000..6094f2242e1 --- /dev/null +++ b/samples/client/petstore/javascript/test/api/StoreApiTest.java @@ -0,0 +1,75 @@ +package io.swagger.petstore.test; + +import io.swagger.client.ApiException; + +import io.swagger.client.*; +import io.swagger.client.api.*; +import io.swagger.client.auth.*; +import io.swagger.client.model.*; + +import java.util.Map; +import java.text.SimpleDateFormat; + +import org.junit.*; +import static org.junit.Assert.*; + +public class StoreApiTest { + StoreApi api = null; + + @Before + public void setup() { + api = new StoreApi(); + // setup authentication + ApiKeyAuth apiKeyAuth = (ApiKeyAuth) api.getApiClient().getAuthentication("api_key"); + apiKeyAuth.setApiKey("special-key"); + // set custom date format that is used by the petstore server + api.getApiClient().setDateFormat(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ")); + } + + @Test + public void testGetInventory() throws Exception { + Map inventory = api.getInventory(); + assertTrue(inventory.keySet().size() > 0); + } + + @Test + public void testPlaceOrder() throws Exception { + Order order = createOrder(); + api.placeOrder(order); + + Order fetched = api.getOrderById(String.valueOf(order.getId())); + assertEquals(order.getId(), fetched.getId()); + assertEquals(order.getPetId(), fetched.getPetId()); + assertEquals(order.getQuantity(), fetched.getQuantity()); + } + + @Test + public void testDeleteOrder() throws Exception { + Order order = createOrder(); + api.placeOrder(order); + + Order fetched = api.getOrderById(String.valueOf(order.getId())); + assertEquals(fetched.getId(), order.getId()); + + api.deleteOrder(String.valueOf(order.getId())); + + try { + api.getOrderById(String.valueOf(order.getId())); + // fail("expected an error"); + } catch (ApiException e) { + // ok + } + } + + private Order createOrder() { + Order order = new Order(); + order.setId(new Long(System.currentTimeMillis())); + order.setPetId(new Long(200)); + order.setQuantity(new Integer(13)); + order.setShipDate(new java.util.Date()); + order.setStatus(Order.StatusEnum.PLACED); + order.setComplete(true); + + return order; + } +} diff --git a/samples/client/petstore/javascript/test/api/UserApiTest.java b/samples/client/petstore/javascript/test/api/UserApiTest.java new file mode 100644 index 00000000000..a3f257f568b --- /dev/null +++ b/samples/client/petstore/javascript/test/api/UserApiTest.java @@ -0,0 +1,86 @@ +package io.swagger.petstore.test; + +import io.swagger.client.api.*; +import io.swagger.client.auth.*; +import io.swagger.client.model.*; + +import java.util.Arrays; + +import org.junit.*; +import static org.junit.Assert.*; + +public class UserApiTest { + UserApi api = null; + + @Before + public void setup() { + api = new UserApi(); + // setup authentication + ApiKeyAuth apiKeyAuth = (ApiKeyAuth) api.getApiClient().getAuthentication("api_key"); + apiKeyAuth.setApiKey("special-key"); + } + + @Test + public void testCreateUser() throws Exception { + User user = createUser(); + + api.createUser(user); + + User fetched = api.getUserByName(user.getUsername()); + assertEquals(user.getId(), fetched.getId()); + } + + @Test + public void testCreateUsersWithArray() throws Exception { + User user1 = createUser(); + user1.setUsername("abc123"); + User user2 = createUser(); + user2.setUsername("123abc"); + + api.createUsersWithArrayInput(Arrays.asList(new User[]{user1, user2})); + + User fetched = api.getUserByName(user1.getUsername()); + assertEquals(user1.getId(), fetched.getId()); + } + + @Test + public void testCreateUsersWithList() throws Exception { + User user1 = createUser(); + user1.setUsername("abc123"); + User user2 = createUser(); + user2.setUsername("123abc"); + + api.createUsersWithListInput(Arrays.asList(new User[]{user1, user2})); + + User fetched = api.getUserByName(user1.getUsername()); + assertEquals(user1.getId(), fetched.getId()); + } + + @Test + public void testLoginUser() throws Exception { + User user = createUser(); + api.createUser(user); + + String token = api.loginUser(user.getUsername(), user.getPassword()); + assertTrue(token.startsWith("logged in user session:")); + } + + @Test + public void logoutUser() throws Exception { + api.logoutUser(); + } + + private User createUser() { + User user = new User(); + user.setId(System.currentTimeMillis()); + user.setUsername("fred" + user.getId()); + user.setFirstName("Fred"); + user.setLastName("Meyer"); + user.setEmail("fred@fredmeyer.com"); + user.setPassword("xxXXxx"); + user.setPhone("408-867-5309"); + user.setUserStatus(123); + + return user; + } +} diff --git a/samples/client/petstore/javascript/test/helper.js b/samples/client/petstore/javascript/test/helper.js new file mode 100644 index 00000000000..018b6428af6 --- /dev/null +++ b/samples/client/petstore/javascript/test/helper.js @@ -0,0 +1,19 @@ +var mockrequire = require('mockrequire'); + +var jquery = require('jquery'); +var domino = require('domino'); +var XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest; +var window = domino.createWindow(); +var $ = jquery(window); +$.support.cors = true; +$.ajaxSettings.xhr = function() { + return new XMLHttpRequest(); +}; + +var requireApiWithMocks = function(path) { + return mockrequire('../src/api/' + path, { + 'jquery': $ + }); +}; + +exports.requireApiWithMocks = requireApiWithMocks; diff --git a/samples/client/petstore/javascript/test/mocha.opts b/samples/client/petstore/javascript/test/mocha.opts new file mode 100644 index 00000000000..907011807d6 --- /dev/null +++ b/samples/client/petstore/javascript/test/mocha.opts @@ -0,0 +1 @@ +--timeout 10000 diff --git a/samples/client/petstore/javascript/test/run_tests.html b/samples/client/petstore/javascript/test/run_tests.html new file mode 100644 index 00000000000..c5655275cc5 --- /dev/null +++ b/samples/client/petstore/javascript/test/run_tests.html @@ -0,0 +1,33 @@ + + + + Mocha Tests + + + +
+ + + + + + + + + + + + + + + + diff --git a/samples/client/petstore/objc/SwaggerClient/SWGApiClient.m b/samples/client/petstore/objc/SwaggerClient/SWGApiClient.m index dcd33575fc6..4dce6d2fa8b 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGApiClient.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGApiClient.m @@ -128,24 +128,25 @@ static void (^reachabilityChangeBlock)(int); /* * Detect `Accept` from accepts */ -+ (NSString *) selectHeaderAccept:(NSArray *)accepts -{ ++ (NSString *) selectHeaderAccept:(NSArray *)accepts { if (accepts == nil || [accepts count] == 0) { return @""; } NSMutableArray *lowerAccepts = [[NSMutableArray alloc] initWithCapacity:[accepts count]]; - [accepts enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { - [lowerAccepts addObject:[obj lowercaseString]]; - }]; - - - if ([lowerAccepts containsObject:@"application/json"]) { - return @"application/json"; + for (NSString *string in accepts) { + NSString * lowerAccept = [string lowercaseString]; + if ([lowerAccept containsString:@"application/json"]) { + return @"application/json"; + } + [lowerAccepts addObject:lowerAccept]; } - else { - return [lowerAccepts componentsJoinedByString:@", "]; + + if (lowerAccepts.count == 1) { + return [lowerAccepts firstObject]; } + + return [lowerAccepts componentsJoinedByString:@", "]; } /* @@ -171,7 +172,7 @@ static void (^reachabilityChangeBlock)(int); } + (NSString*)escape:(id)unescaped { - if([unescaped isKindOfClass:[NSString class]]){ + if ([unescaped isKindOfClass:[NSString class]]){ return (NSString *)CFBridgingRelease (CFURLCreateStringByAddingPercentEscapes( NULL, @@ -212,7 +213,7 @@ static void (^reachabilityChangeBlock)(int); -(Boolean) executeRequestWithId:(NSNumber*) requestId { NSSet* matchingItems = [queuedRequests objectsPassingTest:^BOOL(id obj, BOOL *stop) { - if([obj intValue] == [requestId intValue]) { + if ([obj intValue] == [requestId intValue]) { return YES; } else { @@ -220,7 +221,7 @@ static void (^reachabilityChangeBlock)(int); } }]; - if(matchingItems.count == 1) { + if (matchingItems.count == 1) { SWGDebugLog(@"removed request id %@", requestId); [queuedRequests removeObject:requestId]; return YES; @@ -268,7 +269,7 @@ static void (^reachabilityChangeBlock)(int); } // call the reachability block, if configured - if(reachabilityChangeBlock != nil) { + if (reachabilityChangeBlock != nil) { reachabilityChangeBlock(status); } }]; @@ -410,16 +411,16 @@ static void (^reachabilityChangeBlock)(int); completionBlock: (void (^)(id, NSError *))completionBlock { AFHTTPRequestOperation *op = [self HTTPRequestOperationWithRequest:request success:^(AFHTTPRequestOperation *operation, id response) { - if([self executeRequestWithId:requestId]) { + if ([self executeRequestWithId:requestId]) { [self logResponse:operation forRequest:request error:nil]; NSDictionary *responseHeaders = [[operation response] allHeaderFields]; self.HTTPResponseHeaders = responseHeaders; completionBlock(response, nil); } } failure:^(AFHTTPRequestOperation *operation, NSError *error) { - if([self executeRequestWithId:requestId]) { + if ([self executeRequestWithId:requestId]) { NSMutableDictionary *userInfo = [error.userInfo mutableCopy]; - if(operation.responseObject) { + if (operation.responseObject) { // Add in the (parsed) response body. userInfo[SWGResponseObjectErrorKey] = operation.responseObject; } @@ -590,10 +591,10 @@ static void (^reachabilityChangeBlock)(int); // request cache BOOL hasHeaderParams = false; - if(headerParams != nil && [headerParams count] > 0) { + if (headerParams != nil && [headerParams count] > 0) { hasHeaderParams = true; } - if(offlineState) { + if (offlineState) { SWGDebugLog(@"%@ cache forced", resourcePath); [request setCachePolicy:NSURLRequestReturnCacheDataDontLoad]; } @@ -606,7 +607,7 @@ static void (^reachabilityChangeBlock)(int); [request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData]; } - if(hasHeaderParams){ + if (hasHeaderParams){ for(NSString * key in [headerParams keyEnumerator]){ [request setValue:[headerParams valueForKey:key] forHTTPHeaderField:key]; } @@ -639,36 +640,36 @@ static void (^reachabilityChangeBlock)(int); int counter = 0; NSMutableString * requestUrl = [NSMutableString stringWithFormat:@"%@", path]; - if(queryParams != nil){ + if (queryParams != nil){ for(NSString * key in [queryParams keyEnumerator]){ - if(counter == 0) separator = @"?"; + if (counter == 0) separator = @"?"; else separator = @"&"; id queryParam = [queryParams valueForKey:key]; - if([queryParam isKindOfClass:[NSString class]]){ + if ([queryParam isKindOfClass:[NSString class]]){ [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, [SWGApiClient escape:key], [SWGApiClient escape:[queryParams valueForKey:key]]]]; } - else if([queryParam isKindOfClass:[SWGQueryParamCollection class]]){ + else if ([queryParam isKindOfClass:[SWGQueryParamCollection class]]){ SWGQueryParamCollection * coll = (SWGQueryParamCollection*) queryParam; NSArray* values = [coll values]; NSString* format = [coll format]; - if([format isEqualToString:@"csv"]) { + if ([format isEqualToString:@"csv"]) { [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, [SWGApiClient escape:key], [NSString stringWithFormat:@"%@", [values componentsJoinedByString:@","]]]]; } - else if([format isEqualToString:@"tsv"]) { + else if ([format isEqualToString:@"tsv"]) { [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, [SWGApiClient escape:key], [NSString stringWithFormat:@"%@", [values componentsJoinedByString:@"\t"]]]]; } - else if([format isEqualToString:@"pipes"]) { + else if ([format isEqualToString:@"pipes"]) { [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, [SWGApiClient escape:key], [NSString stringWithFormat:@"%@", [values componentsJoinedByString:@"|"]]]]; } - else if([format isEqualToString:@"multi"]) { + else if ([format isEqualToString:@"multi"]) { for(id obj in values) { [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, [SWGApiClient escape:key], [NSString stringWithFormat:@"%@", obj]]]; diff --git a/samples/client/petstore/objc/SwaggerClient/SWGCategory.m b/samples/client/petstore/objc/SwaggerClient/SWGCategory.m index fb3ccecf176..0d10e25426e 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGCategory.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGCategory.m @@ -2,6 +2,17 @@ @implementation SWGCategory +- (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`. diff --git a/samples/client/petstore/objc/SwaggerClient/SWGOrder.m b/samples/client/petstore/objc/SwaggerClient/SWGOrder.m index 83fe5741cd7..abf77a7b399 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGOrder.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGOrder.m @@ -2,6 +2,17 @@ @implementation SWGOrder +- (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`. diff --git a/samples/client/petstore/objc/SwaggerClient/SWGPet.m b/samples/client/petstore/objc/SwaggerClient/SWGPet.m index 3fd315ab011..f4fd77ea33f 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGPet.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGPet.m @@ -2,6 +2,17 @@ @implementation SWGPet +- (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`. diff --git a/samples/client/petstore/objc/SwaggerClient/SWGPetApi.m b/samples/client/petstore/objc/SwaggerClient/SWGPetApi.m index 156700c9a76..c7c2ed175c6 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGPetApi.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGPetApi.m @@ -250,7 +250,7 @@ static SWGPetApi* singletonAPI = nil; NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; - if(status != nil) { + if (status != nil) { queryParams[@"status"] = [[SWGQueryParamCollection alloc] initWithValuesAndFormat: status format: @"multi"]; @@ -334,7 +334,7 @@ static SWGPetApi* singletonAPI = nil; NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; - if(tags != nil) { + if (tags != nil) { queryParams[@"tags"] = [[SWGQueryParamCollection alloc] initWithValuesAndFormat: tags format: @"multi"]; @@ -450,7 +450,7 @@ static SWGPetApi* singletonAPI = nil; NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; // Authentication setting - NSArray *authSettings = @[@"api_key", @"petstore_auth"]; + NSArray *authSettings = @[@"api_key"]; id bodyParam = nil; NSMutableDictionary *formParams = [[NSMutableDictionary alloc] init]; @@ -622,7 +622,7 @@ static SWGPetApi* singletonAPI = nil; NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; - if(apiKey != nil) { + if (apiKey != nil) { headerParams[@"api_key"] = apiKey; } diff --git a/samples/client/petstore/objc/SwaggerClient/SWGTag.m b/samples/client/petstore/objc/SwaggerClient/SWGTag.m index 3bcb9973dfd..b19085e2e6b 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGTag.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGTag.m @@ -2,6 +2,17 @@ @implementation SWGTag +- (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`. diff --git a/samples/client/petstore/objc/SwaggerClient/SWGUser.m b/samples/client/petstore/objc/SwaggerClient/SWGUser.m index d040a6bce6d..ac059240e7f 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGUser.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGUser.m @@ -2,6 +2,17 @@ @implementation SWGUser +- (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`. diff --git a/samples/client/petstore/objc/SwaggerClient/SWGUserApi.m b/samples/client/petstore/objc/SwaggerClient/SWGUserApi.m index 75cf8d51b0e..faf0f928baf 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGUserApi.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGUserApi.m @@ -331,11 +331,11 @@ static SWGUserApi* singletonAPI = nil; NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; - if(username != nil) { + if (username != nil) { queryParams[@"username"] = username; } - if(password != nil) { + if (password != nil) { queryParams[@"password"] = password; } diff --git a/samples/client/petstore/objc/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj b/samples/client/petstore/objc/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj index a5fe06f63b7..867a6811293 100644 --- a/samples/client/petstore/objc/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj +++ b/samples/client/petstore/objc/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj @@ -221,6 +221,7 @@ 6003F587195388D20070C39A /* Frameworks */, 6003F588195388D20070C39A /* Resources */, 429AF5C69E165ED75311B4B0 /* Copy Pods Resources */, + 183E54C09C54DAEB54B2546F /* Embed Pods Frameworks */, ); buildRules = ( ); @@ -240,6 +241,7 @@ 6003F5AB195388D20070C39A /* Frameworks */, 6003F5AC195388D20070C39A /* Resources */, E337D7E459CCFFDF27046FFC /* Copy Pods Resources */, + 111D7956304BD6E860AA8709 /* Embed Pods Frameworks */, ); buildRules = ( ); @@ -302,6 +304,36 @@ /* End PBXResourcesBuildPhase section */ /* Begin PBXShellScriptBuildPhase section */ + 111D7956304BD6E860AA8709 /* Embed Pods Frameworks */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "Embed Pods Frameworks"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-SwaggerClient_Tests/Pods-SwaggerClient_Tests-frameworks.sh\"\n"; + showEnvVarsInLog = 0; + }; + 183E54C09C54DAEB54B2546F /* Embed Pods Frameworks */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "Embed Pods Frameworks"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-SwaggerClient_Example/Pods-SwaggerClient_Example-frameworks.sh\"\n"; + showEnvVarsInLog = 0; + }; 429AF5C69E165ED75311B4B0 /* Copy Pods Resources */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; diff --git a/samples/client/petstore/objc/SwaggerClientTests/Tests/PetApiTest.m b/samples/client/petstore/objc/SwaggerClientTests/Tests/PetApiTest.m index 68add577ac1..421292bbf10 100644 --- a/samples/client/petstore/objc/SwaggerClientTests/Tests/PetApiTest.m +++ b/samples/client/petstore/objc/SwaggerClientTests/Tests/PetApiTest.m @@ -123,6 +123,10 @@ [self waitForExpectationsWithTimeout:10.0 handler:nil]; } +/* +wing328@20151130: comment out the test case below as some data do not contain the 'name' attribute, +which causes an exception when deserializing the data + - (void)testGetPetByStatus { XCTestExpectation *expectation = [self expectationWithDescription:@"testGetPetByStatus"]; SWGPet* pet = [self createPet]; @@ -153,6 +157,7 @@ }]; [self waitForExpectationsWithTimeout:10.0 handler:nil]; } +*/ - (void)testGetPetByTags { XCTestExpectation *expectation = [self expectationWithDescription:@"testGetPetByTags"]; 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 bc03a7974d3..9c918b020c4 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php @@ -100,7 +100,23 @@ class PetApi * @return void * @throws \Swagger\Client\ApiException on non-2xx response */ - public function updatePet($body=null) + 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) { @@ -131,31 +147,32 @@ class PetApi // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present - } else if (count($formParams) > 0) { + } elseif (count($formParams) > 0) { $httpBody = $formParams; // for HTTP post (form) } // this endpoint requires OAuth (access token) - if ($this->apiClient->getConfig()->getAccessToken() !== null) { + + if (strlen($this->apiClient->getConfig()->getAccessToken()) !== 0) { $headerParams['Authorization'] = 'Bearer ' . $this->apiClient->getConfig()->getAccessToken(); } // make the API Call - try - { - list($response, $httpHeader) = $this->apiClient->callApi( + try { + list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( $resourcePath, $method, $queryParams, $httpBody, $headerParams ); + return array(null, $statusCode, $httpHeader); + } catch (ApiException $e) { switch ($e->getCode()) { } throw $e; } - } /** @@ -167,7 +184,23 @@ class PetApi * @return void * @throws \Swagger\Client\ApiException on non-2xx response */ - public function addPet($body=null) + public function addPet($body = null) + { + list($response, $statusCode, $httpHeader) = $this->addPetWithHttpInfo ($body); + return $response; + } + + + /** + * addPetWithHttpInfo + * + * Add a new pet to the store + * + * @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 addPetWithHttpInfo($body = null) { @@ -198,31 +231,31 @@ class PetApi // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present - } else if (count($formParams) > 0) { + } elseif (count($formParams) > 0) { $httpBody = $formParams; // for HTTP post (form) } // this endpoint requires OAuth (access token) - if ($this->apiClient->getConfig()->getAccessToken() !== null) { + if (strlen($this->apiClient->getConfig()->getAccessToken()) !== 0) { $headerParams['Authorization'] = 'Bearer ' . $this->apiClient->getConfig()->getAccessToken(); } // make the API Call - try - { - list($response, $httpHeader) = $this->apiClient->callApi( + try { + list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( $resourcePath, $method, $queryParams, $httpBody, $headerParams ); + return array(null, $statusCode, $httpHeader); + } catch (ApiException $e) { switch ($e->getCode()) { } throw $e; } - } /** @@ -234,7 +267,23 @@ class PetApi * @return \Swagger\Client\Model\Pet[] * @throws \Swagger\Client\ApiException on non-2xx response */ - public function findPetsByStatus($status=null) + public function findPetsByStatus($status = null) + { + list($response, $statusCode, $httpHeader) = $this->findPetsByStatusWithHttpInfo ($status); + return $response; + } + + + /** + * findPetsByStatusWithHttpInfo + * + * Finds Pets by status + * + * @param string[] $status Status values that need to be considered for filter (optional) + * @return Array of \Swagger\Client\Model\Pet[], HTTP status code, HTTP response headers (array of strings) + * @throws \Swagger\Client\ApiException on non-2xx response + */ + public function findPetsByStatusWithHttpInfo($status = null) { @@ -264,29 +313,28 @@ class PetApi // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present - } else if (count($formParams) > 0) { + } elseif (count($formParams) > 0) { $httpBody = $formParams; // for HTTP post (form) } // this endpoint requires OAuth (access token) - if ($this->apiClient->getConfig()->getAccessToken() !== null) { + if (strlen($this->apiClient->getConfig()->getAccessToken()) !== 0) { $headerParams['Authorization'] = 'Bearer ' . $this->apiClient->getConfig()->getAccessToken(); } // make the API Call - try - { - list($response, $httpHeader) = $this->apiClient->callApi( + try { + list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( $resourcePath, $method, $queryParams, $httpBody, $headerParams, '\Swagger\Client\Model\Pet[]' ); if (!$response) { - return null; + return array(null, $statusCode, $httpHeader); } - return $this->apiClient->getSerializer()->deserialize($response, '\Swagger\Client\Model\Pet[]', $httpHeader); + return array($this->apiClient->getSerializer()->deserialize($response, '\Swagger\Client\Model\Pet[]', $httpHeader), $statusCode, $httpHeader); } catch (ApiException $e) { switch ($e->getCode()) { @@ -298,9 +346,6 @@ class PetApi throw $e; } - - return null; - } /** @@ -312,7 +357,23 @@ class PetApi * @return \Swagger\Client\Model\Pet[] * @throws \Swagger\Client\ApiException on non-2xx response */ - public function findPetsByTags($tags=null) + public function findPetsByTags($tags = null) + { + list($response, $statusCode, $httpHeader) = $this->findPetsByTagsWithHttpInfo ($tags); + return $response; + } + + + /** + * findPetsByTagsWithHttpInfo + * + * Finds Pets by tags + * + * @param string[] $tags Tags to filter by (optional) + * @return Array of \Swagger\Client\Model\Pet[], HTTP status code, HTTP response headers (array of strings) + * @throws \Swagger\Client\ApiException on non-2xx response + */ + public function findPetsByTagsWithHttpInfo($tags = null) { @@ -342,29 +403,28 @@ class PetApi // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present - } else if (count($formParams) > 0) { + } elseif (count($formParams) > 0) { $httpBody = $formParams; // for HTTP post (form) } // this endpoint requires OAuth (access token) - if ($this->apiClient->getConfig()->getAccessToken() !== null) { + if (strlen($this->apiClient->getConfig()->getAccessToken()) !== 0) { $headerParams['Authorization'] = 'Bearer ' . $this->apiClient->getConfig()->getAccessToken(); } // make the API Call - try - { - list($response, $httpHeader) = $this->apiClient->callApi( + try { + list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( $resourcePath, $method, $queryParams, $httpBody, $headerParams, '\Swagger\Client\Model\Pet[]' ); if (!$response) { - return null; + return array(null, $statusCode, $httpHeader); } - return $this->apiClient->getSerializer()->deserialize($response, '\Swagger\Client\Model\Pet[]', $httpHeader); + return array($this->apiClient->getSerializer()->deserialize($response, '\Swagger\Client\Model\Pet[]', $httpHeader), $statusCode, $httpHeader); } catch (ApiException $e) { switch ($e->getCode()) { @@ -376,9 +436,6 @@ class PetApi throw $e; } - - return null; - } /** @@ -391,6 +448,22 @@ class PetApi * @throws \Swagger\Client\ApiException on non-2xx response */ public function getPetById($pet_id) + { + list($response, $statusCode, $httpHeader) = $this->getPetByIdWithHttpInfo ($pet_id); + return $response; + } + + + /** + * getPetByIdWithHttpInfo + * + * Find pet by ID + * + * @param int $pet_id ID of pet that needs to be fetched (required) + * @return Array of \Swagger\Client\Model\Pet, HTTP status code, HTTP response headers (array of strings) + * @throws \Swagger\Client\ApiException on non-2xx response + */ + public function getPetByIdWithHttpInfo($pet_id) { // verify the required parameter 'pet_id' is set @@ -428,31 +501,30 @@ class PetApi // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present - } else if (count($formParams) > 0) { + } elseif (count($formParams) > 0) { $httpBody = $formParams; // for HTTP post (form) } // this endpoint requires API key authentication $apiKey = $this->apiClient->getApiKeyWithPrefix('api_key'); - if ($apiKey !== null) { + if (strlen($apiKey) !== 0) { $headerParams['api_key'] = $apiKey; } // make the API Call - try - { - list($response, $httpHeader) = $this->apiClient->callApi( + try { + list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( $resourcePath, $method, $queryParams, $httpBody, $headerParams, '\Swagger\Client\Model\Pet' ); if (!$response) { - return null; + return array(null, $statusCode, $httpHeader); } - return $this->apiClient->getSerializer()->deserialize($response, '\Swagger\Client\Model\Pet', $httpHeader); + return array($this->apiClient->getSerializer()->deserialize($response, '\Swagger\Client\Model\Pet', $httpHeader), $statusCode, $httpHeader); } catch (ApiException $e) { switch ($e->getCode()) { @@ -464,9 +536,6 @@ class PetApi throw $e; } - - return null; - } /** @@ -480,7 +549,25 @@ class PetApi * @return void * @throws \Swagger\Client\ApiException on non-2xx response */ - public function updatePetWithForm($pet_id, $name=null, $status=null) + public function updatePetWithForm($pet_id, $name = null, $status = null) + { + list($response, $statusCode, $httpHeader) = $this->updatePetWithFormWithHttpInfo ($pet_id, $name, $status); + return $response; + } + + + /** + * updatePetWithFormWithHttpInfo + * + * 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) + * @return Array of null, HTTP status code, HTTP response headers (array of strings) + * @throws \Swagger\Client\ApiException on non-2xx response + */ + public function updatePetWithFormWithHttpInfo($pet_id, $name = null, $status = null) { // verify the required parameter 'pet_id' is set @@ -530,31 +617,31 @@ class PetApi // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present - } else if (count($formParams) > 0) { + } elseif (count($formParams) > 0) { $httpBody = $formParams; // for HTTP post (form) } // this endpoint requires OAuth (access token) - if ($this->apiClient->getConfig()->getAccessToken() !== null) { + if (strlen($this->apiClient->getConfig()->getAccessToken()) !== 0) { $headerParams['Authorization'] = 'Bearer ' . $this->apiClient->getConfig()->getAccessToken(); } // make the API Call - try - { - list($response, $httpHeader) = $this->apiClient->callApi( + try { + list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( $resourcePath, $method, $queryParams, $httpBody, $headerParams ); + return array(null, $statusCode, $httpHeader); + } catch (ApiException $e) { switch ($e->getCode()) { } throw $e; } - } /** @@ -567,7 +654,24 @@ class PetApi * @return void * @throws \Swagger\Client\ApiException on non-2xx response */ - public function deletePet($pet_id, $api_key=null) + 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 @@ -608,31 +712,31 @@ class PetApi // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present - } else if (count($formParams) > 0) { + } elseif (count($formParams) > 0) { $httpBody = $formParams; // for HTTP post (form) } // this endpoint requires OAuth (access token) - if ($this->apiClient->getConfig()->getAccessToken() !== null) { + if (strlen($this->apiClient->getConfig()->getAccessToken()) !== 0) { $headerParams['Authorization'] = 'Bearer ' . $this->apiClient->getConfig()->getAccessToken(); } // make the API Call - try - { - list($response, $httpHeader) = $this->apiClient->callApi( + try { + list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( $resourcePath, $method, $queryParams, $httpBody, $headerParams ); + return array(null, $statusCode, $httpHeader); + } catch (ApiException $e) { switch ($e->getCode()) { } throw $e; } - } /** @@ -646,7 +750,25 @@ class PetApi * @return void * @throws \Swagger\Client\ApiException on non-2xx response */ - public function uploadFile($pet_id, $additional_metadata=null, $file=null) + public function uploadFile($pet_id, $additional_metadata = null, $file = null) + { + list($response, $statusCode, $httpHeader) = $this->uploadFileWithHttpInfo ($pet_id, $additional_metadata, $file); + return $response; + } + + + /** + * uploadFileWithHttpInfo + * + * uploads an image + * + * @param int $pet_id ID of pet to update (required) + * @param string $additional_metadata Additional data to pass to server (optional) + * @param \SplFileObject $file file to upload (optional) + * @return Array of null, HTTP status code, HTTP response headers (array of strings) + * @throws \Swagger\Client\ApiException on non-2xx response + */ + public function uploadFileWithHttpInfo($pet_id, $additional_metadata = null, $file = null) { // verify the required parameter 'pet_id' is set @@ -702,31 +824,31 @@ class PetApi // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present - } else if (count($formParams) > 0) { + } elseif (count($formParams) > 0) { $httpBody = $formParams; // for HTTP post (form) } // this endpoint requires OAuth (access token) - if ($this->apiClient->getConfig()->getAccessToken() !== null) { + if (strlen($this->apiClient->getConfig()->getAccessToken()) !== 0) { $headerParams['Authorization'] = 'Bearer ' . $this->apiClient->getConfig()->getAccessToken(); } // make the API Call - try - { - list($response, $httpHeader) = $this->apiClient->callApi( + try { + list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( $resourcePath, $method, $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 d709330b056..07f09d44800 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php @@ -100,6 +100,21 @@ class StoreApi * @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() { @@ -126,31 +141,31 @@ class StoreApi // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present - } else if (count($formParams) > 0) { + } elseif (count($formParams) > 0) { $httpBody = $formParams; // for HTTP post (form) } // this endpoint requires API key authentication $apiKey = $this->apiClient->getApiKeyWithPrefix('api_key'); - if ($apiKey !== null) { + + if (strlen($apiKey) !== 0) { $headerParams['api_key'] = $apiKey; } // make the API Call - try - { - list($response, $httpHeader) = $this->apiClient->callApi( + try { + list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( $resourcePath, $method, $queryParams, $httpBody, $headerParams, 'map[string,int]' ); if (!$response) { - return null; + return array(null, $statusCode, $httpHeader); } - return $this->apiClient->getSerializer()->deserialize($response, 'map[string,int]', $httpHeader); + return array($this->apiClient->getSerializer()->deserialize($response, 'map[string,int]', $httpHeader), $statusCode, $httpHeader); } catch (ApiException $e) { switch ($e->getCode()) { @@ -162,9 +177,6 @@ class StoreApi throw $e; } - - return null; - } /** @@ -176,7 +188,23 @@ class StoreApi * @return \Swagger\Client\Model\Order * @throws \Swagger\Client\ApiException on non-2xx response */ - public function placeOrder($body=null) + 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) { @@ -207,24 +235,23 @@ class StoreApi // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present - } else if (count($formParams) > 0) { + } elseif (count($formParams) > 0) { $httpBody = $formParams; // for HTTP post (form) } // make the API Call - try - { - list($response, $httpHeader) = $this->apiClient->callApi( + try { + list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( $resourcePath, $method, $queryParams, $httpBody, $headerParams, '\Swagger\Client\Model\Order' ); if (!$response) { - return null; + return array(null, $statusCode, $httpHeader); } - return $this->apiClient->getSerializer()->deserialize($response, '\Swagger\Client\Model\Order', $httpHeader); + return array($this->apiClient->getSerializer()->deserialize($response, '\Swagger\Client\Model\Order', $httpHeader), $statusCode, $httpHeader); } catch (ApiException $e) { switch ($e->getCode()) { @@ -236,9 +263,6 @@ class StoreApi throw $e; } - - return null; - } /** @@ -251,6 +275,22 @@ class StoreApi * @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 @@ -288,24 +328,23 @@ class StoreApi // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present - } else if (count($formParams) > 0) { + } elseif (count($formParams) > 0) { $httpBody = $formParams; // for HTTP post (form) } // make the API Call - try - { - list($response, $httpHeader) = $this->apiClient->callApi( + try { + list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( $resourcePath, $method, $queryParams, $httpBody, $headerParams, '\Swagger\Client\Model\Order' ); if (!$response) { - return null; + return array(null, $statusCode, $httpHeader); } - return $this->apiClient->getSerializer()->deserialize($response, '\Swagger\Client\Model\Order', $httpHeader); + return array($this->apiClient->getSerializer()->deserialize($response, '\Swagger\Client\Model\Order', $httpHeader), $statusCode, $httpHeader); } catch (ApiException $e) { switch ($e->getCode()) { @@ -317,9 +356,6 @@ class StoreApi throw $e; } - - return null; - } /** @@ -332,6 +368,22 @@ class StoreApi * @throws \Swagger\Client\ApiException on non-2xx response */ public function deleteOrder($order_id) + { + list($response, $statusCode, $httpHeader) = $this->deleteOrderWithHttpInfo ($order_id); + return $response; + } + + + /** + * deleteOrderWithHttpInfo + * + * Delete purchase order by ID + * + * @param string $order_id ID of the order that needs to be deleted (required) + * @return Array of null, HTTP status code, HTTP response headers (array of strings) + * @throws \Swagger\Client\ApiException on non-2xx response + */ + public function deleteOrderWithHttpInfo($order_id) { // verify the required parameter 'order_id' is set @@ -369,26 +421,26 @@ class StoreApi // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present - } else if (count($formParams) > 0) { + } elseif (count($formParams) > 0) { $httpBody = $formParams; // for HTTP post (form) } // make the API Call - try - { - list($response, $httpHeader) = $this->apiClient->callApi( + try { + list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( $resourcePath, $method, $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/UserApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php index 8ce6301a51e..f200ff51d2a 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php @@ -100,7 +100,23 @@ class UserApi * @return void * @throws \Swagger\Client\ApiException on non-2xx response */ - public function createUser($body=null) + public function createUser($body = null) + { + list($response, $statusCode, $httpHeader) = $this->createUserWithHttpInfo ($body); + return $response; + } + + + /** + * createUserWithHttpInfo + * + * Create user + * + * @param \Swagger\Client\Model\User $body Created user object (optional) + * @return Array of null, HTTP status code, HTTP response headers (array of strings) + * @throws \Swagger\Client\ApiException on non-2xx response + */ + public function createUserWithHttpInfo($body = null) { @@ -131,26 +147,26 @@ class UserApi // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present - } else if (count($formParams) > 0) { + } elseif (count($formParams) > 0) { $httpBody = $formParams; // for HTTP post (form) } // make the API Call - try - { - list($response, $httpHeader) = $this->apiClient->callApi( + try { + list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( $resourcePath, $method, $queryParams, $httpBody, $headerParams ); + return array(null, $statusCode, $httpHeader); + } catch (ApiException $e) { switch ($e->getCode()) { } throw $e; } - } /** @@ -162,7 +178,23 @@ class UserApi * @return void * @throws \Swagger\Client\ApiException on non-2xx response */ - public function createUsersWithArrayInput($body=null) + public function createUsersWithArrayInput($body = null) + { + list($response, $statusCode, $httpHeader) = $this->createUsersWithArrayInputWithHttpInfo ($body); + return $response; + } + + + /** + * createUsersWithArrayInputWithHttpInfo + * + * Creates list of users with given input array + * + * @param \Swagger\Client\Model\User[] $body List of user object (optional) + * @return Array of null, HTTP status code, HTTP response headers (array of strings) + * @throws \Swagger\Client\ApiException on non-2xx response + */ + public function createUsersWithArrayInputWithHttpInfo($body = null) { @@ -193,26 +225,26 @@ class UserApi // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present - } else if (count($formParams) > 0) { + } elseif (count($formParams) > 0) { $httpBody = $formParams; // for HTTP post (form) } // make the API Call - try - { - list($response, $httpHeader) = $this->apiClient->callApi( + try { + list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( $resourcePath, $method, $queryParams, $httpBody, $headerParams ); + return array(null, $statusCode, $httpHeader); + } catch (ApiException $e) { switch ($e->getCode()) { } throw $e; } - } /** @@ -224,7 +256,23 @@ class UserApi * @return void * @throws \Swagger\Client\ApiException on non-2xx response */ - public function createUsersWithListInput($body=null) + public function createUsersWithListInput($body = null) + { + list($response, $statusCode, $httpHeader) = $this->createUsersWithListInputWithHttpInfo ($body); + return $response; + } + + + /** + * createUsersWithListInputWithHttpInfo + * + * Creates list of users with given input array + * + * @param \Swagger\Client\Model\User[] $body List of user object (optional) + * @return Array of null, HTTP status code, HTTP response headers (array of strings) + * @throws \Swagger\Client\ApiException on non-2xx response + */ + public function createUsersWithListInputWithHttpInfo($body = null) { @@ -255,26 +303,26 @@ class UserApi // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present - } else if (count($formParams) > 0) { + } elseif (count($formParams) > 0) { $httpBody = $formParams; // for HTTP post (form) } // make the API Call - try - { - list($response, $httpHeader) = $this->apiClient->callApi( + try { + list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( $resourcePath, $method, $queryParams, $httpBody, $headerParams ); + return array(null, $statusCode, $httpHeader); + } catch (ApiException $e) { switch ($e->getCode()) { } throw $e; } - } /** @@ -287,7 +335,24 @@ class UserApi * @return string * @throws \Swagger\Client\ApiException on non-2xx response */ - public function loginUser($username=null, $password=null) + public function loginUser($username = null, $password = null) + { + list($response, $statusCode, $httpHeader) = $this->loginUserWithHttpInfo ($username, $password); + return $response; + } + + + /** + * loginUserWithHttpInfo + * + * Logs user into the system + * + * @param string $username The user name for login (optional) + * @param string $password The password for login in clear text (optional) + * @return Array of string, HTTP status code, HTTP response headers (array of strings) + * @throws \Swagger\Client\ApiException on non-2xx response + */ + public function loginUserWithHttpInfo($username = null, $password = null) { @@ -320,24 +385,23 @@ class UserApi // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present - } else if (count($formParams) > 0) { + } elseif (count($formParams) > 0) { $httpBody = $formParams; // for HTTP post (form) } // make the API Call - try - { - list($response, $httpHeader) = $this->apiClient->callApi( + try { + list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( $resourcePath, $method, $queryParams, $httpBody, $headerParams, 'string' ); if (!$response) { - return null; + return array(null, $statusCode, $httpHeader); } - return $this->apiClient->getSerializer()->deserialize($response, 'string', $httpHeader); + return array($this->apiClient->getSerializer()->deserialize($response, 'string', $httpHeader), $statusCode, $httpHeader); } catch (ApiException $e) { switch ($e->getCode()) { @@ -349,9 +413,6 @@ class UserApi throw $e; } - - return null; - } /** @@ -363,6 +424,21 @@ class UserApi * @throws \Swagger\Client\ApiException on non-2xx response */ public function logoutUser() + { + list($response, $statusCode, $httpHeader) = $this->logoutUserWithHttpInfo (); + return $response; + } + + + /** + * logoutUserWithHttpInfo + * + * Logs out current logged in user session + * + * @return Array of null, HTTP status code, HTTP response headers (array of strings) + * @throws \Swagger\Client\ApiException on non-2xx response + */ + public function logoutUserWithHttpInfo() { @@ -389,26 +465,26 @@ class UserApi // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present - } else if (count($formParams) > 0) { + } elseif (count($formParams) > 0) { $httpBody = $formParams; // for HTTP post (form) } // make the API Call - try - { - list($response, $httpHeader) = $this->apiClient->callApi( + try { + list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( $resourcePath, $method, $queryParams, $httpBody, $headerParams ); + return array(null, $statusCode, $httpHeader); + } catch (ApiException $e) { switch ($e->getCode()) { } throw $e; } - } /** @@ -421,6 +497,22 @@ class UserApi * @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 @@ -458,24 +550,23 @@ class UserApi // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present - } else if (count($formParams) > 0) { + } elseif (count($formParams) > 0) { $httpBody = $formParams; // for HTTP post (form) } // make the API Call - try - { - list($response, $httpHeader) = $this->apiClient->callApi( + try { + list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( $resourcePath, $method, $queryParams, $httpBody, $headerParams, '\Swagger\Client\Model\User' ); if (!$response) { - return null; + return array(null, $statusCode, $httpHeader); } - return $this->apiClient->getSerializer()->deserialize($response, '\Swagger\Client\Model\User', $httpHeader); + return array($this->apiClient->getSerializer()->deserialize($response, '\Swagger\Client\Model\User', $httpHeader), $statusCode, $httpHeader); } catch (ApiException $e) { switch ($e->getCode()) { @@ -487,9 +578,6 @@ class UserApi throw $e; } - - return null; - } /** @@ -502,7 +590,24 @@ class UserApi * @return void * @throws \Swagger\Client\ApiException on non-2xx response */ - public function updateUser($username, $body=null) + public function updateUser($username, $body = null) + { + list($response, $statusCode, $httpHeader) = $this->updateUserWithHttpInfo ($username, $body); + return $response; + } + + + /** + * updateUserWithHttpInfo + * + * Updated user + * + * @param string $username name that need to be deleted (required) + * @param \Swagger\Client\Model\User $body Updated user object (optional) + * @return Array of null, HTTP status code, HTTP response headers (array of strings) + * @throws \Swagger\Client\ApiException on non-2xx response + */ + public function updateUserWithHttpInfo($username, $body = null) { // verify the required parameter 'username' is set @@ -544,26 +649,26 @@ class UserApi // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present - } else if (count($formParams) > 0) { + } elseif (count($formParams) > 0) { $httpBody = $formParams; // for HTTP post (form) } // make the API Call - try - { - list($response, $httpHeader) = $this->apiClient->callApi( + try { + list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( $resourcePath, $method, $queryParams, $httpBody, $headerParams ); + return array(null, $statusCode, $httpHeader); + } catch (ApiException $e) { switch ($e->getCode()) { } throw $e; } - } /** @@ -576,6 +681,22 @@ class UserApi * @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 @@ -613,26 +734,26 @@ class UserApi // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present - } else if (count($formParams) > 0) { + } elseif (count($formParams) > 0) { $httpBody = $formParams; // for HTTP post (form) } // make the API Call - try - { - list($response, $httpHeader) = $this->apiClient->callApi( + try { + list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( $resourcePath, $method, $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 a0bb07273e4..8730a8c0601 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/ApiClient.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/ApiClient.php @@ -131,7 +131,7 @@ class ApiClient * @throws \Swagger\Client\ApiException on a non 2xx response * @return mixed */ - public function callApi($resourcePath, $method, $queryParams, $postData, $headerParams, $responseType=null) + public function callApi($resourcePath, $method, $queryParams, $postData, $headerParams, $responseType = null) { $headers = array(); @@ -149,7 +149,7 @@ class ApiClient // form data if ($postData and in_array('Content-Type: application/x-www-form-urlencoded', $headers)) { $postData = http_build_query($postData); - } else if ((is_object($postData) or is_array($postData)) and !in_array('Content-Type: multipart/form-data', $headers)) { // json model + } elseif ((is_object($postData) or is_array($postData)) and !in_array('Content-Type: multipart/form-data', $headers)) { // json model $postData = json_encode($this->serializer->sanitizeForSerialization($postData)); } @@ -160,7 +160,7 @@ class ApiClient if ($this->config->getCurlTimeout() != 0) { curl_setopt($curl, CURLOPT_TIMEOUT, $this->config->getCurlTimeout()); } - // return the result on success, rather than just TRUE + // return the result on success, rather than just true curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); @@ -178,21 +178,21 @@ class ApiClient if ($method == self::$POST) { curl_setopt($curl, CURLOPT_POST, true); curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); - } else if ($method == self::$HEAD) { + } elseif ($method == self::$HEAD) { curl_setopt($curl, CURLOPT_NOBODY, true); - } else if ($method == self::$OPTIONS) { + } elseif ($method == self::$OPTIONS) { curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "OPTIONS"); curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); - } else if ($method == self::$PATCH) { + } elseif ($method == self::$PATCH) { curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PATCH"); curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); - } else if ($method == self::$PUT) { + } elseif ($method == self::$PUT) { curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT"); curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); - } else if ($method == self::$DELETE) { + } elseif ($method == self::$DELETE) { curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "DELETE"); curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); - } else if ($method != self::$GET) { + } elseif ($method != self::$GET) { throw new ApiException('Method ' . $method . ' is not recognized.'); } curl_setopt($curl, CURLOPT_URL, $url); @@ -216,7 +216,7 @@ class ApiClient // Make the request $response = curl_exec($curl); $http_header_size = curl_getinfo($curl, CURLINFO_HEADER_SIZE); - $http_header = substr($response, 0, $http_header_size); + $http_header = $this->http_parse_headers(substr($response, 0, $http_header_size)); $http_body = substr($response, $http_header_size); $response_info = curl_getinfo($curl); @@ -228,10 +228,10 @@ class ApiClient // Handle the response if ($response_info['http_code'] == 0) { throw new ApiException("API call to $url timed out: ".serialize($response_info), 0, null, null); - } else if ($response_info['http_code'] >= 200 && $response_info['http_code'] <= 299 ) { + } elseif ($response_info['http_code'] >= 200 && $response_info['http_code'] <= 299 ) { // return raw body if response is a file if ($responseType == '\SplFileObject') { - return array($http_body, $http_header); + return array($http_body, $response_info['http_code'], $http_header); } $data = json_decode($http_body); @@ -249,7 +249,7 @@ class ApiClient $response_info['http_code'], $http_header, $data ); } - return array($data, $http_header); + return array($data, $response_info['http_code'], $http_header); } /** @@ -287,4 +287,52 @@ class ApiClient return implode(',', $content_type); } } + + /** + * Return an array of HTTP response headers + * + * @param string $raw_headers A string of raw HTTP response headers + * + * @return string[] Array of HTTP response heaers + */ + protected function http_parse_headers($raw_headers) + { + // ref/credit: http://php.net/manual/en/function.http-parse-headers.php#112986 + $headers = array(); + $key = ''; // [+] + + foreach(explode("\n", $raw_headers) as $i => $h) + { + $h = explode(':', $h, 2); + + if (isset($h[1])) + { + if (!isset($headers[$h[0]])) + $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]))); // [+] + } + 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]))); // [+] + } + + $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]); // [+] + } // [+] + } + + 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 1fdac785bfd..033f2da7a22 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php @@ -211,7 +211,7 @@ class Configuration */ public function setAccessToken($accessToken) { - $this->$accessToken = $accessToken; + $this->accessToken = $accessToken; return $this; } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php b/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php index 0d281b9d1fa..cc023b61bd2 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php @@ -56,14 +56,14 @@ class ObjectSerializer { if (is_scalar($data) || null === $data) { $sanitized = $data; - } else if ($data instanceof \DateTime) { + } elseif ($data instanceof \DateTime) { $sanitized = $data->format(\DateTime::ISO8601); - } else if (is_array($data)) { + } elseif (is_array($data)) { foreach ($data as $property => $value) { $data[$property] = $this->sanitizeForSerialization($value); } $sanitized = $data; - } else if (is_object($data)) { + } elseif (is_object($data)) { $values = array(); foreach (array_keys($data::$swaggerTypes) as $property) { $getter = $data::$getters[$property]; @@ -198,7 +198,7 @@ class ObjectSerializer $deserialized = $data; } elseif ($class === '\SplFileObject') { // determine file name - if (preg_match('/Content-Disposition: inline; filename=[\'"]?([^\'"\s]+)[\'"]?$/i', $httpHeader, $match)) { + if (array_key_exists('Content-Disposition', $httpHeaders) && preg_match('/inline; filename=[\'"]?([^\'"\s]+)[\'"]?$/i', $httpHeader['Content-Disposition'], $match)) { $filename = Configuration::getDefaultConfiguration()->getTempFolderPath().$match[1]; } else { $filename = tempnam(Configuration::getDefaultConfiguration()->getTempFolderPath(), ''); diff --git a/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php b/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php index fe818069dac..c81b07b38fd 100644 --- a/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php @@ -82,6 +82,10 @@ class PetApiTest extends \PHPUnit_Framework_TestCase $this->assertNotEquals($apiClient3, $apiClient4); // customied pet api not using the old pet api's api client $this->assertNotEquals($pet_api2->getApiClient(), $pet_api3->getApiClient()); + + // test access token + $api_client->getConfig()->setAccessToken("testing_only"); + $this->assertSame('testing_only', $api_client->getConfig()->getAccessToken()); } // test getPetById with a Pet object (id 10005) @@ -101,6 +105,25 @@ class PetApiTest extends \PHPUnit_Framework_TestCase $this->assertSame($response->getTags()[0]->getName(), 'test php tag'); } + // test getPetById with a Pet object (id 10005) + public function testGetPetByIdWithHttpInfo() + { + // 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->getApiClient()->getConfig()->setApiKey('api_key', '111222333444555'); + // return Pet (model) + list($response, $status_code, $response_headers) = $pet_api->getPetByIdWithHttpInfo($pet_id); + $this->assertSame($response->getId(), $pet_id); + $this->assertSame($response->getName(), 'PHP Unit Test'); + $this->assertSame($response->getCategory()->getId(), $pet_id); + $this->assertSame($response->getCategory()->getName(), 'test php category'); + $this->assertSame($response->getTags()[0]->getId(), $pet_id); + $this->assertSame($response->getTags()[0]->getName(), 'test php tag'); + $this->assertSame($status_code, 200); + $this->assertSame($response_headers['Content-Type'], 'application/json'); + } + // test getPetByStatus and verify by the "id" of the response public function testFindPetByStatus() { @@ -145,7 +168,26 @@ class PetApiTest extends \PHPUnit_Framework_TestCase $this->assertSame($response->getName(), 'updatePet'); } - // test updatePet and verify by the "id" of the response + // test updatePetWithFormWithHttpInfo and verify by the "name" of the response + public function testUpdatePetWithFormWithHttpInfo() + { + // initialize the API client + $config = (new Swagger\Client\Configuration())->setHost('http://petstore.swagger.io/v2'); + $api_client = new Swagger\Client\ApiClient($config); + $pet_id = 10001; // ID of pet that needs to be fetched + $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) + $this->assertNull($update_response); + $this->assertSame($status_code, 200); + $this->assertSame($http_headers['Content-Type'], 'application/json'); + $response = $pet_api->getPetById($pet_id); + $this->assertSame($response->getId(), $pet_id); + $this->assertSame($response->getName(), 'update pet with form with http info'); + } + + // test updatePetWithForm and verify by the "name" and "status" of the response public function testUpdatePetWithForm() { // initialize the API client diff --git a/samples/client/petstore/php/swagger_client_profiling.output b/samples/client/petstore/php/swagger_client_profiling.output new file mode 100644 index 00000000000..487dd36f4da --- /dev/null +++ b/samples/client/petstore/php/swagger_client_profiling.output @@ -0,0 +1,31 @@ +0: NEW PETAPI => 0.050940 +0: ADD PET => 0.901768 +0: GET PET => 0.368627 +0: UPDATE PET => 0.366801 +0: DELETE PET => 0.368657 +1: NEW PETAPI => 0.000020 +1: ADD PET => 0.365229 +1: GET PET => 0.366909 +1: UPDATE PET => 0.366458 +1: DELETE PET => 0.365904 +2: NEW PETAPI => 0.000018 +2: ADD PET => 0.367664 +2: GET PET => 0.364671 +2: UPDATE PET => 0.365267 +2: DELETE PET => 0.366162 +3: NEW PETAPI => 0.000018 +3: ADD PET => 0.364907 +3: GET PET => 0.364156 +3: UPDATE PET => 0.366996 +3: DELETE PET => 0.366705 +4: NEW PETAPI => 0.000018 +4: ADD PET => 0.370373 +4: GET PET => 0.365455 +4: UPDATE PET => 0.365915 +4: DELETE PET => 0.368835 +5: NEW PETAPI => 0.000017 +5: ADD PET => 0.367148 +5: GET PET => 0.368994 +5: UPDATE PET => 0.368870 +5: DELETE PET => 0.367270 +6: FINISH diff --git a/samples/client/petstore/php/swagger_client_profiling.php b/samples/client/petstore/php/swagger_client_profiling.php new file mode 100644 index 00000000000..20a3d6b6bf5 --- /dev/null +++ b/samples/client/petstore/php/swagger_client_profiling.php @@ -0,0 +1,80 @@ + %f\n", $prof_names[$i], $prof_timing[$i+1]-$prof_timing[$i]); + } + echo "{$prof_names[$size-1]}\n"; +} + +$counter = 5; // run 5 times by default +$new_pet_id = 50001; // ID of pet that needs to be fetched + +for ($x = 0; $x <= $counter; $x++) { + try { + prof_flag("$x: NEW PETAPI"); + $pet_api = new Swagger\Client\Api\PetApi(); + + // ~~~ ADD PET ~~~ + prof_flag("$x: ADD PET"); + // add pet (post json) + $new_pet = new Swagger\Client\Model\Pet; + $new_pet->setId($new_pet_id); + $new_pet->setName("profiler"); + $new_pet->setStatus("available"); + $new_pet->setPhotoUrls(array("http://profiler.com")); + // new tag + $tag= new Swagger\Client\Model\Tag; + $tag->setId($new_pet_id); // use the same id as pet + $tag->setName("profile tag 1"); + // new category + $category = new Swagger\Client\Model\Category; + $category->setId($new_pet_id); // use the same id as pet + $category->setName("profile category 1"); + + $new_pet->setTags(array($tag)); + $new_pet->setCategory($category); + + // add a new pet (model) + $add_response = $pet_api->addPet($new_pet); + + // ~~~ GET PET ~~~ + prof_flag("$x: GET PET"); + $response = $pet_api->getPetById($new_pet_id); + + // ~~~ UPDATE PET WITH FORM ~~~ + prof_flag("$x: UPDATE PET"); + $response = $pet_api->updatePetWithForm($new_pet_id, "new profiler", "sold"); + + // ~~~ DELETE PET ~~~ + prof_flag("$x: DELETE PET"); + $response = $pet_api->deletePet($new_pet_id); + + } catch (Swagger\Client\ApiException $e) { + echo 'Caught exception: ', $e->getMessage(), "\n"; + echo 'HTTP response headers: ', print_r($e->getResponseHeaders(), true), "\n"; + echo 'HTTP response body: ', print_r($e->getResponseBody(), true), "\n"; + echo 'HTTP status code: ', $e->getCode(), "\n"; + } + +} + +prof_flag("$x: FINISH"); +prof_print(); + + diff --git a/samples/client/petstore/python/.coverage b/samples/client/petstore/python/.coverage index ddd00f77a03..26331c636b3 100644 --- a/samples/client/petstore/python/.coverage +++ b/samples/client/petstore/python/.coverage @@ -1 +1 @@ -!coverage.py: This is a private format, don't read it directly!{"lines": {"/Users/williamcheng/Code/wing328/swagger-codegen/samples/client/petstore/python/swagger_client/apis/pet_api.py": [512, 513, 514, 516, 86, 18, 20, 22, 23, 26, 539, 28, 29, 542, 543, 32, 548, 37, 39, 40, 41, 42, 555, 556, 45, 558, 559, 560, 562, 564, 565, 566, 568, 569, 571, 574, 575, 576, 580, 581, 70, 584, 73, 586, 587, 588, 589, 590, 591, 592, 593, 594, 595, 596, 598, 88, 90, 92, 93, 95, 96, 97, 100, 101, 102, 106, 107, 621, 622, 624, 625, 626, 79, 116, 117, 118, 631, 632, 121, 122, 635, 124, 638, 639, 641, 642, 643, 645, 647, 649, 650, 651, 652, 653, 654, 656, 145, 146, 659, 148, 661, 150, 665, 666, 155, 156, 538, 159, 160, 673, 162, 675, 164, 677, 166, 679, 168, 169, 171, 172, 173, 541, 176, 177, 178, 115, 182, 183, 186, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 552, 200, 119, 120, 377, 221, 222, 549, 224, 225, 226, 231, 232, 431, 235, 236, 110, 238, 240, 241, 242, 244, 246, 247, 249, 383, 252, 253, 254, 258, 259, 262, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 276, 46, 48, 297, 298, 300, 301, 302, 44, 307, 308, 311, 312, 314, 316, 317, 318, 320, 322, 323, 325, 113, 328, 329, 330, 334, 335, 338, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 485, 352, 84, 114, 373, 374, 376, 660, 378, 149, 384, 387, 390, 391, 393, 394, 395, 397, 399, 401, 402, 404, 407, 408, 409, 413, 414, 69, 417, 419, 420, 421, 422, 423, 424, 425, 426, 427, 428, 429, 669, 72, 671, 74, 672, 83, 454, 455, 457, 458, 459, 674, 112, 464, 465, 468, 471, 472, 676, 474, 475, 476, 478, 480, 80, 482, 483, 484, 678, 486, 487, 489, 492, 493, 494, 680, 498, 499, 502, 681, 504, 505, 506, 507, 508, 509, 510, 511], "/Users/williamcheng/Code/wing328/swagger-codegen/samples/client/petstore/python/swagger_client/apis/user_api.py": [32, 355, 37, 39, 200, 124, 428, 589, 48, 18, 20, 22, 23, 276, 26, 507, 28, 29], "/Users/williamcheng/Code/wing328/swagger-codegen/samples/client/petstore/python/swagger_client/api_client.py": [518, 525, 526, 527, 19, 21, 22, 23, 24, 537, 26, 27, 28, 29, 30, 31, 32, 33, 34, 547, 36, 37, 40, 42, 44, 558, 49, 52, 566, 568, 569, 570, 571, 572, 573, 575, 68, 69, 70, 75, 76, 77, 79, 80, 82, 84, 91, 96, 98, 102, 103, 104, 107, 108, 109, 111, 112, 115, 116, 117, 118, 119, 120, 123, 124, 125, 126, 129, 130, 131, 134, 137, 138, 141, 144, 145, 146, 147, 149, 152, 153, 155, 157, 158, 160, 162, 171, 172, 174, 176, 191, 192, 194, 195, 196, 197, 198, 199, 200, 201, 202, 204, 205, 212, 213, 214, 216, 217, 219, 231, 235, 236, 240, 242, 251, 252, 254, 255, 256, 257, 258, 260, 261, 262, 263, 267, 268, 269, 272, 274, 275, 276, 278, 279, 280, 281, 283, 286, 287, 288, 316, 317, 318, 319, 320, 322, 323, 324, 325, 326, 327, 328, 329, 330, 332, 333, 337, 338, 339, 340, 341, 345, 351, 352, 353, 354, 355, 356, 357, 358, 359, 360, 361, 362, 363, 369, 370, 371, 372, 379, 387, 389, 390, 392, 393, 394, 395, 548, 397, 398, 399, 400, 401, 402, 404, 406, 413, 414, 416, 418, 419, 421, 423, 430, 431, 433, 435, 436, 438, 440, 448, 450, 453, 454, 455, 456, 458, 459, 467, 546, 493, 502, 503, 508, 510], "/Users/williamcheng/Code/wing328/swagger-codegen/samples/client/petstore/python/swagger_client/models/category.py": [72, 74, 109, 19, 21, 22, 104, 25, 29, 30, 96, 100, 114, 102, 39, 40, 41, 103, 44, 45, 46, 112, 49, 50, 83, 116, 94, 52, 122, 61, 85, 63], "/Users/williamcheng/Code/wing328/swagger-codegen/samples/client/petstore/python/swagger_client/rest.py": [20, 21, 23, 24, 25, 26, 27, 28, 31, 33, 35, 36, 40, 42, 48, 51, 53, 54, 55, 56, 57, 59, 63, 65, 72, 74, 82, 83, 88, 92, 95, 98, 101, 102, 103, 104, 105, 106, 109, 110, 121, 122, 124, 129, 130, 132, 135, 137, 138, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 152, 153, 154, 155, 156, 159, 160, 161, 166, 170, 171, 174, 176, 177, 179, 181, 182, 183, 184, 186, 191, 198, 199, 200, 201, 203, 204, 205, 206, 207, 208, 210, 211, 212, 213, 214, 215, 217, 225, 227, 228, 229, 230, 231, 232, 239, 243, 244, 245, 246, 248, 249, 251], "/Users/williamcheng/Code/wing328/swagger-codegen/samples/client/petstore/python/swagger_client/models/__init__.py": [1, 4, 5, 6, 7, 8], "/Users/williamcheng/Code/wing328/swagger-codegen/samples/client/petstore/python/swagger_client/apis/store_api.py": [18, 276, 22, 23, 26, 28, 29, 197, 32, 37, 39, 40, 41, 44, 46, 48, 20, 68, 69, 71, 72, 79, 82, 83, 85, 87, 89, 91, 92, 94, 97, 98, 99, 103, 104, 107, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 121], "/Users/williamcheng/Code/wing328/swagger-codegen/samples/client/petstore/python/swagger_client/configuration.py": [135, 136, 137, 138, 139, 142, 19, 149, 22, 23, 25, 26, 27, 29, 158, 31, 32, 34, 36, 37, 39, 40, 41, 170, 43, 172, 46, 47, 189, 179, 52, 54, 59, 61, 190, 63, 192, 224, 67, 69, 71, 200, 73, 204, 80, 81, 82, 84, 213, 86, 199, 88, 90, 219, 92, 221, 222, 223, 96, 225, 98, 100, 102, 230, 104, 167, 111, 76, 168, 157, 122, 123, 42, 21], "/Users/williamcheng/Code/wing328/swagger-codegen/samples/client/petstore/python/swagger_client/__init__.py": [1, 4, 5, 6, 7, 8, 11, 12, 13, 16, 18, 20], "/Users/williamcheng/Code/wing328/swagger-codegen/samples/client/petstore/python/swagger_client/models/pet.py": [128, 130, 150, 172, 139, 141, 19, 215, 21, 22, 152, 25, 29, 30, 161, 163, 39, 40, 41, 42, 43, 44, 45, 174, 48, 49, 50, 51, 52, 53, 54, 183, 57, 58, 59, 60, 61, 62, 64, 194, 195, 200, 73, 202, 75, 206, 208, 209, 210, 211, 84, 213, 86, 185, 216, 218, 220, 222, 95, 97, 226, 228, 106, 108, 117, 119, 212], "/Users/williamcheng/Code/wing328/swagger-codegen/samples/client/petstore/python/swagger_client/models/user.py": [70, 136, 202, 272, 81, 147, 213, 22, 25, 92, 29, 158, 224, 103, 169, 235, 114, 19, 180, 30, 246, 266, 191, 125, 21], "/Users/williamcheng/Code/wing328/swagger-codegen/samples/client/petstore/python/swagger_client/apis/__init__.py": [1, 4, 5, 6], "/Users/williamcheng/Code/wing328/swagger-codegen/samples/client/petstore/python/swagger_client/models/order.py": [130, 44, 141, 45, 19, 21, 22, 152, 25, 29, 30, 52, 161, 163, 39, 40, 41, 42, 43, 172, 173, 174, 175, 48, 49, 50, 51, 180, 53, 54, 57, 58, 59, 60, 61, 62, 191, 64, 202, 75, 86, 176, 222, 97, 228, 178, 108, 119], "/Users/williamcheng/Code/wing328/swagger-codegen/samples/client/petstore/python/swagger_client/models/tag.py": [72, 74, 109, 19, 21, 22, 104, 25, 29, 30, 96, 100, 114, 102, 39, 40, 41, 103, 44, 45, 46, 112, 49, 50, 83, 116, 94, 52, 122, 61, 85, 63]}} \ No newline at end of file +!coverage.py: This is a private format, don't read it directly!{"lines": {"/Users/williamcheng/Code/wing328/swagger-codegen/samples/client/petstore/python/swagger_client/__init__.py": [1, 4, 5, 6, 7, 8, 11, 12, 13, 16, 18, 20], "/Users/williamcheng/Code/wing328/swagger-codegen/samples/client/petstore/python/swagger_client/apis/pet_api.py": [512, 513, 514, 516, 86, 18, 20, 22, 23, 26, 539, 28, 29, 542, 543, 32, 548, 37, 39, 40, 41, 42, 555, 556, 45, 558, 559, 560, 562, 564, 565, 566, 568, 569, 571, 574, 575, 576, 580, 581, 70, 584, 73, 586, 587, 588, 589, 590, 591, 592, 593, 594, 595, 596, 598, 88, 90, 92, 93, 95, 96, 97, 100, 101, 102, 106, 107, 621, 622, 624, 625, 626, 79, 116, 117, 118, 631, 632, 121, 122, 635, 124, 638, 639, 641, 642, 643, 645, 647, 649, 650, 651, 652, 653, 654, 656, 145, 146, 659, 148, 661, 150, 665, 666, 155, 156, 538, 159, 160, 673, 162, 675, 164, 677, 166, 679, 168, 169, 171, 172, 173, 541, 176, 177, 178, 115, 182, 183, 186, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 200, 119, 120, 377, 221, 222, 549, 224, 225, 226, 231, 232, 431, 235, 236, 110, 238, 240, 552, 242, 244, 246, 247, 249, 383, 252, 253, 254, 258, 259, 262, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 276, 46, 48, 297, 298, 300, 301, 302, 44, 307, 308, 311, 312, 314, 316, 317, 318, 320, 322, 323, 325, 113, 328, 329, 330, 334, 335, 338, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 485, 352, 84, 114, 373, 374, 376, 660, 378, 149, 384, 387, 390, 391, 393, 394, 395, 397, 399, 401, 402, 404, 407, 408, 409, 413, 414, 69, 417, 419, 420, 421, 422, 423, 424, 425, 426, 427, 428, 429, 669, 72, 241, 671, 74, 672, 83, 454, 455, 457, 458, 459, 674, 112, 464, 465, 468, 471, 472, 676, 474, 475, 476, 478, 480, 80, 482, 483, 484, 678, 486, 487, 489, 492, 493, 494, 680, 498, 499, 502, 681, 504, 505, 506, 507, 508, 509, 510, 511], "/Users/williamcheng/Code/wing328/swagger-codegen/samples/client/petstore/python/swagger_client/models/order.py": [130, 172, 141, 173, 19, 21, 22, 152, 25, 29, 30, 52, 161, 163, 39, 40, 41, 42, 43, 44, 45, 174, 175, 48, 49, 50, 51, 180, 53, 54, 57, 58, 59, 60, 61, 62, 191, 64, 202, 75, 86, 176, 222, 97, 228, 178, 234, 108, 240, 119], "/Users/williamcheng/Code/wing328/swagger-codegen/samples/client/petstore/python/swagger_client/models/__init__.py": [1, 4, 5, 6, 7, 8], "/Users/williamcheng/Code/wing328/swagger-codegen/samples/client/petstore/python/swagger_client/models/tag.py": [128, 132, 134, 72, 74, 109, 19, 21, 22, 104, 25, 29, 30, 96, 100, 114, 102, 39, 40, 41, 103, 44, 45, 46, 112, 49, 50, 83, 116, 94, 52, 122, 61, 85, 63], "/Users/williamcheng/Code/wing328/swagger-codegen/samples/client/petstore/python/swagger_client/apis/user_api.py": [32, 355, 37, 39, 200, 124, 428, 589, 48, 18, 20, 22, 23, 276, 26, 507, 28, 29], "/Users/williamcheng/Code/wing328/swagger-codegen/samples/client/petstore/python/swagger_client/configuration.py": [135, 136, 137, 138, 139, 142, 19, 149, 22, 23, 25, 26, 27, 29, 158, 31, 32, 34, 36, 37, 39, 40, 41, 170, 43, 172, 46, 47, 189, 179, 52, 54, 59, 61, 190, 63, 192, 224, 67, 69, 71, 200, 73, 204, 80, 81, 82, 84, 213, 86, 199, 88, 90, 219, 92, 221, 222, 223, 96, 225, 98, 100, 102, 230, 104, 167, 111, 76, 168, 157, 122, 123, 42, 21], "/Users/williamcheng/Code/wing328/swagger-codegen/samples/client/petstore/python/swagger_client/apis/store_api.py": [18, 276, 22, 23, 26, 28, 29, 197, 32, 37, 39, 40, 41, 44, 46, 48, 20, 68, 69, 71, 72, 79, 82, 83, 85, 87, 89, 91, 92, 94, 97, 98, 99, 103, 104, 107, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 121], "/Users/williamcheng/Code/wing328/swagger-codegen/samples/client/petstore/python/swagger_client/models/category.py": [128, 134, 72, 74, 109, 19, 21, 22, 104, 25, 29, 30, 96, 100, 114, 102, 39, 40, 41, 103, 44, 45, 46, 112, 49, 50, 83, 116, 94, 52, 122, 61, 85, 63], "/Users/williamcheng/Code/wing328/swagger-codegen/samples/client/petstore/python/swagger_client/rest.py": [20, 21, 23, 24, 25, 26, 27, 28, 31, 33, 35, 36, 40, 42, 48, 51, 53, 54, 55, 56, 57, 59, 63, 65, 72, 74, 82, 83, 88, 92, 95, 98, 101, 102, 103, 104, 105, 106, 109, 110, 121, 122, 124, 129, 130, 132, 135, 137, 138, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 152, 153, 154, 155, 156, 159, 160, 161, 166, 170, 171, 174, 176, 177, 179, 181, 182, 183, 184, 186, 191, 198, 199, 200, 201, 203, 204, 205, 206, 207, 208, 210, 211, 212, 213, 214, 215, 217, 225, 227, 228, 229, 230, 231, 232, 239, 243, 244, 245, 246, 248, 249, 251], "/Users/williamcheng/Code/wing328/swagger-codegen/samples/client/petstore/python/swagger_client/models/pet.py": [128, 130, 150, 172, 139, 141, 19, 215, 21, 22, 152, 25, 29, 30, 161, 163, 39, 40, 41, 42, 43, 44, 45, 174, 48, 49, 50, 51, 52, 53, 54, 183, 57, 58, 59, 60, 61, 62, 64, 194, 195, 200, 73, 202, 75, 206, 208, 209, 210, 211, 84, 213, 86, 185, 216, 218, 220, 222, 95, 97, 226, 228, 234, 108, 238, 240, 117, 119, 212, 106], "/Users/williamcheng/Code/wing328/swagger-codegen/samples/client/petstore/python/swagger_client/api_client.py": [518, 525, 526, 527, 19, 21, 22, 23, 24, 537, 26, 27, 28, 29, 30, 31, 32, 33, 34, 547, 36, 37, 40, 42, 44, 558, 49, 52, 566, 568, 569, 570, 571, 572, 573, 575, 68, 69, 70, 75, 76, 77, 79, 80, 82, 84, 91, 96, 98, 102, 103, 104, 107, 108, 109, 111, 112, 115, 116, 117, 118, 119, 120, 123, 124, 125, 126, 129, 130, 131, 134, 137, 138, 141, 144, 145, 146, 147, 149, 152, 153, 155, 157, 158, 160, 162, 171, 172, 174, 176, 191, 192, 194, 195, 196, 197, 198, 199, 200, 201, 202, 204, 205, 212, 213, 214, 216, 217, 219, 231, 235, 236, 240, 242, 251, 252, 254, 255, 256, 257, 258, 260, 261, 262, 263, 267, 268, 269, 272, 274, 275, 276, 278, 279, 280, 281, 283, 286, 287, 288, 316, 317, 318, 319, 320, 322, 323, 324, 325, 326, 327, 328, 329, 330, 332, 333, 337, 338, 339, 340, 341, 345, 351, 352, 353, 354, 355, 356, 357, 358, 359, 360, 361, 362, 363, 369, 370, 371, 372, 379, 387, 389, 390, 392, 393, 394, 395, 548, 397, 398, 399, 400, 401, 402, 404, 406, 413, 414, 416, 418, 419, 421, 423, 430, 431, 433, 435, 436, 438, 440, 448, 450, 453, 454, 455, 456, 458, 459, 467, 546, 493, 502, 503, 508, 510], "/Users/williamcheng/Code/wing328/swagger-codegen/samples/client/petstore/python/swagger_client/models/user.py": [278, 70, 136, 202, 272, 81, 147, 213, 22, 25, 92, 29, 158, 224, 103, 169, 235, 284, 114, 19, 180, 30, 246, 266, 191, 125, 21], "/Users/williamcheng/Code/wing328/swagger-codegen/samples/client/petstore/python/swagger_client/apis/__init__.py": [1, 4, 5, 6]}} \ No newline at end of file diff --git a/samples/client/petstore/python/dev-requirements.txt.log b/samples/client/petstore/python/dev-requirements.txt.log index 316a9394b50..bd935e805bf 100644 --- a/samples/client/petstore/python/dev-requirements.txt.log +++ b/samples/client/petstore/python/dev-requirements.txt.log @@ -34,3 +34,94 @@ Requirement already satisfied (use --upgrade to upgrade): randomize in ./venv/li Requirement already satisfied (use --upgrade to upgrade): virtualenv>=1.11.2 in ./venv/lib/python2.7/site-packages (from tox->-r dev-requirements.txt (line 2)) Requirement already satisfied (use --upgrade to upgrade): py>=1.4.17 in ./venv/lib/python2.7/site-packages (from tox->-r dev-requirements.txt (line 2)) Requirement already satisfied (use --upgrade to upgrade): pluggy<0.4.0,>=0.3.0 in ./venv/lib/python2.7/site-packages (from tox->-r dev-requirements.txt (line 2)) +Requirement already satisfied (use --upgrade to upgrade): nose in ./venv/lib/python2.7/site-packages (from -r dev-requirements.txt (line 1)) +Requirement already satisfied (use --upgrade to upgrade): tox in ./venv/lib/python2.7/site-packages (from -r dev-requirements.txt (line 2)) +Requirement already satisfied (use --upgrade to upgrade): coverage in ./venv/lib/python2.7/site-packages (from -r dev-requirements.txt (line 3)) +Requirement already satisfied (use --upgrade to upgrade): randomize in ./venv/lib/python2.7/site-packages (from -r dev-requirements.txt (line 4)) +Requirement already satisfied (use --upgrade to upgrade): virtualenv>=1.11.2 in ./venv/lib/python2.7/site-packages (from tox->-r dev-requirements.txt (line 2)) +Requirement already satisfied (use --upgrade to upgrade): py>=1.4.17 in ./venv/lib/python2.7/site-packages (from tox->-r dev-requirements.txt (line 2)) +Requirement already satisfied (use --upgrade to upgrade): pluggy<0.4.0,>=0.3.0 in ./venv/lib/python2.7/site-packages (from tox->-r dev-requirements.txt (line 2)) +Requirement already satisfied (use --upgrade to upgrade): nose in ./venv/lib/python2.7/site-packages (from -r dev-requirements.txt (line 1)) +Requirement already satisfied (use --upgrade to upgrade): tox in ./venv/lib/python2.7/site-packages (from -r dev-requirements.txt (line 2)) +Requirement already satisfied (use --upgrade to upgrade): coverage in ./venv/lib/python2.7/site-packages (from -r dev-requirements.txt (line 3)) +Requirement already satisfied (use --upgrade to upgrade): randomize in ./venv/lib/python2.7/site-packages (from -r dev-requirements.txt (line 4)) +Requirement already satisfied (use --upgrade to upgrade): virtualenv>=1.11.2 in ./venv/lib/python2.7/site-packages (from tox->-r dev-requirements.txt (line 2)) +Requirement already satisfied (use --upgrade to upgrade): py>=1.4.17 in ./venv/lib/python2.7/site-packages (from tox->-r dev-requirements.txt (line 2)) +Requirement already satisfied (use --upgrade to upgrade): pluggy<0.4.0,>=0.3.0 in ./venv/lib/python2.7/site-packages (from tox->-r dev-requirements.txt (line 2)) +Requirement already satisfied (use --upgrade to upgrade): nose in ./venv/lib/python2.7/site-packages (from -r dev-requirements.txt (line 1)) +Requirement already satisfied (use --upgrade to upgrade): tox in ./venv/lib/python2.7/site-packages (from -r dev-requirements.txt (line 2)) +Requirement already satisfied (use --upgrade to upgrade): coverage in ./venv/lib/python2.7/site-packages (from -r dev-requirements.txt (line 3)) +Requirement already satisfied (use --upgrade to upgrade): randomize in ./venv/lib/python2.7/site-packages (from -r dev-requirements.txt (line 4)) +Requirement already satisfied (use --upgrade to upgrade): virtualenv>=1.11.2 in ./venv/lib/python2.7/site-packages (from tox->-r dev-requirements.txt (line 2)) +Requirement already satisfied (use --upgrade to upgrade): py>=1.4.17 in ./venv/lib/python2.7/site-packages (from tox->-r dev-requirements.txt (line 2)) +Requirement already satisfied (use --upgrade to upgrade): pluggy<0.4.0,>=0.3.0 in ./venv/lib/python2.7/site-packages (from tox->-r dev-requirements.txt (line 2)) +Requirement already satisfied (use --upgrade to upgrade): nose in ./venv/lib/python2.7/site-packages (from -r dev-requirements.txt (line 1)) +Requirement already satisfied (use --upgrade to upgrade): tox in ./venv/lib/python2.7/site-packages (from -r dev-requirements.txt (line 2)) +Requirement already satisfied (use --upgrade to upgrade): coverage in ./venv/lib/python2.7/site-packages (from -r dev-requirements.txt (line 3)) +Requirement already satisfied (use --upgrade to upgrade): randomize in ./venv/lib/python2.7/site-packages (from -r dev-requirements.txt (line 4)) +Requirement already satisfied (use --upgrade to upgrade): virtualenv>=1.11.2 in ./venv/lib/python2.7/site-packages (from tox->-r dev-requirements.txt (line 2)) +Requirement already satisfied (use --upgrade to upgrade): py>=1.4.17 in ./venv/lib/python2.7/site-packages (from tox->-r dev-requirements.txt (line 2)) +Requirement already satisfied (use --upgrade to upgrade): pluggy<0.4.0,>=0.3.0 in ./venv/lib/python2.7/site-packages (from tox->-r dev-requirements.txt (line 2)) +Requirement already satisfied (use --upgrade to upgrade): nose in ./venv/lib/python2.7/site-packages (from -r dev-requirements.txt (line 1)) +Requirement already satisfied (use --upgrade to upgrade): tox in ./venv/lib/python2.7/site-packages (from -r dev-requirements.txt (line 2)) +Requirement already satisfied (use --upgrade to upgrade): coverage in ./venv/lib/python2.7/site-packages (from -r dev-requirements.txt (line 3)) +Requirement already satisfied (use --upgrade to upgrade): randomize in ./venv/lib/python2.7/site-packages (from -r dev-requirements.txt (line 4)) +Requirement already satisfied (use --upgrade to upgrade): virtualenv>=1.11.2 in ./venv/lib/python2.7/site-packages (from tox->-r dev-requirements.txt (line 2)) +Requirement already satisfied (use --upgrade to upgrade): py>=1.4.17 in ./venv/lib/python2.7/site-packages (from tox->-r dev-requirements.txt (line 2)) +Requirement already satisfied (use --upgrade to upgrade): pluggy<0.4.0,>=0.3.0 in ./venv/lib/python2.7/site-packages (from tox->-r dev-requirements.txt (line 2)) +Collecting nose (from -r dev-requirements.txt (line 1)) + Using cached nose-1.3.7-py2-none-any.whl +Collecting tox (from -r dev-requirements.txt (line 2)) + Using cached tox-2.2.1-py2.py3-none-any.whl +Collecting coverage (from -r dev-requirements.txt (line 3)) + Downloading coverage-4.0.3.tar.gz (354kB) +Collecting randomize (from -r dev-requirements.txt (line 4)) + Using cached randomize-0.13-py2.py3-none-any.whl +Requirement already satisfied (use --upgrade to upgrade): virtualenv>=1.11.2 in /Library/Python/2.7/site-packages (from tox->-r dev-requirements.txt (line 2)) +Collecting py>=1.4.17 (from tox->-r dev-requirements.txt (line 2)) + Downloading py-1.4.31-py2.py3-none-any.whl (81kB) +Collecting pluggy<0.4.0,>=0.3.0 (from tox->-r dev-requirements.txt (line 2)) + Using cached pluggy-0.3.1-py2.py3-none-any.whl +Installing collected packages: nose, py, pluggy, tox, coverage, randomize +Collecting nose (from -r dev-requirements.txt (line 1)) + Using cached nose-1.3.7-py2-none-any.whl +Collecting tox (from -r dev-requirements.txt (line 2)) + Using cached tox-2.2.1-py2.py3-none-any.whl +Collecting coverage (from -r dev-requirements.txt (line 3)) + Using cached coverage-4.0.3.tar.gz +Collecting randomize (from -r dev-requirements.txt (line 4)) + Using cached randomize-0.13-py2.py3-none-any.whl +Requirement already satisfied (use --upgrade to upgrade): virtualenv>=1.11.2 in /Library/Python/2.7/site-packages (from tox->-r dev-requirements.txt (line 2)) +Collecting py>=1.4.17 (from tox->-r dev-requirements.txt (line 2)) + Using cached py-1.4.31-py2.py3-none-any.whl +Collecting pluggy<0.4.0,>=0.3.0 (from tox->-r dev-requirements.txt (line 2)) + Using cached pluggy-0.3.1-py2.py3-none-any.whl +Installing collected packages: nose, py, pluggy, tox, coverage, randomize +Requirement already satisfied (use --upgrade to upgrade): nose in ./venv/lib/python2.7/site-packages (from -r dev-requirements.txt (line 1)) +Requirement already satisfied (use --upgrade to upgrade): tox in ./venv/lib/python2.7/site-packages (from -r dev-requirements.txt (line 2)) +Requirement already satisfied (use --upgrade to upgrade): coverage in ./venv/lib/python2.7/site-packages (from -r dev-requirements.txt (line 3)) +Requirement already satisfied (use --upgrade to upgrade): randomize in ./venv/lib/python2.7/site-packages (from -r dev-requirements.txt (line 4)) +Requirement already satisfied (use --upgrade to upgrade): virtualenv>=1.11.2 in ./venv/lib/python2.7/site-packages (from tox->-r dev-requirements.txt (line 2)) +Requirement already satisfied (use --upgrade to upgrade): py>=1.4.17 in ./venv/lib/python2.7/site-packages (from tox->-r dev-requirements.txt (line 2)) +Requirement already satisfied (use --upgrade to upgrade): pluggy<0.4.0,>=0.3.0 in ./venv/lib/python2.7/site-packages (from tox->-r dev-requirements.txt (line 2)) +Requirement already satisfied (use --upgrade to upgrade): nose in ./venv/lib/python2.7/site-packages (from -r dev-requirements.txt (line 1)) +Requirement already satisfied (use --upgrade to upgrade): tox in ./venv/lib/python2.7/site-packages (from -r dev-requirements.txt (line 2)) +Requirement already satisfied (use --upgrade to upgrade): coverage in ./venv/lib/python2.7/site-packages (from -r dev-requirements.txt (line 3)) +Requirement already satisfied (use --upgrade to upgrade): randomize in ./venv/lib/python2.7/site-packages (from -r dev-requirements.txt (line 4)) +Requirement already satisfied (use --upgrade to upgrade): virtualenv>=1.11.2 in ./venv/lib/python2.7/site-packages (from tox->-r dev-requirements.txt (line 2)) +Requirement already satisfied (use --upgrade to upgrade): py>=1.4.17 in ./venv/lib/python2.7/site-packages (from tox->-r dev-requirements.txt (line 2)) +Requirement already satisfied (use --upgrade to upgrade): pluggy<0.4.0,>=0.3.0 in ./venv/lib/python2.7/site-packages (from tox->-r dev-requirements.txt (line 2)) +Requirement already satisfied (use --upgrade to upgrade): nose in ./venv/lib/python2.7/site-packages (from -r dev-requirements.txt (line 1)) +Requirement already satisfied (use --upgrade to upgrade): tox in ./venv/lib/python2.7/site-packages (from -r dev-requirements.txt (line 2)) +Requirement already satisfied (use --upgrade to upgrade): coverage in ./venv/lib/python2.7/site-packages (from -r dev-requirements.txt (line 3)) +Requirement already satisfied (use --upgrade to upgrade): randomize in ./venv/lib/python2.7/site-packages (from -r dev-requirements.txt (line 4)) +Requirement already satisfied (use --upgrade to upgrade): virtualenv>=1.11.2 in ./venv/lib/python2.7/site-packages (from tox->-r dev-requirements.txt (line 2)) +Requirement already satisfied (use --upgrade to upgrade): py>=1.4.17 in ./venv/lib/python2.7/site-packages (from tox->-r dev-requirements.txt (line 2)) +Requirement already satisfied (use --upgrade to upgrade): pluggy<0.4.0,>=0.3.0 in ./venv/lib/python2.7/site-packages (from tox->-r dev-requirements.txt (line 2)) +Requirement already satisfied (use --upgrade to upgrade): nose in ./venv/lib/python2.7/site-packages (from -r dev-requirements.txt (line 1)) +Requirement already satisfied (use --upgrade to upgrade): tox in ./venv/lib/python2.7/site-packages (from -r dev-requirements.txt (line 2)) +Requirement already satisfied (use --upgrade to upgrade): coverage in ./venv/lib/python2.7/site-packages (from -r dev-requirements.txt (line 3)) +Requirement already satisfied (use --upgrade to upgrade): randomize in ./venv/lib/python2.7/site-packages (from -r dev-requirements.txt (line 4)) +Requirement already satisfied (use --upgrade to upgrade): virtualenv>=1.11.2 in ./venv/lib/python2.7/site-packages (from tox->-r dev-requirements.txt (line 2)) +Requirement already satisfied (use --upgrade to upgrade): py>=1.4.17 in ./venv/lib/python2.7/site-packages (from tox->-r dev-requirements.txt (line 2)) +Requirement already satisfied (use --upgrade to upgrade): pluggy<0.4.0,>=0.3.0 in ./venv/lib/python2.7/site-packages (from tox->-r dev-requirements.txt (line 2)) diff --git a/samples/client/petstore/python/swagger_client/models/category.py b/samples/client/petstore/python/swagger_client/models/category.py index 06ad3b8421f..7c36ea3ec47 100644 --- a/samples/client/petstore/python/swagger_client/models/category.py +++ b/samples/client/petstore/python/swagger_client/models/category.py @@ -124,3 +124,16 @@ class Category(object): 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/order.py b/samples/client/petstore/python/swagger_client/models/order.py index 40e4504de87..39081233b11 100644 --- a/samples/client/petstore/python/swagger_client/models/order.py +++ b/samples/client/petstore/python/swagger_client/models/order.py @@ -230,3 +230,16 @@ class Order(object): 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/pet.py b/samples/client/petstore/python/swagger_client/models/pet.py index d8700908eb7..eafb352f2d0 100644 --- a/samples/client/petstore/python/swagger_client/models/pet.py +++ b/samples/client/petstore/python/swagger_client/models/pet.py @@ -230,3 +230,16 @@ class Pet(object): 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/tag.py b/samples/client/petstore/python/swagger_client/models/tag.py index 262fc10f338..2041940dadf 100644 --- a/samples/client/petstore/python/swagger_client/models/tag.py +++ b/samples/client/petstore/python/swagger_client/models/tag.py @@ -124,3 +124,16 @@ class Tag(object): 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/user.py b/samples/client/petstore/python/swagger_client/models/user.py index 7f74d20f3d3..a3ad99fa4c5 100644 --- a/samples/client/petstore/python/swagger_client/models/user.py +++ b/samples/client/petstore/python/swagger_client/models/user.py @@ -274,3 +274,16 @@ class User(object): 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/tests/test_pet_model.py b/samples/client/petstore/python/tests/test_pet_model.py index 0b0df18a8d0..d2bd3c9ca3d 100644 --- a/samples/client/petstore/python/tests/test_pet_model.py +++ b/samples/client/petstore/python/tests/test_pet_model.py @@ -38,3 +38,36 @@ class PetModelTests(unittest.TestCase): " 'status': 'available',\n" " 'tags': [{'id': 1, 'name': None}]}") self.assertEqual(data, self.pet.to_str()) + + def test_equal(self): + self.pet1 = swagger_client.Pet() + self.pet1.name = "test name" + self.pet1.id = 1 + self.pet1.photo_urls = ["string"] + self.pet1.status = "available" + cate1 = swagger_client.Category() + cate1.id = 1 + cate1.name = "dog" + self.pet.category = cate1 + tag1 = swagger_client.Tag() + tag1.id = 1 + self.pet1.tags = [tag1] + + self.pet2 = swagger_client.Pet() + self.pet2.name = "test name" + self.pet2.id = 1 + self.pet2.photo_urls = ["string"] + self.pet2.status = "available" + cate2 = swagger_client.Category() + cate2.id = 1 + cate2.name = "dog" + self.pet.category = cate2 + tag2 = swagger_client.Tag() + tag2.id = 1 + self.pet2.tags = [tag2] + + self.assertTrue(self.pet1 == self.pet2) + + # reset pet1 tags to empty array so that object comparison returns false + self.pet1.tags = [] + self.assertFalse(self.pet1 == self.pet2) diff --git a/samples/client/petstore/qt5cpp/PetStore/PetApiTests.cpp b/samples/client/petstore/qt5cpp/PetStore/PetApiTests.cpp index 829fbe92640..e2d0ffb5d37 100644 --- a/samples/client/petstore/qt5cpp/PetStore/PetApiTests.cpp +++ b/samples/client/petstore/qt5cpp/PetStore/PetApiTests.cpp @@ -35,34 +35,12 @@ void PetApiTests::runTests() { delete tests; } -void PetApiTests::getPetByIdTest() { - SWGPetApi* api = getApi(); - - static QEventLoop loop; - QTimer timer; - timer.setInterval(1000); - timer.setSingleShot(true); - - auto validator = [](SWGPet* pet) { - QVERIFY(pet->getId() == 3); - loop.quit(); - }; - - connect(api, &SWGPetApi::getPetByIdSignal, this, validator); - connect(&timer, &QTimer::timeout, &loop, &QEventLoop::quit); - api->getPetById(3); - timer.start(); - loop.exec(); - QVERIFY2(timer.isActive(), "didn't finish within timeout"); - delete api; -} - void PetApiTests::findPetsByStatusTest() { SWGPetApi* api = getApi(); static QEventLoop loop; QTimer timer; - timer.setInterval(1000); + timer.setInterval(4000); timer.setSingleShot(true); auto validator = [](QList* pets) { diff --git a/samples/client/petstore/qt5cpp/PetStore/PetApiTests.h b/samples/client/petstore/qt5cpp/PetStore/PetApiTests.h index 9fdc939ab11..e219bb9a639 100644 --- a/samples/client/petstore/qt5cpp/PetStore/PetApiTests.h +++ b/samples/client/petstore/qt5cpp/PetStore/PetApiTests.h @@ -25,7 +25,6 @@ signals: bool success(); private slots: - void getPetByIdTest(); void findPetsByStatusTest(); void createAndGetPetTest(); void updatePetTest(); diff --git a/samples/client/petstore/qt5cpp/PetStore/PetStore.pro.user b/samples/client/petstore/qt5cpp/PetStore/PetStore.pro.user index a506d15a1d1..c8f28a4d2b1 100644 --- a/samples/client/petstore/qt5cpp/PetStore/PetStore.pro.user +++ b/samples/client/petstore/qt5cpp/PetStore/PetStore.pro.user @@ -1,10 +1,10 @@ - + EnvironmentId - {e1009bf2-3b8d-440a-a972-23a1fd0a9453} + {20946a4e-8558-4260-a72e-14a8108ad944} ProjectExplorer.Project.ActiveTarget @@ -58,14 +58,14 @@ ProjectExplorer.Project.Target.0 - Desktop Qt 5.4.1 clang 64bit - Desktop Qt 5.4.1 clang 64bit - qt.54.clang_64_kit + Desktop Qt 5.5.1 clang 64bit + Desktop Qt 5.5.1 clang 64bit + qt.55.clang_64_kit 0 0 0 - /Users/tony/dev/projects/swagger-api/swagger-codegen/samples/client/petstore/qt5cpp/build-PetStore-Desktop_Qt_5_4_1_clang_64bit-Debug + /Users/williamcheng/Code/wing328/swagger-codegen/samples/client/petstore/qt5cpp/build-PetStore-Desktop_Qt_5_5_1_clang_64bit-Debug true @@ -76,6 +76,7 @@ true false + false false @@ -125,7 +126,7 @@ true - /Users/tony/dev/projects/swagger-api/swagger-codegen/samples/client/petstore/qt5cpp/build-PetStore-Desktop_Qt_5_4_1_clang_64bit-Release + /Users/williamcheng/Code/wing328/swagger-codegen/samples/client/petstore/qt5cpp/build-PetStore-Desktop_Qt_5_5_1_clang_64bit-Release true @@ -136,6 +137,7 @@ true false + false false @@ -216,12 +218,10 @@ true false true - /usr/local/bin/valgrind + valgrind - 11 - 14 - 12 - 13 + 0 + 1 2 3 4 @@ -231,14 +231,16 @@ 8 9 10 - 0 - 1 + 11 + 12 + 13 + 14 2 PetStore - Qt4ProjectManager.Qt4RunConfiguration:/Users/tony/dev/projects/swagger-api/swagger-codegen/samples/client/petstore/qt5cpp/PetStore/PetStore.pro + Qt4ProjectManager.Qt4RunConfiguration:/Users/williamcheng/Code/wing328/swagger-codegen/samples/client/petstore/qt5cpp/PetStore/PetStore.pro PetStore.pro false diff --git a/samples/client/petstore/qt5cpp/client/SWGHelpers.cpp b/samples/client/petstore/qt5cpp/client/SWGHelpers.cpp index 7f4d748c2dc..6b439996724 100644 --- a/samples/client/petstore/qt5cpp/client/SWGHelpers.cpp +++ b/samples/client/petstore/qt5cpp/client/SWGHelpers.cpp @@ -1,9 +1,9 @@ #include "SWGHelpers.h" #include "SWGModelFactory.h" #include "SWGObject.h" -#import -#import -#import +#include +#include +#include namespace Swagger { @@ -25,6 +25,14 @@ setValue(void* value, QJsonValue obj, QString type, QString complexType) { qint64 *val = static_cast(value); *val = obj.toVariant().toLongLong(); } + else if(QStringLiteral("float").compare(type) == 0) { + float *val = static_cast(value); + *val = obj.toDouble(); + } + else if(QStringLiteral("double").compare(type) == 0) { + double *val = static_cast(value); + *val = obj.toDouble(); + } else if (QStringLiteral("QString").compare(type) == 0) { QString **val = static_cast(value); @@ -86,6 +94,16 @@ setValue(void* value, QJsonValue obj, QString type, QString complexType) { setValue(&val, jval, QStringLiteral("bool"), QStringLiteral("")); output->append((void*)&val); } + else if(QStringLiteral("float").compare(complexType) == 0) { + float val; + setValue(&val, jval, QStringLiteral("float"), QStringLiteral("")); + output->append((void*)&val); + } + else if(QStringLiteral("double").compare(complexType) == 0) { + double val; + setValue(&val, jval, QStringLiteral("double"), QStringLiteral("")); + output->append((void*)&val); + } } } QList **val = static_cast**>(value); @@ -131,6 +149,14 @@ toJsonValue(QString name, void* value, QJsonObject* output, QString type) { bool* str = static_cast(value); output->insert(name, QJsonValue(*str)); } + else if(QStringLiteral("float").compare(type) == 0) { + float* str = static_cast(value); + output->insert(name, QJsonValue((double)*str)); + } + else if(QStringLiteral("double").compare(type) == 0) { + double* str = static_cast(value); + output->insert(name, QJsonValue(*str)); + } } void diff --git a/samples/client/petstore/qt5cpp/client/SWGPet.h b/samples/client/petstore/qt5cpp/client/SWGPet.h index e9cb4d08233..3f9320f1507 100644 --- a/samples/client/petstore/qt5cpp/client/SWGPet.h +++ b/samples/client/petstore/qt5cpp/client/SWGPet.h @@ -10,10 +10,10 @@ #include -#include "SWGTag.h" -#include -#include "SWGCategory.h" #include +#include "SWGCategory.h" +#include +#include "SWGTag.h" #include "SWGObject.h" diff --git a/samples/client/petstore/ruby/lib/petstore.rb b/samples/client/petstore/ruby/lib/petstore.rb index c13e99f29fc..4c21fb331d3 100644 --- a/samples/client/petstore/ruby/lib/petstore.rb +++ b/samples/client/petstore/ruby/lib/petstore.rb @@ -19,17 +19,17 @@ require 'petstore/api/pet_api' module Petstore class << self - # Configure sdk using block. - # Petstore.configure do |config| - # config.username = "xxx" - # config.password = "xxx" - # end - # If no block given, return the configuration singleton instance. + # Customize default settings for the SDK using block. + # Petstore.configure do |config| + # config.username = "xxx" + # config.password = "xxx" + # end + # If no block given, return the default Configuration object. def configure if block_given? - yield Configuration.instance + yield(Configuration.default) else - Configuration.instance + Configuration.default end end end 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 887f86dd45c..9641ad0b707 100644 --- a/samples/client/petstore/ruby/lib/petstore/api/pet_api.rb +++ b/samples/client/petstore/ruby/lib/petstore/api/pet_api.rb @@ -4,8 +4,8 @@ module Petstore class PetApi attr_accessor :api_client - def initialize(api_client = nil) - @api_client = api_client || Configuration.api_client + def initialize(api_client = ApiClient.default) + @api_client = api_client end # Update an existing pet @@ -14,8 +14,18 @@ module Petstore # @option opts [Pet] :body Pet object that needs to be added to the store # @return [nil] def update_pet(opts = {}) - if Configuration.debugging - Configuration.logger.debug "Calling API: PetApi#update_pet ..." + 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 @@ -43,16 +53,16 @@ module Petstore auth_names = ['petstore_auth'] - @api_client.call_api(:PUT, path, + data, status_code, headers = @api_client.call_api(:PUT, path, :header_params => header_params, :query_params => query_params, :form_params => form_params, :body => post_body, :auth_names => auth_names) - if Configuration.debugging - Configuration.logger.debug "API called: PetApi#update_pet" + 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 nil + return data, status_code, headers end # Add a new pet to the store @@ -61,8 +71,18 @@ module Petstore # @option opts [Pet] :body Pet object that needs to be added to the store # @return [nil] def add_pet(opts = {}) - if Configuration.debugging - Configuration.logger.debug "Calling API: PetApi#add_pet ..." + add_pet_with_http_info(opts) + return nil + end + + # 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 [Array<(nil, Fixnum, Hash)>] nil, response status code and response headers + def add_pet_with_http_info(opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug "Calling API: PetApi#add_pet ..." end # resource path @@ -90,16 +110,16 @@ module Petstore auth_names = ['petstore_auth'] - @api_client.call_api(:POST, path, + data, status_code, headers = @api_client.call_api(:POST, path, :header_params => header_params, :query_params => query_params, :form_params => form_params, :body => post_body, :auth_names => auth_names) - if Configuration.debugging - Configuration.logger.debug "API called: PetApi#add_pet" + if @api_client.config.debugging + @api_client.config.logger.debug "API called: PetApi#add_pet\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" end - return nil + return data, status_code, headers end # Finds Pets by status @@ -108,8 +128,18 @@ module Petstore # @option opts [Array] :status Status values that need to be considered for filter # @return [Array] def find_pets_by_status(opts = {}) - if Configuration.debugging - Configuration.logger.debug "Calling API: PetApi#find_pets_by_status ..." + data, status_code, headers = find_pets_by_status_with_http_info(opts) + return data + end + + # Finds Pets by status + # Multiple status values can be provided with comma seperated strings + # @param [Hash] opts the optional parameters + # @option opts [Array] :status Status values that need to be considered for filter + # @return [Array<(Array, Fixnum, Hash)>] Array data, response status code and response headers + def find_pets_by_status_with_http_info(opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug "Calling API: PetApi#find_pets_by_status ..." end # resource path @@ -138,17 +168,17 @@ module Petstore auth_names = ['petstore_auth'] - result = @api_client.call_api(:GET, path, + data, status_code, headers = @api_client.call_api(:GET, path, :header_params => header_params, :query_params => query_params, :form_params => form_params, :body => post_body, :auth_names => auth_names, :return_type => 'Array') - if Configuration.debugging - Configuration.logger.debug "API called: PetApi#find_pets_by_status. Result: #{result.inspect}" + if @api_client.config.debugging + @api_client.config.logger.debug "API called: PetApi#find_pets_by_status\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" end - return result + return data, status_code, headers end # Finds Pets by tags @@ -157,8 +187,18 @@ module Petstore # @option opts [Array] :tags Tags to filter by # @return [Array] def find_pets_by_tags(opts = {}) - if Configuration.debugging - Configuration.logger.debug "Calling API: PetApi#find_pets_by_tags ..." + data, status_code, headers = find_pets_by_tags_with_http_info(opts) + return data + end + + # 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<(Array, Fixnum, Hash)>] Array data, response status code and response headers + def find_pets_by_tags_with_http_info(opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug "Calling API: PetApi#find_pets_by_tags ..." end # resource path @@ -187,17 +227,17 @@ module Petstore auth_names = ['petstore_auth'] - result = @api_client.call_api(:GET, path, + data, status_code, headers = @api_client.call_api(:GET, path, :header_params => header_params, :query_params => query_params, :form_params => form_params, :body => post_body, :auth_names => auth_names, :return_type => 'Array') - if Configuration.debugging - Configuration.logger.debug "API called: PetApi#find_pets_by_tags. Result: #{result.inspect}" + if @api_client.config.debugging + @api_client.config.logger.debug "API called: PetApi#find_pets_by_tags\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" end - return result + return data, status_code, headers end # Find pet by ID @@ -206,8 +246,18 @@ module Petstore # @param [Hash] opts the optional parameters # @return [Pet] def get_pet_by_id(pet_id, opts = {}) - if Configuration.debugging - Configuration.logger.debug "Calling API: PetApi#get_pet_by_id ..." + data, status_code, headers = get_pet_by_id_with_http_info(pet_id, opts) + return data + end + + # 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<(Pet, Fixnum, Hash)>] Pet data, response status code and response headers + def get_pet_by_id_with_http_info(pet_id, opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug "Calling API: PetApi#get_pet_by_id ..." end # verify the required parameter 'pet_id' is set @@ -238,17 +288,17 @@ module Petstore auth_names = ['api_key'] - result = @api_client.call_api(:GET, path, + data, status_code, headers = @api_client.call_api(:GET, path, :header_params => header_params, :query_params => query_params, :form_params => form_params, :body => post_body, :auth_names => auth_names, :return_type => 'Pet') - if Configuration.debugging - Configuration.logger.debug "API called: PetApi#get_pet_by_id. Result: #{result.inspect}" + if @api_client.config.debugging + @api_client.config.logger.debug "API called: PetApi#get_pet_by_id\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" end - return result + return data, status_code, headers end # Updates a pet in the store with form data @@ -259,8 +309,20 @@ module Petstore # @option opts [String] :status Updated status of the pet # @return [nil] def update_pet_with_form(pet_id, opts = {}) - if Configuration.debugging - Configuration.logger.debug "Calling API: PetApi#update_pet_with_form ..." + update_pet_with_form_with_http_info(pet_id, opts) + return nil + end + + # Updates a pet in the store with form data + # + # @param pet_id ID of pet that needs to be updated + # @param [Hash] opts the optional parameters + # @option opts [String] :name Updated name of the pet + # @option opts [String] :status Updated status of the pet + # @return [Array<(nil, Fixnum, Hash)>] nil, response status code and response headers + def update_pet_with_form_with_http_info(pet_id, opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug "Calling API: PetApi#update_pet_with_form ..." end # verify the required parameter 'pet_id' is set @@ -293,16 +355,16 @@ module Petstore auth_names = ['petstore_auth'] - @api_client.call_api(:POST, path, + data, status_code, headers = @api_client.call_api(:POST, path, :header_params => header_params, :query_params => query_params, :form_params => form_params, :body => post_body, :auth_names => auth_names) - if Configuration.debugging - Configuration.logger.debug "API called: PetApi#update_pet_with_form" + if @api_client.config.debugging + @api_client.config.logger.debug "API called: PetApi#update_pet_with_form\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" end - return nil + return data, status_code, headers end # Deletes a pet @@ -312,8 +374,19 @@ module Petstore # @option opts [String] :api_key # @return [nil] def delete_pet(pet_id, opts = {}) - if Configuration.debugging - Configuration.logger.debug "Calling API: PetApi#delete_pet ..." + 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 @@ -345,16 +418,16 @@ module Petstore auth_names = ['petstore_auth'] - @api_client.call_api(:DELETE, path, + data, status_code, headers = @api_client.call_api(:DELETE, path, :header_params => header_params, :query_params => query_params, :form_params => form_params, :body => post_body, :auth_names => auth_names) - if Configuration.debugging - Configuration.logger.debug "API called: PetApi#delete_pet" + 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 nil + return data, status_code, headers end # uploads an image @@ -365,8 +438,20 @@ module Petstore # @option opts [File] :file file to upload # @return [nil] def upload_file(pet_id, opts = {}) - if Configuration.debugging - Configuration.logger.debug "Calling API: PetApi#upload_file ..." + upload_file_with_http_info(pet_id, opts) + return nil + end + + # uploads an image + # + # @param pet_id ID of pet to update + # @param [Hash] opts the optional parameters + # @option opts [String] :additional_metadata Additional data to pass to server + # @option opts [File] :file file to upload + # @return [Array<(nil, Fixnum, Hash)>] nil, response status code and response headers + def upload_file_with_http_info(pet_id, opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug "Calling API: PetApi#upload_file ..." end # verify the required parameter 'pet_id' is set @@ -399,16 +484,16 @@ module Petstore auth_names = ['petstore_auth'] - @api_client.call_api(:POST, path, + data, status_code, headers = @api_client.call_api(:POST, path, :header_params => header_params, :query_params => query_params, :form_params => form_params, :body => post_body, :auth_names => auth_names) - if Configuration.debugging - Configuration.logger.debug "API called: PetApi#upload_file" + if @api_client.config.debugging + @api_client.config.logger.debug "API called: PetApi#upload_file\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" end - return nil + 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 235ff1c4106..1d8a92e288f 100644 --- a/samples/client/petstore/ruby/lib/petstore/api/store_api.rb +++ b/samples/client/petstore/ruby/lib/petstore/api/store_api.rb @@ -4,8 +4,8 @@ module Petstore class StoreApi attr_accessor :api_client - def initialize(api_client = nil) - @api_client = api_client || Configuration.api_client + def initialize(api_client = ApiClient.default) + @api_client = api_client end # Returns pet inventories by status @@ -13,8 +13,17 @@ module Petstore # @param [Hash] opts the optional parameters # @return [Hash] def get_inventory(opts = {}) - if Configuration.debugging - Configuration.logger.debug "Calling API: StoreApi#get_inventory ..." + 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 @@ -42,17 +51,17 @@ module Petstore auth_names = ['api_key'] - result = @api_client.call_api(:GET, path, + data, status_code, headers = @api_client.call_api(:GET, path, :header_params => header_params, :query_params => query_params, :form_params => form_params, :body => post_body, :auth_names => auth_names, :return_type => 'Hash') - if Configuration.debugging - Configuration.logger.debug "API called: StoreApi#get_inventory. Result: #{result.inspect}" + 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 result + return data, status_code, headers end # Place an order for a pet @@ -61,8 +70,18 @@ module Petstore # @option opts [Order] :body order placed for purchasing the pet # @return [Order] def place_order(opts = {}) - if Configuration.debugging - Configuration.logger.debug "Calling API: StoreApi#place_order ..." + 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 @@ -90,17 +109,17 @@ module Petstore auth_names = [] - result = @api_client.call_api(:POST, path, + data, status_code, headers = @api_client.call_api(:POST, path, :header_params => header_params, :query_params => query_params, :form_params => form_params, :body => post_body, :auth_names => auth_names, :return_type => 'Order') - if Configuration.debugging - Configuration.logger.debug "API called: StoreApi#place_order. Result: #{result.inspect}" + 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 result + return data, status_code, headers end # Find purchase order by ID @@ -109,8 +128,18 @@ module Petstore # @param [Hash] opts the optional parameters # @return [Order] def get_order_by_id(order_id, opts = {}) - if Configuration.debugging - Configuration.logger.debug "Calling API: StoreApi#get_order_by_id ..." + 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 @@ -141,17 +170,17 @@ module Petstore auth_names = [] - result = @api_client.call_api(:GET, path, + data, status_code, headers = @api_client.call_api(:GET, path, :header_params => header_params, :query_params => query_params, :form_params => form_params, :body => post_body, :auth_names => auth_names, :return_type => 'Order') - if Configuration.debugging - Configuration.logger.debug "API called: StoreApi#get_order_by_id. Result: #{result.inspect}" + 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 result + return data, status_code, headers end # Delete purchase order by ID @@ -160,8 +189,18 @@ module Petstore # @param [Hash] opts the optional parameters # @return [nil] def delete_order(order_id, opts = {}) - if Configuration.debugging - Configuration.logger.debug "Calling API: StoreApi#delete_order ..." + delete_order_with_http_info(order_id, opts) + return nil + end + + # 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 [Array<(nil, Fixnum, Hash)>] nil, response status code and response headers + def delete_order_with_http_info(order_id, opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug "Calling API: StoreApi#delete_order ..." end # verify the required parameter 'order_id' is set @@ -192,16 +231,16 @@ module Petstore auth_names = [] - @api_client.call_api(:DELETE, path, + data, status_code, headers = @api_client.call_api(:DELETE, path, :header_params => header_params, :query_params => query_params, :form_params => form_params, :body => post_body, :auth_names => auth_names) - if Configuration.debugging - Configuration.logger.debug "API called: StoreApi#delete_order" + if @api_client.config.debugging + @api_client.config.logger.debug "API called: StoreApi#delete_order\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" end - return nil + 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 7f546330f3a..e1c8332b835 100644 --- a/samples/client/petstore/ruby/lib/petstore/api/user_api.rb +++ b/samples/client/petstore/ruby/lib/petstore/api/user_api.rb @@ -4,8 +4,8 @@ module Petstore class UserApi attr_accessor :api_client - def initialize(api_client = nil) - @api_client = api_client || Configuration.api_client + def initialize(api_client = ApiClient.default) + @api_client = api_client end # Create user @@ -14,8 +14,18 @@ module Petstore # @option opts [User] :body Created user object # @return [nil] def create_user(opts = {}) - if Configuration.debugging - Configuration.logger.debug "Calling API: UserApi#create_user ..." + create_user_with_http_info(opts) + return nil + end + + # 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 [Array<(nil, Fixnum, Hash)>] nil, response status code and response headers + def create_user_with_http_info(opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug "Calling API: UserApi#create_user ..." end # resource path @@ -43,16 +53,16 @@ module Petstore auth_names = [] - @api_client.call_api(:POST, path, + data, status_code, headers = @api_client.call_api(:POST, path, :header_params => header_params, :query_params => query_params, :form_params => form_params, :body => post_body, :auth_names => auth_names) - if Configuration.debugging - Configuration.logger.debug "API called: UserApi#create_user" + if @api_client.config.debugging + @api_client.config.logger.debug "API called: UserApi#create_user\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" end - return nil + return data, status_code, headers end # Creates list of users with given input array @@ -61,8 +71,18 @@ module Petstore # @option opts [Array] :body List of user object # @return [nil] def create_users_with_array_input(opts = {}) - if Configuration.debugging - Configuration.logger.debug "Calling API: UserApi#create_users_with_array_input ..." + create_users_with_array_input_with_http_info(opts) + return nil + end + + # Creates list of users with given input array + # + # @param [Hash] opts the optional parameters + # @option opts [Array] :body List of user object + # @return [Array<(nil, Fixnum, Hash)>] nil, response status code and response headers + def create_users_with_array_input_with_http_info(opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug "Calling API: UserApi#create_users_with_array_input ..." end # resource path @@ -90,16 +110,16 @@ module Petstore auth_names = [] - @api_client.call_api(:POST, path, + data, status_code, headers = @api_client.call_api(:POST, path, :header_params => header_params, :query_params => query_params, :form_params => form_params, :body => post_body, :auth_names => auth_names) - if Configuration.debugging - Configuration.logger.debug "API called: UserApi#create_users_with_array_input" + if @api_client.config.debugging + @api_client.config.logger.debug "API called: UserApi#create_users_with_array_input\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" end - return nil + return data, status_code, headers end # Creates list of users with given input array @@ -108,8 +128,18 @@ module Petstore # @option opts [Array] :body List of user object # @return [nil] def create_users_with_list_input(opts = {}) - if Configuration.debugging - Configuration.logger.debug "Calling API: UserApi#create_users_with_list_input ..." + create_users_with_list_input_with_http_info(opts) + return nil + end + + # Creates list of users with given input array + # + # @param [Hash] opts the optional parameters + # @option opts [Array] :body List of user object + # @return [Array<(nil, Fixnum, Hash)>] nil, response status code and response headers + def create_users_with_list_input_with_http_info(opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug "Calling API: UserApi#create_users_with_list_input ..." end # resource path @@ -137,16 +167,16 @@ module Petstore auth_names = [] - @api_client.call_api(:POST, path, + data, status_code, headers = @api_client.call_api(:POST, path, :header_params => header_params, :query_params => query_params, :form_params => form_params, :body => post_body, :auth_names => auth_names) - if Configuration.debugging - Configuration.logger.debug "API called: UserApi#create_users_with_list_input" + if @api_client.config.debugging + @api_client.config.logger.debug "API called: UserApi#create_users_with_list_input\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" end - return nil + return data, status_code, headers end # Logs user into the system @@ -156,8 +186,19 @@ module Petstore # @option opts [String] :password The password for login in clear text # @return [String] def login_user(opts = {}) - if Configuration.debugging - Configuration.logger.debug "Calling API: UserApi#login_user ..." + data, status_code, headers = login_user_with_http_info(opts) + return data + end + + # 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 [Array<(String, Fixnum, Hash)>] String data, response status code and response headers + def login_user_with_http_info(opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug "Calling API: UserApi#login_user ..." end # resource path @@ -187,17 +228,17 @@ module Petstore auth_names = [] - result = @api_client.call_api(:GET, path, + data, status_code, headers = @api_client.call_api(:GET, path, :header_params => header_params, :query_params => query_params, :form_params => form_params, :body => post_body, :auth_names => auth_names, :return_type => 'String') - if Configuration.debugging - Configuration.logger.debug "API called: UserApi#login_user. Result: #{result.inspect}" + if @api_client.config.debugging + @api_client.config.logger.debug "API called: UserApi#login_user\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" end - return result + return data, status_code, headers end # Logs out current logged in user session @@ -205,8 +246,17 @@ module Petstore # @param [Hash] opts the optional parameters # @return [nil] def logout_user(opts = {}) - if Configuration.debugging - Configuration.logger.debug "Calling API: UserApi#logout_user ..." + logout_user_with_http_info(opts) + return nil + end + + # Logs out current logged in user session + # + # @param [Hash] opts the optional parameters + # @return [Array<(nil, Fixnum, Hash)>] nil, response status code and response headers + def logout_user_with_http_info(opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug "Calling API: UserApi#logout_user ..." end # resource path @@ -234,16 +284,16 @@ module Petstore auth_names = [] - @api_client.call_api(:GET, path, + data, status_code, headers = @api_client.call_api(:GET, path, :header_params => header_params, :query_params => query_params, :form_params => form_params, :body => post_body, :auth_names => auth_names) - if Configuration.debugging - Configuration.logger.debug "API called: UserApi#logout_user" + if @api_client.config.debugging + @api_client.config.logger.debug "API called: UserApi#logout_user\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" end - return nil + return data, status_code, headers end # Get user by user name @@ -252,8 +302,18 @@ module Petstore # @param [Hash] opts the optional parameters # @return [User] def get_user_by_name(username, opts = {}) - if Configuration.debugging - Configuration.logger.debug "Calling API: UserApi#get_user_by_name ..." + 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 @@ -284,17 +344,17 @@ module Petstore auth_names = [] - result = @api_client.call_api(:GET, path, + data, status_code, headers = @api_client.call_api(:GET, path, :header_params => header_params, :query_params => query_params, :form_params => form_params, :body => post_body, :auth_names => auth_names, :return_type => 'User') - if Configuration.debugging - Configuration.logger.debug "API called: UserApi#get_user_by_name. Result: #{result.inspect}" + 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 result + return data, status_code, headers end # Updated user @@ -304,8 +364,19 @@ module Petstore # @option opts [User] :body Updated user object # @return [nil] def update_user(username, opts = {}) - if Configuration.debugging - Configuration.logger.debug "Calling API: UserApi#update_user ..." + update_user_with_http_info(username, opts) + return nil + end + + # 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 [Array<(nil, Fixnum, Hash)>] nil, response status code and response headers + def update_user_with_http_info(username, opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug "Calling API: UserApi#update_user ..." end # verify the required parameter 'username' is set @@ -336,16 +407,16 @@ module Petstore auth_names = [] - @api_client.call_api(:PUT, path, + data, status_code, headers = @api_client.call_api(:PUT, path, :header_params => header_params, :query_params => query_params, :form_params => form_params, :body => post_body, :auth_names => auth_names) - if Configuration.debugging - Configuration.logger.debug "API called: UserApi#update_user" + if @api_client.config.debugging + @api_client.config.logger.debug "API called: UserApi#update_user\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" end - return nil + return data, status_code, headers end # Delete user @@ -354,8 +425,18 @@ module Petstore # @param [Hash] opts the optional parameters # @return [nil] def delete_user(username, opts = {}) - if Configuration.debugging - Configuration.logger.debug "Calling API: UserApi#delete_user ..." + 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 @@ -386,16 +467,16 @@ module Petstore auth_names = [] - @api_client.call_api(:DELETE, path, + data, status_code, headers = @api_client.call_api(:DELETE, path, :header_params => header_params, :query_params => query_params, :form_params => form_params, :body => post_body, :auth_names => auth_names) - if Configuration.debugging - Configuration.logger.debug "API called: UserApi#delete_user" + 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 nil + 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 92a61bac4a6..52a3eb43855 100644 --- a/samples/client/petstore/ruby/lib/petstore/api_client.rb +++ b/samples/client/petstore/ruby/lib/petstore/api_client.rb @@ -7,36 +7,37 @@ require 'uri' module Petstore class ApiClient - - attr_accessor :host + # The Configuration object holding settings to be used in the API client. + attr_accessor :config # Defines the headers to be used in HTTP requests of all API calls by default. # # @return [Hash] attr_accessor :default_headers - # Stores the HTTP response from the last API call using this API client. - attr_accessor :last_response - - def initialize(host = nil) - @host = host || Configuration.base_url - @format = 'json' + def initialize(config = Configuration.default) + @config = config @user_agent = "ruby-swagger-#{VERSION}" @default_headers = { - 'Content-Type' => "application/#{@format.downcase}", + 'Content-Type' => "application/json", 'User-Agent' => @user_agent } end + def self.default + @@default ||= ApiClient.new + end + + # Call an API with given options. + # + # @return [Array<(Object, Fixnum, Hash)>] an array of 3 elements: + # the data deserialized from response body (could be nil), response status code and response headers. def call_api(http_method, path, opts = {}) request = build_request(http_method, path, opts) response = request.run - # record as last response - @last_response = response - - if Configuration.debugging - Configuration.logger.debug "HTTP response body ~BEGIN~\n#{response.body}\n~END~\n" + if @config.debugging + @config.logger.debug "HTTP response body ~BEGIN~\n#{response.body}\n~END~\n" end unless response.success? @@ -47,10 +48,11 @@ module Petstore end if opts[:return_type] - deserialize(response, opts[:return_type]) + data = deserialize(response, opts[:return_type]) else - nil + data = nil end + return data, response.code, response.headers end def build_request(http_method, path, opts = {}) @@ -69,24 +71,33 @@ module Petstore :method => http_method, :headers => header_params, :params => query_params, - :ssl_verifypeer => Configuration.verify_ssl, - :sslcert => Configuration.cert_file, - :sslkey => Configuration.key_file, - :cainfo => Configuration.ssl_ca_cert, - :verbose => Configuration.debugging + :ssl_verifypeer => @config.verify_ssl, + :sslcert => @config.cert_file, + :sslkey => @config.key_file, + :cainfo => @config.ssl_ca_cert, + :verbose => @config.debugging } if [:post, :patch, :put, :delete].include?(http_method) req_body = build_request_body(header_params, form_params, opts[:body]) req_opts.update :body => req_body - if Configuration.debugging - Configuration.logger.debug "HTTP request body param ~BEGIN~\n#{req_body}\n~END~\n" + if @config.debugging + @config.logger.debug "HTTP request body param ~BEGIN~\n#{req_body}\n~END~\n" end end Typhoeus::Request.new(url, req_opts) end + # Check if the given MIME is a JSON MIME. + # JSON MIME examples: + # application/json + # application/json; charset=UTF8 + # APPLICATION/JSON + def json_mime?(mime) + !!(mime =~ /\Aapplication\/json(;.*)?\z/i) + end + # Deserialize the response to the given return type. # # @param [String] return_type some examples: "User", "Array[User]", "Hash[String,Integer]" @@ -100,9 +111,7 @@ module Petstore # ensuring a default content type content_type = response.headers['Content-Type'] || 'application/json' - unless content_type.start_with?('application/json') - fail "Content-Type is not supported: #{content_type}" - end + fail "Content-Type is not supported: #{content_type}" unless json_mime?(content_type) begin data = JSON.parse("[#{body}]", :symbolize_names => true)[0] @@ -162,7 +171,7 @@ module Petstore # @see Configuration#temp_folder_path # @return [File] the file downloaded def download_file(response) - tmp_file = Tempfile.new '', Configuration.temp_folder_path + tmp_file = Tempfile.new '', @config.temp_folder_path content_disposition = response.headers['Content-Disposition'] if content_disposition filename = content_disposition[/filename=['"]?([^'"\s]+)['"]?/, 1] @@ -174,15 +183,15 @@ module Petstore tmp_file.close! File.open(path, 'w') { |file| file.write(response.body) } - Configuration.logger.info "File written to #{path}. Please move the file to a proper "\ - "folder for further processing and delete the temp afterwards" + @config.logger.info "File written to #{path}. Please move the file to a proper folder "\ + "for further processing and delete the temp afterwards" File.new(path) end def build_request_url(path) # Add leading and trailing slashes to path path = "/#{path}".gsub(/\/+/, '/') - URI.encode(host + path) + URI.encode(@config.base_url + path) end def build_request_body(header_params, form_params, body) @@ -210,7 +219,7 @@ module Petstore # Update hearder and query params based on authentication settings. def update_params_for_auth!(header_params, query_params, auth_names) Array(auth_names).each do |auth_name| - auth_setting = Configuration.auth_settings[auth_name] + auth_setting = @config.auth_settings[auth_name] next unless auth_setting case auth_setting[:in] when 'header' then header_params[auth_setting[:key]] = auth_setting[:value] @@ -229,26 +238,21 @@ module Petstore # @param [Array] accepts array for Accept # @return [String] the Accept header (e.g. application/json) def select_header_accept(accepts) - if accepts.empty? - return - elsif accepts.any?{ |s| s.casecmp('application/json') == 0 } - 'application/json' # look for json data by default - else - accepts.join(',') - end + return nil if accepts.nil? || accepts.empty? + # use JSON when present, otherwise use all of the provided + json_accept = accepts.find { |s| json_mime?(s) } + return json_accept || accepts.join(',') end # Return Content-Type header based on an array of content types provided. # @param [Array] content_types array for Content-Type # @return [String] the Content-Type header (e.g. application/json) def select_header_content_type(content_types) - if content_types.empty? - 'application/json' # use application/json by default - elsif content_types.any?{ |s| s.casecmp('application/json')==0 } - 'application/json' # use application/json if it's included - else - content_types[0] # otherwise, use the first one - end + # use application/json by default + return 'application/json' if content_types.nil? || content_types.empty? + # use JSON when present, otherwise use the first one + json_content_type = content_types.find { |s| json_mime?(s) } + return json_content_type || content_types.first end # Convert object (array, hash, object, etc) to JSON string. diff --git a/samples/client/petstore/ruby/lib/petstore/configuration.rb b/samples/client/petstore/ruby/lib/petstore/configuration.rb index 4f7bd1c1b80..7173a4450c6 100644 --- a/samples/client/petstore/ruby/lib/petstore/configuration.rb +++ b/samples/client/petstore/ruby/lib/petstore/configuration.rb @@ -1,14 +1,7 @@ require 'uri' -require 'singleton' module Petstore class Configuration - - include Singleton - - # Default api client - attr_accessor :api_client - # Defines url scheme attr_accessor :scheme @@ -94,17 +87,6 @@ module Petstore attr_accessor :force_ending_format - class << self - def method_missing(method_name, *args, &block) - config = Configuration.instance - if config.respond_to?(method_name) - config.send(method_name, *args, &block) - else - super - end - end - end - def initialize @scheme = 'http' @host = 'petstore.swagger.io' @@ -118,10 +100,17 @@ module Petstore @inject_format = false @force_ending_format = false @logger = defined?(Rails) ? Rails.logger : Logger.new(STDOUT) + + yield(self) if block_given? end - def api_client - @api_client ||= ApiClient.new + # The default Configuration object. + def self.default + @@default ||= Configuration.new + end + + def configure + yield(self) if block_given? end def scheme=(scheme) diff --git a/samples/client/petstore/ruby/lib/petstore/models/category.rb b/samples/client/petstore/ruby/lib/petstore/models/category.rb index 1e36eac4147..e223e747e74 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/category.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/category.rb @@ -1,21 +1,21 @@ module Petstore - # class Category < BaseObject - attr_accessor :id, :name - # attribute mapping from ruby-style variable name to JSON key + attr_accessor :id + + attr_accessor :name + + # Attribute mapping from ruby-style variable name to JSON key. def self.attribute_map { - # :'id' => :'id', - # :'name' => :'name' } end - # attribute type + # Attribute type mapping. def self.swagger_types { :'id' => :'Integer', @@ -25,7 +25,7 @@ module Petstore end def initialize(attributes = {}) - return if !attributes.is_a?(Hash) || attributes.empty? + 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} @@ -41,5 +41,22 @@ module Petstore end + # Check equality by comparing each attribute. + def ==(o) + return true if self.equal?(o) + self.class == o.class && + id == o.id && + name == o.name + end + + # @see the `==` method + def eql?(o) + self == o + end + + # Calculate hash code according to all attributes. + def hash + [id, name].hash + 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 ab6f8f00189..19a33d1cfc3 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/order.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/order.rb @@ -1,33 +1,38 @@ module Petstore - # class Order < BaseObject - attr_accessor :id, :pet_id, :quantity, :ship_date, :status, :complete - # attribute mapping from ruby-style variable name to JSON key + attr_accessor :id + + attr_accessor :pet_id + + attr_accessor :quantity + + attr_accessor :ship_date + + # Order Status + attr_accessor :status + + attr_accessor :complete + + # Attribute mapping from ruby-style variable name to JSON key. def self.attribute_map { - # :'id' => :'id', - # :'pet_id' => :'petId', - # :'quantity' => :'quantity', - # :'ship_date' => :'shipDate', - # Order Status :'status' => :'status', - # :'complete' => :'complete' } end - # attribute type + # Attribute type mapping. def self.swagger_types { :'id' => :'Integer', @@ -41,7 +46,7 @@ module Petstore end def initialize(attributes = {}) - return if !attributes.is_a?(Hash) || attributes.empty? + 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} @@ -73,6 +78,7 @@ module Petstore end + # Custom attribute writer method checking allowed values (enum). def status=(status) allowed_values = ["placed", "approved", "delivered"] if status && !allowed_values.include?(status) @@ -81,5 +87,26 @@ module Petstore @status = status end + # Check equality by comparing each attribute. + def ==(o) + return true if self.equal?(o) + self.class == o.class && + id == o.id && + pet_id == o.pet_id && + quantity == o.quantity && + ship_date == o.ship_date && + status == o.status && + complete == o.complete + end + + # @see the `==` method + def eql?(o) + self == o + end + + # Calculate hash code according to all attributes. + def hash + [id, pet_id, quantity, ship_date, status, complete].hash + end end end diff --git a/samples/client/petstore/ruby/lib/petstore/models/pet.rb b/samples/client/petstore/ruby/lib/petstore/models/pet.rb index a208cf3f87c..fb967cbbab4 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/pet.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/pet.rb @@ -1,33 +1,38 @@ module Petstore - # class Pet < BaseObject - attr_accessor :id, :category, :name, :photo_urls, :tags, :status - # attribute mapping from ruby-style variable name to JSON key + attr_accessor :id + + attr_accessor :category + + attr_accessor :name + + attr_accessor :photo_urls + + attr_accessor :tags + + # pet status in the store + attr_accessor :status + + # 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', - # pet status in the store :'status' => :'status' } end - # attribute type + # Attribute type mapping. def self.swagger_types { :'id' => :'Integer', @@ -41,7 +46,7 @@ module Petstore end def initialize(attributes = {}) - return if !attributes.is_a?(Hash) || attributes.empty? + 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} @@ -77,6 +82,7 @@ module Petstore end + # Custom attribute writer method checking allowed values (enum). def status=(status) allowed_values = ["available", "pending", "sold"] if status && !allowed_values.include?(status) @@ -85,5 +91,26 @@ module Petstore @status = status end + # Check equality by comparing each attribute. + def ==(o) + return true if self.equal?(o) + self.class == o.class && + id == o.id && + category == o.category && + name == o.name && + photo_urls == o.photo_urls && + tags == o.tags && + status == o.status + end + + # @see the `==` method + def eql?(o) + self == o + end + + # Calculate hash code according to all attributes. + def hash + [id, category, name, photo_urls, tags, status].hash + end end end diff --git a/samples/client/petstore/ruby/lib/petstore/models/tag.rb b/samples/client/petstore/ruby/lib/petstore/models/tag.rb index 3fb5e1f969c..681c2a2a5c9 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/tag.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/tag.rb @@ -1,21 +1,21 @@ module Petstore - # class Tag < BaseObject - attr_accessor :id, :name - # attribute mapping from ruby-style variable name to JSON key + attr_accessor :id + + attr_accessor :name + + # Attribute mapping from ruby-style variable name to JSON key. def self.attribute_map { - # :'id' => :'id', - # :'name' => :'name' } end - # attribute type + # Attribute type mapping. def self.swagger_types { :'id' => :'Integer', @@ -25,7 +25,7 @@ module Petstore end def initialize(attributes = {}) - return if !attributes.is_a?(Hash) || attributes.empty? + 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} @@ -41,5 +41,22 @@ module Petstore end + # Check equality by comparing each attribute. + def ==(o) + return true if self.equal?(o) + self.class == o.class && + id == o.id && + name == o.name + end + + # @see the `==` method + def eql?(o) + self == o + end + + # Calculate hash code according to all attributes. + def hash + [id, name].hash + end end end diff --git a/samples/client/petstore/ruby/lib/petstore/models/user.rb b/samples/client/petstore/ruby/lib/petstore/models/user.rb index 3a6d5f354e0..ca00bf34be1 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/user.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/user.rb @@ -1,39 +1,46 @@ module Petstore - # class User < BaseObject - attr_accessor :id, :username, :first_name, :last_name, :email, :password, :phone, :user_status - # attribute mapping from ruby-style variable name to JSON key + attr_accessor :id + + attr_accessor :username + + attr_accessor :first_name + + attr_accessor :last_name + + attr_accessor :email + + attr_accessor :password + + attr_accessor :phone + + # User Status + attr_accessor :user_status + + # 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 :'user_status' => :'userStatus' } end - # attribute type + # Attribute type mapping. def self.swagger_types { :'id' => :'Integer', @@ -49,7 +56,7 @@ module Petstore end def initialize(attributes = {}) - return if !attributes.is_a?(Hash) || attributes.empty? + 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} @@ -89,5 +96,28 @@ module Petstore end + # Check equality by comparing each attribute. + def ==(o) + return true if self.equal?(o) + self.class == o.class && + id == o.id && + username == o.username && + first_name == o.first_name && + last_name == o.last_name && + email == o.email && + password == o.password && + phone == o.phone && + user_status == o.user_status + end + + # @see the `==` method + def eql?(o) + self == o + end + + # Calculate hash code according to all attributes. + def hash + [id, username, first_name, last_name, email, password, phone, user_status].hash + end end end diff --git a/samples/client/petstore/ruby/petstore_profiling.output b/samples/client/petstore/ruby/petstore_profiling.output new file mode 100644 index 00000000000..36750b5e2b9 --- /dev/null +++ b/samples/client/petstore/ruby/petstore_profiling.output @@ -0,0 +1,315 @@ +Measure Mode: wall_time +Thread ID: 70329221636600 +Fiber ID: 70329234076680 +Total: 10.998497 +Sort by: self_time + + %self total self wait child calls name + 99.20 10.920 10.911 0.000 0.010 20 #easy_perform + 0.05 0.005 0.005 0.000 0.000 1392 Symbol#to_s + 0.04 0.019 0.005 0.000 0.015 268 Ethon::Curls::Options#set_option + 0.02 0.003 0.003 0.000 0.000 718 Ethon::Easy::Operations#handle + 0.02 0.003 0.003 0.000 0.000 657 String#downcase + 0.02 0.003 0.003 0.000 0.000 658 FFI::Enum#to_native + 0.02 0.003 0.003 0.000 0.000 678 FFI::Enum#from_native + 0.02 0.029 0.002 0.000 0.027 200 *Proc#call + 0.02 0.034 0.002 0.000 0.032 210 *Array#each + 0.02 0.014 0.002 0.000 0.012 309 *Class#new + 0.02 0.004 0.002 0.000 0.003 390 #easy_getinfo + 0.02 0.002 0.002 0.000 0.000 175 Typhoeus::EasyFactory#renamed_options + 0.01 0.001 0.001 0.000 0.000 744 Kernel#respond_to? + 0.01 0.003 0.001 0.000 0.002 201 *#method_missing + 0.01 0.006 0.001 0.000 0.005 75 Hash#each + 0.01 0.020 0.001 0.000 0.019 56 *Hash#each_pair + 0.01 0.001 0.001 0.000 0.000 430 Symbol#to_sym + 0.01 0.004 0.001 0.000 0.003 210 Ethon::Curls::Infos#get_info_double + 0.01 0.003 0.001 0.000 0.002 175 *Array#map + 0.01 0.001 0.001 0.000 0.000 268 Ethon::Curls::Options#easy_options + 0.01 0.001 0.001 0.000 0.000 201 #instance + 0.01 0.001 0.001 0.000 0.000 420 Ethon::Curls::Infos#double_ptr + 0.01 0.002 0.001 0.000 0.001 250 FFI::Pointer#read_string + 0.01 0.001 0.001 0.000 0.000 80 Hash#initialize_copy + 0.01 0.001 0.001 0.000 0.000 240 Typhoeus::Response::Header#set_value + 0.01 0.001 0.001 0.000 0.000 656 Kernel#is_a? + 0.01 0.001 0.001 0.000 0.000 42 String#gsub + 0.01 0.003 0.001 0.000 0.002 120 Ethon::Curls::Infos#get_info_long + 0.01 0.004 0.001 0.000 0.004 120 Typhoeus::Response::Header#process_line + 0.01 0.001 0.001 0.000 0.001 85 #easy_setopt_string + 0.01 0.001 0.001 0.000 0.000 140 String#split + 0.01 0.001 0.001 0.000 0.000 485 Kernel#nil? + 0.01 0.001 0.001 0.000 0.000 240 Ethon::Curls::Infos#long_ptr + 0.01 0.001 0.001 0.000 0.000 42 #easy_setopt_callback + 0.01 0.006 0.001 0.000 0.006 20 Petstore::ApiClient#build_request + 0.00 0.001 0.000 0.000 0.001 90 #easy_setopt_long + 0.00 0.000 0.000 0.000 0.000 170 FFI::AbstractMemory#get_bytes + 0.00 0.001 0.000 0.000 0.000 30 #informations_to_mirror + 0.00 0.002 0.000 0.000 0.002 120 Typhoeus::Response::Header#process_pair + 0.00 0.002 0.000 0.000 0.002 60 Ethon::Curls::Infos#get_info_string + 0.00 0.000 0.000 0.000 0.000 190 String#to_s + 0.00 0.000 0.000 0.000 0.000 130 Kernel#class + 0.00 0.000 0.000 0.000 0.000 240 String#strip + 0.00 0.001 0.000 0.000 0.001 42 Mutex#synchronize + 0.00 0.000 0.000 0.000 0.000 268 Hash#include? + 0.00 0.000 0.000 0.000 0.000 36 String#sub + 0.00 0.001 0.000 0.000 0.001 21 FFI::AutoPointer#initialize + 0.00 0.000 0.000 0.000 0.000 400 Array#include? + 0.00 10.941 0.000 0.000 10.941 20 Ethon::Easy::Operations#perform + 0.00 0.000 0.000 0.000 0.000 185 Integer#to_i + 0.00 0.006 0.000 0.000 0.006 21 Ethon::Easy::Callbacks#set_callbacks + 0.00 0.001 0.000 0.000 0.001 80 Ethon::Easy::Header#compose_header + 0.00 0.000 0.000 0.000 0.000 210 FFI::AbstractMemory#read_double + 0.00 0.001 0.000 0.000 0.000 90 #find_type + 0.00 0.001 0.000 0.000 0.001 90 #type_size + 0.00 0.002 0.000 0.000 0.001 30 Ethon::Easy::Informations#httpauth_avail + 0.00 0.000 0.000 0.000 0.000 80 #slist_append + 0.00 0.001 0.000 0.000 0.001 85 Kernel#initialize_dup + 0.00 0.000 0.000 0.000 0.000 330 Hash#has_key? + 0.00 10.993 0.000 0.000 10.992 20 Petstore::ApiClient#call_api + 0.00 0.000 0.000 0.000 0.000 80 String#encode + 0.00 0.001 0.000 0.000 0.000 20 Petstore::Configuration#auth_settings + 0.00 0.001 0.000 0.000 0.000 140 Typhoeus::Response::Informations#response_code + 0.00 0.000 0.000 0.000 0.000 65 #attribute_map + 0.00 0.000 0.000 0.000 0.000 35 Petstore::ApiClient#json_mime? + 0.00 0.001 0.000 0.000 0.000 85 Ethon::Easy::Http::Actionable#form + 0.00 0.000 0.000 0.000 0.000 45 Hash#keys + 0.00 0.023 0.000 0.000 0.022 20 Ethon::Easy::Http::Actionable#setup + 0.00 0.002 0.000 0.000 0.001 80 Typhoeus::EasyFactory#easy + 0.00 0.001 0.000 0.000 0.001 20 Typhoeus::Request::Callbacks#execute_callbacks + 0.00 0.001 0.000 0.000 0.000 40 Hash#merge + 0.00 0.001 0.000 0.000 0.000 80 Ethon::Easy::Util#escape_zero_byte + 0.00 0.000 0.000 0.000 0.000 120 Ethon::Curls::Infos#string_ptr + 0.00 0.001 0.000 0.000 0.000 50 Enumerable#find + 0.00 0.000 0.000 0.000 0.000 80 FFI::AbstractMemory#get_string + 0.00 0.000 0.000 0.000 0.000 80 Typhoeus::Request::Responseable#response + 0.00 0.000 0.000 0.000 0.000 120 FFI::AbstractMemory#read_long + 0.00 0.000 0.000 0.000 0.000 120 Hash#[]= + 0.00 0.001 0.000 0.000 0.001 40 Typhoeus::Response::Status#success? + 0.00 10.998 0.000 0.000 10.998 5 PetstoreProfiling#call_apis + 0.00 0.000 0.000 0.000 0.000 20 #easy_reset + 0.00 0.007 0.000 0.000 0.007 25 Typhoeus::Response::Informations#headers + 0.00 0.000 0.000 0.000 0.000 90 Fixnum#<< + 0.00 0.001 0.000 0.000 0.001 20 Petstore::ApiClient#build_request_url + 0.00 0.032 0.000 0.000 0.031 20 Typhoeus::EasyFactory#get + 0.00 0.001 0.000 0.000 0.001 45 Kernel#dup + 0.00 0.000 0.000 0.000 0.000 21 #easy_setopt_debug_callback + 0.00 0.016 0.000 0.000 0.016 30 #from_easy + 0.00 0.000 0.000 0.000 0.000 20 String#lines + 0.00 0.001 0.000 0.000 0.000 20 Typhoeus::Request#set_defaults + 0.00 0.006 0.000 0.000 0.006 20 Typhoeus::Response::Header#initialize + 0.00 0.000 0.000 0.000 0.000 40 Typhoeus::Request::Callbacks::Types#on_complete + 0.00 0.000 0.000 0.000 0.000 120 Symbol#to_proc + 0.00 0.001 0.000 0.000 0.000 20 Typhoeus::EasyFactory#set_callback + 0.00 10.974 0.000 0.000 10.973 20 Typhoeus::Request::Operations#run + 0.00 0.001 0.000 0.000 0.001 60 *Petstore::BaseObject#_to_hash + 0.00 0.000 0.000 0.000 0.000 90 FFI::Type#size + 0.00 0.000 0.000 0.000 0.000 60 FFI::AbstractMemory#read_pointer + 0.00 0.002 0.000 0.000 0.002 20 Typhoeus::Request::Operations#finish + 0.00 0.001 0.000 0.000 0.000 21 URI::Escape#escape + 0.00 0.000 0.000 0.000 0.000 40 Typhoeus::Request::Callbacks::Types#on_success + 0.00 0.000 0.000 0.000 0.000 22 Ethon::Loggable#logger + 0.00 0.000 0.000 0.000 0.000 65 Typhoeus::Response#mock + 0.00 0.006 0.000 0.000 0.006 20 Ethon::Easy#reset + 0.00 0.001 0.000 0.000 0.000 30 #easy_setopt_ffipointer + 0.00 0.001 0.000 0.000 0.001 5 JSON::Ext::Generator::GeneratorMethods::Hash#to_json + 0.00 3.494 0.000 0.000 3.494 5 Petstore::PetApi#get_pet_by_id_with_http_info + 0.00 0.000 0.000 0.000 0.000 160 Kernel#block_given? + 0.00 3.220 0.000 0.000 3.219 5 Petstore::PetApi#update_pet_with_form_with_http_info + 0.00 0.001 0.000 0.000 0.001 30 Ethon::Easy::Informations#effective_url + 0.00 0.006 0.000 0.000 0.006 20 Typhoeus::Response::Header#parse + 0.00 10.975 0.000 0.000 10.975 20 Typhoeus::Request::Before#run + 0.00 0.011 0.000 0.000 0.011 20 Ethon::Easy#mirror + 0.00 0.000 0.000 0.000 0.000 40 #easies + 0.00 0.000 0.000 0.000 0.000 40 Typhoeus::EasyFactory#sanitize_timeout! + 0.00 0.000 0.000 0.000 0.000 5 JSON::Ext::Parser#parse + 0.00 0.000 0.000 0.000 0.000 50 String#to_sym + 0.00 0.000 0.000 0.000 0.000 70 Hash#fetch + 0.00 0.001 0.000 0.000 0.001 20 Typhoeus::Request#initialize + 0.00 0.005 0.000 0.000 0.005 20 Typhoeus::EasyFactory#sanitize + 0.00 0.000 0.000 0.000 0.000 21 URI::RFC2396_Parser#escape + 0.00 0.001 0.000 0.000 0.001 30 Ethon::Easy::Informations#total_time + 0.00 0.001 0.000 0.000 0.001 30 Ethon::Easy::Informations#appconnect_time + 0.00 2.141 0.000 0.000 2.141 5 Petstore::PetApi#delete_pet_with_http_info + 0.00 0.001 0.000 0.000 0.000 20 Petstore::ApiClient#select_header_accept + 0.00 0.000 0.000 0.000 0.000 30 Enumerable#inject + 0.00 0.000 0.000 0.000 0.000 80 Integer#chr + 0.00 0.000 0.000 0.000 0.000 90 Fixnum#< + 0.00 10.974 0.000 0.000 10.974 20 Typhoeus::Request::BlockConnection#run + 0.00 2.143 0.000 0.000 2.143 5 Petstore::PetApi#add_pet_with_http_info + 0.00 0.000 0.000 0.000 0.000 21 Logger#add + 0.00 0.020 0.000 0.000 0.020 20 Ethon::Easy::ResponseCallbacks#complete + 0.00 0.000 0.000 0.000 0.000 21 Logger#debug + 0.00 10.975 0.000 0.000 10.974 20 Typhoeus::Request::Stubbable#run + 0.00 0.004 0.000 0.000 0.004 20 Ethon::Easy::Header#headers= + 0.00 0.000 0.000 0.000 0.000 20 Typhoeus::Request::Cacheable#response= + 0.00 0.001 0.000 0.000 0.001 50 *Petstore::BaseObject#_deserialize + 0.00 0.000 0.000 0.000 0.000 35 Module#const_get + 0.00 0.000 0.000 0.000 0.000 20 Ethon::Easy::Http::Actionable#params + 0.00 0.003 0.000 0.000 0.003 10 Ethon::Easy::Http::Postable#set_form + 0.00 0.000 0.000 0.000 0.000 50 Symbol#=~ + 0.00 0.001 0.000 0.000 0.001 30 Ethon::Easy::Informations#pretransfer_time + 0.00 0.000 0.000 0.000 0.000 30 Typhoeus::Response#initialize + 0.00 0.000 0.000 0.000 0.000 10 Petstore::Pet#initialize + 0.00 0.000 0.000 0.000 0.000 20 Petstore::ApiClient#select_header_content_type + 0.00 0.002 0.000 0.000 0.002 20 Ethon::Easy::Options#nosignal= + 0.00 0.001 0.000 0.000 0.001 20 Ethon::Easy::Http::Actionable#initialize + 0.00 0.000 0.000 0.000 0.000 21 #define_finalizer + 0.00 0.002 0.000 0.000 0.001 20 Ethon::Easy::Http#fabricate + 0.00 0.001 0.000 0.000 0.001 30 Ethon::Easy::Informations#primary_ip + 0.00 0.000 0.000 0.000 0.000 119 NilClass#nil? + 0.00 0.001 0.000 0.000 0.001 30 Ethon::Easy::Informations#redirect_time + 0.00 0.001 0.000 0.000 0.001 30 Ethon::Easy::Informations#starttransfer_time + 0.00 0.000 0.000 0.000 0.000 20 Symbol#downcase + 0.00 0.000 0.000 0.000 0.000 21 Kernel#method + 0.00 0.000 0.000 0.000 0.000 20 Petstore::Configuration#api_key_with_prefix + 0.00 0.000 0.000 0.000 0.000 25 #attribute_map + 0.00 10.974 0.000 0.000 10.974 20 Typhoeus::Request::Cacheable#run + 0.00 0.000 0.000 0.000 0.000 20 Typhoeus::Request::Callbacks::Types#on_headers + 0.00 0.001 0.000 0.000 0.001 30 Ethon::Easy::Informations#namelookup_time + 0.00 0.001 0.000 0.000 0.001 30 Ethon::Easy::Informations#connect_time + 0.00 0.001 0.000 0.000 0.001 30 Ethon::Easy::Informations#request_size + 0.00 0.000 0.000 0.000 0.000 21 String#force_encoding + 0.00 0.000 0.000 0.000 0.000 20 #before + 0.00 0.000 0.000 0.000 0.000 40 Typhoeus::Response::Informations#return_code + 0.00 0.000 0.000 0.000 0.000 30 Ethon::Easy::Mirror#initialize + 0.00 0.000 0.000 0.000 0.000 15 Petstore::ApiClient#build_request_body + 0.00 0.001 0.000 0.000 0.001 30 Ethon::Easy::Informations#redirect_count + 0.00 0.025 0.000 0.000 0.025 20 Ethon::Easy::Http#http_request + 0.00 0.001 0.000 0.000 0.001 30 Ethon::Easy::Informations#response_code + 0.00 0.000 0.000 0.000 0.000 50 Ethon::Easy::Http::Actionable#query_options + 0.00 0.000 0.000 0.000 0.000 25 #attribute_map + 0.00 0.000 0.000 0.000 0.000 25 NilClass#to_s + 0.00 0.007 0.000 0.000 0.007 20 #release + 0.00 0.000 0.000 0.000 0.000 20 Ethon::Easy::ResponseCallbacks#on_headers + 0.00 0.000 0.000 0.000 0.000 20 #response_for + 0.00 0.001 0.000 0.000 0.001 20 Ethon::Easy::Http::Actionable#parse_options + 0.00 0.000 0.000 0.000 0.000 35 Hash#delete + 0.00 0.000 0.000 0.000 0.000 45 Typhoeus::Response::Informations#response_headers + 0.00 0.000 0.000 0.000 0.000 20 #easy_escape + 0.00 0.000 0.000 0.000 0.000 21 FFI::AutoPointer::Releaser#initialize + 0.00 0.000 0.000 0.000 0.000 21 Ethon::Easy::Callbacks#header_write_callback + 0.00 0.000 0.000 0.000 0.000 21 Ethon::Easy::DebugInfo#initialize + 0.00 0.000 0.000 0.000 0.000 20 Typhoeus::EasyFactory#initialize + 0.00 0.000 0.000 0.000 0.000 20 Typhoeus::Request::Memoizable#response= + 0.00 0.000 0.000 0.000 0.000 105 Module#=== + 0.00 0.000 0.000 0.000 0.000 80 String#include? + 0.00 0.000 0.000 0.000 0.000 21 Ethon::Easy::Callbacks#body_write_callback + 0.00 0.000 0.000 0.000 0.000 16 Array#join + 0.00 0.000 0.000 0.000 0.000 20 #find_by + 0.00 0.005 0.000 0.000 0.005 5 Petstore::ApiClient#deserialize + 0.00 0.000 0.000 0.000 0.000 30 Regexp#=== + 0.00 0.006 0.000 0.000 0.006 10 Ethon::Easy::ResponseCallbacks#headers + 0.00 0.000 0.000 0.000 0.000 21 Ethon::Easy::Callbacks#debug_callback + 0.00 0.000 0.000 0.000 0.000 20 Ethon::Easy::ResponseCallbacks#on_complete + 0.00 0.002 0.000 0.000 0.002 20 Ethon::Easy::Options#url= + 0.00 0.000 0.000 0.000 0.000 84 Kernel#kind_of? + 0.00 0.000 0.000 0.000 0.000 40 Typhoeus::Request::Cacheable#cacheable? + 0.00 0.017 0.000 0.000 0.017 21 Ethon::Easy#set_attributes + 0.00 0.000 0.000 0.000 0.000 20 Module#const_defined? + 0.00 0.001 0.000 0.000 0.001 20 #get + 0.00 0.000 0.000 0.000 0.000 20 #pid + 0.00 0.000 0.000 0.000 0.000 40 String#bytesize + 0.00 0.000 0.000 0.000 0.000 20 Ethon::Easy::Params#initialize + 0.00 0.000 0.000 0.000 0.000 20 Kernel#lambda + 0.00 0.000 0.000 0.000 0.000 20 String#capitalize + 0.00 0.000 0.000 0.000 0.000 25 Ethon::Easy::Queryable#query_pairs + 0.00 0.000 0.000 0.000 0.000 195 Symbol#=== + 0.00 0.000 0.000 0.000 0.000 20 Ethon::Easy::Form#initialize + 0.00 0.000 0.000 0.000 0.000 13 FFI::MemoryPointer#initialize + 0.00 0.000 0.000 0.000 0.000 105 Hash#key? + 0.00 0.000 0.000 0.000 0.000 20 Ethon::Easy#escape + 0.00 0.000 0.000 0.000 0.000 20 #all + 0.00 0.000 0.000 0.000 0.000 10 Typhoeus::Request::Callbacks#execute_headers_callbacks + 0.00 0.000 0.000 0.000 0.000 20 Typhoeus::Response::Header#set_default_proc_on + 0.00 0.000 0.000 0.000 0.000 15 Hash#update + 0.00 0.000 0.000 0.000 0.000 60 FFI::Pointer#null? + 0.00 0.001 0.000 0.000 0.001 20 Ethon::Easy::Options#sslcert= + 0.00 0.001 0.000 0.000 0.001 20 Ethon::Easy::Queryable#to_s + 0.00 0.000 0.000 0.000 0.000 55 Ethon::Easy::Queryable#empty? + 0.00 0.000 0.000 0.000 0.000 20 Hash#default_proc= + 0.00 0.000 0.000 0.000 0.000 10 Petstore::Category#initialize + 0.00 0.000 0.000 0.000 0.000 10 Petstore::Tag#initialize + 0.00 0.000 0.000 0.000 0.000 21 FFI::Pointer#initialize + 0.00 0.002 0.000 0.000 0.001 20 Ethon::Easy::Options#verbose= + 0.00 0.002 0.000 0.000 0.002 20 Ethon::Easy::Options#maxredirs= + 0.00 0.001 0.000 0.000 0.001 20 Ethon::Easy::Options#sslkey= + 0.00 0.000 0.000 0.000 0.000 20 Array#pop + 0.00 0.000 0.000 0.000 0.000 21 FFI::Pointer#type_size + 0.00 0.000 0.000 0.000 0.000 20 Ethon::Easy::Http::Actionable#url + 0.00 0.000 0.000 0.000 0.000 20 Typhoeus::Request::BlockConnection#blocked? + 0.00 0.002 0.000 0.000 0.002 20 Ethon::Easy::Options#ssl_verifypeer= + 0.00 0.000 0.000 0.000 0.000 20 Ethon::Easy::Http::Actionable#options + 0.00 0.000 0.000 0.000 0.000 10 Ethon::Easy::ResponseCallbacks#body + 0.00 0.000 0.000 0.000 0.000 10 Petstore::Pet#status= + 0.00 0.001 0.000 0.000 0.001 20 Ethon::Easy::Options#cainfo= + 0.00 0.000 0.000 0.000 0.000 30 Array#last + 0.00 0.001 0.000 0.000 0.001 20 Petstore::ApiClient#update_params_for_auth! + 0.00 0.003 0.000 0.000 0.003 5 Petstore::ApiClient#convert_to_type + 0.00 10.998 0.000 0.000 10.998 1 PetstoreProfiling#run + 0.00 0.012 0.000 0.000 0.011 10 Ethon::Easy::Http::Post#setup + 0.00 0.000 0.000 0.000 0.000 5 JSON::Ext::Parser#initialize + 0.00 0.000 0.000 0.000 0.000 20 Typhoeus::Request::Memoizable#memoizable? + 0.00 0.000 0.000 0.000 0.000 20 Typhoeus::Response::Header#raw + 0.00 0.002 0.000 0.000 0.002 5 Petstore::ApiClient#object_to_http_body + 0.00 0.000 0.000 0.000 0.000 20 Typhoeus::Request::Responseable#response= + 0.00 0.000 0.000 0.000 0.000 15 Fixnum#to_s + 0.00 0.001 0.000 0.000 0.001 15 *Petstore::BaseObject#to_hash + 0.00 0.000 0.000 0.000 0.000 10 Array#any? + 0.00 0.000 0.000 0.000 0.000 10 Ethon::Easy::Queryable#build_query_pairs + 0.00 0.000 0.000 0.000 0.000 1 #easy_init + 0.00 0.000 0.000 0.000 0.000 10 Ethon::Easy::Queryable#pairs_for + 0.00 0.001 0.000 0.000 0.000 5 Petstore::PetApi#initialize + 0.00 0.000 0.000 0.000 0.000 10 Array#compact + 0.00 0.003 0.000 0.000 0.002 15 *Petstore::BaseObject#build_from_hash + 0.00 0.000 0.000 0.000 0.000 20 Typhoeus::Request::Streamable#streaming? + 0.00 0.000 0.000 0.000 0.000 10 Ethon::Easy::Http::Actionable#params_encoding + 0.00 0.000 0.000 0.000 0.000 10 FFI::AbstractMemory#put_bytes + 0.00 3.494 0.000 0.000 3.494 5 Petstore::PetApi#get_pet_by_id + 0.00 0.000 0.000 0.000 0.000 20 Proc#to_proc + 0.00 0.000 0.000 0.000 0.000 5 Petstore::Configuration#api_client + 0.00 0.006 0.000 0.000 0.006 5 Ethon::Easy::Http::Delete#setup + 0.00 0.001 0.000 0.000 0.001 10 Ethon::Easy::Options#postfieldsize= + 0.00 0.001 0.000 0.000 0.001 10 Ethon::Easy::Options#copypostfields= + 0.00 0.005 0.000 0.000 0.005 5 Ethon::Easy::Http::Get#setup + 0.00 2.143 0.000 0.000 2.143 5 Petstore::PetApi#add_pet + 0.00 0.000 0.000 0.000 0.000 20 #free + 0.00 0.000 0.000 0.000 0.000 1 Petstore::Configuration#initialize + 0.00 2.141 0.000 0.000 2.141 5 Petstore::PetApi#delete_pet + 0.00 0.000 0.000 0.000 0.000 20 Kernel#Array + 0.00 0.000 0.000 0.000 0.000 45 Kernel#respond_to_missing? + 0.00 0.000 0.000 0.000 0.000 1 #global_init + 0.00 0.000 0.000 0.000 0.000 5 #swagger_types + 0.00 0.001 0.000 0.000 0.001 5 Petstore::ApiClient#object_to_hash + 0.00 0.000 0.000 0.000 0.000 2 Logger#initialize + 0.00 0.000 0.000 0.000 0.000 10 Ethon::Easy::Form#multipart? + 0.00 0.000 0.000 0.000 0.000 5 JSON::Ext::Generator::State#initialize_copy + 0.00 0.000 0.000 0.000 0.000 2 MonitorMixin#initialize + 0.00 3.220 0.000 0.000 3.220 5 Petstore::PetApi#update_pet_with_form + 0.00 0.000 0.000 0.000 0.000 5 #swagger_types + 0.00 0.000 0.000 0.000 0.000 1 Petstore::ApiClient#initialize + 0.00 0.003 0.000 0.000 0.003 5 Kernel#tap + 0.00 0.000 0.000 0.000 0.000 5 JSON#parse + 0.00 0.000 0.000 0.000 0.000 5 Ethon::Easy::Options#customrequest= + 0.00 0.000 0.000 0.000 0.000 5 Ethon::Easy::Queryable#recursively_generate_pairs + 0.00 0.000 0.000 0.000 0.000 5 #swagger_types + 0.00 0.000 0.000 0.000 0.000 2 Logger::LogDevice#initialize + 0.00 10.998 0.000 0.000 10.998 1 Integer#times + 0.00 0.000 0.000 0.000 0.000 1 Petstore::Configuration#base_url + 0.00 0.000 0.000 0.000 0.000 2 MonitorMixin#mon_initialize + 0.00 0.000 0.000 0.000 0.000 35 String#=== + 0.00 0.000 0.000 0.000 0.000 3 Kernel#proc + 0.00 0.000 0.000 0.000 0.000 5 Typhoeus::Response::Informations#response_body + 0.00 0.000 0.000 0.000 0.000 10 Kernel#=== + 0.00 0.001 0.000 0.000 0.001 1 Ethon::Easy#initialize + 0.00 0.000 0.000 0.000 0.000 5 Ethon::Easy::Queryable#encode_hash_pairs + 0.00 0.000 0.000 0.000 0.000 5 String#encoding + 0.00 0.000 0.000 0.000 0.000 5 Array#first + 0.00 0.000 0.000 0.000 0.000 5 Hash#[] + 0.00 0.000 0.000 0.000 0.000 2 BasicObject#initialize + 0.00 0.000 0.000 0.000 0.000 1 Ethon::Loggable#default_logger + 0.00 0.000 0.000 0.000 0.000 2 Logger::Formatter#initialize + 0.00 0.000 0.000 0.000 0.000 1 #init + 0.00 0.000 0.000 0.000 0.000 2 Mutex#initialize + 0.00 0.000 0.000 0.000 0.000 1 Ethon::Loggable#rails_logger + 0.00 0.000 0.000 0.000 0.000 10 BasicObject#== + +* indicates recursively called methods diff --git a/samples/client/petstore/ruby/petstore_profiling.rb b/samples/client/petstore/ruby/petstore_profiling.rb new file mode 100644 index 00000000000..485bd40c0c7 --- /dev/null +++ b/samples/client/petstore/ruby/petstore_profiling.rb @@ -0,0 +1,75 @@ +# To run this profiling: +# gem install ruby-prof +# ruby -Ilib petstore_profiling.rb + +require 'petstore' +require 'ruby-prof' + +class PetstoreProfiling + attr_accessor :total, :new_pet_id, :output_file + + def initialize + @total = 5 + @new_pet_id = 50002 + @output_file = './petstore_profiling.output' + end + + def call_apis + pet_api = Petstore::PetApi.new + + ### ADD PET ### + pet = Petstore::Pet.new + pet.id = new_pet_id + pet.name = "profiler" + pet.status = "available" + pet.photo_urls = ["http://profiler.com"] + # new tag + tag= Petstore::Tag.new + tag.id = new_pet_id # use the same id as pet + tag.name = "profile tag 1" + # new category + category = Petstore::Category.new + category.id = new_pet_id # use the same id as pet + category.name = "profile category 1" + + pet.tags = [tag] + pet.category = category + + # add a new pet (model) + pet_api.add_pet(body: pet) + + ### GET PET ### + pet = pet_api.get_pet_by_id(new_pet_id) + + ### UPDATE PET WITH FORM ### + pet_api.update_pet_with_form(new_pet_id, name: 'new profiler', status: 'sold') + + ### DELETE PET ### + pet_api.delete_pet(new_pet_id) + rescue Petstore::ApiError => e + puts "Caught error: #{e.message}" + puts "HTTP response headers: #{e.response_headers}" + puts "HTTP response body: #{e.response_body}" + puts "HTTP status code: #{e.code}" + end + + def run + puts "Running profiling... (total: #{@total})" + + RubyProf.start + @total.times { call_apis } + result = RubyProf.stop + + printer = RubyProf::FlatPrinter.new(result) + File.open(@output_file, 'w') do |file| + printer.print(file) + end + + puts "Profiling results written to #{@output_file}" + end +end + +if __FILE__ == $0 + profiling = PetstoreProfiling.new + profiling.run +end diff --git a/samples/client/petstore/ruby/spec/api_client_spec.rb b/samples/client/petstore/ruby/spec/api_client_spec.rb index eeb27300bf3..c2bfef4e8e4 100644 --- a/samples/client/petstore/ruby/spec/api_client_spec.rb +++ b/samples/client/petstore/ruby/spec/api_client_spec.rb @@ -10,34 +10,34 @@ describe Petstore::ApiClient do context 'host' do it 'removes http from host' do Petstore.configure { |c| c.host = 'http://example.com' } - Petstore.configure.host.should == 'example.com' + Petstore::Configuration.default.host.should == 'example.com' end it 'removes https from host' do Petstore.configure { |c| c.host = 'https://wookiee.com' } - Petstore.configure.host.should == 'wookiee.com' + Petstore::ApiClient.default.config.host.should == 'wookiee.com' end it 'removes trailing path from host' do Petstore.configure { |c| c.host = 'hobo.com/v4' } - Petstore.configure.host.should == 'hobo.com' + Petstore::Configuration.default.host.should == 'hobo.com' end end context 'base_path' do it "prepends a slash to base_path" do Petstore.configure { |c| c.base_path = 'v4/dog' } - Petstore.configure.base_path.should == '/v4/dog' + Petstore::Configuration.default.base_path.should == '/v4/dog' end it "doesn't prepend a slash if one is already there" do Petstore.configure { |c| c.base_path = '/v4/dog' } - Petstore.configure.base_path.should == '/v4/dog' + Petstore::Configuration.default.base_path.should == '/v4/dog' end it "ends up as a blank string if nil" do Petstore.configure { |c| c.base_path = nil } - Petstore.configure.base_path.should == '' + Petstore::Configuration.default.base_path.should == '' end end @@ -53,13 +53,26 @@ describe Petstore::ApiClient do end api_client = Petstore::ApiClient.new + + config2 = Petstore::Configuration.new do |c| + c.api_key_prefix['api_key'] = 'PREFIX2' + c.api_key['api_key'] = 'special-key2' + end + api_client2 = Petstore::ApiClient.new(config2) + auth_names = ['api_key', 'unknown'] + header_params = {} query_params = {} - auth_names = ['api_key', 'unknown'] api_client.update_params_for_auth! header_params, query_params, auth_names header_params.should == {'api_key' => 'PREFIX special-key'} query_params.should == {} + + header_params = {} + query_params = {} + api_client2.update_params_for_auth! header_params, query_params, auth_names + header_params.should == {'api_key' => 'PREFIX2 special-key2'} + query_params.should == {} end it "sets header api-key parameter without prefix" do @@ -145,4 +158,52 @@ describe Petstore::ApiClient do end end + describe "#json_mime?" do + let(:api_client) { Petstore::ApiClient.new } + + it "works" do + api_client.json_mime?(nil).should == false + api_client.json_mime?('').should == false + + api_client.json_mime?('application/json').should == true + api_client.json_mime?('application/json; charset=UTF8').should == true + api_client.json_mime?('APPLICATION/JSON').should == true + + api_client.json_mime?('application/xml').should == false + api_client.json_mime?('text/plain').should == false + api_client.json_mime?('application/jsonp').should == false + end + end + + describe "#select_header_accept" do + let(:api_client) { Petstore::ApiClient.new } + + it "works" do + api_client.select_header_accept(nil).should == nil + api_client.select_header_accept([]).should == nil + + api_client.select_header_accept(['application/json']).should == 'application/json' + api_client.select_header_accept(['application/xml', 'application/json; charset=UTF8']).should == 'application/json; charset=UTF8' + api_client.select_header_accept(['APPLICATION/JSON', 'text/html']).should == 'APPLICATION/JSON' + + api_client.select_header_accept(['application/xml']).should == 'application/xml' + api_client.select_header_accept(['text/html', 'application/xml']).should == 'text/html,application/xml' + end + end + + describe "#select_header_content_type" do + let(:api_client) { Petstore::ApiClient.new } + + it "works" do + api_client.select_header_content_type(nil).should == 'application/json' + api_client.select_header_content_type([]).should == 'application/json' + + api_client.select_header_content_type(['application/json']).should == 'application/json' + api_client.select_header_content_type(['application/xml', 'application/json; charset=UTF8']).should == 'application/json; charset=UTF8' + api_client.select_header_content_type(['APPLICATION/JSON', 'text/html']).should == 'APPLICATION/JSON' + api_client.select_header_content_type(['application/xml']).should == 'application/xml' + api_client.select_header_content_type(['text/plain', 'application/xml']).should == 'text/plain' + end + end + end diff --git a/samples/client/petstore/ruby/spec/configuration_spec.rb b/samples/client/petstore/ruby/spec/configuration_spec.rb index 9f86f5602b7..eb29b54c2a7 100644 --- a/samples/client/petstore/ruby/spec/configuration_spec.rb +++ b/samples/client/petstore/ruby/spec/configuration_spec.rb @@ -1,7 +1,7 @@ require 'spec_helper' describe Petstore::Configuration do - let(:config) { Petstore::Configuration.instance } + let(:config) { Petstore::Configuration.default } before(:each) do Petstore.configure do |c| diff --git a/samples/client/petstore/ruby/spec/pet_spec.rb b/samples/client/petstore/ruby/spec/pet_spec.rb index c9858eca37a..9426d2024b9 100644 --- a/samples/client/petstore/ruby/spec/pet_spec.rb +++ b/samples/client/petstore/ruby/spec/pet_spec.rb @@ -50,6 +50,17 @@ describe "Pet" do pet.category.name.should == "category test" end + it "should fetch a pet object with http info" do + pet, status_code, headers = @pet_api.get_pet_by_id_with_http_info(10002) + status_code.should == 200 + headers['Content-Type'].should == 'application/json' + pet.should be_a(Petstore::Pet) + pet.id.should == 10002 + pet.name.should == "RUBY UNIT TESTING" + pet.tags[0].name.should == "tag test" + pet.category.name.should == "category test" + end + it "should not find a pet that does not exist" do begin @pet_api.get_pet_by_id(-10002) @@ -125,5 +136,40 @@ describe "Pet" do result = @pet_api.upload_file(10002, file: File.new('hello.txt'), additional_metadata: 'metadata') result.should be_nil end + + it "should implement eql? and hash" do + pet1 = Petstore::Pet.new + pet2 = Petstore::Pet.new + pet1.should == pet2 + pet2.should == pet1 + pet1.eql?(pet2).should == true + pet2.eql?(pet1).should == true + pet1.hash.should == pet2.hash + pet1.should == pet1 + pet1.eql?(pet1).should == true + pet1.hash.should == pet1.hash + + pet1.name = 'really-happy' + pet1.photo_urls = ['http://foo.bar.com/1', 'http://foo.bar.com/2'] + pet1.should_not == pet2 + pet2.should_not == pet1 + pet1.eql?(pet2).should == false + pet2.eql?(pet1).should == false + pet1.hash.should_not == pet2.hash + pet1.should == pet1 + pet1.eql?(pet1).should == true + pet1.hash.should == pet1.hash + + pet2.name = 'really-happy' + pet2.photo_urls = ['http://foo.bar.com/1', 'http://foo.bar.com/2'] + pet1.should == pet2 + pet2.should == pet1 + pet1.eql?(pet2).should == true + pet2.eql?(pet1).should == true + pet1.hash.should == pet2.hash + pet2.should == pet2 + pet2.eql?(pet2).should == true + pet2.hash.should == pet2.hash + end end end diff --git a/samples/client/petstore/ruby/spec/spec_helper.rb b/samples/client/petstore/ruby/spec/spec_helper.rb index b8ba0f73975..26da98f9c42 100644 --- a/samples/client/petstore/ruby/spec/spec_helper.rb +++ b/samples/client/petstore/ruby/spec/spec_helper.rb @@ -36,7 +36,7 @@ end # help #end -API_CLIENT = Petstore::ApiClient.new +API_CLIENT = Petstore::ApiClient.new(Petstore::Configuration.new) # always delete and then re-create the pet object with 10002 def prepare_pet(pet_api) diff --git a/samples/client/petstore/swift/Cartfile b/samples/client/petstore/swift/Cartfile index 745e00376a8..5e4bd352eef 100644 --- a/samples/client/petstore/swift/Cartfile +++ b/samples/client/petstore/swift/Cartfile @@ -1,2 +1,2 @@ -github "Alamofire/Alamofire" >= 3.0.0 +github "Alamofire/Alamofire" >= 3.1.0 github "mxcl/PromiseKit" >=1.5.3 diff --git a/samples/client/petstore/swift/PetstoreClient.podspec b/samples/client/petstore/swift/PetstoreClient.podspec index 3caf12083de..ed41db4bfb1 100644 --- a/samples/client/petstore/swift/PetstoreClient.podspec +++ b/samples/client/petstore/swift/PetstoreClient.podspec @@ -7,5 +7,5 @@ Pod::Spec.new do |s| s.license = 'Apache License, Version 2.0' s.source_files = 'PetstoreClient/Classes/Swaggers/**/*.swift' s.dependency 'PromiseKit', '~> 2.1' - s.dependency 'Alamofire', '~> 3.0.0' + s.dependency 'Alamofire', '~> 3.1.0' end diff --git a/samples/client/petstore/typescript-node/api.ts b/samples/client/petstore/typescript-node/api.ts index ab5f05b46cb..3ae51281c65 100644 --- a/samples/client/petstore/typescript-node/api.ts +++ b/samples/client/petstore/typescript-node/api.ts @@ -104,8 +104,10 @@ class ApiKeyAuth implements Authentication { } class OAuth implements Authentication { + public accessToken: string; + applyToRequest(requestOptions: request.Options): void { - // TODO: support oauth + requestOptions.headers["Authorization"] = "Bearer " + this.accessToken; } } @@ -129,8 +131,8 @@ export class UserApi { 'petstore_auth': new OAuth(), } - constructor(url: string, basePath?: string); - constructor(private url: string, basePathOrUsername: string, password?: string, basePath?: string) { + constructor(basePath?: string); + constructor(basePathOrUsername: string, password?: string, basePath?: string) { if (password) { if (basePath) { this.basePath = basePath; @@ -145,6 +147,10 @@ export class UserApi { set apiKey(key: string) { this.authentications.api_key.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)){ @@ -159,7 +165,7 @@ export class UserApi { * @param body Created user object */ public createUser (body?: User) : Promise<{ response: http.ClientResponse; body?: any; }> { - const path = this.url + this.basePath + '/user'; + const path = this.basePath + '/user'; let queryParameters: any = {}; let headerParams: any = this.extendObj({}, this.defaultHeaders); let formParams: any = {}; @@ -208,7 +214,7 @@ export class UserApi { * @param body List of user object */ public createUsersWithArrayInput (body?: Array) : Promise<{ response: http.ClientResponse; body?: any; }> { - const path = this.url + this.basePath + '/user/createWithArray'; + const path = this.basePath + '/user/createWithArray'; let queryParameters: any = {}; let headerParams: any = this.extendObj({}, this.defaultHeaders); let formParams: any = {}; @@ -257,7 +263,7 @@ export class UserApi { * @param body List of user object */ public createUsersWithListInput (body?: Array) : Promise<{ response: http.ClientResponse; body?: any; }> { - const path = this.url + this.basePath + '/user/createWithList'; + const path = this.basePath + '/user/createWithList'; let queryParameters: any = {}; let headerParams: any = this.extendObj({}, this.defaultHeaders); let formParams: any = {}; @@ -307,7 +313,7 @@ export class UserApi { * @param password The password for login in clear text */ public loginUser (username?: string, password?: string) : Promise<{ response: http.ClientResponse; body: string; }> { - const path = this.url + this.basePath + '/user/login'; + const path = this.basePath + '/user/login'; let queryParameters: any = {}; let headerParams: any = this.extendObj({}, this.defaultHeaders); let formParams: any = {}; @@ -362,7 +368,7 @@ export class UserApi { * */ public logoutUser () : Promise<{ response: http.ClientResponse; body?: any; }> { - const path = this.url + this.basePath + '/user/logout'; + const path = this.basePath + '/user/logout'; let queryParameters: any = {}; let headerParams: any = this.extendObj({}, this.defaultHeaders); let formParams: any = {}; @@ -410,7 +416,7 @@ export class UserApi { * @param username The name that needs to be fetched. Use user1 for testing. */ public getUserByName (username: string) : Promise<{ response: http.ClientResponse; body: User; }> { - const path = this.url + this.basePath + '/user/{username}' + const path = this.basePath + '/user/{username}' .replace('{' + 'username' + '}', String(username)); let queryParameters: any = {}; let headerParams: any = this.extendObj({}, this.defaultHeaders); @@ -465,7 +471,7 @@ export class UserApi { * @param body Updated user object */ public updateUser (username: string, body?: User) : Promise<{ response: http.ClientResponse; body?: any; }> { - const path = this.url + this.basePath + '/user/{username}' + const path = this.basePath + '/user/{username}' .replace('{' + 'username' + '}', String(username)); let queryParameters: any = {}; let headerParams: any = this.extendObj({}, this.defaultHeaders); @@ -520,7 +526,7 @@ export class UserApi { * @param username The name that needs to be deleted */ public deleteUser (username: string) : Promise<{ response: http.ClientResponse; body?: any; }> { - const path = this.url + this.basePath + '/user/{username}' + const path = this.basePath + '/user/{username}' .replace('{' + 'username' + '}', String(username)); let queryParameters: any = {}; let headerParams: any = this.extendObj({}, this.defaultHeaders); @@ -581,8 +587,8 @@ export class PetApi { 'petstore_auth': new OAuth(), } - constructor(url: string, basePath?: string); - constructor(private url: string, basePathOrUsername: string, password?: string, basePath?: string) { + constructor(basePath?: string); + constructor(basePathOrUsername: string, password?: string, basePath?: string) { if (password) { if (basePath) { this.basePath = basePath; @@ -597,6 +603,10 @@ export class PetApi { set apiKey(key: string) { this.authentications.api_key.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)){ @@ -611,7 +621,7 @@ export class PetApi { * @param body Pet object that needs to be added to the store */ public updatePet (body?: Pet) : Promise<{ response: http.ClientResponse; body?: any; }> { - const path = this.url + this.basePath + '/pet'; + const path = this.basePath + '/pet'; let queryParameters: any = {}; let headerParams: any = this.extendObj({}, this.defaultHeaders); let formParams: any = {}; @@ -662,7 +672,7 @@ export class PetApi { * @param body Pet object that needs to be added to the store */ public addPet (body?: Pet) : Promise<{ response: http.ClientResponse; body?: any; }> { - const path = this.url + this.basePath + '/pet'; + const path = this.basePath + '/pet'; let queryParameters: any = {}; let headerParams: any = this.extendObj({}, this.defaultHeaders); let formParams: any = {}; @@ -713,7 +723,7 @@ export class PetApi { * @param status Status values that need to be considered for filter */ public findPetsByStatus (status?: Array) : Promise<{ response: http.ClientResponse; body: Array; }> { - const path = this.url + this.basePath + '/pet/findByStatus'; + const path = this.basePath + '/pet/findByStatus'; let queryParameters: any = {}; let headerParams: any = this.extendObj({}, this.defaultHeaders); let formParams: any = {}; @@ -767,7 +777,7 @@ export class PetApi { * @param tags Tags to filter by */ public findPetsByTags (tags?: Array) : Promise<{ response: http.ClientResponse; body: Array; }> { - const path = this.url + this.basePath + '/pet/findByTags'; + const path = this.basePath + '/pet/findByTags'; let queryParameters: any = {}; let headerParams: any = this.extendObj({}, this.defaultHeaders); let formParams: any = {}; @@ -821,7 +831,7 @@ export class PetApi { * @param petId ID of pet that needs to be fetched */ public getPetById (petId: number) : Promise<{ response: http.ClientResponse; body: Pet; }> { - const path = this.url + this.basePath + '/pet/{petId}' + const path = this.basePath + '/pet/{petId}' .replace('{' + 'petId' + '}', String(petId)); let queryParameters: any = {}; let headerParams: any = this.extendObj({}, this.defaultHeaders); @@ -879,7 +889,7 @@ export class PetApi { * @param status Updated status of the pet */ public updatePetWithForm (petId: string, name?: string, status?: string) : Promise<{ response: http.ClientResponse; body?: any; }> { - const path = this.url + this.basePath + '/pet/{petId}' + const path = this.basePath + '/pet/{petId}' .replace('{' + 'petId' + '}', String(petId)); let queryParameters: any = {}; let headerParams: any = this.extendObj({}, this.defaultHeaders); @@ -944,7 +954,7 @@ export class PetApi { * @param apiKey */ public deletePet (petId: number, apiKey?: string) : Promise<{ response: http.ClientResponse; body?: any; }> { - const path = this.url + this.basePath + '/pet/{petId}' + const path = this.basePath + '/pet/{petId}' .replace('{' + 'petId' + '}', String(petId)); let queryParameters: any = {}; let headerParams: any = this.extendObj({}, this.defaultHeaders); @@ -1004,7 +1014,7 @@ export class PetApi { * @param file file to upload */ public uploadFile (petId: number, additionalMetadata?: string, file?: any) : Promise<{ response: http.ClientResponse; body?: any; }> { - const path = this.url + this.basePath + '/pet/{petId}/uploadImage' + const path = this.basePath + '/pet/{petId}/uploadImage' .replace('{' + 'petId' + '}', String(petId)); let queryParameters: any = {}; let headerParams: any = this.extendObj({}, this.defaultHeaders); @@ -1076,8 +1086,8 @@ export class StoreApi { 'petstore_auth': new OAuth(), } - constructor(url: string, basePath?: string); - constructor(private url: string, basePathOrUsername: string, password?: string, basePath?: string) { + constructor(basePath?: string); + constructor(basePathOrUsername: string, password?: string, basePath?: string) { if (password) { if (basePath) { this.basePath = basePath; @@ -1092,6 +1102,10 @@ export class StoreApi { set apiKey(key: string) { this.authentications.api_key.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)){ @@ -1105,7 +1119,7 @@ export class StoreApi { * Returns a map of status codes to quantities */ public getInventory () : Promise<{ response: http.ClientResponse; body: { [key: string]: number; }; }> { - const path = this.url + this.basePath + '/store/inventory'; + const path = this.basePath + '/store/inventory'; let queryParameters: any = {}; let headerParams: any = this.extendObj({}, this.defaultHeaders); let formParams: any = {}; @@ -1155,7 +1169,7 @@ export class StoreApi { * @param body order placed for purchasing the pet */ public placeOrder (body?: Order) : Promise<{ response: http.ClientResponse; body: Order; }> { - const path = this.url + this.basePath + '/store/order'; + const path = this.basePath + '/store/order'; let queryParameters: any = {}; let headerParams: any = this.extendObj({}, this.defaultHeaders); let formParams: any = {}; @@ -1204,7 +1218,7 @@ export class StoreApi { * @param orderId ID of pet that needs to be fetched */ public getOrderById (orderId: string) : Promise<{ response: http.ClientResponse; body: Order; }> { - const path = this.url + this.basePath + '/store/order/{orderId}' + const path = this.basePath + '/store/order/{orderId}' .replace('{' + 'orderId' + '}', String(orderId)); let queryParameters: any = {}; let headerParams: any = this.extendObj({}, this.defaultHeaders); @@ -1258,7 +1272,7 @@ export class StoreApi { * @param orderId ID of the order that needs to be deleted */ public deleteOrder (orderId: string) : Promise<{ response: http.ClientResponse; body?: any; }> { - const path = this.url + this.basePath + '/store/order/{orderId}' + const path = this.basePath + '/store/order/{orderId}' .replace('{' + 'orderId' + '}', String(orderId)); let queryParameters: any = {}; let headerParams: any = this.extendObj({}, this.defaultHeaders); diff --git a/samples/client/petstore/typescript-node/client.ts b/samples/client/petstore/typescript-node/client.ts index 506f33f014e..891feef3902 100644 --- a/samples/client/petstore/typescript-node/client.ts +++ b/samples/client/petstore/typescript-node/client.ts @@ -1,11 +1,18 @@ import api = require('./api'); import fs = require('fs'); -var petApi = new api.PetApi('http://petstore.swagger.io/'); +var petApi = new api.PetApi(); petApi.apiKey = 'special-key'; +var tag1 = new api.Tag(); +tag1.id = 18291; +tag1.name = 'TS tag 1'; + var pet = new api.Pet(); pet.name = 'TypeScriptDoggie'; +pet.id = 18291; +pet.photoUrls = ["http://url1", "http://url2"]; +pet.tags = [tag1]; var petId: any; diff --git a/samples/server/petstore/flaskConnexion/README.md b/samples/server/petstore/flaskConnexion/README.md index d85f471ba40..2b8c96e6170 100644 --- a/samples/server/petstore/flaskConnexion/README.md +++ b/samples/server/petstore/flaskConnexion/README.md @@ -3,7 +3,7 @@ ## 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/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. +is an example of building a swagger-enabled flask server. This example uses the [connexion](https://github.com/zalando/connexion) library on top of Flask. diff --git a/samples/server/petstore/flaskConnexion/controllers/default_controller.py b/samples/server/petstore/flaskConnexion/controllers/default_controller.py index 8d771afed91..d42c48575d1 100644 --- a/samples/server/petstore/flaskConnexion/controllers/default_controller.py +++ b/samples/server/petstore/flaskConnexion/controllers/default_controller.py @@ -23,6 +23,18 @@ def update_user(username, body) -> str: def delete_user(username) -> str: return 'do some magic!' +def get_inventory() -> str: + return 'do some magic!' + +def place_order(body) -> str: + return 'do some magic!' + +def get_order_by_id(orderId) -> str: + return 'do some magic!' + +def delete_order(orderId) -> str: + return 'do some magic!' + def update_pet(body) -> str: return 'do some magic!' @@ -46,15 +58,3 @@ def delete_pet(petId, apiKey) -> str: def upload_file(petId, additionalMetadata, file) -> str: return 'do some magic!' - -def get_inventory() -> str: - return 'do some magic!' - -def place_order(body) -> str: - return 'do some magic!' - -def get_order_by_id(orderId) -> str: - return 'do some magic!' - -def delete_order(orderId) -> str: - return 'do some magic!' diff --git a/samples/server/petstore/flaskConnexion/swagger/swagger.yaml b/samples/server/petstore/flaskConnexion/swagger/swagger.yaml index 047d1652a87..1a4ff85e60a 100644 --- a/samples/server/petstore/flaskConnexion/swagger/swagger.yaml +++ b/samples/server/petstore/flaskConnexion/swagger/swagger.yaml @@ -45,7 +45,6 @@ paths: - petstore_auth: - "write:pets" - "read:pets" - x-operationId: "add_pet" x-tags: - tag: "pet" put: @@ -78,7 +77,6 @@ paths: - petstore_auth: - "write:pets" - "read:pets" - x-operationId: "update_pet" x-tags: - tag: "pet" /pet/findByStatus: @@ -114,7 +112,6 @@ paths: - petstore_auth: - "write:pets" - "read:pets" - x-operationId: "find_pets_by_status" x-tags: - tag: "pet" /pet/findByTags: @@ -150,7 +147,6 @@ paths: - petstore_auth: - "write:pets" - "read:pets" - x-operationId: "find_pets_by_tags" x-tags: - tag: "pet" /pet/{petId}: @@ -185,7 +181,6 @@ paths: - petstore_auth: - "write:pets" - "read:pets" - x-operationId: "get_pet_by_id" x-tags: - tag: "pet" post: @@ -222,7 +217,6 @@ paths: - petstore_auth: - "write:pets" - "read:pets" - x-operationId: "update_pet_with_form" x-tags: - tag: "pet" delete: @@ -253,7 +247,6 @@ paths: - petstore_auth: - "write:pets" - "read:pets" - x-operationId: "delete_pet" x-tags: - tag: "pet" /pet/{petId}/uploadImage: @@ -292,7 +285,6 @@ paths: - petstore_auth: - "write:pets" - "read:pets" - x-operationId: "upload_file" x-tags: - tag: "pet" /store/inventory: @@ -316,7 +308,6 @@ paths: format: "int32" security: - api_key: [] - x-operationId: "get_inventory" x-tags: - tag: "store" /store/order: @@ -343,7 +334,6 @@ paths: $ref: "#/definitions/Order" 400: description: "Invalid Order" - x-operationId: "place_order" x-tags: - tag: "store" /store/order/{orderId}: @@ -372,7 +362,6 @@ paths: description: "Invalid ID supplied" 404: description: "Order not found" - x-operationId: "get_order_by_id" x-tags: - tag: "store" delete: @@ -396,7 +385,6 @@ paths: description: "Invalid ID supplied" 404: description: "Order not found" - x-operationId: "delete_order" x-tags: - tag: "store" /user: @@ -419,7 +407,6 @@ paths: responses: default: description: "successful operation" - x-operationId: "create_user" x-tags: - tag: "user" /user/createWithArray: @@ -444,7 +431,6 @@ paths: responses: default: description: "successful operation" - x-operationId: "create_users_with_array_input" x-tags: - tag: "user" /user/createWithList: @@ -469,7 +455,6 @@ paths: responses: default: description: "successful operation" - x-operationId: "create_users_with_list_input" x-tags: - tag: "user" /user/login: @@ -500,7 +485,6 @@ paths: type: "string" 400: description: "Invalid username/password supplied" - x-operationId: "login_user" x-tags: - tag: "user" /user/logout: @@ -517,7 +501,6 @@ paths: responses: default: description: "successful operation" - x-operationId: "logout_user" x-tags: - tag: "user" /user/{username}: @@ -555,7 +538,6 @@ paths: description: "Invalid username supplied" 404: description: "User not found" - x-operationId: "get_user_by_name" x-tags: - tag: "user" put: @@ -584,7 +566,6 @@ paths: description: "Invalid user supplied" 404: description: "User not found" - x-operationId: "update_user" x-tags: - tag: "user" delete: @@ -607,14 +588,9 @@ paths: description: "Invalid username supplied" 404: description: "User not found" - x-operationId: "delete_user" x-tags: - tag: "user" securityDefinitions: - api_key: - type: "apiKey" - name: "api_key" - in: "header" petstore_auth: type: "oauth2" authorizationUrl: "http://petstore.swagger.io/api/oauth/dialog" @@ -622,6 +598,10 @@ securityDefinitions: scopes: write:pets: "modify pets in your account" read:pets: "read your pets" + api_key: + type: "apiKey" + name: "api_key" + in: "header" definitions: User: properties: diff --git a/samples/server/petstore/java-inflector/inflector.yaml b/samples/server/petstore/java-inflector/inflector.yaml index 25ec6dde3f2..8a11ca3b659 100644 --- a/samples/server/petstore/java-inflector/inflector.yaml +++ b/samples/server/petstore/java-inflector/inflector.yaml @@ -1,6 +1,6 @@ controllerPackage: io.swagger.handler modelPackage: io.swagger.model -swaggerUrl: ./src/main/swagger/swagger.json +swaggerUrl: ./src/main/swagger/swagger.yaml modelMappings: User : io.swagger.model.User Category : io.swagger.model.Category @@ -8,3 +8,7 @@ modelMappings: Tag : io.swagger.model.Tag Order : io.swagger.model.Order +entityProcessors: + - json + - xml + - yaml \ No newline at end of file diff --git a/samples/server/petstore/java-inflector/pom.xml b/samples/server/petstore/java-inflector/pom.xml index 7b7ec1d8b3d..681c0c874c0 100644 --- a/samples/server/petstore/java-inflector/pom.xml +++ b/samples/server/petstore/java-inflector/pom.xml @@ -74,16 +74,16 @@ - + io.swagger swagger-inflector - 1.0.0-SNAPSHOT + 1.0.0 1.0.0 - 1.5.3 + 1.5.4 9.2.9.v20150224 1.0.1 4.8.2 diff --git a/samples/server/petstore/java-inflector/src/main/java/io/swagger/handler/PetController.java b/samples/server/petstore/java-inflector/src/main/java/io/swagger/handler/PetController.java index 9f31acf53da..fe5735bbdbe 100644 --- a/samples/server/petstore/java-inflector/src/main/java/io/swagger/handler/PetController.java +++ b/samples/server/petstore/java-inflector/src/main/java/io/swagger/handler/PetController.java @@ -13,7 +13,7 @@ import io.swagger.model.*; import io.swagger.model.Pet; import java.io.File; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2015-08-24T17:25:49.737-07:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2015-11-30T10:22:45.081-08:00") public class PetController { /** * Uncomment and implement as you see fit. These operations will map diff --git a/samples/server/petstore/java-inflector/src/main/java/io/swagger/handler/StoreController.java b/samples/server/petstore/java-inflector/src/main/java/io/swagger/handler/StoreController.java index 3506b6b920c..4d7b6ddaaf5 100644 --- a/samples/server/petstore/java-inflector/src/main/java/io/swagger/handler/StoreController.java +++ b/samples/server/petstore/java-inflector/src/main/java/io/swagger/handler/StoreController.java @@ -13,7 +13,7 @@ import io.swagger.model.*; import java.util.Map; import io.swagger.model.Order; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2015-08-24T17:25:49.737-07:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2015-11-30T10:22:45.081-08:00") public class StoreController { /** * Uncomment and implement as you see fit. These operations will map diff --git a/samples/server/petstore/java-inflector/src/main/java/io/swagger/handler/UserController.java b/samples/server/petstore/java-inflector/src/main/java/io/swagger/handler/UserController.java index 3ca4fa0e394..73fc2e202be 100644 --- a/samples/server/petstore/java-inflector/src/main/java/io/swagger/handler/UserController.java +++ b/samples/server/petstore/java-inflector/src/main/java/io/swagger/handler/UserController.java @@ -13,7 +13,7 @@ import io.swagger.model.*; import io.swagger.model.User; import java.util.*; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2015-08-24T17:25:49.737-07:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2015-11-30T10:22:45.081-08:00") public class UserController { /** * Uncomment and implement as you see fit. These operations will map diff --git a/samples/server/petstore/java-inflector/src/main/java/io/swagger/model/Category.java b/samples/server/petstore/java-inflector/src/main/java/io/swagger/model/Category.java index 03a37fef5b0..cd5f99dc6cc 100644 --- a/samples/server/petstore/java-inflector/src/main/java/io/swagger/model/Category.java +++ b/samples/server/petstore/java-inflector/src/main/java/io/swagger/model/Category.java @@ -6,7 +6,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2015-08-24T17:25:49.737-07:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2015-11-30T10:22:45.081-08:00") public class Category { private Long id = null; diff --git a/samples/server/petstore/java-inflector/src/main/java/io/swagger/model/Order.java b/samples/server/petstore/java-inflector/src/main/java/io/swagger/model/Order.java index de3a2f8b9eb..4b56d2bd164 100644 --- a/samples/server/petstore/java-inflector/src/main/java/io/swagger/model/Order.java +++ b/samples/server/petstore/java-inflector/src/main/java/io/swagger/model/Order.java @@ -7,7 +7,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2015-08-24T17:25:49.737-07:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2015-11-30T10:22:45.081-08:00") public class Order { private Long id = null; diff --git a/samples/server/petstore/java-inflector/src/main/java/io/swagger/model/Pet.java b/samples/server/petstore/java-inflector/src/main/java/io/swagger/model/Pet.java index eb81026f601..374a529a538 100644 --- a/samples/server/petstore/java-inflector/src/main/java/io/swagger/model/Pet.java +++ b/samples/server/petstore/java-inflector/src/main/java/io/swagger/model/Pet.java @@ -9,7 +9,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2015-08-24T17:25:49.737-07:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2015-11-30T10:22:45.081-08:00") public class Pet { private Long id = null; diff --git a/samples/server/petstore/java-inflector/src/main/java/io/swagger/model/Tag.java b/samples/server/petstore/java-inflector/src/main/java/io/swagger/model/Tag.java index 8c8f2597461..4bcc82f7749 100644 --- a/samples/server/petstore/java-inflector/src/main/java/io/swagger/model/Tag.java +++ b/samples/server/petstore/java-inflector/src/main/java/io/swagger/model/Tag.java @@ -6,7 +6,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2015-08-24T17:25:49.737-07:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2015-11-30T10:22:45.081-08:00") public class Tag { private Long id = null; diff --git a/samples/server/petstore/java-inflector/src/main/java/io/swagger/model/User.java b/samples/server/petstore/java-inflector/src/main/java/io/swagger/model/User.java index be5261cdb70..cdc4debe376 100644 --- a/samples/server/petstore/java-inflector/src/main/java/io/swagger/model/User.java +++ b/samples/server/petstore/java-inflector/src/main/java/io/swagger/model/User.java @@ -6,7 +6,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2015-08-24T17:25:49.737-07:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaInflectorServerCodegen", date = "2015-11-30T10:22:45.081-08:00") public class User { private Long id = null; diff --git a/samples/server/petstore/java-inflector/src/main/swagger/swagger.json b/samples/server/petstore/java-inflector/src/main/swagger/swagger.json deleted file mode 100644 index 36ecd60503e..00000000000 --- a/samples/server/petstore/java-inflector/src/main/swagger/swagger.json +++ /dev/null @@ -1,770 +0,0 @@ -{ - "swagger" : "2.0", - "info" : { - "description" : "This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters", - "version" : "1.0.0", - "title" : "Swagger Petstore", - "termsOfService" : "http://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", - "schemes" : [ "http" ], - "paths" : { - "/pet" : { - "post" : { - "tags" : [ "pet" ], - "summary" : "Add a new pet to the store", - "description" : "", - "operationId" : "addPet", - "consumes" : [ "application/json", "application/xml" ], - "produces" : [ "application/json", "application/xml" ], - "parameters" : [ { - "in" : "body", - "name" : "body", - "description" : "Pet object that needs to be added to the store", - "required" : false, - "schema" : { - "$ref" : "#/definitions/Pet" - } - } ], - "responses" : { - "405" : { - "description" : "Invalid input" - } - }, - "security" : [ { - "petstore_auth" : [ "write:pets", "read:pets" ] - } ] - }, - "put" : { - "tags" : [ "pet" ], - "summary" : "Update an existing pet", - "description" : "", - "operationId" : "updatePet", - "consumes" : [ "application/json", "application/xml" ], - "produces" : [ "application/json", "application/xml" ], - "parameters" : [ { - "in" : "body", - "name" : "body", - "description" : "Pet object that needs to be added to the store", - "required" : false, - "schema" : { - "$ref" : "#/definitions/Pet" - } - } ], - "responses" : { - "405" : { - "description" : "Validation exception" - }, - "404" : { - "description" : "Pet not found" - }, - "400" : { - "description" : "Invalid ID supplied" - } - }, - "security" : [ { - "petstore_auth" : [ "write:pets", "read:pets" ] - } ] - } - }, - "/pet/findByStatus" : { - "get" : { - "tags" : [ "pet" ], - "summary" : "Finds Pets by status", - "description" : "Multiple status values can be provided with comma seperated strings", - "operationId" : "findPetsByStatus", - "produces" : [ "application/json", "application/xml" ], - "parameters" : [ { - "name" : "status", - "in" : "query", - "description" : "Status values that need to be considered for filter", - "required" : false, - "type" : "array", - "items" : { - "type" : "string" - }, - "collectionFormat" : "multi", - "default" : "available" - } ], - "responses" : { - "200" : { - "description" : "successful operation", - "schema" : { - "type" : "array", - "items" : { - "$ref" : "#/definitions/Pet" - } - } - }, - "400" : { - "description" : "Invalid status value" - } - }, - "security" : [ { - "petstore_auth" : [ "write:pets", "read:pets" ] - } ] - } - }, - "/pet/findByTags" : { - "get" : { - "tags" : [ "pet" ], - "summary" : "Finds Pets by tags", - "description" : "Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.", - "operationId" : "findPetsByTags", - "produces" : [ "application/json", "application/xml" ], - "parameters" : [ { - "name" : "tags", - "in" : "query", - "description" : "Tags to filter by", - "required" : false, - "type" : "array", - "items" : { - "type" : "string" - }, - "collectionFormat" : "multi" - } ], - "responses" : { - "200" : { - "description" : "successful operation", - "schema" : { - "type" : "array", - "items" : { - "$ref" : "#/definitions/Pet" - } - } - }, - "400" : { - "description" : "Invalid tag value" - } - }, - "security" : [ { - "petstore_auth" : [ "write:pets", "read:pets" ] - } ] - } - }, - "/pet/{petId}" : { - "get" : { - "tags" : [ "pet" ], - "summary" : "Find pet by ID", - "description" : "Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions", - "operationId" : "getPetById", - "produces" : [ "application/json", "application/xml" ], - "parameters" : [ { - "name" : "petId", - "in" : "path", - "description" : "ID of pet that needs to be fetched", - "required" : true, - "type" : "integer", - "format" : "int64" - } ], - "responses" : { - "404" : { - "description" : "Pet not found" - }, - "200" : { - "description" : "successful operation", - "schema" : { - "$ref" : "#/definitions/Pet" - } - }, - "400" : { - "description" : "Invalid ID supplied" - } - }, - "security" : [ { - "api_key" : [ ] - }, { - "petstore_auth" : [ "write:pets", "read:pets" ] - } ] - }, - "post" : { - "tags" : [ "pet" ], - "summary" : "Updates a pet in the store with form data", - "description" : "", - "operationId" : "updatePetWithForm", - "consumes" : [ "application/x-www-form-urlencoded" ], - "produces" : [ "application/json", "application/xml" ], - "parameters" : [ { - "name" : "petId", - "in" : "path", - "description" : "ID of pet that needs to be updated", - "required" : true, - "type" : "string" - }, { - "name" : "name", - "in" : "formData", - "description" : "Updated name of the pet", - "required" : false, - "type" : "string" - }, { - "name" : "status", - "in" : "formData", - "description" : "Updated status of the pet", - "required" : false, - "type" : "string" - } ], - "responses" : { - "405" : { - "description" : "Invalid input" - } - }, - "security" : [ { - "petstore_auth" : [ "write:pets", "read:pets" ] - } ] - }, - "delete" : { - "tags" : [ "pet" ], - "summary" : "Deletes a pet", - "description" : "", - "operationId" : "deletePet", - "produces" : [ "application/json", "application/xml" ], - "parameters" : [ { - "name" : "api_key", - "in" : "header", - "description" : "", - "required" : false, - "type" : "string" - }, { - "name" : "petId", - "in" : "path", - "description" : "Pet id to delete", - "required" : true, - "type" : "integer", - "format" : "int64" - } ], - "responses" : { - "400" : { - "description" : "Invalid pet value" - } - }, - "security" : [ { - "petstore_auth" : [ "write:pets", "read:pets" ] - } ] - } - }, - "/pet/{petId}/uploadImage" : { - "post" : { - "tags" : [ "pet" ], - "summary" : "uploads an image", - "description" : "", - "operationId" : "uploadFile", - "consumes" : [ "multipart/form-data" ], - "produces" : [ "application/json", "application/xml" ], - "parameters" : [ { - "name" : "petId", - "in" : "path", - "description" : "ID of pet to update", - "required" : true, - "type" : "integer", - "format" : "int64" - }, { - "name" : "additionalMetadata", - "in" : "formData", - "description" : "Additional data to pass to server", - "required" : false, - "type" : "string" - }, { - "name" : "file", - "in" : "formData", - "description" : "file to upload", - "required" : false, - "type" : "file" - } ], - "responses" : { - "default" : { - "description" : "successful operation" - } - }, - "security" : [ { - "petstore_auth" : [ "write:pets", "read:pets" ] - } ] - } - }, - "/store/inventory" : { - "get" : { - "tags" : [ "store" ], - "summary" : "Returns pet inventories by status", - "description" : "Returns a map of status codes to quantities", - "operationId" : "getInventory", - "produces" : [ "application/json", "application/xml" ], - "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/json", "application/xml" ], - "parameters" : [ { - "in" : "body", - "name" : "body", - "description" : "order placed for purchasing the pet", - "required" : false, - "schema" : { - "$ref" : "#/definitions/Order" - } - } ], - "responses" : { - "200" : { - "description" : "successful operation", - "schema" : { - "$ref" : "#/definitions/Order" - } - }, - "400" : { - "description" : "Invalid Order" - } - } - } - }, - "/store/order/{orderId}" : { - "get" : { - "tags" : [ "store" ], - "summary" : "Find purchase order by ID", - "description" : "For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions", - "operationId" : "getOrderById", - "produces" : [ "application/json", "application/xml" ], - "parameters" : [ { - "name" : "orderId", - "in" : "path", - "description" : "ID of pet that needs to be fetched", - "required" : true, - "type" : "string" - } ], - "responses" : { - "404" : { - "description" : "Order not found" - }, - "200" : { - "description" : "successful operation", - "schema" : { - "$ref" : "#/definitions/Order" - } - }, - "400" : { - "description" : "Invalid ID supplied" - } - } - }, - "delete" : { - "tags" : [ "store" ], - "summary" : "Delete purchase order by ID", - "description" : "For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors", - "operationId" : "deleteOrder", - "produces" : [ "application/json", "application/xml" ], - "parameters" : [ { - "name" : "orderId", - "in" : "path", - "description" : "ID of the order that needs to be deleted", - "required" : true, - "type" : "string" - } ], - "responses" : { - "404" : { - "description" : "Order not found" - }, - "400" : { - "description" : "Invalid ID supplied" - } - } - } - }, - "/user" : { - "post" : { - "tags" : [ "user" ], - "summary" : "Create user", - "description" : "This can only be done by the logged in user.", - "operationId" : "createUser", - "produces" : [ "application/json", "application/xml" ], - "parameters" : [ { - "in" : "body", - "name" : "body", - "description" : "Created user object", - "required" : false, - "schema" : { - "$ref" : "#/definitions/User" - } - } ], - "responses" : { - "default" : { - "description" : "successful operation" - } - } - } - }, - "/user/createWithArray" : { - "post" : { - "tags" : [ "user" ], - "summary" : "Creates list of users with given input array", - "description" : "", - "operationId" : "createUsersWithArrayInput", - "produces" : [ "application/json", "application/xml" ], - "parameters" : [ { - "in" : "body", - "name" : "body", - "description" : "List of user object", - "required" : false, - "schema" : { - "type" : "array", - "items" : { - "$ref" : "#/definitions/User" - } - } - } ], - "responses" : { - "default" : { - "description" : "successful operation" - } - } - } - }, - "/user/createWithList" : { - "post" : { - "tags" : [ "user" ], - "summary" : "Creates list of users with given input array", - "description" : "", - "operationId" : "createUsersWithListInput", - "produces" : [ "application/json", "application/xml" ], - "parameters" : [ { - "in" : "body", - "name" : "body", - "description" : "List of user object", - "required" : false, - "schema" : { - "type" : "array", - "items" : { - "$ref" : "#/definitions/User" - } - } - } ], - "responses" : { - "default" : { - "description" : "successful operation" - } - } - } - }, - "/user/login" : { - "get" : { - "tags" : [ "user" ], - "summary" : "Logs user into the system", - "description" : "", - "operationId" : "loginUser", - "produces" : [ "application/json", "application/xml" ], - "parameters" : [ { - "name" : "username", - "in" : "query", - "description" : "The user name for login", - "required" : false, - "type" : "string" - }, { - "name" : "password", - "in" : "query", - "description" : "The password for login in clear text", - "required" : false, - "type" : "string" - } ], - "responses" : { - "200" : { - "description" : "successful operation", - "schema" : { - "type" : "string" - } - }, - "400" : { - "description" : "Invalid username/password supplied" - } - } - } - }, - "/user/logout" : { - "get" : { - "tags" : [ "user" ], - "summary" : "Logs out current logged in user session", - "description" : "", - "operationId" : "logoutUser", - "produces" : [ "application/json", "application/xml" ], - "parameters" : [ ], - "responses" : { - "default" : { - "description" : "successful operation" - } - } - } - }, - "/user/{username}" : { - "get" : { - "tags" : [ "user" ], - "summary" : "Get user by user name", - "description" : "", - "operationId" : "getUserByName", - "produces" : [ "application/json", "application/xml" ], - "parameters" : [ { - "name" : "username", - "in" : "path", - "description" : "The name that needs to be fetched. Use user1 for testing. ", - "required" : true, - "type" : "string" - } ], - "responses" : { - "404" : { - "description" : "User not found" - }, - "200" : { - "description" : "successful operation", - "schema" : { - "$ref" : "#/definitions/User" - }, - "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" - } - } - }, - "put" : { - "tags" : [ "user" ], - "summary" : "Updated user", - "description" : "This can only be done by the logged in user.", - "operationId" : "updateUser", - "produces" : [ "application/json", "application/xml" ], - "parameters" : [ { - "name" : "username", - "in" : "path", - "description" : "name that need to be deleted", - "required" : true, - "type" : "string" - }, { - "in" : "body", - "name" : "body", - "description" : "Updated user object", - "required" : false, - "schema" : { - "$ref" : "#/definitions/User" - } - } ], - "responses" : { - "404" : { - "description" : "User not found" - }, - "400" : { - "description" : "Invalid user supplied" - } - } - }, - "delete" : { - "tags" : [ "user" ], - "summary" : "Delete user", - "description" : "This can only be done by the logged in user.", - "operationId" : "deleteUser", - "produces" : [ "application/json", "application/xml" ], - "parameters" : [ { - "name" : "username", - "in" : "path", - "description" : "The name that needs to be deleted", - "required" : true, - "type" : "string" - } ], - "responses" : { - "404" : { - "description" : "User not found" - }, - "400" : { - "description" : "Invalid username supplied" - } - } - } - } - }, - "securityDefinitions" : { - "api_key" : { - "type" : "apiKey", - "name" : "api_key", - "in" : "header" - }, - "petstore_auth" : { - "type" : "oauth2", - "authorizationUrl" : "http://petstore.swagger.io/api/oauth/dialog", - "flow" : "implicit", - "scopes" : { - "write:pets" : "modify pets in your account", - "read:pets" : "read your pets" - } - } - }, - "definitions" : { - "User" : { - "properties" : { - "id" : { - "type" : "integer", - "format" : "int64" - }, - "username" : { - "type" : "string" - }, - "firstName" : { - "type" : "string" - }, - "lastName" : { - "type" : "string" - }, - "email" : { - "type" : "string" - }, - "password" : { - "type" : "string" - }, - "phone" : { - "type" : "string" - }, - "userStatus" : { - "type" : "integer", - "format" : "int32", - "description" : "User Status" - } - }, - "xml" : { - "name" : "User" - } - }, - "Category" : { - "properties" : { - "id" : { - "type" : "integer", - "format" : "int64" - }, - "name" : { - "type" : "string" - } - }, - "xml" : { - "name" : "Category" - } - }, - "Pet" : { - "required" : [ "name", "photoUrls" ], - "properties" : { - "id" : { - "type" : "integer", - "format" : "int64" - }, - "category" : { - "$ref" : "#/definitions/Category" - }, - "name" : { - "type" : "string", - "example" : "doggie" - }, - "photoUrls" : { - "type" : "array", - "xml" : { - "name" : "photoUrl", - "wrapped" : true - }, - "items" : { - "type" : "string" - } - }, - "tags" : { - "type" : "array", - "xml" : { - "name" : "tag", - "wrapped" : true - }, - "items" : { - "$ref" : "#/definitions/Tag" - } - }, - "status" : { - "type" : "string", - "description" : "pet status in the store", - "enum" : [ "available", "pending", "sold" ] - } - }, - "xml" : { - "name" : "Pet" - } - }, - "Tag" : { - "properties" : { - "id" : { - "type" : "integer", - "format" : "int64" - }, - "name" : { - "type" : "string" - } - }, - "xml" : { - "name" : "Tag" - } - }, - "Order" : { - "properties" : { - "id" : { - "type" : "integer", - "format" : "int64" - }, - "petId" : { - "type" : "integer", - "format" : "int64" - }, - "quantity" : { - "type" : "integer", - "format" : "int32" - }, - "shipDate" : { - "type" : "string", - "format" : "date-time" - }, - "status" : { - "type" : "string", - "description" : "Order Status", - "enum" : [ "placed", "approved", "delivered" ] - }, - "complete" : { - "type" : "boolean" - } - }, - "xml" : { - "name" : "Order" - } - } - } -} \ No newline at end of file diff --git a/samples/server/petstore/java-inflector/src/main/swagger/swagger.yaml b/samples/server/petstore/java-inflector/src/main/swagger/swagger.yaml new file mode 100644 index 00000000000..49a3405de09 --- /dev/null +++ b/samples/server/petstore/java-inflector/src/main/swagger/swagger.yaml @@ -0,0 +1,667 @@ +--- +swagger: "2.0" +info: + description: "This is a sample server Petstore server. You can find out more about\ + \ Swagger at http://swagger.io or on irc.freenode.net,\ + \ #swagger. For this sample, you can use the api key \"special-key\" to test\ + \ the authorization filters" + version: "1.0.0" + title: "Swagger Petstore" + termsOfService: "http://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" +schemes: +- "http" +paths: + /pet: + post: + tags: + - "pet" + summary: "Add a new pet to the store" + description: "" + operationId: "addPet" + consumes: + - "application/json" + - "application/xml" + produces: + - "application/json" + - "application/xml" + parameters: + - in: "body" + name: "body" + description: "Pet object that needs to be added to the store" + required: false + schema: + $ref: "#/definitions/Pet" + responses: + 405: + description: "Invalid input" + security: + - petstore_auth: + - "write:pets" + - "read:pets" + put: + tags: + - "pet" + summary: "Update an existing pet" + description: "" + operationId: "updatePet" + consumes: + - "application/json" + - "application/xml" + produces: + - "application/json" + - "application/xml" + parameters: + - in: "body" + name: "body" + description: "Pet object that needs to be added to the store" + required: false + schema: + $ref: "#/definitions/Pet" + responses: + 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 seperated strings" + operationId: "findPetsByStatus" + produces: + - "application/json" + - "application/xml" + parameters: + - name: "status" + in: "query" + description: "Status values that need to be considered for filter" + required: false + type: "array" + items: + type: "string" + collectionFormat: "multi" + default: "available" + responses: + 200: + description: "successful operation" + schema: + type: "array" + items: + $ref: "#/definitions/Pet" + 400: + description: "Invalid status value" + security: + - petstore_auth: + - "write:pets" + - "read:pets" + /pet/findByTags: + get: + tags: + - "pet" + summary: "Finds Pets by tags" + description: "Muliple tags can be provided with comma seperated strings. Use\ + \ tag1, tag2, tag3 for testing." + operationId: "findPetsByTags" + produces: + - "application/json" + - "application/xml" + parameters: + - name: "tags" + in: "query" + description: "Tags to filter by" + required: false + type: "array" + items: + type: "string" + collectionFormat: "multi" + responses: + 200: + description: "successful operation" + schema: + type: "array" + items: + $ref: "#/definitions/Pet" + 400: + description: "Invalid tag value" + security: + - petstore_auth: + - "write:pets" + - "read:pets" + /pet/{petId}: + get: + tags: + - "pet" + summary: "Find pet by ID" + description: "Returns a pet when ID < 10. ID > 10 or nonintegers will simulate\ + \ API error conditions" + operationId: "getPetById" + produces: + - "application/json" + - "application/xml" + parameters: + - name: "petId" + in: "path" + description: "ID of pet that needs to be fetched" + required: true + type: "integer" + format: "int64" + responses: + 200: + description: "successful operation" + schema: + $ref: "#/definitions/Pet" + 400: + description: "Invalid ID supplied" + 404: + description: "Pet not found" + security: + - api_key: [] + - petstore_auth: + - "write:pets" + - "read:pets" + post: + tags: + - "pet" + summary: "Updates a pet in the store with form data" + description: "" + operationId: "updatePetWithForm" + consumes: + - "application/x-www-form-urlencoded" + produces: + - "application/json" + - "application/xml" + parameters: + - name: "petId" + in: "path" + description: "ID of pet that needs to be updated" + required: true + type: "string" + - name: "name" + in: "formData" + description: "Updated name of the pet" + required: false + type: "string" + - name: "status" + in: "formData" + description: "Updated status of the pet" + required: false + type: "string" + responses: + 405: + description: "Invalid input" + security: + - petstore_auth: + - "write:pets" + - "read:pets" + delete: + tags: + - "pet" + summary: "Deletes a pet" + description: "" + operationId: "deletePet" + produces: + - "application/json" + - "application/xml" + parameters: + - name: "api_key" + in: "header" + description: "" + required: false + type: "string" + - name: "petId" + in: "path" + description: "Pet id to delete" + required: true + type: "integer" + format: "int64" + responses: + 400: + description: "Invalid pet value" + security: + - petstore_auth: + - "write:pets" + - "read:pets" + /pet/{petId}/uploadImage: + post: + tags: + - "pet" + summary: "uploads an image" + description: "" + operationId: "uploadFile" + consumes: + - "multipart/form-data" + produces: + - "application/json" + - "application/xml" + parameters: + - name: "petId" + in: "path" + description: "ID of pet to update" + required: true + type: "integer" + format: "int64" + - name: "additionalMetadata" + in: "formData" + description: "Additional data to pass to server" + required: false + type: "string" + - name: "file" + in: "formData" + description: "file to upload" + required: false + type: "file" + responses: + default: + description: "successful operation" + security: + - petstore_auth: + - "write:pets" + - "read:pets" + /store/inventory: + get: + tags: + - "store" + summary: "Returns pet inventories by status" + description: "Returns a map of status codes to quantities" + operationId: "getInventory" + produces: + - "application/json" + - "application/xml" + 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/json" + - "application/xml" + parameters: + - in: "body" + name: "body" + description: "order placed for purchasing the pet" + required: false + schema: + $ref: "#/definitions/Order" + responses: + 200: + description: "successful operation" + schema: + $ref: "#/definitions/Order" + 400: + description: "Invalid Order" + /store/order/{orderId}: + get: + tags: + - "store" + summary: "Find purchase order by ID" + description: "For valid response try integer IDs with value <= 5 or > 10. Other\ + \ values will generated exceptions" + operationId: "getOrderById" + produces: + - "application/json" + - "application/xml" + parameters: + - name: "orderId" + in: "path" + description: "ID of pet that needs to be fetched" + required: true + type: "string" + responses: + 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/json" + - "application/xml" + parameters: + - name: "orderId" + in: "path" + description: "ID of the order that needs to be deleted" + required: true + type: "string" + responses: + 400: + description: "Invalid ID supplied" + 404: + description: "Order not found" + /user: + post: + tags: + - "user" + summary: "Create user" + description: "This can only be done by the logged in user." + operationId: "createUser" + produces: + - "application/json" + - "application/xml" + parameters: + - in: "body" + name: "body" + description: "Created user object" + required: false + schema: + $ref: "#/definitions/User" + responses: + default: + description: "successful operation" + /user/createWithArray: + post: + tags: + - "user" + summary: "Creates list of users with given input array" + description: "" + operationId: "createUsersWithArrayInput" + produces: + - "application/json" + - "application/xml" + parameters: + - in: "body" + name: "body" + description: "List of user object" + required: false + schema: + type: "array" + items: + $ref: "#/definitions/User" + responses: + default: + description: "successful operation" + /user/createWithList: + post: + tags: + - "user" + summary: "Creates list of users with given input array" + description: "" + operationId: "createUsersWithListInput" + produces: + - "application/json" + - "application/xml" + parameters: + - in: "body" + name: "body" + description: "List of user object" + required: false + schema: + type: "array" + items: + $ref: "#/definitions/User" + responses: + default: + description: "successful operation" + /user/login: + get: + tags: + - "user" + summary: "Logs user into the system" + description: "" + operationId: "loginUser" + produces: + - "application/json" + - "application/xml" + parameters: + - name: "username" + in: "query" + description: "The user name for login" + required: false + type: "string" + - name: "password" + in: "query" + description: "The password for login in clear text" + required: false + type: "string" + responses: + 200: + description: "successful operation" + schema: + type: "string" + 400: + description: "Invalid username/password supplied" + /user/logout: + get: + tags: + - "user" + summary: "Logs out current logged in user session" + description: "" + operationId: "logoutUser" + produces: + - "application/json" + - "application/xml" + parameters: [] + responses: + default: + description: "successful operation" + /user/{username}: + get: + tags: + - "user" + summary: "Get user by user name" + description: "" + operationId: "getUserByName" + produces: + - "application/json" + - "application/xml" + parameters: + - name: "username" + in: "path" + description: "The name that needs to be fetched. Use user1 for testing. " + required: true + type: "string" + responses: + 200: + 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" + put: + tags: + - "user" + summary: "Updated user" + description: "This can only be done by the logged in user." + operationId: "updateUser" + produces: + - "application/json" + - "application/xml" + parameters: + - name: "username" + in: "path" + description: "name that need to be deleted" + required: true + type: "string" + - in: "body" + name: "body" + description: "Updated user object" + required: false + schema: + $ref: "#/definitions/User" + responses: + 400: + description: "Invalid user supplied" + 404: + description: "User not found" + delete: + tags: + - "user" + summary: "Delete user" + description: "This can only be done by the logged in user." + operationId: "deleteUser" + produces: + - "application/json" + - "application/xml" + parameters: + - name: "username" + in: "path" + description: "The name that needs to be deleted" + required: true + type: "string" + responses: + 400: + description: "Invalid username supplied" + 404: + description: "User not found" +securityDefinitions: + api_key: + type: "apiKey" + name: "api_key" + in: "header" + petstore_auth: + type: "oauth2" + authorizationUrl: "http://petstore.swagger.io/api/oauth/dialog" + flow: "implicit" + scopes: + write:pets: "modify pets in your account" + read:pets: "read your pets" +definitions: + User: + properties: + id: + type: "integer" + format: "int64" + username: + type: "string" + firstName: + type: "string" + lastName: + type: "string" + email: + type: "string" + password: + type: "string" + phone: + type: "string" + userStatus: + type: "integer" + format: "int32" + description: "User Status" + xml: + name: "User" + Category: + properties: + id: + type: "integer" + format: "int64" + name: + type: "string" + xml: + name: "Category" + Pet: + required: + - "name" + - "photoUrls" + properties: + id: + type: "integer" + format: "int64" + category: + $ref: "#/definitions/Category" + name: + type: "string" + example: "doggie" + photoUrls: + type: "array" + xml: + name: "photoUrl" + wrapped: true + items: + type: "string" + tags: + type: "array" + xml: + name: "tag" + wrapped: true + items: + $ref: "#/definitions/Tag" + status: + type: "string" + description: "pet status in the store" + enum: + - "available" + - "pending" + - "sold" + xml: + name: "Pet" + Tag: + properties: + id: + type: "integer" + format: "int64" + name: + type: "string" + xml: + name: "Tag" + Order: + properties: + id: + type: "integer" + format: "int64" + petId: + type: "integer" + format: "int64" + quantity: + type: "integer" + format: "int32" + shipDate: + type: "string" + format: "date-time" + status: + type: "string" + description: "Order Status" + enum: + - "placed" + - "approved" + - "delivered" + complete: + type: "boolean" + xml: + name: "Order" diff --git a/samples/server/petstore/jaxrs/README.md b/samples/server/petstore/jaxrs/README.md index 00431f63dbc..ee5dba41872 100644 --- a/samples/server/petstore/jaxrs/README.md +++ b/samples/server/petstore/jaxrs/README.md @@ -12,3 +12,12 @@ To run the server, please execute the following: ``` mvn clean package jetty:run ``` + +You can then view the swagger listing here: + +``` +http://localhost:8080/v2/swagger.json +``` + +Note that if you have configured the `host` to be something other than localhost, the calls through +swagger-ui will be directed to that host and not localhost! \ No newline at end of file diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/ApiException.java b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/ApiException.java index 765ae959367..774fb35a355 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.JaxRSServerCodegen", date = "2015-11-05T22:31:25.130-08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-12-01T23:25:59.622+08:00") 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 9559bd394aa..384b1f1a7ce 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.JaxRSServerCodegen", date = "2015-11-05T22:31:25.130-08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-12-01T23:25:59.622+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/src/gen/java/io/swagger/api/ApiResponseMessage.java b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/ApiResponseMessage.java index 2460847cf6a..af9aceb63cc 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.JaxRSServerCodegen", date = "2015-11-05T22:31:25.130-08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-12-01T23:25:59.622+08:00") 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/NotFoundException.java b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/NotFoundException.java index 58dc8bcd1ad..363eb26f8fd 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.JaxRSServerCodegen", date = "2015-11-05T22:31:25.130-08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-12-01T23:25:59.622+08:00") 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 e8db743f900..7058e7da819 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 @@ -19,14 +19,16 @@ 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") @io.swagger.annotations.Api(description = "the pet API") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-11-05T22:31:25.130-08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-12-01T23:25:59.622+08:00") public class PetApi { private final PetApiService delegate = PetApiServiceFactory.getPetApi(); @@ -47,9 +49,9 @@ public class PetApi { @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) + 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); + return delegate.updatePet(body,securityContext); } @POST @@ -64,9 +66,9 @@ public class PetApi { @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) + public Response addPet(@ApiParam(value = "Pet object that needs to be added to the store" ) Pet body,@Context SecurityContext securityContext) throws NotFoundException { - return delegate.addPet(body); + return delegate.addPet(body,securityContext); } @GET @Path("/findByStatus") @@ -83,9 +85,9 @@ public class PetApi { @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") @QueryParam("status") List status) + public Response findPetsByStatus(@ApiParam(value = "Status values that need to be considered for filter", defaultValue="available") @QueryParam("status") List status,@Context SecurityContext securityContext) throws NotFoundException { - return delegate.findPetsByStatus(status); + return delegate.findPetsByStatus(status,securityContext); } @GET @Path("/findByTags") @@ -102,9 +104,9 @@ public class PetApi { @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) + public Response findPetsByTags(@ApiParam(value = "Tags to filter by") @QueryParam("tags") List tags,@Context SecurityContext securityContext) throws NotFoundException { - return delegate.findPetsByTags(tags); + return delegate.findPetsByTags(tags,securityContext); } @GET @Path("/{petId}") @@ -120,9 +122,9 @@ public class PetApi { @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) + 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); + return delegate.getPetById(petId,securityContext); } @POST @Path("/{petId}") @@ -137,11 +139,9 @@ public class PetApi { @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) + 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); + return delegate.updatePetWithForm(petId,name,status,securityContext); } @DELETE @Path("/{petId}") @@ -156,10 +156,9 @@ public class PetApi { @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid pet value", response = Void.class) }) - public Response deletePet(@ApiParam(value = "Pet id to delete",required=true) @PathParam("petId") Long petId, - @ApiParam(value = "" )@HeaderParam("api_key") String apiKey) + 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); + return delegate.deletePet(petId,apiKey,securityContext); } @POST @Path("/{petId}/uploadImage") @@ -174,12 +173,9 @@ public class PetApi { @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Void.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) + 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) throws NotFoundException { - return delegate.uploadFile(petId,additionalMetadata,fileDetail); + return delegate.uploadFile(petId,additionalMetadata,fileDetail,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 b7e1ead74cc..7ac9e1693af 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 @@ -17,32 +17,33 @@ 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 = "2015-11-05T22:31:25.130-08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-12-01T23:25:59.622+08:00") public abstract class PetApiService { - public abstract Response updatePet(Pet body) + public abstract Response updatePet(Pet body,SecurityContext securityContext) throws NotFoundException; - public abstract Response addPet(Pet body) + public abstract Response addPet(Pet body,SecurityContext securityContext) throws NotFoundException; - public abstract Response findPetsByStatus(List status) + public abstract Response findPetsByStatus(List status,SecurityContext securityContext) throws NotFoundException; - public abstract Response findPetsByTags(List tags) + public abstract Response findPetsByTags(List tags,SecurityContext securityContext) throws NotFoundException; - public abstract Response getPetById(Long petId) + public abstract Response getPetById(Long petId,SecurityContext securityContext) throws NotFoundException; - public abstract Response updatePetWithForm(String petId,String name,String status) + public abstract Response updatePetWithForm(String petId,String name,String status,SecurityContext securityContext) throws NotFoundException; - public abstract Response deletePet(Long petId,String apiKey) + public abstract Response deletePet(Long petId,String apiKey,SecurityContext securityContext) throws NotFoundException; - public abstract Response uploadFile(Long petId,String additionalMetadata,FormDataContentDisposition fileDetail) + public abstract Response uploadFile(Long petId,String additionalMetadata,FormDataContentDisposition fileDetail,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 7c9b500470a..0143cc89976 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 @@ -19,14 +19,16 @@ 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("/store") @io.swagger.annotations.Api(description = "the store API") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-11-05T22:31:25.130-08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-12-01T23:25:59.622+08:00") public class StoreApi { private final StoreApiService delegate = StoreApiServiceFactory.getStoreApi(); @@ -40,9 +42,9 @@ public class StoreApi { @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Integer.class, responseContainer = "Map") }) - public Response getInventory() + public Response getInventory(@Context SecurityContext securityContext) throws NotFoundException { - return delegate.getInventory(); + return delegate.getInventory(securityContext); } @POST @Path("/order") @@ -54,9 +56,9 @@ public class StoreApi { @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) + public Response placeOrder(@ApiParam(value = "order placed for purchasing the pet" ) Order body,@Context SecurityContext securityContext) throws NotFoundException { - return delegate.placeOrder(body); + return delegate.placeOrder(body,securityContext); } @GET @Path("/order/{orderId}") @@ -70,9 +72,9 @@ public class StoreApi { @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) + public Response getOrderById(@ApiParam(value = "ID of pet that needs to be fetched",required=true) @PathParam("orderId") String orderId,@Context SecurityContext securityContext) throws NotFoundException { - return delegate.getOrderById(orderId); + return delegate.getOrderById(orderId,securityContext); } @DELETE @Path("/order/{orderId}") @@ -84,9 +86,8 @@ public class StoreApi { @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) + public Response deleteOrder(@ApiParam(value = "ID of the order that needs to be deleted",required=true) @PathParam("orderId") String orderId,@Context SecurityContext securityContext) throws NotFoundException { - return delegate.deleteOrder(orderId); + return delegate.deleteOrder(orderId,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 721117cf3b3..f1f0714dd38 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 @@ -17,20 +17,21 @@ 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 = "2015-11-05T22:31:25.130-08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-12-01T23:25:59.622+08:00") public abstract class StoreApiService { - public abstract Response getInventory() + public abstract Response getInventory(SecurityContext securityContext) throws NotFoundException; - public abstract Response placeOrder(Order body) + public abstract Response placeOrder(Order body,SecurityContext securityContext) throws NotFoundException; - public abstract Response getOrderById(String orderId) + public abstract Response getOrderById(String orderId,SecurityContext securityContext) throws NotFoundException; - public abstract Response deleteOrder(String orderId) + public abstract Response deleteOrder(String orderId,SecurityContext securityContext) throws NotFoundException; } 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 718fbbe9a9a..f4018f7e94d 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 @@ -19,14 +19,16 @@ 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("/user") @io.swagger.annotations.Api(description = "the user API") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-11-05T22:31:25.130-08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-12-01T23:25:59.622+08:00") public class UserApi { private final UserApiService delegate = UserApiServiceFactory.getUserApi(); @@ -38,9 +40,9 @@ public class UserApi { @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) + public Response createUser(@ApiParam(value = "Created user object" ) User body,@Context SecurityContext securityContext) throws NotFoundException { - return delegate.createUser(body); + return delegate.createUser(body,securityContext); } @POST @Path("/createWithArray") @@ -50,9 +52,9 @@ public class UserApi { @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) + public Response createUsersWithArrayInput(@ApiParam(value = "List of user object" ) List body,@Context SecurityContext securityContext) throws NotFoundException { - return delegate.createUsersWithArrayInput(body); + return delegate.createUsersWithArrayInput(body,securityContext); } @POST @Path("/createWithList") @@ -62,9 +64,9 @@ public class UserApi { @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) + public Response createUsersWithListInput(@ApiParam(value = "List of user object" ) List body,@Context SecurityContext securityContext) throws NotFoundException { - return delegate.createUsersWithListInput(body); + return delegate.createUsersWithListInput(body,securityContext); } @GET @Path("/login") @@ -76,10 +78,9 @@ public class UserApi { @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) + 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) throws NotFoundException { - return delegate.loginUser(username,password); + return delegate.loginUser(username,password,securityContext); } @GET @Path("/logout") @@ -89,9 +90,9 @@ public class UserApi { @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Void.class) }) - public Response logoutUser() + public Response logoutUser(@Context SecurityContext securityContext) throws NotFoundException { - return delegate.logoutUser(); + return delegate.logoutUser(securityContext); } @GET @Path("/{username}") @@ -105,9 +106,9 @@ public class UserApi { @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) + 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); + return delegate.getUserByName(username,securityContext); } @PUT @Path("/{username}") @@ -119,10 +120,9 @@ public class UserApi { @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) + 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) throws NotFoundException { - return delegate.updateUser(username,body); + return delegate.updateUser(username,body,securityContext); } @DELETE @Path("/{username}") @@ -134,9 +134,8 @@ public class UserApi { @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) + 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); + 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 aebc957e25c..66437bebdc4 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 @@ -17,32 +17,33 @@ 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 = "2015-11-05T22:31:25.130-08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-12-01T23:25:59.622+08:00") public abstract class UserApiService { - public abstract Response createUser(User body) + public abstract Response createUser(User body,SecurityContext securityContext) throws NotFoundException; - public abstract Response createUsersWithArrayInput(List body) + public abstract Response createUsersWithArrayInput(List body,SecurityContext securityContext) throws NotFoundException; - public abstract Response createUsersWithListInput(List body) + public abstract Response createUsersWithListInput(List body,SecurityContext securityContext) throws NotFoundException; - public abstract Response loginUser(String username,String password) + public abstract Response loginUser(String username,String password,SecurityContext securityContext) throws NotFoundException; - public abstract Response logoutUser() + public abstract Response logoutUser(SecurityContext securityContext) throws NotFoundException; - public abstract Response getUserByName(String username) + public abstract Response getUserByName(String username,SecurityContext securityContext) throws NotFoundException; - public abstract Response updateUser(String username,User body) + public abstract Response updateUser(String username,User body,SecurityContext securityContext) throws NotFoundException; - public abstract Response deleteUser(String username) + public abstract Response deleteUser(String username,SecurityContext securityContext) throws NotFoundException; } 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 0acf355555c..023da1a9013 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 @@ -4,9 +4,11 @@ package io.swagger.model; import io.swagger.annotations.*; import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.Objects; + @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-11-05T22:31:25.130-08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-12-01T23:25:59.622+08:00") public class Category { private Long id = null; @@ -38,6 +40,24 @@ public class Category { + @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(); 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 07b422a67f5..cea0908230b 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 @@ -5,9 +5,11 @@ import java.util.Date; import io.swagger.annotations.*; import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.Objects; + @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-11-05T22:31:25.130-08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-12-01T23:25:59.622+08:00") public class Order { private Long id = null; @@ -95,6 +97,28 @@ public class Order { + @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(); 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 af735dcc3b2..6ce50aa3302 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,9 +7,11 @@ import java.util.*; import io.swagger.annotations.*; import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.Objects; + @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-11-05T22:31:25.130-08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-12-01T23:25:59.622+08:00") public class Pet { private Long id = null; @@ -97,6 +99,28 @@ public class Pet { + @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(); 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 1102fa408bf..e9d97e9fe05 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 @@ -4,9 +4,11 @@ package io.swagger.model; import io.swagger.annotations.*; import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.Objects; + @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-11-05T22:31:25.130-08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-12-01T23:25:59.622+08:00") public class Tag { private Long id = null; @@ -38,6 +40,24 @@ public class Tag { + @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(); 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 d170b2c7df0..6e17298795a 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 @@ -4,9 +4,11 @@ package io.swagger.model; import io.swagger.annotations.*; import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.Objects; + @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-11-05T22:31:25.130-08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-12-01T23:25:59.622+08:00") public class User { private Long id = null; @@ -117,6 +119,30 @@ public class User { + @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(); 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 5137ffe7912..1907ffd40a5 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 @@ -17,61 +17,62 @@ 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 = "2015-11-05T22:31:25.130-08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-11-23T10:25:42.314Z") public class PetApiServiceImpl extends PetApiService { @Override - public Response updatePet(Pet body) + 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) + 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) + 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) + 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) + 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) + 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) + 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,FormDataContentDisposition fileDetail) + public Response uploadFile(Long petId,String additionalMetadata,FormDataContentDisposition fileDetail,SecurityContext securityContext) throws NotFoundException { // do some magic! return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); diff --git a/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java b/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java index 4d9011b4943..c60547a73a0 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 @@ -17,33 +17,34 @@ 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 = "2015-11-05T22:31:25.130-08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-11-23T10:25:42.314Z") public class StoreApiServiceImpl extends StoreApiService { @Override - public Response getInventory() + 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) + 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) + 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) + public Response deleteOrder(String orderId,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 991849edc17..2c3f3edd1fd 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 @@ -17,61 +17,62 @@ 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 = "2015-11-05T22:31:25.130-08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-11-23T10:25:42.314Z") public class UserApiServiceImpl extends UserApiService { @Override - public Response createUser(User body) + 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) + 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) + 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) + 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() + 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) + 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) + 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) + 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/sinatra/api/pet_api.rb b/samples/server/petstore/sinatra/api/pet_api.rb index 5f995c531d8..7ccad2056b9 100644 --- a/samples/server/petstore/sinatra/api/pet_api.rb +++ b/samples/server/petstore/sinatra/api/pet_api.rb @@ -1,7 +1,7 @@ require 'json' -MyApp.add_route('PUT', '/pet', { +MyApp.add_route('PUT', '/v2/pet', { "resourcePath" => "/Pet", "summary" => "Update an existing pet", "nickname" => "update_pet", @@ -28,7 +28,7 @@ MyApp.add_route('PUT', '/pet', { end -MyApp.add_route('POST', '/pet', { +MyApp.add_route('POST', '/v2/pet', { "resourcePath" => "/Pet", "summary" => "Add a new pet to the store", "nickname" => "add_pet", @@ -55,7 +55,7 @@ MyApp.add_route('POST', '/pet', { end -MyApp.add_route('GET', '/pet/findByStatus', { +MyApp.add_route('GET', '/v2/pet/findByStatus', { "resourcePath" => "/Pet", "summary" => "Finds Pets by status", "nickname" => "find_pets_by_status", @@ -85,7 +85,7 @@ MyApp.add_route('GET', '/pet/findByStatus', { end -MyApp.add_route('GET', '/pet/findByTags', { +MyApp.add_route('GET', '/v2/pet/findByTags', { "resourcePath" => "/Pet", "summary" => "Finds Pets by tags", "nickname" => "find_pets_by_tags", @@ -115,7 +115,7 @@ MyApp.add_route('GET', '/pet/findByTags', { end -MyApp.add_route('GET', '/pet/{petId}', { +MyApp.add_route('GET', '/v2/pet/{petId}', { "resourcePath" => "/Pet", "summary" => "Find pet by ID", "nickname" => "get_pet_by_id", @@ -142,7 +142,7 @@ MyApp.add_route('GET', '/pet/{petId}', { end -MyApp.add_route('POST', '/pet/{petId}', { +MyApp.add_route('POST', '/v2/pet/{petId}', { "resourcePath" => "/Pet", "summary" => "Updates a pet in the store with form data", "nickname" => "update_pet_with_form", @@ -169,7 +169,7 @@ MyApp.add_route('POST', '/pet/{petId}', { end -MyApp.add_route('DELETE', '/pet/{petId}', { +MyApp.add_route('DELETE', '/v2/pet/{petId}', { "resourcePath" => "/Pet", "summary" => "Deletes a pet", "nickname" => "delete_pet", @@ -203,7 +203,7 @@ MyApp.add_route('DELETE', '/pet/{petId}', { end -MyApp.add_route('POST', '/pet/{petId}/uploadImage', { +MyApp.add_route('POST', '/v2/pet/{petId}/uploadImage', { "resourcePath" => "/Pet", "summary" => "uploads an image", "nickname" => "upload_file", diff --git a/samples/server/petstore/sinatra/api/store_api.rb b/samples/server/petstore/sinatra/api/store_api.rb index 24498387412..37938b304db 100644 --- a/samples/server/petstore/sinatra/api/store_api.rb +++ b/samples/server/petstore/sinatra/api/store_api.rb @@ -1,7 +1,7 @@ require 'json' -MyApp.add_route('GET', '/store/inventory', { +MyApp.add_route('GET', '/v2/store/inventory', { "resourcePath" => "/Store", "summary" => "Returns pet inventories by status", "nickname" => "get_inventory", @@ -21,7 +21,7 @@ MyApp.add_route('GET', '/store/inventory', { end -MyApp.add_route('POST', '/store/order', { +MyApp.add_route('POST', '/v2/store/order', { "resourcePath" => "/Store", "summary" => "Place an order for a pet", "nickname" => "place_order", @@ -48,7 +48,7 @@ MyApp.add_route('POST', '/store/order', { end -MyApp.add_route('GET', '/store/order/{orderId}', { +MyApp.add_route('GET', '/v2/store/order/{orderId}', { "resourcePath" => "/Store", "summary" => "Find purchase order by ID", "nickname" => "get_order_by_id", @@ -75,7 +75,7 @@ MyApp.add_route('GET', '/store/order/{orderId}', { end -MyApp.add_route('DELETE', '/store/order/{orderId}', { +MyApp.add_route('DELETE', '/v2/store/order/{orderId}', { "resourcePath" => "/Store", "summary" => "Delete purchase order by ID", "nickname" => "delete_order", diff --git a/samples/server/petstore/sinatra/api/user_api.rb b/samples/server/petstore/sinatra/api/user_api.rb index 98f50549ba1..7b890004891 100644 --- a/samples/server/petstore/sinatra/api/user_api.rb +++ b/samples/server/petstore/sinatra/api/user_api.rb @@ -1,7 +1,7 @@ require 'json' -MyApp.add_route('POST', '/user', { +MyApp.add_route('POST', '/v2/user', { "resourcePath" => "/User", "summary" => "Create user", "nickname" => "create_user", @@ -28,7 +28,7 @@ MyApp.add_route('POST', '/user', { end -MyApp.add_route('POST', '/user/createWithArray', { +MyApp.add_route('POST', '/v2/user/createWithArray', { "resourcePath" => "/User", "summary" => "Creates list of users with given input array", "nickname" => "create_users_with_array_input", @@ -55,7 +55,7 @@ MyApp.add_route('POST', '/user/createWithArray', { end -MyApp.add_route('POST', '/user/createWithList', { +MyApp.add_route('POST', '/v2/user/createWithList', { "resourcePath" => "/User", "summary" => "Creates list of users with given input array", "nickname" => "create_users_with_list_input", @@ -82,7 +82,7 @@ MyApp.add_route('POST', '/user/createWithList', { end -MyApp.add_route('GET', '/user/login', { +MyApp.add_route('GET', '/v2/user/login', { "resourcePath" => "/User", "summary" => "Logs user into the system", "nickname" => "login_user", @@ -122,7 +122,7 @@ MyApp.add_route('GET', '/user/login', { end -MyApp.add_route('GET', '/user/logout', { +MyApp.add_route('GET', '/v2/user/logout', { "resourcePath" => "/User", "summary" => "Logs out current logged in user session", "nickname" => "logout_user", @@ -142,7 +142,7 @@ MyApp.add_route('GET', '/user/logout', { end -MyApp.add_route('GET', '/user/{username}', { +MyApp.add_route('GET', '/v2/user/{username}', { "resourcePath" => "/User", "summary" => "Get user by user name", "nickname" => "get_user_by_name", @@ -154,7 +154,7 @@ MyApp.add_route('GET', '/user/{username}', { { "name" => "username", - "description" => "The name that needs to be fetched. Use user1 for testing. ", + "description" => "The name that needs to be fetched. Use user1 for testing.", "dataType" => "string", "paramType" => "path", }, @@ -169,7 +169,7 @@ MyApp.add_route('GET', '/user/{username}', { end -MyApp.add_route('PUT', '/user/{username}', { +MyApp.add_route('PUT', '/v2/user/{username}', { "resourcePath" => "/User", "summary" => "Updated user", "nickname" => "update_user", @@ -203,7 +203,7 @@ MyApp.add_route('PUT', '/user/{username}', { end -MyApp.add_route('DELETE', '/user/{username}', { +MyApp.add_route('DELETE', '/v2/user/{username}', { "resourcePath" => "/User", "summary" => "Delete user", "nickname" => "delete_user", diff --git a/samples/server/petstore/sinatra/lib/swaggering.rb b/samples/server/petstore/sinatra/lib/swaggering.rb index 79aca1da2c9..1357bb19134 100644 --- a/samples/server/petstore/sinatra/lib/swaggering.rb +++ b/samples/server/petstore/sinatra/lib/swaggering.rb @@ -26,14 +26,22 @@ class Swaggering < Sinatra::Base cross_origin Swaggering.to_resource_listing } + + # for swagger.yaml + get("/swagger.yaml") { + cross_origin + File.read("./swagger.yaml"); + } + @@configuration ||= Configuration.new yield(@@configuration) if block_given? end def self.add_route(method, path, swag={}, opts={}, &block) - fullPath = swag["resourcePath"].to_s + @@configuration.format_specifier + path + #fullPath = swag["resourcePath"].to_s + @@configuration.format_specifier + path + fullPath = path.gsub(/{(.*)}/, ':\1') - accepted = case method + accepted = case method.to_s.downcase when 'get' get(fullPath, opts, &block) true @@ -47,6 +55,7 @@ class Swaggering < Sinatra::Base put(fullPath, opts, &block) true else + puts "Error adding route: #{method} #{fullPath}" false end diff --git a/samples/server/petstore/sinatra/my_app.rb b/samples/server/petstore/sinatra/my_app.rb index 9f4d991d0f1..33376ef311d 100644 --- a/samples/server/petstore/sinatra/my_app.rb +++ b/samples/server/petstore/sinatra/my_app.rb @@ -7,3 +7,7 @@ class MyApp < Swaggering end end +# include the api files +Dir["./api/*.rb"].each { |file| + require file +} diff --git a/samples/server/petstore/sinatra/swagger.yaml b/samples/server/petstore/sinatra/swagger.yaml new file mode 100644 index 00000000000..49a3405de09 --- /dev/null +++ b/samples/server/petstore/sinatra/swagger.yaml @@ -0,0 +1,667 @@ +--- +swagger: "2.0" +info: + description: "This is a sample server Petstore server. You can find out more about\ + \ Swagger at http://swagger.io or on irc.freenode.net,\ + \ #swagger. For this sample, you can use the api key \"special-key\" to test\ + \ the authorization filters" + version: "1.0.0" + title: "Swagger Petstore" + termsOfService: "http://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" +schemes: +- "http" +paths: + /pet: + post: + tags: + - "pet" + summary: "Add a new pet to the store" + description: "" + operationId: "addPet" + consumes: + - "application/json" + - "application/xml" + produces: + - "application/json" + - "application/xml" + parameters: + - in: "body" + name: "body" + description: "Pet object that needs to be added to the store" + required: false + schema: + $ref: "#/definitions/Pet" + responses: + 405: + description: "Invalid input" + security: + - petstore_auth: + - "write:pets" + - "read:pets" + put: + tags: + - "pet" + summary: "Update an existing pet" + description: "" + operationId: "updatePet" + consumes: + - "application/json" + - "application/xml" + produces: + - "application/json" + - "application/xml" + parameters: + - in: "body" + name: "body" + description: "Pet object that needs to be added to the store" + required: false + schema: + $ref: "#/definitions/Pet" + responses: + 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 seperated strings" + operationId: "findPetsByStatus" + produces: + - "application/json" + - "application/xml" + parameters: + - name: "status" + in: "query" + description: "Status values that need to be considered for filter" + required: false + type: "array" + items: + type: "string" + collectionFormat: "multi" + default: "available" + responses: + 200: + description: "successful operation" + schema: + type: "array" + items: + $ref: "#/definitions/Pet" + 400: + description: "Invalid status value" + security: + - petstore_auth: + - "write:pets" + - "read:pets" + /pet/findByTags: + get: + tags: + - "pet" + summary: "Finds Pets by tags" + description: "Muliple tags can be provided with comma seperated strings. Use\ + \ tag1, tag2, tag3 for testing." + operationId: "findPetsByTags" + produces: + - "application/json" + - "application/xml" + parameters: + - name: "tags" + in: "query" + description: "Tags to filter by" + required: false + type: "array" + items: + type: "string" + collectionFormat: "multi" + responses: + 200: + description: "successful operation" + schema: + type: "array" + items: + $ref: "#/definitions/Pet" + 400: + description: "Invalid tag value" + security: + - petstore_auth: + - "write:pets" + - "read:pets" + /pet/{petId}: + get: + tags: + - "pet" + summary: "Find pet by ID" + description: "Returns a pet when ID < 10. ID > 10 or nonintegers will simulate\ + \ API error conditions" + operationId: "getPetById" + produces: + - "application/json" + - "application/xml" + parameters: + - name: "petId" + in: "path" + description: "ID of pet that needs to be fetched" + required: true + type: "integer" + format: "int64" + responses: + 200: + description: "successful operation" + schema: + $ref: "#/definitions/Pet" + 400: + description: "Invalid ID supplied" + 404: + description: "Pet not found" + security: + - api_key: [] + - petstore_auth: + - "write:pets" + - "read:pets" + post: + tags: + - "pet" + summary: "Updates a pet in the store with form data" + description: "" + operationId: "updatePetWithForm" + consumes: + - "application/x-www-form-urlencoded" + produces: + - "application/json" + - "application/xml" + parameters: + - name: "petId" + in: "path" + description: "ID of pet that needs to be updated" + required: true + type: "string" + - name: "name" + in: "formData" + description: "Updated name of the pet" + required: false + type: "string" + - name: "status" + in: "formData" + description: "Updated status of the pet" + required: false + type: "string" + responses: + 405: + description: "Invalid input" + security: + - petstore_auth: + - "write:pets" + - "read:pets" + delete: + tags: + - "pet" + summary: "Deletes a pet" + description: "" + operationId: "deletePet" + produces: + - "application/json" + - "application/xml" + parameters: + - name: "api_key" + in: "header" + description: "" + required: false + type: "string" + - name: "petId" + in: "path" + description: "Pet id to delete" + required: true + type: "integer" + format: "int64" + responses: + 400: + description: "Invalid pet value" + security: + - petstore_auth: + - "write:pets" + - "read:pets" + /pet/{petId}/uploadImage: + post: + tags: + - "pet" + summary: "uploads an image" + description: "" + operationId: "uploadFile" + consumes: + - "multipart/form-data" + produces: + - "application/json" + - "application/xml" + parameters: + - name: "petId" + in: "path" + description: "ID of pet to update" + required: true + type: "integer" + format: "int64" + - name: "additionalMetadata" + in: "formData" + description: "Additional data to pass to server" + required: false + type: "string" + - name: "file" + in: "formData" + description: "file to upload" + required: false + type: "file" + responses: + default: + description: "successful operation" + security: + - petstore_auth: + - "write:pets" + - "read:pets" + /store/inventory: + get: + tags: + - "store" + summary: "Returns pet inventories by status" + description: "Returns a map of status codes to quantities" + operationId: "getInventory" + produces: + - "application/json" + - "application/xml" + 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/json" + - "application/xml" + parameters: + - in: "body" + name: "body" + description: "order placed for purchasing the pet" + required: false + schema: + $ref: "#/definitions/Order" + responses: + 200: + description: "successful operation" + schema: + $ref: "#/definitions/Order" + 400: + description: "Invalid Order" + /store/order/{orderId}: + get: + tags: + - "store" + summary: "Find purchase order by ID" + description: "For valid response try integer IDs with value <= 5 or > 10. Other\ + \ values will generated exceptions" + operationId: "getOrderById" + produces: + - "application/json" + - "application/xml" + parameters: + - name: "orderId" + in: "path" + description: "ID of pet that needs to be fetched" + required: true + type: "string" + responses: + 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/json" + - "application/xml" + parameters: + - name: "orderId" + in: "path" + description: "ID of the order that needs to be deleted" + required: true + type: "string" + responses: + 400: + description: "Invalid ID supplied" + 404: + description: "Order not found" + /user: + post: + tags: + - "user" + summary: "Create user" + description: "This can only be done by the logged in user." + operationId: "createUser" + produces: + - "application/json" + - "application/xml" + parameters: + - in: "body" + name: "body" + description: "Created user object" + required: false + schema: + $ref: "#/definitions/User" + responses: + default: + description: "successful operation" + /user/createWithArray: + post: + tags: + - "user" + summary: "Creates list of users with given input array" + description: "" + operationId: "createUsersWithArrayInput" + produces: + - "application/json" + - "application/xml" + parameters: + - in: "body" + name: "body" + description: "List of user object" + required: false + schema: + type: "array" + items: + $ref: "#/definitions/User" + responses: + default: + description: "successful operation" + /user/createWithList: + post: + tags: + - "user" + summary: "Creates list of users with given input array" + description: "" + operationId: "createUsersWithListInput" + produces: + - "application/json" + - "application/xml" + parameters: + - in: "body" + name: "body" + description: "List of user object" + required: false + schema: + type: "array" + items: + $ref: "#/definitions/User" + responses: + default: + description: "successful operation" + /user/login: + get: + tags: + - "user" + summary: "Logs user into the system" + description: "" + operationId: "loginUser" + produces: + - "application/json" + - "application/xml" + parameters: + - name: "username" + in: "query" + description: "The user name for login" + required: false + type: "string" + - name: "password" + in: "query" + description: "The password for login in clear text" + required: false + type: "string" + responses: + 200: + description: "successful operation" + schema: + type: "string" + 400: + description: "Invalid username/password supplied" + /user/logout: + get: + tags: + - "user" + summary: "Logs out current logged in user session" + description: "" + operationId: "logoutUser" + produces: + - "application/json" + - "application/xml" + parameters: [] + responses: + default: + description: "successful operation" + /user/{username}: + get: + tags: + - "user" + summary: "Get user by user name" + description: "" + operationId: "getUserByName" + produces: + - "application/json" + - "application/xml" + parameters: + - name: "username" + in: "path" + description: "The name that needs to be fetched. Use user1 for testing. " + required: true + type: "string" + responses: + 200: + 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" + put: + tags: + - "user" + summary: "Updated user" + description: "This can only be done by the logged in user." + operationId: "updateUser" + produces: + - "application/json" + - "application/xml" + parameters: + - name: "username" + in: "path" + description: "name that need to be deleted" + required: true + type: "string" + - in: "body" + name: "body" + description: "Updated user object" + required: false + schema: + $ref: "#/definitions/User" + responses: + 400: + description: "Invalid user supplied" + 404: + description: "User not found" + delete: + tags: + - "user" + summary: "Delete user" + description: "This can only be done by the logged in user." + operationId: "deleteUser" + produces: + - "application/json" + - "application/xml" + parameters: + - name: "username" + in: "path" + description: "The name that needs to be deleted" + required: true + type: "string" + responses: + 400: + description: "Invalid username supplied" + 404: + description: "User not found" +securityDefinitions: + api_key: + type: "apiKey" + name: "api_key" + in: "header" + petstore_auth: + type: "oauth2" + authorizationUrl: "http://petstore.swagger.io/api/oauth/dialog" + flow: "implicit" + scopes: + write:pets: "modify pets in your account" + read:pets: "read your pets" +definitions: + User: + properties: + id: + type: "integer" + format: "int64" + username: + type: "string" + firstName: + type: "string" + lastName: + type: "string" + email: + type: "string" + password: + type: "string" + phone: + type: "string" + userStatus: + type: "integer" + format: "int32" + description: "User Status" + xml: + name: "User" + Category: + properties: + id: + type: "integer" + format: "int64" + name: + type: "string" + xml: + name: "Category" + Pet: + required: + - "name" + - "photoUrls" + properties: + id: + type: "integer" + format: "int64" + category: + $ref: "#/definitions/Category" + name: + type: "string" + example: "doggie" + photoUrls: + type: "array" + xml: + name: "photoUrl" + wrapped: true + items: + type: "string" + tags: + type: "array" + xml: + name: "tag" + wrapped: true + items: + $ref: "#/definitions/Tag" + status: + type: "string" + description: "pet status in the store" + enum: + - "available" + - "pending" + - "sold" + xml: + name: "Pet" + Tag: + properties: + id: + type: "integer" + format: "int64" + name: + type: "string" + xml: + name: "Tag" + Order: + properties: + id: + type: "integer" + format: "int64" + petId: + type: "integer" + format: "int64" + quantity: + type: "integer" + format: "int32" + shipDate: + type: "string" + format: "date-time" + status: + type: "string" + description: "Order Status" + enum: + - "placed" + - "approved" + - "delivered" + complete: + type: "boolean" + xml: + name: "Order" diff --git a/samples/server/petstore/slim/SwaggerServer/.htaccess b/samples/server/petstore/slim/SwaggerServer/.htaccess new file mode 100644 index 00000000000..e47b5fb8a0c --- /dev/null +++ b/samples/server/petstore/slim/SwaggerServer/.htaccess @@ -0,0 +1,5 @@ + + RewriteEngine On + RewriteCond %{REQUEST_FILENAME} !-f + RewriteRule ^(.*)$ index.php?_url=/$1 [QSA,L] + \ No newline at end of file diff --git a/samples/server/petstore/slim/SwaggerServer/README.md b/samples/server/petstore/slim/SwaggerServer/README.md new file mode 100644 index 00000000000..3b19f46bd38 --- /dev/null +++ b/samples/server/petstore/slim/SwaggerServer/README.md @@ -0,0 +1,10 @@ +# 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/swagger-api/swagger-core/wiki) from a remote server, you can easily generate a server stub. This +is an example of building a PHP server. + +This example uses the [Slim Framework](http://www.slimframework.com/). To see how to make this your own, please take a look at the template here: + +[TEMPLATES](https://github.com/swagger-api/swagger-codegen/tree/master/modules/swagger-codegen/src/main/resources/slim/) diff --git a/samples/server/petstore/slim/SwaggerServer/composer.json b/samples/server/petstore/slim/SwaggerServer/composer.json new file mode 100644 index 00000000000..c55c8181765 --- /dev/null +++ b/samples/server/petstore/slim/SwaggerServer/composer.json @@ -0,0 +1,6 @@ +{ + "minimum-stability": "RC", + "require": { + "slim/slim": "3.*" + } +} \ No newline at end of file diff --git a/samples/server/petstore/slim/SwaggerServer/index.php b/samples/server/petstore/slim/SwaggerServer/index.php new file mode 100644 index 00000000000..1db11f806fb --- /dev/null +++ b/samples/server/petstore/slim/SwaggerServer/index.php @@ -0,0 +1,336 @@ +POST('/user', function($request, $response, $args) { + + + + $body = $request->getParsedBody(); + $response->write('How about implementing createUser as a POST method ?'); + return $response; + }); + + +/** + * POST createUsersWithArrayInput + * Summary: Creates list of users with given input array + * Notes: + * Output-Formats: [application/xml, application/json] + */ +$app->POST('/user/createWithArray', function($request, $response, $args) { + + + + $body = $request->getParsedBody(); + $response->write('How about implementing createUsersWithArrayInput as a POST method ?'); + return $response; + }); + + +/** + * POST createUsersWithListInput + * Summary: Creates list of users with given input array + * Notes: + * Output-Formats: [application/xml, application/json] + */ +$app->POST('/user/createWithList', function($request, $response, $args) { + + + + $body = $request->getParsedBody(); + $response->write('How about implementing createUsersWithListInput as a POST method ?'); + return $response; + }); + + +/** + * GET loginUser + * Summary: Logs user into the system + * Notes: + * Output-Formats: [application/xml, application/json] + */ +$app->GET('/user/login', function($request, $response, $args) { + + $queryParams = $request->getQueryParams(); + $username = $queryParams['username']; $password = $queryParams['password']; + + + $response->write('How about implementing loginUser as a GET method ?'); + return $response; + }); + + +/** + * GET logoutUser + * Summary: Logs out current logged in user session + * Notes: + * Output-Formats: [application/xml, application/json] + */ +$app->GET('/user/logout', function($request, $response, $args) { + + + + + $response->write('How about implementing logoutUser as a GET method ?'); + return $response; + }); + + +/** + * GET getUserByName + * Summary: Get user by user name + * Notes: + * Output-Formats: [application/xml, application/json] + */ +$app->GET('/user/{username}', function($request, $response, $args) { + + + + + $response->write('How about implementing getUserByName as a GET method ?'); + return $response; + }); + + +/** + * PUT updateUser + * Summary: Updated user + * Notes: This can only be done by the logged in user. + * Output-Formats: [application/xml, application/json] + */ +$app->PUT('/user/{username}', function($request, $response, $args) { + + + + $body = $request->getParsedBody(); + $response->write('How about implementing updateUser as a PUT method ?'); + return $response; + }); + + +/** + * DELETE deleteUser + * Summary: Delete user + * Notes: This can only be done by the logged in user. + * Output-Formats: [application/xml, application/json] + */ +$app->DELETE('/user/{username}', function($request, $response, $args) { + + + + + $response->write('How about implementing deleteUser as a DELETE method ?'); + return $response; + }); + + +/** + * GET getInventory + * Summary: Returns pet inventories by status + * Notes: Returns a map of status codes to quantities + * Output-Formats: [application/json] + */ +$app->GET('/store/inventory', function($request, $response, $args) { + + + + + $response->write('How about implementing getInventory as a GET method ?'); + return $response; + }); + + +/** + * POST placeOrder + * Summary: Place an order for a pet + * Notes: + * Output-Formats: [application/xml, application/json] + */ +$app->POST('/store/order', function($request, $response, $args) { + + + + $body = $request->getParsedBody(); + $response->write('How about implementing placeOrder as a POST method ?'); + return $response; + }); + + +/** + * GET getOrderById + * Summary: Find purchase order by ID + * Notes: For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * Output-Formats: [application/xml, application/json] + */ +$app->GET('/store/order/{orderId}', function($request, $response, $args) { + + + + + $response->write('How about implementing getOrderById as a GET method ?'); + return $response; + }); + + +/** + * DELETE deleteOrder + * Summary: Delete purchase order by ID + * Notes: For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * Output-Formats: [application/xml, application/json] + */ +$app->DELETE('/store/order/{orderId}', function($request, $response, $args) { + + + + + $response->write('How about implementing deleteOrder as a DELETE method ?'); + return $response; + }); + + +/** + * PUT updatePet + * Summary: Update an existing pet + * Notes: + * Output-Formats: [application/xml, application/json] + */ +$app->PUT('/pet', function($request, $response, $args) { + + + + $body = $request->getParsedBody(); + $response->write('How about implementing updatePet as a PUT method ?'); + return $response; + }); + + +/** + * POST addPet + * Summary: Add a new pet to the store + * Notes: + * Output-Formats: [application/xml, application/json] + */ +$app->POST('/pet', function($request, $response, $args) { + + + + $body = $request->getParsedBody(); + $response->write('How about implementing addPet as a POST method ?'); + return $response; + }); + + +/** + * GET findPetsByStatus + * Summary: Finds Pets by status + * Notes: Multiple status values can be provided with comma seperated strings + * Output-Formats: [application/xml, application/json] + */ +$app->GET('/pet/findByStatus', function($request, $response, $args) { + + $queryParams = $request->getQueryParams(); + $status = $queryParams['status']; + + + $response->write('How about implementing findPetsByStatus as a GET method ?'); + return $response; + }); + + +/** + * GET findPetsByTags + * Summary: Finds Pets by tags + * Notes: Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + * Output-Formats: [application/xml, application/json] + */ +$app->GET('/pet/findByTags', function($request, $response, $args) { + + $queryParams = $request->getQueryParams(); + $tags = $queryParams['tags']; + + + $response->write('How about implementing findPetsByTags as a GET method ?'); + return $response; + }); + + +/** + * GET getPetById + * Summary: Find pet by ID + * Notes: Returns a single pet + * Output-Formats: [application/xml, application/json] + */ +$app->GET('/pet/{petId}', function($request, $response, $args) { + + + + + $response->write('How about implementing getPetById as a GET method ?'); + return $response; + }); + + +/** + * POST updatePetWithForm + * Summary: Updates a pet in the store with form data + * Notes: + * Output-Formats: [application/xml, application/json] + */ +$app->POST('/pet/{petId}', function($request, $response, $args) { + + + $name = $args['name']; $status = $args['status']; + + $response->write('How about implementing updatePetWithForm as a POST method ?'); + return $response; + }); + + +/** + * DELETE deletePet + * Summary: Deletes a pet + * Notes: + * Output-Formats: [application/xml, application/json] + */ +$app->DELETE('/pet/{petId}', function($request, $response, $args) { + $headers = $request->getHeaders(); + + + + $response->write('How about implementing deletePet as a DELETE method ?'); + return $response; + }); + + +/** + * POST uploadFile + * Summary: uploads an image + * Notes: + * Output-Formats: [application/json] + */ +$app->POST('/pet/{petId}/uploadImage', function($request, $response, $args) { + + + $additionalMetadata = $args['additionalMetadata']; $file = $args['file']; + + $response->write('How about implementing uploadFile as a POST method ?'); + return $response; + }); + + + +$app->run(); diff --git a/samples/server/petstore/slim/SwaggerServer/lib/models/ApiResponse.php b/samples/server/petstore/slim/SwaggerServer/lib/models/ApiResponse.php new file mode 100644 index 00000000000..25779f3fc34 --- /dev/null +++ b/samples/server/petstore/slim/SwaggerServer/lib/models/ApiResponse.php @@ -0,0 +1,18 @@ +