diff --git a/.gitignore b/.gitignore index 0dc52799236..2e1d1355309 100644 --- a/.gitignore +++ b/.gitignore @@ -91,13 +91,19 @@ samples/client/petstore/swift/SwaggerClientTests/Pods/Pods.xcodeproj/xcshareddat samples/client/petstore/csharp/SwaggerClientTest/.vs samples/client/petstore/csharp/SwaggerClientTest/obj samples/client/petstore/csharp/SwaggerClientTest/bin -samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/vendor/ +samples/client/petstore/csharp/SwaggerClientTest/packages samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/ samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/ -samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/nuget.exe samples/client/petstore/csharp/SwaggerClientTest/TestResult.xml samples/client/petstore/csharp/SwaggerClientTest/nuget.exe samples/client/petstore/csharp/SwaggerClientTest/testrunner/ +samples/client/petstore/csharp/SwaggerClient/.vs +samples/client/petstore/csharp/SwaggerClient/nuget.exe +samples/client/petstore/csharp/SwaggerClient/obj +samples/client/petstore/csharp/SwaggerClient/bin +samples/client/petstore/csharp/SwaggerClient/obj/Debug/ +samples/client/petstore/csharp/SwaggerClient/bin/Debug/ +samples/client/petstore/csharp/SwaggerClient/packages # Python *.pyc @@ -107,3 +113,16 @@ samples/client/petstore/python/swagger_client.egg-info/SOURCES.txt samples/client/petstore/python/.coverage samples/client/petstore/python/.projectile samples/client/petstore/python/.venv/ + +# ts +samples/client/petstore/typescript-node/npm/node_modules +samples/client/petstore/typescript-fetch/with-package-metadata/node_modules +samples/client/petstore/typescript-fetch/with-package-metadata/dist +samples/client/petstore/typescript-fetch/with-package-metadata/typings +samples/client/petstore/typescript-fetch/default/node_modules +samples/client/petstore/typescript-fetch/default/dist +samples/client/petstore/typescript-fetch/default/typings +samples/client/petstore/typescript-fetch/default-es6/node_modules +samples/client/petstore/typescript-fetch/default-es6/dist +samples/client/petstore/typescript-fetch/default-es6/typings + diff --git a/README.md b/README.md index 5d43198847d..bce750740c7 100644 --- a/README.md +++ b/README.md @@ -51,6 +51,7 @@ Check out [Swagger-Spec](https://github.com/OAI/OpenAPI-Specification) for addit - [Java JAX-RS (Apache CXF 2 / 3)](#java-jax-rs-apache-cxf-2--3) - [Java JAX-RS (Resteasy)](#java-jax-rs-resteasy) - [Java Spring MVC](#java-spring-mvc) + - [Java SpringBoot](#java-springboot) - [Haskell Servant](#haskell-servant) - [ASP.NET 5 Web API](#aspnet-5-web-api) - [To build the codegen library](#to-build-the-codegen-library) @@ -59,6 +60,7 @@ Check out [Swagger-Spec](https://github.com/OAI/OpenAPI-Specification) for addit - [Online Generators](#online-generators) - [Guidelines for Contribution](https://github.com/swagger-api/swagger-codegen/wiki/Guidelines-for-Contribution) - [Companies/Projects using Swagger Codegen](#companiesprojects-using-swagger-codegen) + - [Swagger Codegen Core Team](#swagger-codegen-core-team) - [License](#license) @@ -688,6 +690,31 @@ java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate \ -o samples/server/petstore/spring-mvc ``` +### Java SpringBoot + +``` +java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate \ + -i http://petstore.swagger.io/v2/swagger.json \ + -l springboot \ + -o samples/server/petstore/springboot +``` + +You can also set a Json file with basePackage & configPackage properties : +Example : +``` +{ +"basePackage":"io.swagger", +"configPackage":"io.swagger.config" +} +``` +For use it add option ```-c myOptions.json``` to the generation command + +To Use-it : +in the generated folder try ``` mvn package ``` for build jar. +Start your server ``` java -jar target/swagger-springboot-server-1.0.0.jar ``` +SpringBoot listening on default port 8080 + + ### Haskell Servant ``` @@ -763,6 +790,7 @@ Here are some companies/projects using Swagger Codegen in production. To add you - [Acunetix](https://www.acunetix.com/) - [Atlassian](https://www.atlassian.com/) - [beemo](http://www.beemo.eu) +- [bitly](https://bitly.com) - [Cachet Financial](http://www.cachetfinancial.com/) - [CloudBoost](https://www.CloudBoost.io/) - [Cupix](http://www.cupix.com) @@ -779,9 +807,12 @@ Here are some companies/projects using Swagger Codegen in production. To add you - [nViso](http://www.nviso.ch/) - [Okiok](https://www.okiok.com) - [OSDN](https://osdn.jp) +- [PagerDuty](https://www.pagerduty.com) +- [Pepipost](https://www.pepipost.com) - [Pixoneye](http://www.pixoneye.com/) - [PostAffiliatePro](https://www.postaffiliatepro.com/) - [Reload! A/S](https://reload.dk/) +- [REstore](https://www.restore.eu) - [Royal Bank of Canada (RBC)](http://www.rbc.com/canada.html) - [SmartRecruiters](https://www.smartrecruiters.com/) - [StyleRecipe](http://stylerecipe.co.jp) @@ -790,7 +821,92 @@ Here are some companies/projects using Swagger Codegen in production. To add you - [uShip](https://www.uship.com/) - [Zalando](https://tech.zalando.com) - [ZEEF.com](https://zeef.com/) -- [REstore](https://www.restore.eu) + +# Swagger Codegen Core Team + +Swaagger Codegen core team members are contributors who have been making signficiant contributions (review issues, fix bugs, make enhancements, etc) to the project on a regular basis. + +## API Clients +| Langauges | Core Team (join date) | +|:-------------|:-------------| +| ActionScript | | +| C++ | | +| C# | @jimschubert (2016/05/01) | | +| Clojure | @xhh (2016/05/01) | +| Dart | | +| Groovy | | +| Go | @guohuang (2016/05/01) @neilotoole (2016/05/01) | +| Java | @cbornet (2016/05/01) @xhh (2016/05/01) | +| NodeJS/Javascript | @xhh (2016/05/01) | +| ObjC | @mateuszmackowiak (2016/05/09) | +| Perl | @wing328 (2016/05/01) | +| PHP | @arnested (2016/05/01) | +| Python | @scottrw93 (2016/05/01) | +| Ruby | @wing328 (2016/05/01) | +| Scala | | +| Swift | @jaz-ah (2016/05/01) @Edubits (2016/05/01) | +| TypeScript (Node) | @Vrolijkx (2016/05/01) | +| TypeScript (Angular1) | @Vrolijkx (2016/05/01) | +| TypeScript (Angular2) | @Vrolijkx (2016/05/01) | +| TypeScript (Fetch) | | +## Server Stubs +| Langauges | Core Team (date joined) | +|:------------- |:-------------| +| C# ASP.NET5 | @jimschubert (2016/05/01) | +| Haskell Servant | | +| Java Spring Boot | | +| Java SpringMVC | @kolyjjj (2016/05/01) | +| Java JAX-RS | | +| NodeJS | @kolyjjj (2016/05/01) | +| PHP Lumen | @abcsum (2016/05/01) | +| PHP Silex | | +| PHP Slim | | +| Python Flask | | +| Ruby Sinatra | @wing328 (2016/05/01) | | +| Scala Scalatra | | | + +## Template Creator +Here is a list of template creators: + * API Clients: + * Akka-Scala: @cchafer + * C# (.NET 2.0): @who + * Clojure: @xhh + * Dart: @yissachar + * Groovy: @victorgit + * Go: @wing328 + * Java (Retrofit): @0legg + * Java (Retrofi2): @emilianobonassi + * Java (Jersey2): @xhh + * Java (okhttp-gson): @xhh + * Javascript/NodeJS: @jfiala + * Javascript (Closure-annotated Angular) @achew22 + * Perl: @wing328 + * Swift: @tkqubo + * TypeScript (Node): @mhardorf + * TypeScript (Angular1): @mhardorf + * TypeScript (Fetch): @leonyu + * TypeScript (Angular2): @roni-frantchi + * Server Stubs + * C# ASP.NET5: @jimschubert + * Haskell Servant: @algas + * Java Spring Boot: @diyfr + * JAX-RS RestEasy: @chameleon82 + * JAX-RS CXF: @hiveship + * PHP Lumen: @abcsum + * PHP Slim: @jfastnacht + +## How to join the core team + +Here are the requirements to become a core team member: +- rank within top 50 in https://github.com/swagger-api/swagger-codegen/graphs/contributors + - to contribute, here are some good [starting points](https://github.com/swagger-api/swagger-codegen/issues?q=is%3Aopen+is%3Aissue+label%3A%22Need+community+contribution%22) +- regular contributions to the project + - about 3 hours per week + - for contribution, it can be addressing issues, reviewing PRs submitted by others, submitting PR to fix bugs or make enhancements, etc + + To join the core team, please reach out to wing328hk@gmail.com (@wing328) for more information. + + To become a Template Creator, simply submit a PR for new API client (e.g. Rust, Elixir) or server stub (e.g. Ruby Grape) generator. License ------- diff --git a/bin/all-petstore.sh b/bin/all-petstore.sh index 2bb63f6d573..849af6b5d4a 100755 --- a/bin/all-petstore.sh +++ b/bin/all-petstore.sh @@ -29,7 +29,7 @@ cd $APP_DIR ./bin/java-petstore-jersey2.sh ./bin/java-petstore-okhttp-gson.sh ./bin/java-petstore-retrofit.sh -+./bin/java-petstore-retrofit2.sh +./bin/java-petstore-retrofit2.sh ./bin/jaxrs-petstore-server.sh ./bin/nodejs-petstore-server.sh ./bin/objc-petstore.sh diff --git a/bin/csharp-petstore.sh b/bin/csharp-petstore.sh index c042dd9c0cd..a82efa9af10 100755 --- a/bin/csharp-petstore.sh +++ b/bin/csharp-petstore.sh @@ -26,6 +26,6 @@ fi # if you've executed sbt assembly previously it will use that instead. export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" -ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l csharp -o samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient" +ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l csharp -o samples/client/petstore/csharp/SwaggerClient" java $JAVA_OPTS -jar $executable $ags diff --git a/bin/haskell-servant-petstore.sh b/bin/haskell-servant-petstore.sh index 7032a6af26c..0095e2ccc7c 100755 --- a/bin/haskell-servant-petstore.sh +++ b/bin/haskell-servant-petstore.sh @@ -26,6 +26,6 @@ fi # if you've executed sbt assembly previously it will use that instead. export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" -ags="$@ generate -t modules/swagger-codegen/src/main/resources/haskell-servant -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l haskell-servant -o samples/server/petstore/haskell-servant" +ags="$@ generate -t modules/swagger-codegen/src/main/resources/haskell-servant -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l haskell -o samples/server/petstore/haskell-servant" java $JAVA_OPTS -jar $executable $ags diff --git a/bin/javascript-promise-petstore.sh b/bin/javascript-promise-petstore.sh index f6e7ef13913..fac0f221424 100755 --- a/bin/javascript-promise-petstore.sh +++ b/bin/javascript-promise-petstore.sh @@ -27,7 +27,7 @@ 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 \ +-i modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l javascript \ -o samples/client/petstore/javascript-promise \ --additional-properties usePromises=true" diff --git a/bin/springboot-petstore-server.sh b/bin/springboot-petstore-server.sh new file mode 100755 index 00000000000..83d810ba595 --- /dev/null +++ b/bin/springboot-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/JavaSpringBoot -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l springboot -o samples/server/petstore/springboot" + +java $JAVA_OPTS -jar $executable $ags diff --git a/bin/typescript-fetch-petstore-all.sh b/bin/typescript-fetch-petstore-all.sh new file mode 100755 index 00000000000..d39c16d8803 --- /dev/null +++ b/bin/typescript-fetch-petstore-all.sh @@ -0,0 +1,5 @@ +#!/bin/sh + +./bin/typescript-fetch-petstore-target-es6.sh +./bin/typescript-fetch-petstore-target-with-package-metadata.sh +./bin/typescript-fetch-petstore.sh diff --git a/bin/typescript-fetch-petstore-target-es6.json b/bin/typescript-fetch-petstore-target-es6.json new file mode 100644 index 00000000000..83914bd569c --- /dev/null +++ b/bin/typescript-fetch-petstore-target-es6.json @@ -0,0 +1,3 @@ +{ + "supportsES6": true +} diff --git a/bin/typescript-fetch-petstore-target-es6.sh b/bin/typescript-fetch-petstore-target-es6.sh new file mode 100755 index 00000000000..3734e7e3449 --- /dev/null +++ b/bin/typescript-fetch-petstore-target-es6.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 typescript-fetch -c bin/typescript-fetch-petstore-target-es6.json -o samples/client/petstore/typescript-fetch/default-es6" + +java $JAVA_OPTS -jar $executable $ags diff --git a/bin/typescript-fetch-petstore-target-with-package-metadata.json b/bin/typescript-fetch-petstore-target-with-package-metadata.json new file mode 100644 index 00000000000..b8193c8fa74 --- /dev/null +++ b/bin/typescript-fetch-petstore-target-with-package-metadata.json @@ -0,0 +1,4 @@ +{ + "npmName": "@swagger/typescript-fetch-petstore", + "npmVersion": "0.0.1" +} diff --git a/bin/typescript-fetch-petstore-target-with-package-metadata.sh b/bin/typescript-fetch-petstore-target-with-package-metadata.sh new file mode 100755 index 00000000000..3c4978c8a80 --- /dev/null +++ b/bin/typescript-fetch-petstore-target-with-package-metadata.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 typescript-fetch -c bin/typescript-fetch-petstore-target-with-package-metadata.json -o samples/client/petstore/typescript-fetch/with-package-metadata" + +java $JAVA_OPTS -jar $executable $ags diff --git a/bin/typescript-fetch-petstore.sh b/bin/typescript-fetch-petstore.sh new file mode 100755 index 00000000000..6283285c736 --- /dev/null +++ b/bin/typescript-fetch-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 -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l typescript-fetch -o samples/client/petstore/typescript-fetch/default" + +java $JAVA_OPTS -jar $executable $ags diff --git a/bin/windows/csharp-petstore.bat b/bin/windows/csharp-petstore.bat index 227ed319441..fbfc18d334d 100755 --- a/bin/windows/csharp-petstore.bat +++ b/bin/windows/csharp-petstore.bat @@ -5,6 +5,6 @@ If Not Exist %executable% ( ) set JAVA_OPTS=%JAVA_OPTS% -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties -set ags=generate -t modules\swagger-codegen\src\main\resources\csharp -i modules\swagger-codegen\src\test\resources\2_0\petstore.json -l csharp -o samples\client\petstore\csharp\SwaggerClientTest\Lib\SwaggerClient +set ags=generate -t modules\swagger-codegen\src\main\resources\csharp -i modules\swagger-codegen\src\test\resources\2_0\petstore.json -l csharp -o samples\client\petstore\csharp\SwaggerClient java %JAVA_OPTS% -jar %executable% %ags% diff --git a/bin/windows/springboot-petstore-server.bat b/bin/windows/springboot-petstore-server.bat new file mode 100644 index 00000000000..18077852db3 --- /dev/null +++ b/bin/windows/springboot-petstore-server.bat @@ -0,0 +1,10 @@ +set executable=.\modules\swagger-codegen-cli\target\swagger-codegen-cli.jar + +If Not Exist %executable% ( + mvn clean package +) + +set JAVA_OPTS=%JAVA_OPTS% -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties +set ags=generate -t modules\swagger-codegen\src\main\resources\JavaSpringBoot -i modules\swagger-codegen\src\test\resources\2_0\petstore.json -l springboot -o samples\server\petstore\springboot + +java %JAVA_OPTS% -jar %executable% %ags% \ No newline at end of file diff --git a/bin/windows/typescript-fetch.bat b/bin/windows/typescript-fetch.bat new file mode 100755 index 00000000000..b3ff19ea211 --- /dev/null +++ b/bin/windows/typescript-fetch.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-fetch -i modules\swagger-codegen\src\test\resources\2_0\petstore.json -l typescript-fetch -o samples\client\petstore\typescript-fetch + +java %JAVA_OPTS% -jar %executable% %ags% diff --git a/modules/swagger-codegen/pom.xml b/modules/swagger-codegen/pom.xml index afaecfc3512..9ea75ad3c88 100644 --- a/modules/swagger-codegen/pom.xml +++ b/modules/swagger-codegen/pom.xml @@ -252,8 +252,8 @@ ${slf4j-version} - commons-lang - commons-lang + org.apache.commons + commons-lang3 ${commons-lang-version} 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 1d97fe829b8..b4b414bb00d 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 @@ -89,7 +89,7 @@ public class CodegenConstants { public static final String MODEL_NAME_SUFFIX_DESC = "Suffix that will be appended to all model names. Default is the empty string."; public static final String OPTIONAL_EMIT_DEFAULT_VALUES = "optionalEmitDefaultValues"; - public static final String OPTIONAL_EMIT_DEFAULT_VALUES_DESC = "Set DataMember's EmitDefaultValue, default false."; + public static final String OPTIONAL_EMIT_DEFAULT_VALUES_DESC = "Set DataMember's EmitDefaultValue."; public static final String GIT_USER_ID = "gitUserId"; public static final String GIT_USER_ID_DESC = "Git user ID, e.g. swagger-api."; @@ -103,4 +103,6 @@ public class CodegenConstants { public static final String HTTP_USER_AGENT = "httpUserAgent"; public static final String HTTP_USER_AGENT_DESC = "HTTP user agent, e.g. codegen_csharp_api_client, default to 'Swagger-Codegen/{packageVersion}}/{language}'"; + public static final String SUPPORTS_ES6 = "supportsES6"; + public static final String SUPPORTS_ES6_DESC = "Generate code that conforms to ES6."; } 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 db000e9c63e..5d71a347df0 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 @@ -9,8 +9,8 @@ import io.swagger.models.parameters.*; import io.swagger.models.properties.*; import io.swagger.models.properties.PropertyBuilder.PropertyId; import io.swagger.util.Json; -import org.apache.commons.lang.StringEscapeUtils; -import org.apache.commons.lang.StringUtils; +import org.apache.commons.lang3.StringEscapeUtils; +import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -55,6 +55,10 @@ public class DefaultCodegen { protected Boolean ensureUniqueParams = true; protected String gitUserId, gitRepoId, releaseNote; protected String httpUserAgent; + // How to encode special characters like $ + // They are translated to words like "Dollar" and prefixed with ' + // Then translated back during JSON encoding and decoding + protected Map specialCharReplacements = new HashMap(); public List cliOptions() { return cliOptions; @@ -325,7 +329,11 @@ public class DefaultCodegen { @SuppressWarnings("static-method") public String escapeText(String input) { if (input != null) { - return StringEscapeUtils.escapeJava(input).replace("\\/", "/"); + // remove \t, \n, \r + // repalce \ with \\ + // repalce " with \" + // outter unescape to retain the original multi-byte characters + return StringEscapeUtils.unescapeJava(StringEscapeUtils.escapeJava(input).replace("\\/", "/")).replaceAll("[\\t\\n\\r]"," ").replace("\\", "\\\\").replace("\"", "\\\""); } return input; } @@ -728,6 +736,31 @@ public class DefaultCodegen { CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG_DESC).defaultValue(Boolean.TRUE.toString())); cliOptions.add(CliOption.newBoolean(CodegenConstants.ENSURE_UNIQUE_PARAMS, CodegenConstants .ENSURE_UNIQUE_PARAMS_DESC).defaultValue(Boolean.TRUE.toString())); + + // initalize special character mapping + initalizeSpecialCharacterMapping(); + } + + /** + * Initalize special character mapping + */ + protected void initalizeSpecialCharacterMapping() { + // Initialize special characters + specialCharReplacements.put('$', "Dollar"); + specialCharReplacements.put('^', "Caret"); + specialCharReplacements.put('|', "Pipe"); + specialCharReplacements.put('=', "Equal"); + specialCharReplacements.put('*', "Star"); + specialCharReplacements.put('-', "Minus"); + specialCharReplacements.put('&', "Ampersand"); + specialCharReplacements.put('%', "Percent"); + specialCharReplacements.put('#', "Hash"); + specialCharReplacements.put('@', "At"); + specialCharReplacements.put('!', "Exclamation"); + specialCharReplacements.put('+', "Plus"); + specialCharReplacements.put(':', "Colon"); + specialCharReplacements.put('>', "GreaterThan"); + specialCharReplacements.put('<', "LessThan"); } /** diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java index b5a920004c8..8be354df1ee 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java @@ -286,8 +286,9 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { for (String templateName : config.modelTestTemplateFiles().keySet()) { String suffix = config.modelTestTemplateFiles().get(templateName); String filename = config.modelTestFileFolder() + File.separator + config.toModelTestFilename(name) + suffix; - if (!config.shouldOverwrite(filename)) { - LOGGER.info("Skipped overwriting " + filename); + // do not overwrite test file that already exists + if (new File(filename).exists()) { + LOGGER.info("File exists. Skipped overwriting " + filename); continue; } String templateFile = getFullTemplateFile(config, templateName); @@ -419,11 +420,11 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { // to generate api test files for (String templateName : config.apiTestTemplateFiles().keySet()) { String filename = config.apiTestFilename(templateName, tag); - if (!config.shouldOverwrite(filename) && new File(filename).exists()) { - LOGGER.info("Skipped overwriting " + filename); + // do not overwrite test file that already exists + if (new File(filename).exists()) { + LOGGER.info("File exists. Skipped overwriting " + filename); continue; } - String templateFile = getFullTemplateFile(config, templateName); String template = readTemplate(templateFile); Template tmpl = Mustache.compiler() diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractCSharpCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractCSharpCodegen.java index e9d6457f6f0..128686b615b 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractCSharpCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractCSharpCodegen.java @@ -2,7 +2,7 @@ package io.swagger.codegen.languages; import io.swagger.codegen.*; import io.swagger.models.properties.*; -import org.apache.commons.lang.StringUtils; +import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -12,7 +12,7 @@ import java.util.*; public abstract class AbstractCSharpCodegen extends DefaultCodegen implements CodegenConfig { protected boolean optionalAssemblyInfoFlag = true; - protected boolean optionalProjectFileFlag = false; + protected boolean optionalProjectFileFlag = true; protected boolean optionalEmitDefaultValue = false; protected boolean optionalMethodArgumentFlag = true; protected boolean useDateTimeOffsetFlag = false; @@ -21,7 +21,12 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co protected String packageVersion = "1.0.0"; protected String packageName = "IO.Swagger"; - protected String sourceFolder = "src" + File.separator + packageName; + + protected String sourceFolder = "src"; + + // TODO: Add option for test folder output location. Nice to allow e.g. ./test instead of ./src. + // This would require updating relative paths (e.g. path to main project file in test project file) + protected String testFolder = sourceFolder; protected Set collectionTypes; protected Set mapTypes; @@ -273,12 +278,12 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co @Override public String apiFileFolder() { - return outputFolder + File.separator + sourceFolder + File.separator + apiPackage().replace('.', File.separatorChar); + return outputFolder + File.separator + sourceFolder + File.separator + packageName + File.separator + apiPackage(); } @Override public String modelFileFolder() { - return outputFolder + File.separator + sourceFolder + File.separator + modelPackage().replace('.', File.separatorChar); + return outputFolder + File.separator + sourceFolder + File.separator + packageName + File.separator + modelPackage(); } @Override @@ -528,7 +533,6 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co return toModelName(name) + "Tests"; } - public void setPackageName(String packageName) { this.packageName = packageName; } @@ -541,7 +545,6 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co this.sourceFolder = sourceFolder; } - @Override public String toEnumVarName(String name, String datatype) { String enumName = sanitizeName(name); @@ -590,4 +593,8 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co } } */ + + public String testPackageName() { + return this.packageName + ".Test"; + } } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractTypeScriptClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractTypeScriptClientCodegen.java index b5ac095e573..9e30ae657c8 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractTypeScriptClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractTypeScriptClientCodegen.java @@ -6,11 +6,12 @@ import io.swagger.models.properties.*; import java.util.*; import java.io.File; -import org.apache.commons.lang.StringUtils; +import org.apache.commons.lang3.StringUtils; public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen implements CodegenConfig { protected String modelPropertyNaming= "camelCase"; + protected Boolean supportsES6 = true; public AbstractTypeScriptClientCodegen() { super(); @@ -63,16 +64,22 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp typeMapping.put("UUID", "string"); cliOptions.add(new CliOption(CodegenConstants.MODEL_PROPERTY_NAMING, CodegenConstants.MODEL_PROPERTY_NAMING_DESC).defaultValue("camelCase")); - + cliOptions.add(new CliOption(CodegenConstants.SUPPORTS_ES6, CodegenConstants.SUPPORTS_ES6_DESC).defaultValue("false")); } @Override public void processOpts() { super.processOpts(); + if (additionalProperties.containsKey(CodegenConstants.MODEL_PROPERTY_NAMING)) { setModelPropertyNaming((String) additionalProperties.get(CodegenConstants.MODEL_PROPERTY_NAMING)); } + + if (additionalProperties.containsKey(CodegenConstants.SUPPORTS_ES6)) { + setSupportsES6(Boolean.valueOf((String)additionalProperties.get(CodegenConstants.SUPPORTS_ES6))); + additionalProperties.put("supportsES6", getSupportsES6()); + } } @@ -286,4 +293,11 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp return postProcessModelsEnum(objs); } + public void setSupportsES6(Boolean value) { + supportsES6 = value; + } + + public Boolean getSupportsES6() { + return supportsES6; + } } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AkkaScalaClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AkkaScalaClientCodegen.java index 523fa6ae8c6..43faca235d0 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AkkaScalaClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AkkaScalaClientCodegen.java @@ -26,7 +26,7 @@ import io.swagger.models.properties.LongProperty; import io.swagger.models.properties.MapProperty; import io.swagger.models.properties.Property; import io.swagger.models.properties.StringProperty; -import org.apache.commons.lang.StringUtils; +import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AndroidClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AndroidClientCodegen.java index 0d021eba9f9..282c4d88647 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AndroidClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AndroidClientCodegen.java @@ -15,7 +15,7 @@ import java.io.File; import java.util.Arrays; import java.util.HashSet; -import org.apache.commons.lang.StringUtils; +import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AspNet5ServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AspNet5ServerCodegen.java index cf8915974e6..099d049707b 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AspNet5ServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AspNet5ServerCodegen.java @@ -2,7 +2,7 @@ package io.swagger.codegen.languages; import io.swagger.codegen.*; import io.swagger.models.properties.*; -import org.apache.commons.lang.StringUtils; +import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -11,6 +11,8 @@ import java.util.*; public class AspNet5ServerCodegen extends AbstractCSharpCodegen { + protected String sourceFolder = "src" + File.separator + packageName; + @SuppressWarnings("hiding") protected Logger LOGGER = LoggerFactory.getLogger(AspNet5ServerCodegen.class); 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 1212795e1bb..2fc8738f067 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 @@ -25,8 +25,8 @@ import java.util.Map; import java.util.ArrayList; import java.util.Iterator; -import org.apache.commons.lang.StringUtils; -import org.apache.commons.lang.WordUtils; +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.lang3.text.WordUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -68,9 +68,6 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen { modelDocTemplateFiles.put("model_doc.mustache", ".md"); apiDocTemplateFiles.put("api_doc.mustache", ".md"); - // C# client default - setSourceFolder("src" + File.separator + "main" + File.separator + "csharp"); - cliOptions.clear(); // CLI options @@ -141,9 +138,9 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen { public void processOpts() { super.processOpts(); - apiPackage = packageName + ".Api"; - modelPackage = packageName + ".Model"; - clientPackage = packageName + ".Client"; + apiPackage = "Api"; + modelPackage = "Model"; + clientPackage = "Client"; additionalProperties.put("clientPackage", clientPackage); @@ -157,6 +154,10 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen { if (additionalProperties.containsKey(CodegenConstants.DOTNET_FRAMEWORK)) { setTargetFramework((String) additionalProperties.get(CodegenConstants.DOTNET_FRAMEWORK)); + } else { + // Ensure default is set. + setTargetFramework(NET45); + additionalProperties.put("targetFramework", this.targetFramework); } if (NET35.equals(this.targetFramework)) { @@ -201,8 +202,12 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen { .get(CodegenConstants.OPTIONAL_ASSEMBLY_INFO).toString())); } - String packageFolder = sourceFolder + File.separator + packageName.replace(".", java.io.File.separator); - String clientPackageDir = sourceFolder + File.separator + clientPackage.replace(".", java.io.File.separator); + final String testPackageName = testPackageName(); + String packageFolder = sourceFolder + File.separator + packageName; + String clientPackageDir = packageFolder + File.separator + clientPackage; + String testPackageFolder = testFolder + File.separator + testPackageName; + + additionalProperties.put("testPackageName", testPackageName); //Compute the relative path to the bin directory where the external assemblies live //This is necessary to properly generate the project file @@ -210,7 +215,7 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen { String binRelativePath = "..\\"; for (int i = 0; i < packageDepth; i = i + 1) binRelativePath += "..\\"; - binRelativePath += "vendor\\"; + binRelativePath += "vendor"; additionalProperties.put("binRelativePath", binRelativePath); supportingFiles.add(new SupportingFile("Configuration.mustache", @@ -222,9 +227,13 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen { supportingFiles.add(new SupportingFile("ApiResponse.mustache", clientPackageDir, "ApiResponse.cs")); - supportingFiles.add(new SupportingFile("compile.mustache", "", "compile.bat")); - supportingFiles.add(new SupportingFile("compile-mono.sh.mustache", "", "compile-mono.sh")); - supportingFiles.add(new SupportingFile("packages.config.mustache", "vendor" + java.io.File.separator, "packages.config")); + supportingFiles.add(new SupportingFile("compile.mustache", "", "build.bat")); + supportingFiles.add(new SupportingFile("compile-mono.sh.mustache", "", "build.sh")); + + // copy package.config to nuget's standard location for project-level installs + supportingFiles.add(new SupportingFile("packages.config.mustache", packageFolder + File.separator, "packages.config")); + supportingFiles.add(new SupportingFile("packages_test.config.mustache", testPackageFolder + File.separator, "packages.config")); + supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore")); @@ -233,7 +242,14 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen { supportingFiles.add(new SupportingFile("AssemblyInfo.mustache", packageFolder + File.separator + "Properties", "AssemblyInfo.cs")); } if (optionalProjectFileFlag) { - supportingFiles.add(new SupportingFile("Project.mustache", packageFolder, clientPackage + ".csproj")); + supportingFiles.add(new SupportingFile("Solution.mustache", "", packageName + ".sln")); + supportingFiles.add(new SupportingFile("Project.mustache", packageFolder, packageName + ".csproj")); + + // TODO: Check if test project output is enabled, partially related to #2506. Should have options for: + // 1) No test project + // 2) No model tests + // 3) No api tests + supportingFiles.add(new SupportingFile("TestProject.mustache", testPackageFolder, testPackageName + ".csproj")); } additionalProperties.put("apiDocPath", apiDocPath); @@ -439,4 +455,13 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen { return (outputFolder + "/" + modelDocPath).replace('/', File.separatorChar); } + @Override + public String apiTestFileFolder() { + return outputFolder + File.separator + testFolder + File.separator + testPackageName() + File.separator + apiPackage(); + } + + @Override + public String modelTestFileFolder() { + return outputFolder + File.separator + testFolder + File.separator + testPackageName() + File.separator + modelPackage(); + } } 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 2c60a30754b..73ef83bc9cc 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 @@ -11,7 +11,7 @@ import io.swagger.models.Contact; import io.swagger.models.Info; import io.swagger.models.License; import io.swagger.models.Swagger; -import org.apache.commons.lang.StringUtils; +import org.apache.commons.lang3.StringUtils; import java.io.File; import java.util.Map; diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FlashClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FlashClientCodegen.java index b5699a93a34..a9eb1a97de7 100755 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FlashClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FlashClientCodegen.java @@ -17,7 +17,7 @@ import io.swagger.models.properties.LongProperty; import io.swagger.models.properties.MapProperty; import io.swagger.models.properties.Property; import io.swagger.models.properties.StringProperty; -import org.apache.commons.lang.StringUtils; +import org.apache.commons.lang3.StringUtils; import java.io.File; import java.util.Arrays; diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GoClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GoClientCodegen.java index fe25436c901..4e34424eab7 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GoClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GoClientCodegen.java @@ -9,7 +9,7 @@ import io.swagger.models.parameters.Parameter; import java.io.File; import java.util.*; -import org.apache.commons.lang.StringUtils; +import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -450,4 +450,4 @@ public class GoClientCodegen extends DefaultCodegen implements CodegenConfig { public void setPackageVersion(String packageVersion) { this.packageVersion = packageVersion; } -} \ No newline at end of file +} diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/HaskellServantCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/HaskellServantCodegen.java index a78bb441c48..324ca56e70b 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/HaskellServantCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/HaskellServantCodegen.java @@ -18,12 +18,6 @@ public class HaskellServantCodegen extends DefaultCodegen implements CodegenConf protected String sourceFolder = "src"; protected String apiVersion = "0.0.1"; - - // How to encode special characters like $ - // They are translated to words like "Dollar" and prefixed with ' - // Then translated back during JSON encoding and decoding - private Map specialCharReplacements = new HashMap(); - /** * Configures the type of generator. * @@ -57,20 +51,8 @@ public class HaskellServantCodegen extends DefaultCodegen implements CodegenConf public HaskellServantCodegen() { super(); - // Initialize special characters - specialCharReplacements.put('$', "Dollar"); - specialCharReplacements.put('^', "Caret"); - specialCharReplacements.put('|', "Pipe"); - specialCharReplacements.put('=', "Equal"); - specialCharReplacements.put('*', "Star"); + // override the mapping for "-" (Minus) to keep the original mapping in Haskell specialCharReplacements.put('-', "Dash"); - specialCharReplacements.put('&', "Ampersand"); - specialCharReplacements.put('%', "Percent"); - specialCharReplacements.put('#', "Hash"); - specialCharReplacements.put('@', "At"); - specialCharReplacements.put('!', "Exclamation"); - specialCharReplacements.put('+', "Plus"); - // set the output folder here outputFolder = "generated-code/haskell-servant"; diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JMeterCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JMeterCodegen.java index 903cb7ba76e..2d08c9741e9 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JMeterCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JMeterCodegen.java @@ -183,4 +183,4 @@ public class JMeterCodegen extends DefaultCodegen implements CodegenConfig { 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 e607670313c..bc839f07d18 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 @@ -9,9 +9,9 @@ import io.swagger.models.Swagger; import io.swagger.models.parameters.FormParameter; import io.swagger.models.parameters.Parameter; import io.swagger.models.properties.*; -import org.apache.commons.lang.BooleanUtils; -import org.apache.commons.lang.StringUtils; -import org.apache.commons.lang.WordUtils; +import org.apache.commons.lang3.BooleanUtils; +import org.apache.commons.lang3.StringUtils; +//import org.apache.commons.lang3.WordUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaResteasyServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaResteasyServerCodegen.java index 5f715a43621..b919430035d 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaResteasyServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaResteasyServerCodegen.java @@ -4,7 +4,7 @@ import io.swagger.codegen.*; import io.swagger.models.Operation; import io.swagger.models.Path; import io.swagger.models.Swagger; -import org.apache.commons.lang.StringUtils; +import org.apache.commons.lang3.StringUtils; import java.io.File; import java.util.*; diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavascriptClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavascriptClientCodegen.java index feec76d8de2..d937842a128 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavascriptClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavascriptClientCodegen.java @@ -33,7 +33,7 @@ import io.swagger.models.properties.Property; import io.swagger.models.properties.RefProperty; import io.swagger.models.properties.StringProperty; -import org.apache.commons.lang.StringUtils; +import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -839,6 +839,7 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo @SuppressWarnings("unchecked") @Override public Map postProcessModels(Map objs) { + objs = super.postProcessModelsEnum(objs); List models = (List) objs.get("models"); for (Object _mo : models) { Map mo = (Map) _mo; @@ -853,8 +854,6 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo cm.vendorExtensions.put("x-all-required", allRequired); for (CodegenProperty var : cm.vars) { - Map allowableValues = var.allowableValues; - // Add JSDoc @type value for this property. String jsDocType = getJSDocTypeWithBraces(cm, var); var.vendorExtensions.put("x-jsdoc-type", jsDocType); @@ -862,40 +861,6 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo if (Boolean.TRUE.equals(var.required)) { required.add(var.name); } - - // 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 (Object value : values) { - Map enumVar = new HashMap(); - String enumName; - if (truncateIdx == 0) { - enumName = value.toString(); - } else { - enumName = value.toString().substring(truncateIdx); - if ("".equals(enumName)) { - enumName = value.toString(); - } - } - enumVar.put("name", toEnumVarName(enumName, var.datatype)); - enumVar.put("value",toEnumValue(value.toString(), var.datatype)); - enumVars.add(enumVar); - } - allowableValues.put("enumVars", enumVars); } if (supportsInheritance) { diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavascriptClosureAngularClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavascriptClosureAngularClientCodegen.java index 2a2dfd86c9d..55c3fab96b0 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavascriptClosureAngularClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavascriptClosureAngularClientCodegen.java @@ -8,7 +8,7 @@ import java.util.TreeSet; import java.util.*; import java.io.File; -import org.apache.commons.lang.StringUtils; +import org.apache.commons.lang3.StringUtils; public class JavascriptClosureAngularClientCodegen extends DefaultCodegen implements CodegenConfig { public JavascriptClosureAngularClientCodegen() { diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/LumenServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/LumenServerCodegen.java index 55e72f79384..fbd98c034df 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/LumenServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/LumenServerCodegen.java @@ -232,4 +232,4 @@ public class LumenServerCodegen extends DefaultCodegen implements CodegenConfig type = swaggerType; return toModelName(type); } -} \ No newline at end of file +} 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 21e319f6ec9..46b6083e2e4 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 @@ -19,7 +19,7 @@ import java.util.List; import java.util.Map; import java.util.Set; -import org.apache.commons.lang.StringUtils; +import org.apache.commons.lang3.StringUtils; public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { public static final String CLASS_PREFIX = "classPrefix"; @@ -28,6 +28,9 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { public static final String AUTHOR_EMAIL = "authorEmail"; public static final String GIT_REPO_URL = "gitRepoURL"; public static final String LICENSE = "license"; + + public static final String BinaryDataType = "ObjcClientCodegenBinaryData"; + protected Set foundationClasses = new HashSet(); protected String podName = "SwaggerClient"; protected String podVersion = "1.0.0"; @@ -39,6 +42,8 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { protected String[] specialWords = {"new", "copy"}; protected String apiDocPath = "docs/"; protected String modelDocPath = "docs/"; + + protected Set advancedMapingTypes = new HashSet(); public ObjcClientCodegen() { super(); @@ -66,6 +71,18 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { defaultIncludes.add("NSMutableArray"); defaultIncludes.add("NSMutableDictionary"); + defaultIncludes.add(BinaryDataType); + + advancedMapingTypes.add("NSDictionary"); + advancedMapingTypes.add("NSArray"); + advancedMapingTypes.add("NSMutableArray"); + advancedMapingTypes.add("NSMutableDictionary"); + advancedMapingTypes.add("NSObject"); + advancedMapingTypes.add("NSNumber"); + advancedMapingTypes.add("NSURL"); + advancedMapingTypes.add("NSString"); + advancedMapingTypes.add("NSDate"); + languageSpecificPrimitives.clear(); languageSpecificPrimitives.add("NSNumber"); languageSpecificPrimitives.add("NSString"); @@ -92,10 +109,8 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { typeMapping.put("List", "NSArray"); typeMapping.put("object", "NSObject"); typeMapping.put("file", "NSURL"); - //TODO binary should be mapped to byte array - // mapped to String as a workaround - typeMapping.put("binary", "NSString"); - typeMapping.put("ByteArray", "NSString"); + typeMapping.put("binary", BinaryDataType); + typeMapping.put("ByteArray", BinaryDataType); // ref: http://www.tutorialspoint.com/objective_c/objective_c_basic_syntax.htm setReservedWordsLowerCase( @@ -223,6 +238,10 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { supportingFiles.add(new SupportingFile("JSONResponseSerializer-body.mustache", swaggerFolder, classPrefix + "JSONResponseSerializer.m")); supportingFiles.add(new SupportingFile("JSONRequestSerializer-body.mustache", swaggerFolder, classPrefix + "JSONRequestSerializer.m")); supportingFiles.add(new SupportingFile("JSONRequestSerializer-header.mustache", swaggerFolder, classPrefix + "JSONRequestSerializer.h")); + supportingFiles.add(new SupportingFile("ResponseDeserializer-body.mustache", swaggerFolder, classPrefix + "ResponseDeserializer.m")); + supportingFiles.add(new SupportingFile("ResponseDeserializer-header.mustache", swaggerFolder, classPrefix + "ResponseDeserializer.h")); + supportingFiles.add(new SupportingFile("Sanitizer-body.mustache", swaggerFolder, classPrefix + "Sanitizer.m")); + supportingFiles.add(new SupportingFile("Sanitizer-header.mustache", swaggerFolder, classPrefix + "Sanitizer.h")); supportingFiles.add(new SupportingFile("JSONValueTransformer+ISO8601.m", swaggerFolder, "JSONValueTransformer+ISO8601.m")); supportingFiles.add(new SupportingFile("JSONValueTransformer+ISO8601.h", swaggerFolder, "JSONValueTransformer+ISO8601.h")); supportingFiles.add(new SupportingFile("Configuration-body.mustache", swaggerFolder, classPrefix + "Configuration.m")); @@ -278,19 +297,26 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { String innerType = getSwaggerType(inner); String innerTypeDeclaration = getTypeDeclaration(inner); - if (innerTypeDeclaration.endsWith("*")) { innerTypeDeclaration = innerTypeDeclaration.substring(0, innerTypeDeclaration.length() - 1); } - + + if(innerTypeDeclaration.equalsIgnoreCase(BinaryDataType)) { + return "NSData*"; + } // In this codition, type of property p is array of primitive, - // return container type with pointer, e.g. `NSArray* /* NSString */' - if (languageSpecificPrimitives.contains(innerType)) { - return getSwaggerType(p) + "*" + " /* " + innerTypeDeclaration + " */"; + // return container type with pointer, e.g. `NSArray**' + if (languageSpecificPrimitives.contains(innerTypeDeclaration)) { + return getSwaggerType(p) + "<" + innerTypeDeclaration + "*>*"; } // In this codition, type of property p is array of model, // return container type combine inner type with pointer, e.g. `NSArray*' else { + for (String sd : advancedMapingTypes) { + if(innerTypeDeclaration.startsWith(sd)) { + return getSwaggerType(p) + "<" + innerTypeDeclaration + "*>*"; + } + } return getSwaggerType(p) + "<" + innerTypeDeclaration + ">*"; } } else if (p instanceof MapProperty) { @@ -298,11 +324,20 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { Property inner = mp.getAdditionalProperties(); String innerTypeDeclaration = getTypeDeclaration(inner); - + if (innerTypeDeclaration.endsWith("*")) { innerTypeDeclaration = innerTypeDeclaration.substring(0, innerTypeDeclaration.length() - 1); } - return getSwaggerType(p) + "* /* NSString, " + innerTypeDeclaration + " */"; + if (languageSpecificPrimitives.contains(innerTypeDeclaration)) { + return getSwaggerType(p) + "*"; + } else { + for (String s : advancedMapingTypes) { + if(innerTypeDeclaration.startsWith(s)) { + return getSwaggerType(p) + "*"; + } + } + return getSwaggerType(p) + "*"; + } } else { String swaggerType = getSwaggerType(p); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PerlClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PerlClientCodegen.java index e4744bf037c..e17084a3bc5 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PerlClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PerlClientCodegen.java @@ -27,7 +27,7 @@ import java.util.Arrays; import java.util.HashSet; import java.util.regex.Matcher; -import org.apache.commons.lang.StringUtils; +import org.apache.commons.lang3.StringUtils; public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig { public static final String MODULE_NAME = "moduleName"; 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 91346cad696..738ffd4e0d5 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 @@ -37,9 +37,13 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { protected String packagePath = "SwaggerClient-php"; protected String artifactVersion = "1.0.0"; protected String srcBasePath = "lib"; + protected String testBasePath = "test"; + protected String docsBasePath = "docs"; + protected String apiDirName = "Api"; + protected String modelDirName = "Model"; protected String variableNamingConvention= "snake_case"; - protected String apiDocPath = "docs/"; - protected String modelDocPath = "docs/"; + protected String apiDocPath = docsBasePath + "/" + apiDirName; + protected String modelDocPath = docsBasePath + "/" + modelDirName; public PhpClientCodegen() { super(); @@ -51,9 +55,8 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { modelTestTemplateFiles.put("model_test.mustache", ".php"); apiTestTemplateFiles.put("api_test.mustache", ".php"); embeddedTemplateDir = templateDir = "php"; - apiPackage = invokerPackage + "\\Api"; - modelPackage = invokerPackage + "\\Model"; - testPackage = invokerPackage + "\\Tests"; + apiPackage = invokerPackage + "\\" + apiDirName; + modelPackage = invokerPackage + "\\" + modelDirName; modelDocTemplateFiles.put("model_doc.mustache", ".md"); apiDocTemplateFiles.put("api_doc.mustache", ".md"); @@ -233,6 +236,9 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { additionalProperties.put("apiDocPath", apiDocPath); additionalProperties.put("modelDocPath", modelDocPath); + // make test path available in mustache template + additionalProperties.put("testBasePath", testBasePath); + supportingFiles.add(new SupportingFile("configuration.mustache", toPackagePath(invokerPackage, srcBasePath), "Configuration.php")); supportingFiles.add(new SupportingFile("ApiClient.mustache", toPackagePath(invokerPackage, srcBasePath), "ApiClient.php")); supportingFiles.add(new SupportingFile("ApiException.mustache", toPackagePath(invokerPackage, srcBasePath), "ApiException.php")); @@ -262,23 +268,21 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { @Override public String apiTestFileFolder() { - return (outputFolder + "/" + toPackagePath(testPackage, srcBasePath)); + return (outputFolder + "/" + getPackagePath() + "/" + testBasePath + "/" + apiDirName); } @Override public String modelTestFileFolder() { - return (outputFolder + "/" + toPackagePath(testPackage, srcBasePath)); + return (outputFolder + "/" + getPackagePath() + "/" + testBasePath + "/" + modelDirName); } @Override public String apiDocFileFolder() { - //return (outputFolder + "/" + apiDocPath).replace('/', File.separatorChar); return (outputFolder + "/" + getPackagePath() + "/" + apiDocPath); } @Override public String modelDocFileFolder() { - //return (outputFolder + "/" + modelDocPath).replace('/', File.separatorChar); return (outputFolder + "/" + getPackagePath() + "/" + modelDocPath); } 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 1bc95cfdd67..113c6a6e1c1 100755 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PythonClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PythonClientCodegen.java @@ -3,17 +3,23 @@ package io.swagger.codegen.languages; import io.swagger.codegen.CliOption; import io.swagger.codegen.CodegenConfig; import io.swagger.codegen.CodegenConstants; +import io.swagger.codegen.CodegenModel; import io.swagger.codegen.CodegenParameter; +import io.swagger.codegen.CodegenProperty; import io.swagger.codegen.CodegenType; import io.swagger.codegen.DefaultCodegen; import io.swagger.codegen.SupportingFile; import io.swagger.models.properties.*; import java.io.File; +import java.util.ArrayList; import java.util.Arrays; +import java.util.HashMap; import java.util.HashSet; +import java.util.List; +import java.util.Map; -import org.apache.commons.lang.StringUtils; +import org.apache.commons.lang3.StringUtils; public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig { protected String packageName; @@ -21,6 +27,8 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig protected String apiDocPath = "docs/"; protected String modelDocPath = "docs/"; + protected Map regexModifiers; + private String testFolder; public PythonClientCodegen() { @@ -87,6 +95,14 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig "assert", "else", "if", "pass", "yield", "break", "except", "import", "print", "class", "exec", "in", "raise", "continue", "finally", "is", "return", "def", "for", "lambda", "try", "self")); + + regexModifiers = new HashMap(); + regexModifiers.put('i', "IGNORECASE"); + regexModifiers.put('l', "LOCALE"); + regexModifiers.put('m', "MULTILINE"); + regexModifiers.put('s', "DOTALL"); + regexModifiers.put('u', "UNICODE"); + regexModifiers.put('x', "VERBOSE"); cliOptions.clear(); cliOptions.add(new CliOption(CodegenConstants.PACKAGE_NAME, "python package name (convention: snake_case).") @@ -143,6 +159,46 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig private static String dropDots(String str) { return str.replaceAll("\\.", "_"); } + + @Override + public void postProcessParameter(CodegenParameter parameter){ + postProcessPattern(parameter.pattern, parameter.vendorExtensions); + } + + @Override + public void postProcessModelProperty(CodegenModel model, CodegenProperty property) { + postProcessPattern(property.pattern, property.vendorExtensions); + } + + /* + * The swagger pattern spec follows the Perl convention and style of modifiers. Python + * does not support this in as natural a way so it needs to convert it. See + * https://docs.python.org/2/howto/regex.html#compilation-flags for details. + */ + public void postProcessPattern(String pattern, Map vendorExtensions){ + if(pattern != null) { + int i = pattern.lastIndexOf('/'); + + //Must follow Perl /pattern/modifiers convention + if(pattern.charAt(0) != '/' || i < 2) { + throw new IllegalArgumentException("Pattern must follow the Perl " + + "/pattern/modifiers convention. "+pattern+" is not valid."); + } + + String regex = pattern.substring(1, i).replace("'", "\'"); + List modifiers = new ArrayList(); + + for(char c : pattern.substring(i).toCharArray()) { + if(regexModifiers.containsKey(c)) { + String modifier = regexModifiers.get(c); + modifiers.add(modifier); + } + } + + vendorExtensions.put("x-regex", regex); + vendorExtensions.put("x-modifiers", modifiers); + } + } @Override public CodegenType getTag() { 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 f9c0990c182..6655a28f1d5 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 @@ -19,7 +19,7 @@ import java.util.HashSet; import java.util.Iterator; import java.util.Map; -import org.apache.commons.lang.StringUtils; +import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -224,6 +224,12 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore")); + writeOptional(outputFolder, new SupportingFile("rspec.mustache", "", ".rspec")); + writeOptional(outputFolder, new SupportingFile("spec_helper.mustache", specFolder, "spec_helper.rb")); + writeOptional(outputFolder, new SupportingFile("configuration_spec.mustache", specFolder, "configuration_spec.rb")); + writeOptional(outputFolder, new SupportingFile("api_client_spec.mustache", specFolder, "api_client_spec.rb")); + // not including base object test as the moment as not all API has model + //writeOptional(outputFolder, new SupportingFile("base_object_spec.mustache", specFolder, "base_object_spec.rb")); } @Override @@ -644,10 +650,11 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { this.gemAuthorEmail = gemAuthorEmail; } - @Override public boolean shouldOverwrite(String filename) { // skip spec file as the file might have been updated with new test cases - return super.shouldOverwrite(filename) && !filename.endsWith("_spec.rb"); + return !(skipOverwrite && new File(filename).exists()); + // + //return super.shouldOverwrite(filename) && !filename.endsWith("_spec.rb"); } } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ScalaClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ScalaClientCodegen.java index a13c7a54e70..992693810da 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ScalaClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ScalaClientCodegen.java @@ -26,7 +26,7 @@ import java.util.Iterator; import java.util.List; import java.util.Map; -import org.apache.commons.lang.StringUtils; +import org.apache.commons.lang3.StringUtils; public class ScalaClientCodegen extends DefaultCodegen implements CodegenConfig { protected String invokerPackage = "io.swagger.client"; 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 bb7706b13fe..fb3ceab7d78 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 @@ -17,7 +17,7 @@ import java.util.Arrays; import java.util.HashSet; import java.util.Map; -import org.apache.commons.lang.StringUtils; +import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SpringBootServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SpringBootServerCodegen.java new file mode 100644 index 00000000000..070f5de6d03 --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SpringBootServerCodegen.java @@ -0,0 +1,281 @@ +package io.swagger.codegen.languages; + +import io.swagger.codegen.*; +import io.swagger.models.Operation; +import io.swagger.models.Path; +import io.swagger.models.Swagger; +import java.io.File; +import java.util.*; + +public class SpringBootServerCodegen extends JavaClientCodegen implements CodegenConfig{ + public static final String CONFIG_PACKAGE = "configPackage"; + public static final String BASE_PACKAGE = "basePackage"; + protected String title = "Petstore Server"; + protected String configPackage = ""; + protected String basePackage = ""; + protected String templateFileName = "api.mustache"; + + public SpringBootServerCodegen() { + super(); + outputFolder = "generated-code/javaSpringBoot"; + modelTemplateFiles.put("model.mustache", ".java"); + apiTemplateFiles.put(templateFileName, ".java"); + embeddedTemplateDir = templateDir = "JavaSpringBoot"; + apiPackage = "io.swagger.api"; + modelPackage = "io.swagger.model"; + configPackage = "io.swagger.configuration"; + invokerPackage = "io.swagger.api"; + basePackage = "io.swagger"; + artifactId = "swagger-springboot-server"; + + additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, invokerPackage); + additionalProperties.put(CodegenConstants.GROUP_ID, groupId); + additionalProperties.put(CodegenConstants.ARTIFACT_ID, artifactId); + additionalProperties.put(CodegenConstants.ARTIFACT_VERSION, artifactVersion); + additionalProperties.put("title", title); + additionalProperties.put(CodegenConstants.API_PACKAGE, apiPackage); + additionalProperties.put(CONFIG_PACKAGE, configPackage); + additionalProperties.put(BASE_PACKAGE, basePackage); + + cliOptions.add(new CliOption(CONFIG_PACKAGE, "configuration package for generated code")); + cliOptions.add(new CliOption(BASE_PACKAGE, "base package for generated code")); + + supportedLibraries.clear(); + supportedLibraries.put(DEFAULT_LIBRARY, "Default Spring Boot server stub."); + supportedLibraries.put("j8-async", "Use async servlet feature and Java 8's default interface. Generating interface with service " + + "declaration is useful when using Maven plugin. Just provide a implementation with @Controller to instantiate service."); + } + + @Override + public CodegenType getTag() { + return CodegenType.SERVER; + } + + @Override + public String getName() { + return "springboot"; + } + + @Override + public String getHelp() { + return "Generates a Java SpringBoot Server application using the SpringFox integration."; + } + + @Override + public void processOpts() { + super.processOpts(); + + // clear model and api doc template as this codegen + // does not support auto-generated markdown doc at the moment + modelDocTemplateFiles.remove("model_doc.mustache"); + apiDocTemplateFiles.remove("api_doc.mustache"); + + if (additionalProperties.containsKey(CONFIG_PACKAGE)) { + this.setConfigPackage((String) additionalProperties.get(CONFIG_PACKAGE)); + } + + if (additionalProperties.containsKey(BASE_PACKAGE)) { + this.setBasePackage((String) additionalProperties.get(BASE_PACKAGE)); + } + + supportingFiles.clear(); + supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml")); + supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); + supportingFiles.add(new SupportingFile("apiException.mustache", + (sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "ApiException.java")); + supportingFiles.add(new SupportingFile("apiOriginFilter.mustache", + (sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "ApiOriginFilter.java")); + supportingFiles.add(new SupportingFile("apiResponseMessage.mustache", + (sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "ApiResponseMessage.java")); + supportingFiles.add(new SupportingFile("notFoundException.mustache", + (sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "NotFoundException.java")); + + supportingFiles.add(new SupportingFile("swaggerDocumentationConfig.mustache", + (sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "SwaggerDocumentationConfig.java")); + supportingFiles.add(new SupportingFile("homeController.mustache", + (sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "HomeController.java")); + + supportingFiles.add(new SupportingFile("swagger2SpringBoot.mustache", + (sourceFolder + File.separator + basePackage).replace(".", java.io.File.separator), "Swagger2SpringBoot.java")); + + + supportingFiles.add(new SupportingFile("application.properties", + ("src.main.resources").replace(".", java.io.File.separator), "application.properties")); + + } + + @Override + public void addOperationToGroup(String tag, String resourcePath, Operation operation, CodegenOperation co, Map> operations) { + String basePath = resourcePath; + if (basePath.startsWith("/")) { + basePath = basePath.substring(1); + } + int pos = basePath.indexOf("/"); + if (pos > 0) { + basePath = basePath.substring(0, pos); + } + + if (basePath == "") { + basePath = "default"; + } else { + if (co.path.startsWith("/" + basePath)) { + co.path = co.path.substring(("/" + basePath).length()); + } + co.subresourceOperation = !co.path.isEmpty(); + } + List opList = operations.get(basePath); + if (opList == null) { + opList = new ArrayList(); + operations.put(basePath, opList); + } + opList.add(co); + co.baseName = basePath; + } + + @Override + public void preprocessSwagger(Swagger swagger) { + System.out.println("preprocessSwagger"); + if ("/".equals(swagger.getBasePath())) { + swagger.setBasePath(""); + } + + String host = swagger.getHost(); + String port = "8080"; + if (host != null) { + String[] parts = host.split(":"); + if (parts.length > 1) { + port = parts[1]; + } + } + + this.additionalProperties.put("serverPort", port); + if (swagger != null && swagger.getPaths() != null) { + for (String pathname : swagger.getPaths().keySet()) { + Path path = swagger.getPath(pathname); + if (path.getOperations() != null) { + for (Operation operation : path.getOperations()) { + if (operation.getTags() != null) { + List> tags = new ArrayList>(); + for (String tag : operation.getTags()) { + Map value = new HashMap(); + value.put("tag", tag); + value.put("hasMore", "true"); + tags.add(value); + } + if (tags.size() > 0) { + tags.get(tags.size() - 1).remove("hasMore"); + } + if (operation.getTags().size() > 0) { + String tag = operation.getTags().get(0); + operation.setTags(Arrays.asList(tag)); + } + operation.setVendorExtension("x-tags", tags); + } + } + } + } + } + } + + @Override + public Map postProcessOperations(Map objs) { + Map operations = (Map) objs.get("operations"); + if (operations != null) { + List ops = (List) operations.get("operation"); + for (CodegenOperation operation : ops) { + List responses = operation.responses; + if (responses != null) { + for (CodegenResponse resp : responses) { + if ("0".equals(resp.code)) { + resp.code = "200"; + } + } + } + + if (operation.returnType == null) { + operation.returnType = "Void"; + } else if (operation.returnType.startsWith("List")) { + String rt = operation.returnType; + int end = rt.lastIndexOf(">"); + if (end > 0) { + operation.returnType = rt.substring("List<".length(), end).trim(); + operation.returnContainer = "List"; + } + } else if (operation.returnType.startsWith("Map")) { + String rt = operation.returnType; + int end = rt.lastIndexOf(">"); + if (end > 0) { + operation.returnType = rt.substring("Map<".length(), end).split(",")[1].trim(); + operation.returnContainer = "Map"; + } + } else if (operation.returnType.startsWith("Set")) { + String rt = operation.returnType; + int end = rt.lastIndexOf(">"); + if (end > 0) { + operation.returnType = rt.substring("Set<".length(), end).trim(); + operation.returnContainer = "Set"; + } + } + } + } + if("j8-async".equals(getLibrary())) { + apiTemplateFiles.remove(this.templateFileName); + this.templateFileName = "api-j8-async.mustache"; + apiTemplateFiles.put(this.templateFileName, ".java"); + + int originalPomFileIdx = -1; + for (int i = 0; i < supportingFiles.size(); i++) { + if ("pom.xml".equals(supportingFiles.get(i).destinationFilename)) { + originalPomFileIdx = i; + break; + } + } + if (originalPomFileIdx > -1) { + supportingFiles.remove(originalPomFileIdx); + } + supportingFiles.add(new SupportingFile("pom-j8-async.mustache", "", "pom.xml")); + } + + return objs; + } + + @Override + public String toApiName(String name) { + if (name.length() == 0) { + return "DefaultApi"; + } + name = sanitizeName(name); + return camelize(name) + "Api"; + } + + public void setConfigPackage(String configPackage) { + this.configPackage = configPackage; + } + + public void setBasePackage(String configPackage) { + this.basePackage = configPackage; + } + + @Override + public Map postProcessModels(Map objs) { + // remove the import of "Object" to avoid compilation error + List> imports = (List>) objs.get("imports"); + Iterator> iterator = imports.iterator(); + while (iterator.hasNext()) { + String _import = iterator.next().get("import"); + if (_import.endsWith(".Object")) iterator.remove(); + } + 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) { + // handle default value for enum, e.g. available => StatusEnum.available + if (var.isEnum && var.defaultValue != null && !"null".equals(var.defaultValue)) { + var.defaultValue = var.datatypeWithEnum + "." + var.defaultValue; + } + } + } + return objs; + } +} diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SpringMVCServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SpringMVCServerCodegen.java index 41d17a3e807..8bd7e3c1f8e 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SpringMVCServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SpringMVCServerCodegen.java @@ -2,11 +2,12 @@ package io.swagger.codegen.languages; import io.swagger.codegen.*; import io.swagger.models.Operation; - +import io.swagger.models.Path; +import io.swagger.models.Swagger; import java.io.File; import java.util.*; -public class SpringMVCServerCodegen extends JavaClientCodegen { +public class SpringMVCServerCodegen extends JavaClientCodegen implements CodegenConfig{ public static final String CONFIG_PACKAGE = "configPackage"; protected String title = "Petstore Server"; protected String configPackage = ""; @@ -120,6 +121,51 @@ public class SpringMVCServerCodegen extends JavaClientCodegen { opList.add(co); co.baseName = basePath; } + + @Override + public void preprocessSwagger(Swagger swagger) { + System.out.println("preprocessSwagger"); + if ("/".equals(swagger.getBasePath())) { + swagger.setBasePath(""); + } + + String host = swagger.getHost(); + String port = "8080"; + if (host != null) { + String[] parts = host.split(":"); + if (parts.length > 1) { + port = parts[1]; + } + } + + this.additionalProperties.put("serverPort", port); + if (swagger != null && swagger.getPaths() != null) { + for (String pathname : swagger.getPaths().keySet()) { + Path path = swagger.getPath(pathname); + if (path.getOperations() != null) { + for (Operation operation : path.getOperations()) { + if (operation.getTags() != null) { + List> tags = new ArrayList>(); + for (String tag : operation.getTags()) { + Map value = new HashMap(); + value.put("tag", tag); + value.put("hasMore", "true"); + tags.add(value); + } + if (tags.size() > 0) { + tags.get(tags.size() - 1).remove("hasMore"); + } + if (operation.getTags().size() > 0) { + String tag = operation.getTags().get(0); + operation.setTags(Arrays.asList(tag)); + } + operation.setVendorExtension("x-tags", tags); + } + } + } + } + } + } @Override public Map postProcessOperations(Map objs) { diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/StaticDocCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/StaticDocCodegen.java index 3ff35f170fd..c64fcfb04ef 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/StaticDocCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/StaticDocCodegen.java @@ -85,4 +85,4 @@ public class StaticDocCodegen extends DefaultCodegen implements CodegenConfig { public String modelFileFolder() { return outputFolder + File.separator + sourceFolder + File.separator + "models"; } -} \ No newline at end of file +} diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/StaticHtmlGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/StaticHtmlGenerator.java index 65ec8529930..0db05d5bc0a 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/StaticHtmlGenerator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/StaticHtmlGenerator.java @@ -101,4 +101,4 @@ public class StaticHtmlGenerator extends DefaultCodegen implements CodegenConfig } return objs; } -} \ No newline at end of file +} diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwaggerGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwaggerGenerator.java index b34e6bba5ab..6282f72d8b7 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwaggerGenerator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwaggerGenerator.java @@ -52,4 +52,4 @@ public class SwaggerGenerator extends DefaultCodegen implements CodegenConfig { LOGGER.error(e.getMessage(), e); } } -} \ No newline at end of file +} diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwaggerYamlGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwaggerYamlGenerator.java index 5442000280f..48f0197068b 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwaggerYamlGenerator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwaggerYamlGenerator.java @@ -51,4 +51,4 @@ public class SwaggerYamlGenerator extends DefaultCodegen implements CodegenConfi LOGGER.error(e.getMessage(), e); } } -} \ No newline at end of file +} diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java index 7b6bf8fbdc3..ba846857cb9 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java @@ -13,9 +13,9 @@ import io.swagger.models.parameters.Parameter; import io.swagger.models.properties.ArrayProperty; import io.swagger.models.properties.MapProperty; import io.swagger.models.properties.Property; -import org.apache.commons.lang.ArrayUtils; -import org.apache.commons.lang.StringUtils; -import org.apache.commons.lang.WordUtils; +import org.apache.commons.lang3.ArrayUtils; +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.lang3.text.WordUtils; import javax.annotation.Nullable; import java.util.*; diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TizenClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TizenClientCodegen.java index c3f6d7ab99a..ec58781ab2b 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TizenClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TizenClientCodegen.java @@ -25,7 +25,7 @@ import java.util.HashSet; import java.util.Map; import java.util.Set; -import org.apache.commons.lang.StringUtils; +import org.apache.commons.lang3.StringUtils; public class TizenClientCodegen extends DefaultCodegen implements CodegenConfig { protected static String PREFIX = "Sami"; diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptFetchClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptFetchClientCodegen.java new file mode 100644 index 00000000000..c817162401e --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptFetchClientCodegen.java @@ -0,0 +1,70 @@ +package io.swagger.codegen.languages; + +import io.swagger.codegen.CliOption; +import io.swagger.codegen.SupportingFile; + +import java.io.File; + +public class TypeScriptFetchClientCodegen extends AbstractTypeScriptClientCodegen { + + public static final String NPM_NAME = "npmName"; + public static final String NPM_VERSION = "npmVersion"; + + protected String npmName = null; + protected String npmVersion = "1.0.0"; + + public TypeScriptFetchClientCodegen() { + super(); + outputFolder = "generated-code/typescript-fetch"; + embeddedTemplateDir = templateDir = "TypeScript-Fetch"; + this.cliOptions.add(new CliOption(NPM_NAME, "The name under which you want to publish generated npm package")); + this.cliOptions.add(new CliOption(NPM_VERSION, "The version of your npm package")); + } + + @Override + public void processOpts() { + super.processOpts(); + supportingFiles.add(new SupportingFile("api.mustache", "", "api.ts")); + supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); + supportingFiles.add(new SupportingFile("assign.ts", "", "assign.ts")); + supportingFiles.add(new SupportingFile("README.md", "", "README.md")); + supportingFiles.add(new SupportingFile("package.json.mustache", "", "package.json")); + supportingFiles.add(new SupportingFile("typings.json.mustache", "", "typings.json")); + supportingFiles.add(new SupportingFile("tsconfig.json.mustache", "", "tsconfig.json")); + + if(additionalProperties.containsKey(NPM_NAME)) { + this.setNpmName(additionalProperties.get(NPM_NAME).toString()); + } + + if (additionalProperties.containsKey(NPM_VERSION)) { + this.setNpmVersion(additionalProperties.get(NPM_VERSION).toString()); + } + } + + @Override + public String getName() { + return "typescript-fetch"; + } + + @Override + public String getHelp() { + return "Generates a TypeScript client library using Fetch API (beta)."; + } + + public String getNpmName() { + return npmName; + } + + public void setNpmName(String npmName) { + this.npmName = npmName; + } + + public String getNpmVersion() { + return npmVersion; + } + + public void setNpmVersion(String npmVersion) { + this.npmVersion = npmVersion; + } + +} diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptNodeClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptNodeClientCodegen.java index 3950c1a7ff3..d4207f09cc8 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptNodeClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptNodeClientCodegen.java @@ -41,7 +41,6 @@ public class TypeScriptNodeClientCodegen extends AbstractTypeScriptClientCodegen super.processOpts(); supportingFiles.add(new SupportingFile("api.mustache", null, "api.ts")); supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); - //supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore")); LOGGER.warn("check additionals: " + additionalProperties.get(NPM_NAME)); if(additionalProperties.containsKey(NPM_NAME)) { diff --git a/modules/swagger-codegen/src/main/resources/Java/api.mustache b/modules/swagger-codegen/src/main/resources/Java/api.mustache index 0487cd8ef98..ad7b9051f05 100644 --- a/modules/swagger-codegen/src/main/resources/Java/api.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/api.mustache @@ -5,11 +5,13 @@ import com.sun.jersey.api.client.GenericType; import {{invokerPackage}}.ApiException; import {{invokerPackage}}.ApiClient; import {{invokerPackage}}.Configuration; +import {{modelPackage}}.*; import {{invokerPackage}}.Pair; {{#imports}}import {{import}}; {{/imports}} + {{^fullJavaUtil}} import java.util.ArrayList; import java.util.HashMap; diff --git a/modules/swagger-codegen/src/main/resources/Java/enum_outer_doc.mustache b/modules/swagger-codegen/src/main/resources/Java/enum_outer_doc.mustache index 14b5d524c4a..20c512aaeae 100644 --- a/modules/swagger-codegen/src/main/resources/Java/enum_outer_doc.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/enum_outer_doc.mustache @@ -2,6 +2,6 @@ ## Enum -{{#allowableValues}} -* `{{.}}` -{{/allowableValues}} +{{#allowableValues}}{{#enumVars}} +* `{{name}}` (value: `{{{value}}}`) +{{/enumVars}}{{/allowableValues}} diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/enum_outer_doc.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/enum_outer_doc.mustache index b5370c1360b..20c512aaeae 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/enum_outer_doc.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/enum_outer_doc.mustache @@ -3,5 +3,5 @@ ## Enum {{#allowableValues}}{{#enumVars}} -* `{{name}}` (value: `{{value}}`) +* `{{name}}` (value: `{{{value}}}`) {{/enumVars}}{{/allowableValues}} diff --git a/modules/swagger-codegen/src/main/resources/Java/model.mustache b/modules/swagger-codegen/src/main/resources/Java/model.mustache index 66ba76bcbc5..0ac1d53d2d8 100644 --- a/modules/swagger-codegen/src/main/resources/Java/model.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/model.mustache @@ -1,5 +1,6 @@ package {{package}}; +import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; {{#imports}}import {{import}}; {{/imports}} diff --git a/modules/swagger-codegen/src/main/resources/JavaSpringBoot/README.mustache b/modules/swagger-codegen/src/main/resources/JavaSpringBoot/README.mustache new file mode 100644 index 00000000000..8f9855eedf9 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaSpringBoot/README.mustache @@ -0,0 +1,18 @@ +# Swagger generated server + +Spring Boot Server + + +## Overview +This server was generated by the [swagger-codegen](https://github.com/swagger-api/swagger-codegen) project. +By using the [OpenAPI-Spec](https://github.com/swagger-api/swagger-core), you can easily generate a server stub. +This is an example of building a swagger-enabled server in Java using the SpringBoot framework. + +The underlying library integrating swagger to SpringBoot is [springfox](https://github.com/springfox/springfox) + +Start your server as an simple java application + +You can view the api documentation in swagger-ui by pointing to +http://localhost:8080/ + +Change default port value in application.properties \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaSpringBoot/api.mustache b/modules/swagger-codegen/src/main/resources/JavaSpringBoot/api.mustache new file mode 100644 index 00000000000..126fbf61a2c --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaSpringBoot/api.mustache @@ -0,0 +1,56 @@ +package {{apiPackage}}; + +import {{modelPackage}}.*; + +{{#imports}}import {{import}}; +{{/imports}} + +import io.swagger.annotations.*; + +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RequestPart; +import org.springframework.web.multipart.MultipartFile; + +import java.util.List; + +import static org.springframework.http.MediaType.*; + +@Controller +@RequestMapping(value = "/{{{baseName}}}", produces = {APPLICATION_JSON_VALUE}) +@Api(value = "/{{{baseName}}}", description = "the {{{baseName}}} API") +{{>generatedAnnotation}} +{{#operations}} +public class {{classname}} { + {{#operation}} + + @ApiOperation(value = "{{{summary}}}", notes = "{{{notes}}}", response = {{{returnType}}}.class{{#returnContainer}}, responseContainer = "{{{returnContainer}}}"{{/returnContainer}}{{#hasAuthMethods}}, authorizations = { + {{#authMethods}}@Authorization(value = "{{name}}"{{#isOAuth}}, scopes = { + {{#scopes}}@AuthorizationScope(scope = "{{scope}}", description = "{{description}}"){{#hasMore}}, + {{/hasMore}}{{/scopes}} + }{{/isOAuth}}){{#hasMore}}, + {{/hasMore}}{{/authMethods}} + }{{/hasAuthMethods}}) + @ApiResponses(value = { {{#responses}} + @ApiResponse(code = {{{code}}}, message = "{{{message}}}", response = {{{returnType}}}.class){{#hasMore}},{{/hasMore}}{{/responses}} }) + @RequestMapping(value = "{{{path}}}", + {{#hasProduces}}produces = { {{#produces}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }, {{/hasProduces}} + {{#hasConsumes}}consumes = { {{#consumes}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} },{{/hasConsumes}} + method = RequestMethod.{{httpMethod}}) + public ResponseEntity<{{>returnTypes}}> {{operationId}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}}, + {{/hasMore}}{{/allParams}}) + throws NotFoundException { + // do some magic! + return new ResponseEntity<{{>returnTypes}}>(HttpStatus.OK); + } + + {{/operation}} +} +{{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/JavaSpringBoot/apiException.mustache b/modules/swagger-codegen/src/main/resources/JavaSpringBoot/apiException.mustache new file mode 100644 index 00000000000..11b4036b832 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaSpringBoot/apiException.mustache @@ -0,0 +1,10 @@ +package {{apiPackage}}; + +{{>generatedAnnotation}} +public class ApiException extends Exception{ + private int code; + public ApiException (int code, String msg) { + super(msg); + this.code = code; + } +} diff --git a/modules/swagger-codegen/src/main/resources/JavaSpringBoot/apiOriginFilter.mustache b/modules/swagger-codegen/src/main/resources/JavaSpringBoot/apiOriginFilter.mustache new file mode 100644 index 00000000000..5db3301b3d9 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaSpringBoot/apiOriginFilter.mustache @@ -0,0 +1,27 @@ +package {{apiPackage}}; + +import java.io.IOException; + +import javax.servlet.*; +import javax.servlet.http.HttpServletResponse; + +{{>generatedAnnotation}} +public class ApiOriginFilter implements javax.servlet.Filter { + @Override + public void doFilter(ServletRequest request, ServletResponse response, + FilterChain chain) throws IOException, ServletException { + HttpServletResponse res = (HttpServletResponse) response; + res.addHeader("Access-Control-Allow-Origin", "*"); + res.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT"); + res.addHeader("Access-Control-Allow-Headers", "Content-Type"); + chain.doFilter(request, response); + } + + @Override + public void destroy() { + } + + @Override + public void init(FilterConfig filterConfig) throws ServletException { + } +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaSpringBoot/apiResponseMessage.mustache b/modules/swagger-codegen/src/main/resources/JavaSpringBoot/apiResponseMessage.mustache new file mode 100644 index 00000000000..2b9a2b1f8c5 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaSpringBoot/apiResponseMessage.mustache @@ -0,0 +1,69 @@ +package {{apiPackage}}; + +import javax.xml.bind.annotation.XmlTransient; + +@javax.xml.bind.annotation.XmlRootElement +{{>generatedAnnotation}} +public class ApiResponseMessage { + public static final int ERROR = 1; + public static final int WARNING = 2; + public static final int INFO = 3; + public static final int OK = 4; + public static final int TOO_BUSY = 5; + + int code; + String type; + String message; + + public ApiResponseMessage(){} + + public ApiResponseMessage(int code, String message){ + this.code = code; + switch(code){ + case ERROR: + setType("error"); + break; + case WARNING: + setType("warning"); + break; + case INFO: + setType("info"); + break; + case OK: + setType("ok"); + break; + case TOO_BUSY: + setType("too busy"); + break; + default: + setType("unknown"); + break; + } + this.message = message; + } + + @XmlTransient + public int getCode() { + return code; + } + + public void setCode(int code) { + this.code = code; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } +} diff --git a/modules/swagger-codegen/src/main/resources/JavaSpringBoot/application.properties b/modules/swagger-codegen/src/main/resources/JavaSpringBoot/application.properties new file mode 100644 index 00000000000..858a5f007b5 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaSpringBoot/application.properties @@ -0,0 +1,2 @@ +springfox.documentation.swagger.v2.path=/api-docs +#server.port=8090 \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaSpringBoot/bodyParams.mustache b/modules/swagger-codegen/src/main/resources/JavaSpringBoot/bodyParams.mustache new file mode 100644 index 00000000000..f1137ba7073 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaSpringBoot/bodyParams.mustache @@ -0,0 +1 @@ +{{#isBodyParam}}@ApiParam(value = "{{{description}}}" {{#required}},required=true{{/required}} {{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}) @RequestBody {{{dataType}}} {{paramName}}{{/isBodyParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaSpringBoot/formParams.mustache b/modules/swagger-codegen/src/main/resources/JavaSpringBoot/formParams.mustache new file mode 100644 index 00000000000..65e84817a23 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaSpringBoot/formParams.mustache @@ -0,0 +1,2 @@ +{{#isFormParam}}{{#notFile}} +@ApiParam(value = "{{{description}}}"{{#required}}, required=true{{/required}} {{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}) @RequestPart(value="{{paramName}}"{{#required}}, required=true{{/required}}{{^required}}, required=false{{/required}}) {{{dataType}}} {{paramName}}{{/notFile}}{{#isFile}}@ApiParam(value = "file detail") @RequestPart("file") MultipartFile {{baseName}}{{/isFile}}{{/isFormParam}} diff --git a/modules/swagger-codegen/src/main/resources/JavaSpringBoot/generatedAnnotation.mustache b/modules/swagger-codegen/src/main/resources/JavaSpringBoot/generatedAnnotation.mustache new file mode 100644 index 00000000000..49110fc1ad9 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaSpringBoot/generatedAnnotation.mustache @@ -0,0 +1 @@ +@javax.annotation.Generated(value = "{{generatorClass}}", date = "{{generatedDate}}") \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaSpringBoot/headerParams.mustache b/modules/swagger-codegen/src/main/resources/JavaSpringBoot/headerParams.mustache new file mode 100644 index 00000000000..297d5131d92 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaSpringBoot/headerParams.mustache @@ -0,0 +1 @@ +{{#isHeaderParam}}@ApiParam(value = "{{{description}}}" {{#required}},required=true{{/required}} {{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}) @RequestHeader(value="{{baseName}}", required={{#required}}true{{/required}}{{^required}}false{{/required}}) {{{dataType}}} {{paramName}}{{/isHeaderParam}} diff --git a/modules/swagger-codegen/src/main/resources/JavaSpringBoot/homeController.mustache b/modules/swagger-codegen/src/main/resources/JavaSpringBoot/homeController.mustache new file mode 100644 index 00000000000..a3528010fb1 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaSpringBoot/homeController.mustache @@ -0,0 +1,16 @@ +package {{configPackage}}; + +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; + +/** + * Home redirection to swagger api documentation + */ +@Controller +public class HomeController { + @RequestMapping(value = "/") + public String index() { + System.out.println("swagger-ui.html"); + return "redirect:swagger-ui.html"; + } +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaSpringBoot/model.mustache b/modules/swagger-codegen/src/main/resources/JavaSpringBoot/model.mustache new file mode 100644 index 00000000000..b39a599ae71 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaSpringBoot/model.mustache @@ -0,0 +1,77 @@ +package {{package}}; + +{{#imports}}import {{import}}; +{{/imports}} + +import io.swagger.annotations.*; +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.util.Objects; +{{#models}} + +{{#model}}{{#description}} +/** + * {{description}} + **/{{/description}} +@ApiModel(description = "{{{description}}}") +{{>generatedAnnotation}} +public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} { + {{#vars}}{{#isEnum}} + public enum {{datatypeWithEnum}} { + {{#allowableValues}}{{#values}} {{.}}, {{/values}}{{/allowableValues}} + }; + {{/isEnum}}{{#items}}{{#isEnum}} + public enum {{datatypeWithEnum}} { + {{#allowableValues}}{{#values}} {{.}}, {{/values}}{{/allowableValues}} + }; + {{/isEnum}}{{/items}} + 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(" " + super.toString()).append("\n");{{/parent}} + {{#vars}}sb.append(" {{name}}: ").append({{name}}).append("\n"); + {{/vars}}sb.append("}\n"); + return sb.toString(); + } +} +{{/model}} +{{/models}} diff --git a/modules/swagger-codegen/src/main/resources/JavaSpringBoot/notFoundException.mustache b/modules/swagger-codegen/src/main/resources/JavaSpringBoot/notFoundException.mustache new file mode 100644 index 00000000000..1bd5e207d7b --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaSpringBoot/notFoundException.mustache @@ -0,0 +1,10 @@ +package {{apiPackage}}; + +{{>generatedAnnotation}} +public class NotFoundException extends ApiException { + private int code; + public NotFoundException (int code, String msg) { + super(code, msg); + this.code = code; + } +} diff --git a/modules/swagger-codegen/src/main/resources/JavaSpringBoot/pathParams.mustache b/modules/swagger-codegen/src/main/resources/JavaSpringBoot/pathParams.mustache new file mode 100644 index 00000000000..4a6f7dfc922 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaSpringBoot/pathParams.mustache @@ -0,0 +1 @@ +{{#isPathParam}}@ApiParam(value = "{{{description}}}"{{#required}},required=true{{/required}}{{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{/allowableValues}} {{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}) @PathVariable("{{paramName}}") {{{dataType}}} {{paramName}}{{/isPathParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaSpringBoot/pom.mustache b/modules/swagger-codegen/src/main/resources/JavaSpringBoot/pom.mustache new file mode 100644 index 00000000000..f6cc38793e7 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaSpringBoot/pom.mustache @@ -0,0 +1,54 @@ + + 4.0.0 + {{groupId}} + {{artifactId}} + jar + {{artifactId}} + {{artifactVersion}} + + 2.4.0 + + + org.springframework.boot + spring-boot-starter-parent + 1.3.3.RELEASE + + + src/main/java + + + org.springframework.boot + spring-boot-maven-plugin + + + + repackage + + + + + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-tomcat + provided + + + + io.springfox + springfox-swagger2 + ${springfox-version} + + + io.springfox + springfox-swagger-ui + ${springfox-version} + + + \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaSpringBoot/project/build.properties b/modules/swagger-codegen/src/main/resources/JavaSpringBoot/project/build.properties new file mode 100644 index 00000000000..a8c2f849be3 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaSpringBoot/project/build.properties @@ -0,0 +1 @@ +sbt.version=0.12.0 diff --git a/modules/swagger-codegen/src/main/resources/JavaSpringBoot/project/plugins.sbt b/modules/swagger-codegen/src/main/resources/JavaSpringBoot/project/plugins.sbt new file mode 100644 index 00000000000..713b7f3e993 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaSpringBoot/project/plugins.sbt @@ -0,0 +1,9 @@ +addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "0.8.4") + +libraryDependencies <+= sbtVersion(v => v match { + case "0.11.0" => "com.github.siasia" %% "xsbt-web-plugin" % "0.11.0-0.2.8" + case "0.11.1" => "com.github.siasia" %% "xsbt-web-plugin" % "0.11.1-0.2.10" + case "0.11.2" => "com.github.siasia" %% "xsbt-web-plugin" % "0.11.2-0.2.11" + case "0.11.3" => "com.github.siasia" %% "xsbt-web-plugin" % "0.11.3-0.2.11.1" + case x if (x.startsWith("0.12")) => "com.github.siasia" %% "xsbt-web-plugin" % "0.12.0-0.2.11.1" +}) \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaSpringBoot/queryParams.mustache b/modules/swagger-codegen/src/main/resources/JavaSpringBoot/queryParams.mustache new file mode 100644 index 00000000000..3bb2afcb6cd --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaSpringBoot/queryParams.mustache @@ -0,0 +1 @@ +{{#isQueryParam}}@ApiParam(value = "{{{description}}}"{{#required}}, required = true{{/required}}{{#allowableValues}}, allowableValues = "{{{allowableValues}}}"{{/allowableValues}}{{#defaultValue}}, defaultValue = "{{{defaultValue}}}"{{/defaultValue}}) @RequestParam(value = "{{paramName}}"{{#required}}, required = true{{/required}}{{^required}}, required = false{{/required}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}) {{{dataType}}} {{paramName}}{{/isQueryParam}} diff --git a/modules/swagger-codegen/src/main/resources/JavaSpringBoot/returnTypes.mustache b/modules/swagger-codegen/src/main/resources/JavaSpringBoot/returnTypes.mustache new file mode 100644 index 00000000000..c8f7a56938a --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaSpringBoot/returnTypes.mustache @@ -0,0 +1 @@ +{{#returnContainer}}{{#isMapContainer}}Map{{/isMapContainer}}{{#isListContainer}}List<{{{returnType}}}>{{/isListContainer}}{{/returnContainer}}{{^returnContainer}}{{{returnType}}}{{/returnContainer}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaSpringBoot/swagger2SpringBoot.mustache b/modules/swagger-codegen/src/main/resources/JavaSpringBoot/swagger2SpringBoot.mustache new file mode 100644 index 00000000000..ebd4ae4ac55 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaSpringBoot/swagger2SpringBoot.mustache @@ -0,0 +1,36 @@ +package {{basePackage}}; + +import org.springframework.boot.CommandLineRunner; +import org.springframework.boot.ExitCodeGenerator; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.ComponentScan; + +import springfox.documentation.swagger2.annotations.EnableSwagger2; + +@SpringBootApplication +@EnableSwagger2 +@ComponentScan(basePackages = "{{basePackage}}") +public class Swagger2SpringBoot implements CommandLineRunner { + + @Override + public void run(String... arg0) throws Exception { + if (arg0.length > 0 && arg0[0].equals("exitcode")) { + throw new ExitException(); + } + } + + public static void main(String[] args) throws Exception { + new SpringApplication(Swagger2SpringBoot.class).run(args); + } + + class ExitException extends RuntimeException implements ExitCodeGenerator { + private static final long serialVersionUID = 1L; + + @Override + public int getExitCode() { + return 10; + } + + } +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaSpringBoot/swaggerDocumentationConfig.mustache b/modules/swagger-codegen/src/main/resources/JavaSpringBoot/swaggerDocumentationConfig.mustache new file mode 100644 index 00000000000..1af646a6908 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaSpringBoot/swaggerDocumentationConfig.mustache @@ -0,0 +1,40 @@ +package {{configPackage}}; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import springfox.documentation.builders.ApiInfoBuilder; +import springfox.documentation.builders.RequestHandlerSelectors; +import springfox.documentation.service.ApiInfo; +import springfox.documentation.service.Contact; +import springfox.documentation.spi.DocumentationType; +import springfox.documentation.spring.web.plugins.Docket; + + + +@Configuration +{{>generatedAnnotation}} +public class SwaggerDocumentationConfig { + + ApiInfo apiInfo() { + return new ApiInfoBuilder() + .title("{{appName}}") + .description("{{{appDescription}}}") + .license("{{licenseInfo}}") + .licenseUrl("{{licenseUrl}}") + .termsOfServiceUrl("{{infoUrl}}") + .version("{{appVersion}}") + .contact(new Contact("","", "{{infoEmail}}")) + .build(); + } + + @Bean + public Docket customImplementation(){ + return new Docket(DocumentationType.SWAGGER_2) + .select() + .apis(RequestHandlerSelectors.basePackage("{{apiPackage}}")) + .build() + .apiInfo(apiInfo()); + } + +} diff --git a/modules/swagger-codegen/src/main/resources/Javascript/model_doc.mustache b/modules/swagger-codegen/src/main/resources/Javascript/model_doc.mustache index 306d8a2b3f7..4f2324fa2a7 100644 --- a/modules/swagger-codegen/src/main/resources/Javascript/model_doc.mustache +++ b/modules/swagger-codegen/src/main/resources/Javascript/model_doc.mustache @@ -1,9 +1,25 @@ -{{#models}}{{#model}}# {{moduleName}}.{{classname}} +{{#models}}{{#model}}{{#isEnum}}# {{moduleName}}.{{classname}} + +## Enum + +{{#allowableValues}}{{#enumVars}} +* `{{name}}` (value: `{{{value}}}`) +{{/enumVars}}{{/allowableValues}} +{{/isEnum}}{{^isEnum}}# {{moduleName}}.{{classname}} ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- {{#vars}}**{{name}}** | {{#isPrimitiveType}}**{{datatype}}**{{/isPrimitiveType}}{{^isPrimitiveType}}[**{{datatype}}**]({{complexType}}.md){{/isPrimitiveType}} | {{description}} | {{^required}}[optional] {{/required}}{{#readOnly}}[readonly] {{/readOnly}}{{#defaultValue}}[default to {{defaultValue}}]{{/defaultValue}} {{/vars}} +{{#vars}}{{#isEnum}} -{{/model}}{{/models}} + +## Enum: {{datatypeWithEnum}} + +{{#allowableValues}}{{#enumVars}} +* `{{name}}` (value: `{{{value}}}`) +{{/enumVars}}{{/allowableValues}} + +{{/isEnum}}{{/vars}} +{{/isEnum}}{{/model}}{{/models}} diff --git a/modules/swagger-codegen/src/main/resources/Javascript/partial_model_enum_class.mustache b/modules/swagger-codegen/src/main/resources/Javascript/partial_model_enum_class.mustache index c7d18d35841..9ad7e3d3a90 100644 --- a/modules/swagger-codegen/src/main/resources/Javascript/partial_model_enum_class.mustache +++ b/modules/swagger-codegen/src/main/resources/Javascript/partial_model_enum_class.mustache @@ -5,18 +5,18 @@ * @readonly */ {{/emitJSDoc}} - exports.{{classname}} = { + var exports = { {{#allowableValues}} - {{#values}} + {{#enumVars}} {{#emitJSDoc}} /** - * value: {{{.}}} + * value: {{{value}}} * @const */ {{/emitJSDoc}} - "{{{.}}}": "{{{.}}}"{{^-last}}, + "{{name}}": {{{value}}}{{^-last}}, {{/-last}} - {{/values}} + {{/enumVars}} {{/allowableValues}} }; 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 22823c95626..c84abac129c 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 @@ -28,6 +28,7 @@ io.swagger.codegen.languages.ScalatraServerCodegen io.swagger.codegen.languages.SilexServerCodegen io.swagger.codegen.languages.SinatraServerCodegen io.swagger.codegen.languages.SlimFrameworkServerCodegen +io.swagger.codegen.languages.SpringBootServerCodegen io.swagger.codegen.languages.SpringMVCServerCodegen io.swagger.codegen.languages.StaticDocCodegen io.swagger.codegen.languages.StaticHtmlGenerator @@ -38,6 +39,7 @@ io.swagger.codegen.languages.TizenClientCodegen io.swagger.codegen.languages.TypeScriptAngular2ClientCodegen io.swagger.codegen.languages.TypeScriptAngularClientCodegen io.swagger.codegen.languages.TypeScriptNodeClientCodegen +io.swagger.codegen.languages.TypeScriptFetchClientCodegen io.swagger.codegen.languages.AkkaScalaClientCodegen io.swagger.codegen.languages.CsharpDotNet2ClientCodegen io.swagger.codegen.languages.ClojureClientCodegen diff --git a/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/README.md b/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/README.md new file mode 100644 index 00000000000..8ec43e76497 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/README.md @@ -0,0 +1,44 @@ +# TypeScript-Fetch + +This generator creates TypeScript/JavaScript client that utilizes [Fetch API](https://fetch.spec.whatwg.org/). The codegen Node module can be used in the following environments: + +* Node.JS +* Webpack +* Browserify + +It is usable in both TypeScript and JavaScript. In TypeScript, the definition should be automatically resolved via `typings` in `package.json`. ([Reference](http://www.typescriptlang.org/docs/handbook/typings-for-npm-packages.html)) + +### Installation ### + +`swagger-codegen` does not generate JavaScript directly. The codegen Node module comes with `package.json` that bundles `typescript` and `typings` so it can self-compile. The self-compile is normally run automatically via the `npm` `postinstall` script of `npm install`. + +CAVEAT: Due to [privilege implications](https://docs.npmjs.com/misc/scripts#user), `npm` may skip `postinstall` script if the user is `root`. You would need to manually invoke `npm install` or `npm run postinstall` for the codegen module if that's the case. + +#### NPM repository ### +If you remove `"private": true` from `package.json`, you may publish the module to NPM. In which case, you would be able to install the module as any other NPM module. + +It maybe useful to use [scoped packages](https://docs.npmjs.com/misc/scope). + +#### NPM install local file ### +You should be able to directly install the module using `npm install file:///codegen_path`. + +NOTES: If you do `npm install file:///codegen_path --save` NPM might convert your path to relative path, maybe have adverse affect. `npm install` and `npm shrinkwrap` may misbehave if the installation path is not absolute. + +#### direct copy/symlink ### +You may also simply copy or symlink the codegen into a directly under your project. The syntax of the usage would differ if you take this route. (See below) + +### Usage ### +With ES6 module syntax, the following syntaxes are supported: +``` +import * as localName from 'npmName'; +import {operationId} from 'npmName'; + +import * as localName from './symlinkDir'; +import {operationId} from './symlinkDir'; +``` +With CommonJS, the following syntaxes are supported: +``` +import localName = require('npmName'); + +import localName = require('./symlinkDir')'; +``` \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/api.mustache b/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/api.mustache new file mode 100644 index 00000000000..67d61999aa0 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/api.mustache @@ -0,0 +1,133 @@ +import * as querystring from 'querystring'; +import * as fetch from 'isomorphic-fetch'; +import {assign} from './assign'; + + +{{#models}} +{{#model}} +{{#description}} +/** + * {{{description}}} + */ +{{/description}} +export interface {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}{ +{{#vars}} +{{#description}} + + /** + * {{{description}}} + */ +{{/description}} + "{{name}}"{{^required}}?{{/required}}: {{#isEnum}}{{classname}}.{{{datatypeWithEnum}}}{{/isEnum}}{{^isEnum}}{{{datatype}}}{{/isEnum}}; +{{/vars}} +} + +{{#hasEnums}} +export namespace {{classname}} { +{{#vars}} +{{#isEnum}} + +export type {{datatypeWithEnum}} = {{#allowableValues}}{{#values}}'{{.}}'{{^-last}} | {{/-last}}{{/values}}{{/allowableValues}}; +{{/isEnum}} +{{/vars}} +} +{{/hasEnums}} +{{/model}} +{{/models}} + +{{#apiInfo}} +{{#apis}} +{{#operations}} +//export namespace {{package}} { + 'use strict'; + +{{#description}} + /** + * {{&description}} + */ +{{/description}} + export class {{classname}} { + protected basePath = '{{basePath}}'; + public defaultHeaders : any = {}; + + constructor(basePath?: string) { + if (basePath) { + this.basePath = basePath; + } + } + +{{#operation}} + /** + * {{summary}} + * {{notes}} + {{#allParams}}* @param {{paramName}} {{description}} + {{/allParams}}*/ + public {{nickname}} (params: { {{#allParams}} {{paramName}}{{^required}}?{{/required}}: {{{dataType}}};{{/allParams}} }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}{}{{/returnType}}> { + const localVarPath = this.basePath + '{{path}}'{{#pathParams}} + .replace('{' + '{{baseName}}' + '}', String(params.{{paramName}})){{/pathParams}}; + + let queryParameters: any = assign({}, extraQueryParams); + let headerParams: any = assign({}, this.defaultHeaders); +{{#hasFormParams}} + let formParams: any = {}; + headerParams['Content-Type'] = 'application/x-www-form-urlencoded'; + +{{/hasFormParams}} +{{#hasBodyParam}} + headerParams['Content-Type'] = 'application/json'; + +{{/hasBodyParam}} +{{#allParams}} +{{#required}} + // verify required parameter '{{paramName}}' is set + if (params.{{paramName}} == null) { + throw new Error('Missing required parameter {{paramName}} when calling {{nickname}}'); + } +{{/required}} +{{/allParams}} +{{#queryParams}} + if (params.{{paramName}} !== undefined) { + queryParameters['{{baseName}}'] = params.{{paramName}}; + } + +{{/queryParams}} +{{#headerParams}} + headerParams['{{baseName}}'] = params.{{paramName}}; + +{{/headerParams}} +{{#formParams}} + formParams['{{baseName}}'] = params.{{paramName}}; + +{{/formParams}} + let fetchParams = { + method: '{{httpMethod}}', + headers: headerParams, + {{#bodyParam}}body: JSON.stringify(params.{{paramName}}), + {{/bodyParam}} + {{#hasFormParams}}body: querystring.stringify(formParams), + {{/hasFormParams}} + + }; + + if (extraFetchParams) { + fetchParams = assign(fetchParams, extraFetchParams); + } + + let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); + + return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + let error = new Error(response.statusText); + (error as any).response = response; + throw error; + } + }); + } +{{/operation}} + } +//} +{{/operations}} +{{/apis}} +{{/apiInfo}} diff --git a/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/assign.ts b/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/assign.ts new file mode 100644 index 00000000000..23355144147 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/assign.ts @@ -0,0 +1,18 @@ +export function assign (target: any, ...args: any[]) { + 'use strict'; + if (target === undefined || target === null) { + throw new TypeError('Cannot convert undefined or null to object'); + } + + var output = Object(target); + for (let source of args) { + if (source !== undefined && source !== null) { + for (var nextKey in source) { + if (source.hasOwnProperty(nextKey)) { + output[nextKey] = source[nextKey]; + } + } + } + } + return output; +}; \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/git_push.sh.mustache b/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/git_push.sh.mustache new file mode 100755 index 00000000000..e153ce23ecf --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/git_push.sh.mustache @@ -0,0 +1,52 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 swagger-petstore-perl "minor update" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 + +if [ "$git_user_id" = "" ]; then + git_user_id="{{{gitUserId}}}" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="{{{gitRepoId}}}" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="{{{releaseNote}}}" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=`git remote` +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git crediential in your environment." + git remote add origin https://github.com/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:${GIT_TOKEN}@github.com/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://github.com/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' + diff --git a/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/package.json.mustache b/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/package.json.mustache new file mode 100644 index 00000000000..e6379434b80 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/package.json.mustache @@ -0,0 +1,18 @@ +{ + "name": "{{#npmName}}{{{npmName}}}{{/npmName}}{{^npmName}}typescript-fetch-api{{/npmName}}", + "version": "{{#npmVersion}}{{{npmVersion}}}{{/npmVersion}}{{^npmVersion}}0.0.0{{/npmVersion}}", + "private": true, + "main": "./dist/api.js", + "browser": "./dist/api.js", + "typings": "./dist/api.d.ts", + "dependencies": { + "isomorphic-fetch": "^2.2.1" + }, + "scripts" : { + "install" : "typings install && tsc" + }, + "devDependencies": { + "typescript": "^1.8.10", + "typings": "^0.8.1" + } +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/tsconfig.json.mustache b/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/tsconfig.json.mustache new file mode 100644 index 00000000000..06a057d7a49 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/tsconfig.json.mustache @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "declaration": true, + "target": "{{#supportsES6}}es6{{/supportsES6}}{{^supportsES6}}es5{{/supportsES6}}", + "module": "commonjs", + "noImplicitAny": true, + "outDir": "dist" + }, + "exclude": [ + "dist", + "node_modules", + "typings/browser", + "typings/main", + "typings/main.d.ts" + ] +} diff --git a/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/typings.json.mustache b/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/typings.json.mustache new file mode 100644 index 00000000000..38baf589fb9 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/typings.json.mustache @@ -0,0 +1,9 @@ +{ + "version": false, + "dependencies": {}, + "ambientDependencies": { +{{^supportsES6}} "es6-promise": "registry:dt/es6-promise#0.0.0+20160423074304", +{{/supportsES6}} "node": "registry:dt/node#4.0.0+20160423143914", + "isomorphic-fetch": "registry:dt/isomorphic-fetch#0.0.0+20160505171433" + } +} diff --git a/modules/swagger-codegen/src/main/resources/csharp/Project.mustache b/modules/swagger-codegen/src/main/resources/csharp/Project.mustache index d38e5d92d1e..141d541a5b5 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/Project.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/Project.mustache @@ -39,8 +39,6 @@ - - @@ -48,18 +46,23 @@ - False - {{binRelativePath}}/Newtonsoft.Json.8.0.2/lib/{{targetFrameworkNuget}}/Newtonsoft.Json.dll + $(SolutionDir)\packages\Newtonsoft.Json.8.0.2\lib\{{targetFrameworkNuget}}\Newtonsoft.Json.dll + ..\packages\Newtonsoft.Json.8.0.2\lib\{{targetFrameworkNuget}}\Newtonsoft.Json.dll + ..\..\packages\Newtonsoft.Json.8.0.2\lib\{{targetFrameworkNuget}}\Newtonsoft.Json.dll + {{binRelativePath}}\Newtonsoft.Json.8.0.2\lib\{{targetFrameworkNuget}}\Newtonsoft.Json.dll - {{binRelativePath}}/RestSharp.105.2.3/lib/{{targetFrameworkNuget}}/RestSharp.dll + $(SolutionDir)\packages\RestSharp.105.1.0\lib\{{targetFrameworkNuget}}\RestSharp.dll + ..\packages\RestSharp.105.1.0\lib\{{targetFrameworkNuget}}\RestSharp.dll + ..\..\packages\RestSharp.105.1.0\lib\{{targetFrameworkNuget}}\RestSharp.dll + {{binRelativePath}}\RestSharp.105.1.0\lib\{{targetFrameworkNuget}}\RestSharp.dll - - - - + + + + diff --git a/modules/swagger-codegen/src/main/resources/csharp/README.mustache b/modules/swagger-codegen/src/main/resources/csharp/README.mustache index 06660a3c615..fa0d40873f1 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/README.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/README.mustache @@ -37,8 +37,8 @@ NOTE: RestSharp versions greater than 105.1.0 have a bug which causes file uploa ## Installation Run the following command to generate the DLL -- [Mac/Linux] `/bin/sh compile-mono.sh` -- [Windows] `compile.bat` +- [Mac/Linux] `/bin/sh build.sh` +- [Windows] `build.bat` Then include the DLL (under the `bin` folder) in the C# project, and use the namespaces: ```csharp @@ -72,8 +72,8 @@ namespace Example Configuration.Default.Password = 'YOUR_PASSWORD';{{/isBasic}}{{#isApiKey}} // Configure API key authorization: {{{name}}} Configuration.Default.ApiKey.Add('{{{keyParamName}}}', 'YOUR_API_KEY'); - // Uncomment below to setup prefix (e.g. BEARER) for API key, if needed - // Configuration.Default.ApiKeyPrefix.Add('{{{keyParamName}}}', 'BEARER');{{/isApiKey}}{{#isOAuth}} + // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed + // Configuration.Default.ApiKeyPrefix.Add('{{{keyParamName}}}', 'Bearer');{{/isApiKey}}{{#isOAuth}} // Configure OAuth2 access token for authorization: {{{name}}} Configuration.Default.AccessToken = 'YOUR_ACCESS_TOKEN';{{/isOAuth}}{{/authMethods}} {{/hasAuthMethods}} diff --git a/modules/swagger-codegen/src/main/resources/csharp/Solution.mustache b/modules/swagger-codegen/src/main/resources/csharp/Solution.mustache new file mode 100644 index 00000000000..57f6201600f --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/csharp/Solution.mustache @@ -0,0 +1,27 @@ +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 2012 +VisualStudioVersion = 12.0.0.0 +MinimumVisualStudioVersion = 10.0.0.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "{{packageName}}", "src\{{packageName}}\{{packageName}}.csproj", "{{packageGuid}}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "{{testPackageName}}", "src\{{testPackageName}}\{{testPackageName}}.csproj", "{19F1DEBC-DE5E-4517-8062-F000CD499087}" +EndProject +Global +GlobalSection(SolutionConfigurationPlatforms) = preSolution +Debug|Any CPU = Debug|Any CPU +Release|Any CPU = Release|Any CPU +EndGlobalSection +GlobalSection(ProjectConfigurationPlatforms) = postSolution +{{packageGuid}}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{{packageGuid}}.Debug|Any CPU.Build.0 = Debug|Any CPU +{{packageGuid}}.Release|Any CPU.ActiveCfg = Release|Any CPU +{{packageGuid}}.Release|Any CPU.Build.0 = Release|Any CPU +{19F1DEBC-DE5E-4517-8062-F000CD499087}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{19F1DEBC-DE5E-4517-8062-F000CD499087}.Debug|Any CPU.Build.0 = Debug|Any CPU +{19F1DEBC-DE5E-4517-8062-F000CD499087}.Release|Any CPU.ActiveCfg = Release|Any CPU +{19F1DEBC-DE5E-4517-8062-F000CD499087}.Release|Any CPU.Build.0 = Release|Any CPU +EndGlobalSection +GlobalSection(SolutionProperties) = preSolution +HideSolutionNode = FALSE +EndGlobalSection +EndGlobal \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/csharp/TestProject.mustache b/modules/swagger-codegen/src/main/resources/csharp/TestProject.mustache new file mode 100644 index 00000000000..0e0bd6c1671 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/csharp/TestProject.mustache @@ -0,0 +1,81 @@ + + + + Debug + AnyCPU + {19F1DEBC-DE5E-4517-8062-F000CD499087} + Library + Properties + {{testPackageName}} + {{testPackageName}} + {{^supportsUWP}} + {{targetFramework}} + {{/supportsUWP}} + {{#supportsUWP}} + UAP + 10.0.10240.0 + 10.0.10240.0 + 14 + {{/supportsUWP}} + 512 + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + $(SolutionDir)\packages\Newtonsoft.Json.8.0.2\lib\{{targetFrameworkNuget}}\Newtonsoft.Json.dll + ..\packages\Newtonsoft.Json.8.0.2\lib\{{targetFrameworkNuget}}\Newtonsoft.Json.dll + ..\..\packages\Newtonsoft.Json.8.0.2\lib\{{targetFrameworkNuget}}\Newtonsoft.Json.dll + {{binRelativePath}}\Newtonsoft.Json.8.0.2\lib\{{targetFrameworkNuget}}\Newtonsoft.Json.dll + + + $(SolutionDir)\packages\RestSharp.105.1.0\lib\{{targetFrameworkNuget}}\RestSharp.dll + ..\packages\RestSharp.105.1.0\lib\{{targetFrameworkNuget}}\RestSharp.dll + ..\..\packages\RestSharp.105.1.0\lib\{{targetFrameworkNuget}}\RestSharp.dll + {{binRelativePath}}\RestSharp.105.1.0\lib\{{targetFrameworkNuget}}\RestSharp.dll + + + $(SolutionDir)\packages\NUnit.2.6.3\lib\nunit.framework.dll + ..\packages\NUnit.2.6.3\lib\nunit.framework.dll + ..\..\packages\NUnit.2.6.3\lib\nunit.framework.dll + {{binRelativePath}}\NUnit.2.6.3\lib\nunit.framework.dll + + + + + + + + + + + + {{packageGuid}} + {{packageName}} + + + + diff --git a/modules/swagger-codegen/src/main/resources/csharp/api.mustache b/modules/swagger-codegen/src/main/resources/csharp/api.mustache index 85af270c213..2b3f224cfc5 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/api.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/api.mustache @@ -227,7 +227,7 @@ namespace {{packageName}}.Api if ({{paramName}} != null) {{#isFile}}localVarFileParams.Add("{{baseName}}", Configuration.ApiClient.ParameterToFile("{{baseName}}", {{paramName}}));{{/isFile}}{{^isFile}}localVarFormParams.Add("{{baseName}}", Configuration.ApiClient.ParameterToString({{paramName}})); // form parameter{{/isFile}} {{/formParams}} {{#bodyParam}} - if ({{paramName}}.GetType() != typeof(byte[])) + if ({{paramName}} != null && {{paramName}}.GetType() != typeof(byte[])) { localVarPostBody = Configuration.ApiClient.Serialize({{paramName}}); // http body (model) parameter } @@ -360,7 +360,7 @@ namespace {{packageName}}.Api if ({{paramName}} != null) {{#isFile}}localVarFileParams.Add("{{baseName}}", Configuration.ApiClient.ParameterToFile("{{baseName}}", {{paramName}}));{{/isFile}}{{^isFile}}localVarFormParams.Add("{{baseName}}", Configuration.ApiClient.ParameterToString({{paramName}})); // form parameter{{/isFile}} {{/formParams}} {{#bodyParam}} - if ({{paramName}}.GetType() != typeof(byte[])) + if ({{paramName}} != null && {{paramName}}.GetType() != typeof(byte[])) { localVarPostBody = Configuration.ApiClient.Serialize({{paramName}}); // http body (model) parameter } diff --git a/modules/swagger-codegen/src/main/resources/csharp/api_doc.mustache b/modules/swagger-codegen/src/main/resources/csharp/api_doc.mustache index e445191085a..677ad3edbe1 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/api_doc.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/api_doc.mustache @@ -37,8 +37,8 @@ namespace Example Configuration.Default.Password = 'YOUR_PASSWORD';{{/isBasic}}{{#isApiKey}} // Configure API key authorization: {{{name}}} Configuration.Default.ApiKey.Add('{{{keyParamName}}}', 'YOUR_API_KEY'); - // Uncomment below to setup prefix (e.g. BEARER) for API key, if needed - // Configuration.Default.ApiKeyPrefix.Add('{{{keyParamName}}}', 'BEARER');{{/isApiKey}}{{#isOAuth}} + // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed + // Configuration.Default.ApiKeyPrefix.Add('{{{keyParamName}}}', 'Bearer');{{/isApiKey}}{{#isOAuth}} // Configure OAuth2 access token for authorization: {{{name}}} Configuration.Default.AccessToken = 'YOUR_ACCESS_TOKEN';{{/isOAuth}}{{/authMethods}} {{/hasAuthMethods}} diff --git a/modules/swagger-codegen/src/main/resources/csharp/compile-mono.sh.mustache b/modules/swagger-codegen/src/main/resources/csharp/compile-mono.sh.mustache index b1b0c4f0c73..f93437eb0c8 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/compile-mono.sh.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/compile-mono.sh.mustache @@ -4,17 +4,17 @@ netfx=${frameworkVersion#net} wget -nc https://nuget.org/nuget.exe; mozroots --import --sync -mono nuget.exe install vendor/packages.config -o vendor; +mono nuget.exe install src/{{packageName}}/packages.config -o packages; mkdir -p bin; -cp vendor/Newtonsoft.Json.8.0.2/lib/{{targetFrameworkNuget}}/Newtonsoft.Json.dll bin/Newtonsoft.Json.dll; -cp vendor/RestSharp.105.1.0/lib/{{targetFrameworkNuget}}/RestSharp.dll bin/RestSharp.dll; +cp packages/Newtonsoft.Json.8.0.2/lib/{{targetFrameworkNuget}}/Newtonsoft.Json.dll bin/Newtonsoft.Json.dll; +cp packages/RestSharp.105.1.0/lib/{{targetFrameworkNuget}}/RestSharp.dll bin/RestSharp.dll; mcs -sdk:${netfx} -r:bin/Newtonsoft.Json.dll,\ bin/RestSharp.dll,\ System.Runtime.Serialization.dll \ -target:library \ -out:bin/{{packageName}}.dll \ --recurse:'src/*.cs' \ +-recurse:'src/{{packageName}}/*.cs' \ -doc:bin/{{packageName}}.xml \ -platform:anycpu diff --git a/modules/swagger-codegen/src/main/resources/csharp/compile.mustache b/modules/swagger-codegen/src/main/resources/csharp/compile.mustache index 76b94cad5a1..7f6dcfe0713 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/compile.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/compile.mustache @@ -4,11 +4,11 @@ {{^supportsAsync}}SET CSCPATH=%SYSTEMROOT%\Microsoft.NET\Framework\v3.5{{/supportsAsync}} if not exist ".\nuget.exe" powershell -Command "(new-object System.Net.WebClient).DownloadFile('https://nuget.org/nuget.exe', '.\nuget.exe')" -.\nuget.exe install vendor/packages.config -o vendor +.\nuget.exe install src\{{packageName}}\packages.config -o packages if not exist ".\bin" mkdir bin -copy vendor\Newtonsoft.Json.8.0.2\lib\{{targetFrameworkNuget}}\Newtonsoft.Json.dll bin\Newtonsoft.Json.dll -copy vendor\RestSharp.105.1.0\lib\{{targetFrameworkNuget}}\RestSharp.dll bin\RestSharp.dll +copy packages\Newtonsoft.Json.8.0.2\lib\{{targetFrameworkNuget}}\Newtonsoft.Json.dll bin\Newtonsoft.Json.dll +copy packages\RestSharp.105.1.0\lib\{{targetFrameworkNuget}}\RestSharp.dll bin\RestSharp.dll -%CSCPATH%\csc /reference:bin\Newtonsoft.Json.dll;bin\RestSharp.dll /target:library /out:bin\{{packageName}}.dll /recurse:src\*.cs /doc:bin\{{packageName}}.xml +%CSCPATH%\csc /reference:bin\Newtonsoft.Json.dll;bin\RestSharp.dll /target:library /out:bin\{{packageName}}.dll /recurse:src\{{packageName}}\*.cs /doc:bin\{{packageName}}.xml diff --git a/modules/swagger-codegen/src/main/resources/csharp/modelGeneric.mustache b/modules/swagger-codegen/src/main/resources/csharp/modelGeneric.mustache index 6c5da5e4f56..4d4061a29fd 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/modelGeneric.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/modelGeneric.mustache @@ -32,7 +32,7 @@ /// {{#description}}{{description}}{{/description}}{{^description}}{{name}}{{/description}}{{#required}} (required){{/required}}{{#defaultValue}} (default to {{defaultValue}}){{/defaultValue}}. {{/isReadOnly}} {{/vars}} - public {{classname}}({{#vars}}{{^isReadOnly}}{{{datatypeWithEnum}}}{{#isEnum}}?{{/isEnum}} {{name}} = null{{#hasMore}}, {{/hasMore}}{{/isReadOnly}}{{/vars}}) + public {{classname}}({{#vars}}{{^isReadOnly}}{{{datatypeWithEnum}}}{{#isEnum}}?{{/isEnum}} {{name}} = null{{/isReadOnly}}{{#hasMoreNonReadOnly}}, {{/hasMoreNonReadOnly}}{{/vars}}) { {{#vars}}{{^isReadOnly}}{{#required}}// to ensure "{{name}}" is required (not null) if ({{name}} == null) diff --git a/modules/swagger-codegen/src/main/resources/csharp/packages_test.config.mustache b/modules/swagger-codegen/src/main/resources/csharp/packages_test.config.mustache new file mode 100644 index 00000000000..5464714bcef --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/csharp/packages_test.config.mustache @@ -0,0 +1,6 @@ + + + + + + diff --git a/modules/swagger-codegen/src/main/resources/go/api.mustache b/modules/swagger-codegen/src/main/resources/go/api.mustache index 6ca3a39324f..480db023f6b 100644 --- a/modules/swagger-codegen/src/main/resources/go/api.mustache +++ b/modules/swagger-codegen/src/main/resources/go/api.mustache @@ -35,9 +35,9 @@ func New{{classname}}WithBasePath(basePath string) *{{classname}} { * {{notes}}{{/notes}} * {{#allParams}} * @param {{paramName}} {{description}} -{{/allParams}} * @return {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} +{{/allParams}} * @return {{#returnType}}{{^isListContainer}}*{{/isListContainer}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} */ -func (a {{classname}}) {{nickname}}({{#allParams}}{{paramName}} {{{dataType}}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) ({{#returnType}}{{{returnType}}}, {{/returnType}}APIResponse, error) { +func (a {{classname}}) {{nickname}}({{#allParams}}{{paramName}} {{{dataType}}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) ({{#returnType}}{{^isListContainer}}*{{/isListContainer}}{{{returnType}}}, {{/returnType}}*APIResponse, error) { var httpMethod = "{{httpMethod}}" // create path and map variables @@ -46,7 +46,7 @@ func (a {{classname}}) {{nickname}}({{#allParams}}{{paramName}} {{{dataType}}}{{ {{#allParams}}{{#required}} // verify the required parameter '{{paramName}}' is set if &{{paramName}} == nil { - return {{#returnType}}*new({{{returnType}}}), {{/returnType}}*NewAPIResponseWithError("400 - Bad Request"), errors.New("Missing required parameter '{{paramName}}' when calling {{classname}}->{{operationId}}") + return {{#returnType}}{{#isListContainer}}*{{/isListContainer}}new({{{returnType}}}), {{/returnType}}nil, errors.New("Missing required parameter '{{paramName}}' when calling {{classname}}->{{operationId}}") }{{/required}}{{/allParams}} headerParams := make(map[string]string) @@ -113,10 +113,10 @@ func (a {{classname}}) {{nickname}}({{#allParams}}{{paramName}} {{{dataType}}}{{ {{#returnType}} var successPayload = new({{returnType}}){{/returnType}} httpResponse, err := a.Configuration.APIClient.CallAPI(path, httpMethod, postBody, headerParams, queryParams, formParams, fileName, fileBytes) if err != nil { - return {{#returnType}}*successPayload, {{/returnType}}*NewAPIResponse(httpResponse.RawResponse), err + return {{#returnType}}{{#isListContainer}}*{{/isListContainer}}successPayload, {{/returnType}}NewAPIResponse(httpResponse.RawResponse), err } {{#returnType}} err = json.Unmarshal(httpResponse.Body(), &successPayload){{/returnType}} - return {{#returnType}}*successPayload, {{/returnType}}*NewAPIResponse(httpResponse.RawResponse), err + return {{#returnType}}{{#isListContainer}}*{{/isListContainer}}successPayload, {{/returnType}}NewAPIResponse(httpResponse.RawResponse), err } {{/operation}}{{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/htmlDocs/index.mustache b/modules/swagger-codegen/src/main/resources/htmlDocs/index.mustache index fa0e662b67f..60da5979a89 100644 --- a/modules/swagger-codegen/src/main/resources/htmlDocs/index.mustache +++ b/modules/swagger-codegen/src/main/resources/htmlDocs/index.mustache @@ -127,6 +127,7 @@ {{#responses}}

{{code}}

{{message}} + {{#simpleType}}{{dataType}}{{/simpleType}} {{#examples}}

Example data

Content-Type: {{{contentType}}}
@@ -158,7 +159,7 @@

{{classname}} Up

- {{#vars}}
{{name}} {{^required}}(optional){{/required}}
{{datatype}} {{description}}
+ {{#vars}}
{{name}} {{^required}}(optional){{/required}}
{{^isPrimitiveType}}{{datatype}}{{/isPrimitiveType}} {{description}}
{{#isEnum}}
Enum:
{{#_enum}}
{{this}}
{{/_enum}} diff --git a/modules/swagger-codegen/src/main/resources/nodejs/package.mustache b/modules/swagger-codegen/src/main/resources/nodejs/package.mustache index 86aa21af635..2d2b917c4b2 100644 --- a/modules/swagger-codegen/src/main/resources/nodejs/package.mustache +++ b/modules/swagger-codegen/src/main/resources/nodejs/package.mustache @@ -11,6 +11,6 @@ "dependencies": { "connect": "^3.2.0", "js-yaml": "^3.3.0", - "swagger-tools": "0.9.*" + "swagger-tools": "0.10.1" } } 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 18b756f78b0..5afc917e228 100644 --- a/modules/swagger-codegen/src/main/resources/objc/ApiClient-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/ApiClient-body.mustache @@ -2,10 +2,6 @@ NSString *const {{classPrefix}}ResponseObjectErrorKey = @"{{classPrefix}}ResponseObject"; -NSString *const {{classPrefix}}DeserializationErrorDomainKey = @"{{classPrefix}}DeserializationErrorDomainKey"; - -NSInteger const {{classPrefix}}TypeMismatchErrorCode = 143553; - static long requestId = 0; static bool offlineState = false; static NSMutableSet * queuedRequests = nil; @@ -14,6 +10,30 @@ static AFNetworkReachabilityStatus reachabilityStatus = AFNetworkReachabilitySta static void (^reachabilityChangeBlock)(int); +static NSDictionary * {{classPrefix}}__headerFieldsForResponse(NSURLResponse *response) { + if(![response isKindOfClass:[NSHTTPURLResponse class]]) { + return nil; + } + return ((NSHTTPURLResponse*)response).allHeaderFields; +} + +static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response) { + NSDictionary * headers = {{classPrefix}}__headerFieldsForResponse(response); + if(!headers[@"Content-Disposition"]) { + return [NSString stringWithFormat:@"%@", [[NSProcessInfo processInfo] globallyUniqueString]]; + } + NSString *pattern = @"filename=['\"]?([^'\"\\s]+)['\"]?"; + NSRegularExpression *regexp = [NSRegularExpression regularExpressionWithPattern:pattern + options:NSRegularExpressionCaseInsensitive + error:nil]; + NSString *contentDispositionHeader = headers[@"Content-Disposition"]; + NSTextCheckingResult *match = [regexp firstMatchInString:contentDispositionHeader + options:0 + range:NSMakeRange(0, [contentDispositionHeader length])]; + return [contentDispositionHeader substringWithRange:[match rangeAtIndex:1]]; +} + + @interface {{classPrefix}}ApiClient () @property (readwrite, nonatomic) NSDictionary *HTTPResponseHeaders; @@ -33,6 +53,8 @@ static void (^reachabilityChangeBlock)(int); self.requestSerializer = [AFJSONRequestSerializer serializer]; self.responseSerializer = [AFJSONResponseSerializer serializer]; self.securityPolicy = [self customSecurityPolicy]; + self.responseDeserializer = [[{{classPrefix}}ResponseDeserializer alloc] init]; + self.sanitizer = [[{{classPrefix}}Sanitizer alloc] init]; // configure reachability [self configureCacheReachibility]; } @@ -99,14 +121,12 @@ static void (^reachabilityChangeBlock)(int); va_end(args); } -- (void)logResponse:(AFHTTPRequestOperation *)operation - forRequest:(NSURLRequest *)request - error:(NSError*)error { +- (void)logResponse:(NSURLResponse *)response responseObject:(id)responseObject request:(NSURLRequest *)request error:(NSError *)error { NSString *message = [NSString stringWithFormat:@"\n[DEBUG] HTTP request body \n~BEGIN~\n %@\n~END~\n"\ "[DEBUG] HTTP response body \n~BEGIN~\n %@\n~END~\n", [[NSString alloc] initWithData:request.HTTPBody encoding:NSUTF8StringEncoding], - operation.responseString]; + responseObject]; {{classPrefix}}DebugLog(message); } @@ -222,20 +242,14 @@ static void (^reachabilityChangeBlock)(int); -(Boolean) executeRequestWithId:(NSNumber*) requestId { NSSet* matchingItems = [queuedRequests objectsPassingTest:^BOOL(id obj, BOOL *stop) { - if ([obj intValue] == [requestId intValue]) { - return YES; - } - else { - return NO; - } + return [obj intValue] == [requestId intValue]; }]; if (matchingItems.count == 1) { {{classPrefix}}DebugLog(@"removed request id %@", requestId); [queuedRequests removeObject:requestId]; return YES; - } - else { + } else { return NO; } } @@ -246,7 +260,7 @@ static void (^reachabilityChangeBlock)(int); return reachabilityStatus; } -+(bool) getOfflineState { ++(BOOL) getOfflineState { return offlineState; } @@ -257,29 +271,8 @@ static void (^reachabilityChangeBlock)(int); - (void) configureCacheReachibility { [self.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) { reachabilityStatus = status; - switch (status) { - case AFNetworkReachabilityStatusUnknown: - {{classPrefix}}DebugLog(@"reachability changed to AFNetworkReachabilityStatusUnknown"); - [{{classPrefix}}ApiClient setOfflineState:true]; - break; - - case AFNetworkReachabilityStatusNotReachable: - {{classPrefix}}DebugLog(@"reachability changed to AFNetworkReachabilityStatusNotReachable"); - [{{classPrefix}}ApiClient setOfflineState:true]; - break; - - case AFNetworkReachabilityStatusReachableViaWWAN: - {{classPrefix}}DebugLog(@"reachability changed to AFNetworkReachabilityStatusReachableViaWWAN"); - [{{classPrefix}}ApiClient setOfflineState:false]; - break; - - case AFNetworkReachabilityStatusReachableViaWiFi: - {{classPrefix}}DebugLog(@"reachability changed to AFNetworkReachabilityStatusReachableViaWiFi"); - [{{classPrefix}}ApiClient setOfflineState:false]; - break; - default: - break; - } + {{classPrefix}}DebugLog(@"reachability changed to %@",AFStringFromNetworkReachabilityStatus(status)); + [{{classPrefix}}ApiClient setOfflineState:status == AFNetworkReachabilityStatusUnknown || status == AFNetworkReachabilityStatusNotReachable]; // call the reachability block, if configured if (reachabilityChangeBlock != nil) { @@ -290,245 +283,65 @@ static void (^reachabilityChangeBlock)(int); [self.reachabilityManager startMonitoring]; } -#pragma mark - Deserialize methods - -- (id) deserialize:(id) data class:(NSString *) class error:(NSError **) error { - // return nil if data is nil or class is nil - if (!data || !class) { - return nil; - } - - // remove "*" from class, if ends with "*" - if ([class hasSuffix:@"*"]) { - class = [class substringToIndex:[class length] - 1]; - } - - // pure object - if ([class isEqualToString:@"NSObject"]) { - return data; - } - - NSRegularExpression *regexp = nil; - NSTextCheckingResult *match = nil; - NSMutableArray *resultArray = nil; - NSMutableDictionary *resultDict = nil; - NSString *innerType = nil; - - // list of models - NSString *arrayOfModelsPat = @"NSArray<(.+)>"; - regexp = [NSRegularExpression regularExpressionWithPattern:arrayOfModelsPat - options:NSRegularExpressionCaseInsensitive - error:nil]; - - match = [regexp firstMatchInString:class - options:0 - range:NSMakeRange(0, [class length])]; - - if (match) { - if(![data isKindOfClass: [NSArray class]]) { - if(error) { - NSDictionary * userInfo = @{NSLocalizedDescriptionKey : NSLocalizedString(@"Received response is not an array", nil)}; - *error = [NSError errorWithDomain:{{classPrefix}}DeserializationErrorDomainKey code:{{classPrefix}}TypeMismatchErrorCode userInfo:userInfo]; - } - return nil; - } - NSArray *dataArray = data; - innerType = [class substringWithRange:[match rangeAtIndex:1]]; - - resultArray = [NSMutableArray arrayWithCapacity:[dataArray count]]; - [data enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { - id arrObj = [self deserialize:obj class:innerType error:error]; - if(arrObj) { - [resultArray addObject:arrObj]; - } else { - * stop = YES; - } - }]; - - return resultArray; - } - - // list of primitives - NSString *arrayOfPrimitivesPat = @"NSArray\\* /\\* (.+) \\*/"; - regexp = [NSRegularExpression regularExpressionWithPattern:arrayOfPrimitivesPat - options:NSRegularExpressionCaseInsensitive - error:nil]; - match = [regexp firstMatchInString:class - options:0 - range:NSMakeRange(0, [class length])]; - - if (match) { - NSArray *dataArray = data; - innerType = [class substringWithRange:[match rangeAtIndex:1]]; - - resultArray = [NSMutableArray arrayWithCapacity:[dataArray count]]; - [data enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { - id arrObj = [self deserialize:obj class:innerType error:error]; - if(arrObj) { - [resultArray addObject:arrObj]; - } else { - * stop = YES; - } - }]; - - return resultArray; - } - - // map - NSString *dictPat = @"NSDictionary\\* /\\* (.+?), (.+) \\*/"; - regexp = [NSRegularExpression regularExpressionWithPattern:dictPat - options:NSRegularExpressionCaseInsensitive - error:nil]; - match = [regexp firstMatchInString:class - options:0 - range:NSMakeRange(0, [class length])]; - - if (match) { - NSDictionary *dataDict = data; - NSString *valueType = [class substringWithRange:[match rangeAtIndex:2]]; - - resultDict = [NSMutableDictionary dictionaryWithCapacity:[dataDict count]]; - [data enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { - id dicObj = [self deserialize:obj class:valueType error:error]; - if(dicObj) { - [resultDict setValue:dicObj forKey:key]; - } else { - * stop = YES; - } - }]; - - return resultDict; - } - - // primitives - NSArray *primitiveTypes = @[@"NSString", @"NSDate", @"NSNumber"]; - - if ([primitiveTypes containsObject:class]) { - if ([class isEqualToString:@"NSString"]) { - return [NSString stringWithString:data]; - } - else if ([class isEqualToString:@"NSDate"]) { - return [NSDate dateWithISO8601String:data]; - } - else if ([class isEqualToString:@"NSNumber"]) { - // NSNumber from NSNumber - if ([data isKindOfClass:[NSNumber class]]) { - return data; - } - else if ([data isKindOfClass:[NSString class]]) { - // NSNumber (NSCFBoolean) from NSString - if ([[data lowercaseString] isEqualToString:@"true"] || [[data lowercaseString] isEqualToString:@"false"]) { - return [NSNumber numberWithBool:[data boolValue]]; - // NSNumber from NSString - } else { - NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init]; - formatter.numberStyle = NSNumberFormatterDecimalStyle; - return [formatter numberFromString:data]; - } - } - } - } - - // model - Class ModelClass = NSClassFromString(class); - if ([ModelClass instancesRespondToSelector:@selector(initWithDictionary:error:)]) { - return [(JSONModel *) [ModelClass alloc] initWithDictionary:data error:error]; - } - - return nil; -} - #pragma mark - Operation Methods - (void) operationWithCompletionBlock: (NSURLRequest *)request requestId: (NSNumber *) requestId completionBlock: (void (^)(id, NSError *))completionBlock { - AFHTTPRequestOperation *op = [self HTTPRequestOperationWithRequest:request - success:^(AFHTTPRequestOperation *operation, id response) { - 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]) { - NSMutableDictionary *userInfo = [error.userInfo mutableCopy]; - if (operation.responseObject) { - // Add in the (parsed) response body. - userInfo[{{classPrefix}}ResponseObjectErrorKey] = operation.responseObject; - } - NSError *augmentedError = [error initWithDomain:error.domain code:error.code userInfo:userInfo]; - [self logResponse:nil forRequest:request error:augmentedError]; - - NSDictionary *responseHeaders = [[operation response] allHeaderFields]; - self.HTTPResponseHeaders = responseHeaders; - - completionBlock(nil, augmentedError); - } - }]; - - [self.operationQueue addOperation:op]; + __weak __typeof(self)weakSelf = self; + NSURLSessionDataTask* op = [self dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) { + __strong __typeof(weakSelf)strongSelf = weakSelf; + if (![strongSelf executeRequestWithId:requestId]) { + return; + } + [strongSelf logResponse:response responseObject:responseObject request:request error:error]; + strongSelf.HTTPResponseHeaders = {{classPrefix}}__headerFieldsForResponse(response); + if(!error) { + completionBlock(responseObject, nil); + return; + } + NSMutableDictionary *userInfo = [error.userInfo mutableCopy]; + if (responseObject) { + // Add in the (parsed) response body. + userInfo[{{classPrefix}}ResponseObjectErrorKey] = responseObject; + } + NSError *augmentedError = [error initWithDomain:error.domain code:error.code userInfo:userInfo]; + completionBlock(nil, augmentedError); + }]; + [op resume]; } - (void) downloadOperationWithCompletionBlock: (NSURLRequest *)request requestId: (NSNumber *) requestId completionBlock: (void (^)(id, NSError *))completionBlock { - AFHTTPRequestOperation *op = [self HTTPRequestOperationWithRequest:request - success:^(AFHTTPRequestOperation *operation, id responseObject) { - {{classPrefix}}Configuration *config = [{{classPrefix}}Configuration sharedConfig]; - NSString *directory = nil; - if (config.tempFolderPath) { - directory = config.tempFolderPath; - } - else { - directory = NSTemporaryDirectory(); - } + __weak __typeof(self)weakSelf = self; + NSURLSessionDataTask* op = [self dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) { + __strong __typeof(weakSelf)strongSelf = weakSelf; + if (![strongSelf executeRequestWithId:requestId]) { + return; + } + strongSelf.HTTPResponseHeaders = {{classPrefix}}__headerFieldsForResponse(response); + [strongSelf logResponse:response responseObject:responseObject request:request error:error]; + if(error) { + NSMutableDictionary *userInfo = [error.userInfo mutableCopy]; + if (responseObject) { + userInfo[{{classPrefix}}ResponseObjectErrorKey] = responseObject; + } + NSError *augmentedError = [error initWithDomain:error.domain code:error.code userInfo:userInfo]; + completionBlock(nil, augmentedError); + } + {{classPrefix}}Configuration *config = [{{classPrefix}}Configuration sharedConfig]; + NSString *directory = config.tempFolderPath ?: NSTemporaryDirectory(); + NSString * filename = {{classPrefix}}__fileNameForResponse(response); - NSDictionary *headers = operation.response.allHeaderFields; - NSString *filename = nil; - if ([headers objectForKey:@"Content-Disposition"]) { + NSString *filepath = [directory stringByAppendingPathComponent:filename]; + NSURL *file = [NSURL fileURLWithPath:filepath]; - NSString *pattern = @"filename=['\"]?([^'\"\\s]+)['\"]?"; - NSRegularExpression *regexp = [NSRegularExpression regularExpressionWithPattern:pattern - options:NSRegularExpressionCaseInsensitive - error:nil]; - NSString *contentDispositionHeader = [headers objectForKey:@"Content-Disposition"]; - NSTextCheckingResult *match = [regexp firstMatchInString:contentDispositionHeader - options:0 - range:NSMakeRange(0, [contentDispositionHeader length])]; - filename = [contentDispositionHeader substringWithRange:[match rangeAtIndex:1]]; - } - else { - filename = [NSString stringWithFormat:@"%@", [[NSProcessInfo processInfo] globallyUniqueString]]; - } + [responseObject writeToURL:file atomically:YES]; - NSString *filepath = [directory stringByAppendingPathComponent:filename]; - NSURL *file = [NSURL fileURLWithPath:filepath]; - - [operation.responseData writeToURL:file atomically:YES]; - self.HTTPResponseHeaders = headers; - completionBlock(file, nil); - } failure:^(AFHTTPRequestOperation *operation, NSError *error) { - - if ([self executeRequestWithId:requestId]) { - NSMutableDictionary *userInfo = [error.userInfo mutableCopy]; - if (operation.responseObject) { - userInfo[{{classPrefix}}ResponseObjectErrorKey] = operation.responseObject; - } - - NSError *augmentedError = [error initWithDomain:error.domain code:error.code userInfo:userInfo]; - - - [self logResponse:nil forRequest:request error:augmentedError]; - - NSDictionary *responseHeaders = [[operation response] allHeaderFields]; - self.HTTPResponseHeaders = responseHeaders; - completionBlock(nil, augmentedError); - } - }]; - - [self.operationQueue addOperation:op]; + completionBlock(file, nil); + }]; + [op resume]; } #pragma mark - Perform Request Methods @@ -569,11 +382,11 @@ static void (^reachabilityChangeBlock)(int); } // sanitize parameters - pathParams = [self sanitizeForSerialization:pathParams]; - queryParams = [self sanitizeForSerialization:queryParams]; - headerParams = [self sanitizeForSerialization:headerParams]; - formParams = [self sanitizeForSerialization:formParams]; - body = [self sanitizeForSerialization:body]; + pathParams = [self.sanitizer sanitizeForSerialization:pathParams]; + queryParams = [self.sanitizer sanitizeForSerialization:queryParams]; + headerParams = [self.sanitizer sanitizeForSerialization:headerParams]; + formParams = [self.sanitizer sanitizeForSerialization:formParams]; + body = [self.sanitizer sanitizeForSerialization:body]; // auth setting [self updateHeaderParams:&headerParams queryParams:&queryParams WithAuthSettings:authSettings]; @@ -593,12 +406,13 @@ static void (^reachabilityChangeBlock)(int); NSString* urlString = [[NSURL URLWithString:pathWithQueryParams relativeToURL:self.baseURL] absoluteString]; if (files.count > 0) { + __weak __typeof(self)weakSelf = self; request = [self.requestSerializer multipartFormRequestWithMethod:@"POST" URLString:urlString parameters:nil constructingBodyWithBlock:^(id formData) { [formParams enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { - NSString *objString = [self parameterToString:obj]; + NSString *objString = [weakSelf.sanitizer parameterToString:obj]; NSData *data = [objString dataUsingEncoding:NSUTF8StringEncoding]; [formData appendPartWithFormData:data name:key]; }]; @@ -653,7 +467,7 @@ static void (^reachabilityChangeBlock)(int); [request setHTTPShouldHandleCookies:NO]; NSNumber* requestId = [{{classPrefix}}ApiClient queueRequest]; - if ([responseType isEqualToString:@"NSURL*"]) { + if ([responseType isEqualToString:@"NSURL*"] || [responseType isEqualToString:@"NSURL"]) { [self downloadOperationWithCompletionBlock:request requestId:requestId completionBlock:^(id data, NSError *error) { completionBlock(data, error); }]; @@ -661,7 +475,7 @@ static void (^reachabilityChangeBlock)(int); else { [self operationWithCompletionBlock:request requestId:requestId completionBlock:^(id data, NSError *error) { NSError * serializationError; - id response = [self deserialize:data class:responseType error:&serializationError]; + id response = [self.responseDeserializer deserialize:data class:responseType error:&serializationError]; if(!response && !error){ error = serializationError; } @@ -760,48 +574,6 @@ static void (^reachabilityChangeBlock)(int); *querys = [NSDictionary dictionaryWithDictionary:querysWithAuth]; } -- (id) sanitizeForSerialization:(id) object { - if (object == nil) { - return nil; - } - else if ([object isKindOfClass:[NSString class]] || [object isKindOfClass:[NSNumber class]] || [object isKindOfClass:[{{classPrefix}}QueryParamCollection class]]) { - return object; - } - else if ([object isKindOfClass:[NSDate class]]) { - return [object ISO8601String]; - } - else if ([object isKindOfClass:[NSArray class]]) { - NSArray *objectArray = object; - NSMutableArray *sanitizedObjs = [NSMutableArray arrayWithCapacity:[objectArray count]]; - [object enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { - if (obj) { - [sanitizedObjs addObject:[self sanitizeForSerialization:obj]]; - } - }]; - return sanitizedObjs; - } - else if ([object isKindOfClass:[NSDictionary class]]) { - NSDictionary *objectDict = object; - NSMutableDictionary *sanitizedObjs = [NSMutableDictionary dictionaryWithCapacity:[objectDict count]]; - [object enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { - if (obj) { - [sanitizedObjs setValue:[self sanitizeForSerialization:obj] forKey:key]; - } - }]; - return sanitizedObjs; - } - else if ([object isKindOfClass:[{{classPrefix}}Object class]]) { - return [object toDictionary]; - } - else { - NSException *e = [NSException - exceptionWithName:@"InvalidObjectArgumentException" - reason:[NSString stringWithFormat:@"*** The argument object: %@ is invalid", object] - userInfo:nil]; - @throw e; - } -} - - (AFSecurityPolicy *) customSecurityPolicy { AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone]; @@ -823,30 +595,4 @@ static void (^reachabilityChangeBlock)(int); return securityPolicy; } -- (NSString *) parameterToString:(id)param { - if ([param isKindOfClass:[NSString class]]) { - return param; - } - else if ([param isKindOfClass:[NSNumber class]]) { - return [param stringValue]; - } - else if ([param isKindOfClass:[NSDate class]]) { - return [param ISO8601String]; - } - else if ([param isKindOfClass:[NSArray class]]) { - NSMutableArray *mutableParam; - [param enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { - [mutableParam addObject:[self parameterToString:obj]]; - }]; - return [mutableParam componentsJoinedByString:@","]; - } - else { - NSException *e = [NSException - exceptionWithName:@"InvalidObjectArgumentException" - reason:[NSString stringWithFormat:@"*** The argument object: %@ is invalid", param] - userInfo:nil]; - @throw e; - } -} - @end diff --git a/modules/swagger-codegen/src/main/resources/objc/ApiClient-header.mustache b/modules/swagger-codegen/src/main/resources/objc/ApiClient-header.mustache index 1cf3db5e523..b08112ba445 100644 --- a/modules/swagger-codegen/src/main/resources/objc/ApiClient-header.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/ApiClient-header.mustache @@ -1,11 +1,12 @@ #import #import -#import +#import #import "{{classPrefix}}JSONResponseSerializer.h" #import "{{classPrefix}}JSONRequestSerializer.h" #import "{{classPrefix}}QueryParamCollection.h" #import "{{classPrefix}}Configuration.h" - +#import "{{classPrefix}}ResponseDeserializer.h" +#import "{{classPrefix}}Sanitizer.h" /** * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen @@ -25,22 +26,14 @@ */ extern NSString *const {{classPrefix}}ResponseObjectErrorKey; -/** - * A key for deserialization ErrorDomain - */ -extern NSString *const {{classPrefix}}DeserializationErrorDomainKey; - -/** - * Code for deserialization type mismatch error - */ -extern NSInteger const {{classPrefix}}TypeMismatchErrorCode; - /** * Log debug message macro */ -#define {{classPrefix}}DebugLog(format, ...) [{{classPrefix}}ApiClient debugLog:[NSString stringWithFormat:@"%s", __PRETTY_FUNCTION__] message: format, ##__VA_ARGS__]; +#ifndef {{classPrefix}}DebugLog + #define {{classPrefix}}DebugLog(format, ...) [{{classPrefix}}ApiClient debugLog:[NSString stringWithFormat:@"%s", __PRETTY_FUNCTION__] message: format, ##__VA_ARGS__]; +#endif -@interface {{classPrefix}}ApiClient : AFHTTPRequestOperationManager +@interface {{classPrefix}}ApiClient : AFHTTPSessionManager @property(nonatomic, assign) NSURLRequestCachePolicy cachePolicy; @property(nonatomic, assign) NSTimeInterval timeoutInterval; @@ -49,6 +42,9 @@ extern NSInteger const {{classPrefix}}TypeMismatchErrorCode; /// In order to ensure the HTTPResponseHeaders are correct, it is recommended to initialize one {{classPrefix}}ApiClient instance per thread. @property(nonatomic, readonly) NSDictionary* HTTPResponseHeaders; +@property(nonatomic, strong) id<{{classPrefix}}ResponseDeserializer> responseDeserializer; + +@property(nonatomic, strong) id<{{classPrefix}}Sanitizer> sanitizer; /** * Clears Cache */ @@ -80,7 +76,7 @@ extern NSInteger const {{classPrefix}}TypeMismatchErrorCode; * * @return The client offline state */ -+(bool) getOfflineState; ++(BOOL) getOfflineState; /** * Sets the client reachability, this may be overridden by the reachability manager if reachability changes @@ -176,24 +172,17 @@ extern NSInteger const {{classPrefix}}TypeMismatchErrorCode; queryParams:(NSDictionary **)querys WithAuthSettings:(NSArray *)authSettings; -/** - * Deserializes the given data to Objective-C object. - * - * @param data The data will be deserialized. - * @param class The type of objective-c object. - * @param error The error - */ -- (id) deserialize:(id) data class:(NSString *) class error:(NSError**)error; - /** * Logs request and response * - * @param operation AFHTTPRequestOperation for the HTTP request. + * @param response NSURLResponse for the HTTP request. + * @param responseObject response object of the HTTP request. * @param request The HTTP request. * @param error The error of the HTTP request. */ -- (void)logResponse:(AFHTTPRequestOperation *)operation - forRequest:(NSURLRequest *)request +- (void)logResponse:(NSURLResponse *)response + responseObject:(id)responseObject + request:(NSURLRequest *)request error:(NSError *)error; /** @@ -226,13 +215,6 @@ extern NSInteger const {{classPrefix}}TypeMismatchErrorCode; responseType:(NSString *) responseType completionBlock:(void (^)(id, NSError *))completionBlock; -/** - * Sanitize object for request - * - * @param object The query/path/header/form/body param to be sanitized. - */ -- (id) sanitizeForSerialization:(id) object; - /** * Custom security policy * @@ -240,11 +222,6 @@ extern NSInteger const {{classPrefix}}TypeMismatchErrorCode; */ - (AFSecurityPolicy *) customSecurityPolicy; -/** - * Convert parameter to NSString - */ -- (NSString *) parameterToString: (id) param; - /** * Log debug message */ diff --git a/modules/swagger-codegen/src/main/resources/objc/Configuration-body.mustache b/modules/swagger-codegen/src/main/resources/objc/Configuration-body.mustache index 4f5442ed213..527e16c2b91 100644 --- a/modules/swagger-codegen/src/main/resources/objc/Configuration-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/Configuration-body.mustache @@ -72,7 +72,7 @@ return @""; } else { - return [NSString stringWithFormat:@"BEARER %@", self.accessToken]; + return [NSString stringWithFormat:@"Bearer %@", self.accessToken]; } } diff --git a/modules/swagger-codegen/src/main/resources/objc/Object-body.mustache b/modules/swagger-codegen/src/main/resources/objc/Object-body.mustache index 122484f1ad4..b4599c34f3f 100644 --- a/modules/swagger-codegen/src/main/resources/objc/Object-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/Object-body.mustache @@ -1,4 +1,13 @@ #import "{{classPrefix}}Object.h" @implementation {{classPrefix}}Object + +/** + * Gets the string presentation of the object. + * This method will be called when logging model object using `NSLog`. + */ +- (NSString *)description { + return [[self toDictionary] description]; +} + @end diff --git a/modules/swagger-codegen/src/main/resources/objc/README.mustache b/modules/swagger-codegen/src/main/resources/objc/README.mustache index c0bc1178b0b..ed48e239596 100644 --- a/modules/swagger-codegen/src/main/resources/objc/README.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/README.mustache @@ -70,8 +70,8 @@ Please follow the [installation procedure](#installation--usage) and then run th {{/isBasic}}{{#isApiKey}} // Configure API key authorization: (authentication scheme: {{{name}}}) [apiConfig setApiKey:@"YOUR_API_KEY" forApiKeyIdentifier:@"{{{keyParamName}}}"]; -// Uncomment below to setup prefix (e.g. BEARER) for API key, if needed -//[apiConfig setApiKeyPrefix:@"BEARER" forApiKeyIdentifier:@"{{{keyParamName}}}"]; +// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed +//[apiConfig setApiKeyPrefix:@"Bearer" forApiKeyIdentifier:@"{{{keyParamName}}}"]; {{/isApiKey}}{{#isOAuth}} // Configure OAuth2 access token for authorization: (authentication scheme: {{{name}}}) [apiConfig setAccessToken:@"YOUR_ACCESS_TOKEN"]; diff --git a/modules/swagger-codegen/src/main/resources/objc/ResponseDeserializer-body.mustache b/modules/swagger-codegen/src/main/resources/objc/ResponseDeserializer-body.mustache new file mode 100644 index 00000000000..812ed061c04 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/objc/ResponseDeserializer-body.mustache @@ -0,0 +1,231 @@ +#import "{{classPrefix}}ResponseDeserializer.h" +#import +#import + +NSString *const {{classPrefix}}DeserializationErrorDomainKey = @"{{classPrefix}}DeserializationErrorDomainKey"; + +NSInteger const {{classPrefix}}TypeMismatchErrorCode = 143553; + +NSInteger const {{classPrefix}}EmptyValueOccurredErrorCode = 143509; + +NSInteger const {{classPrefix}}UnknownResponseObjectErrorCode = 143528; + + +@interface {{classPrefix}}ResponseDeserializer () + +@property (nonatomic, strong) NSNumberFormatter* numberFormatter; +@property (nonatomic, strong) NSArray *primitiveTypes; +@property (nonatomic, strong) NSArray *basicReturnTypes; + +@property (nonatomic, strong) NSRegularExpression* arrayOfModelsPatExpression; +@property (nonatomic, strong) NSRegularExpression* arrayOfPrimitivesPatExpression; +@property (nonatomic, strong) NSRegularExpression* dictPatExpression; +@property (nonatomic, strong) NSRegularExpression* dictModelsPatExpression; + +@end + +@implementation {{classPrefix}}ResponseDeserializer + +- (instancetype)init { + self = [super init]; + if (self) { + NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init]; + formatter.numberStyle = NSNumberFormatterDecimalStyle; + _numberFormatter = formatter; + _primitiveTypes = @[@"NSString", @"NSDate", @"NSNumber"]; + _basicReturnTypes = @[@"NSObject", @"id", @"NSData"]; + _arrayOfModelsPatExpression = [NSRegularExpression regularExpressionWithPattern:@"NSArray<(.+)>" + options:NSRegularExpressionCaseInsensitive + error:nil]; + _arrayOfPrimitivesPatExpression = [NSRegularExpression regularExpressionWithPattern:@"NSArray\\* /\\* (.+) \\*/" + options:NSRegularExpressionCaseInsensitive + error:nil]; + _dictPatExpression = [NSRegularExpression regularExpressionWithPattern:@"NSDictionary\\* /\\* (.+?), (.+) \\*/" + options:NSRegularExpressionCaseInsensitive + error:nil]; + _dictModelsPatExpression = [NSRegularExpression regularExpressionWithPattern:@"NSDictionary\\<(.+?), (.+)*\\>" + options:NSRegularExpressionCaseInsensitive + error:nil]; + } + return self; +} + +#pragma mark - Deserialize methods + +- (id) deserialize:(id) data class:(NSString *) className error:(NSError **) error { + // return nil if data is nil or className is nil + if (!data || !className || [data isKindOfClass:[NSNull class]]) { + return nil; + } + + // remove "*" from className, if ends with "*" + if ([className hasSuffix:@"*"]) { + className = [className substringToIndex:[className length] - 1]; + } + // pure object + if ([self.basicReturnTypes containsObject:className]) { + return data; + } + + // primitives + if ([self.primitiveTypes containsObject:className]) { + return [self deserializePrimitiveValue:data class:className error:error]; + } + + NSTextCheckingResult *match = nil; + NSRange range = NSMakeRange(0, [className length]); + // list of models + match = [self.arrayOfModelsPatExpression firstMatchInString:className options:0 range:range]; + if (match) { + NSString *innerType = [className substringWithRange:[match rangeAtIndex:1]]; + return [self deserializeArrayValue:data innerType:innerType error:error]; + } + + // list of primitives + match = [self.arrayOfPrimitivesPatExpression firstMatchInString:className options:0 range:range]; + if (match) { + NSString *innerType = [className substringWithRange:[match rangeAtIndex:1]]; + return [self deserializeArrayValue:data innerType:innerType error:error]; + } + + // map + match = [self.dictPatExpression firstMatchInString:className options:0 range:range]; + if (match) { + NSString *valueType = [className substringWithRange:[match rangeAtIndex:2]]; + return [self deserializeDictionaryValue:data valueType:valueType error:error]; + } + + match = [self.dictModelsPatExpression firstMatchInString:className options:0 range:range]; + if (match) { + NSString *valueType = [className substringWithRange:[match rangeAtIndex:2]]; + return [self deserializeDictionaryValue:data valueType:valueType error:error]; + } + + // model + Class ModelClass = NSClassFromString(className); + if ([ModelClass instancesRespondToSelector:@selector(initWithDictionary:error:)]) { + return [(JSONModel *) [ModelClass alloc] initWithDictionary:data error:error]; + } + + if(error) { + *error = [self unknownResponseErrorWithExpectedType:className data:data]; + } + return nil; +} + +- (id) deserializeDictionaryValue:(id) data valueType:(NSString *) valueType error:(NSError**)error { + if(![data isKindOfClass: [NSDictionary class]]) { + if(error) { + *error = [self typeMismatchErrorWithExpectedType:NSStringFromClass([NSDictionary class]) data:data]; + } + return nil; + } + __block NSMutableDictionary *resultDict = [NSMutableDictionary dictionaryWithCapacity:[data count]]; + for (id key in [data allKeys]) { + id obj = [data valueForKey:key]; + id dicObj = [self deserialize:obj class:valueType error:error]; + if(dicObj) { + [resultDict setValue:dicObj forKey:key]; + } else if([obj isKindOfClass:[NSNull class]]) { + if(self.treatNullAsError) { + if (error) { + *error = [self emptyValueOccurredError]; + } + resultDict = nil; + break; + } + } else { + resultDict = nil; + break; + } + } + return resultDict; +} + +- (id) deserializeArrayValue:(id) data innerType:(NSString *) innerType error:(NSError**)error { + if(![data isKindOfClass: [NSArray class]]) { + if(error) { + *error = [self typeMismatchErrorWithExpectedType:NSStringFromClass([NSArray class]) data:data]; + } + return nil; + } + NSMutableArray* resultArray = [NSMutableArray arrayWithCapacity:[data count]]; + for (id obj in data) { + id arrObj = [self deserialize:obj class:innerType error:error]; + if(arrObj) { + [resultArray addObject:arrObj]; + } else if([obj isKindOfClass:[NSNull class]]) { + if(self.treatNullAsError) { + if (error) { + *error = [self emptyValueOccurredError]; + } + resultArray = nil; + break; + } + } else { + resultArray = nil; + break; + } + } + return resultArray; +}; + +- (id) deserializePrimitiveValue:(id) data class:(NSString *) className error:(NSError**)error { + if ([className isEqualToString:@"NSString"]) { + return [NSString stringWithString:data]; + } + else if ([className isEqualToString:@"NSDate"]) { + return [self deserializeDateValue:data error:error]; + } + else if ([className isEqualToString:@"NSNumber"]) { + // NSNumber from NSNumber + if ([data isKindOfClass:[NSNumber class]]) { + return data; + } + else if ([data isKindOfClass:[NSString class]]) { + // NSNumber (NSCFBoolean) from NSString + if ([[data lowercaseString] isEqualToString:@"true"] || [[data lowercaseString] isEqualToString:@"false"]) { + return @([data boolValue]); + // NSNumber from NSString + } else { + NSNumber* formattedValue = [self.numberFormatter numberFromString:data]; + if(!formattedValue && [data length] > 0 && error) { + *error = [self typeMismatchErrorWithExpectedType:className data:data]; + } + return formattedValue; + } + } + } + if(error) { + *error = [self typeMismatchErrorWithExpectedType:className data:data]; + } + return nil; +} + +- (id) deserializeDateValue:(id) data error:(NSError**)error { + NSDate *date =[NSDate dateWithISO8601String:data]; + if(!date && [data length] > 0 && error) { + *error = [self typeMismatchErrorWithExpectedType:NSStringFromClass([NSDate class]) data:data]; + } + return date; +}; + +-(NSError *)typeMismatchErrorWithExpectedType:(NSString *)expected data:(id)data { + NSString * message = [NSString stringWithFormat:NSLocalizedString(@"Received response [%@] is not an object of type %@",nil),data, expected]; + NSDictionary * userInfo = @{NSLocalizedDescriptionKey : message}; + return [NSError errorWithDomain:{{classPrefix}}DeserializationErrorDomainKey code:{{classPrefix}}TypeMismatchErrorCode userInfo:userInfo]; +} + +-(NSError *)emptyValueOccurredError { + NSString * message = NSLocalizedString(@"Received response contains null value in dictionary or array response",nil); + NSDictionary * userInfo = @{NSLocalizedDescriptionKey : message}; + return [NSError errorWithDomain:{{classPrefix}}DeserializationErrorDomainKey code:{{classPrefix}}EmptyValueOccurredErrorCode userInfo:userInfo]; +} + +-(NSError *)unknownResponseErrorWithExpectedType:(NSString *)expected data:(id)data { + NSString * message = [NSString stringWithFormat:NSLocalizedString(@"Unknown response expected type %@ [reponse: %@]",nil),expected,data]; + NSDictionary * userInfo = @{NSLocalizedDescriptionKey : message}; + return [NSError errorWithDomain:{{classPrefix}}DeserializationErrorDomainKey code:{{classPrefix}}UnknownResponseObjectErrorCode userInfo:userInfo]; +} + +@end diff --git a/modules/swagger-codegen/src/main/resources/objc/ResponseDeserializer-header.mustache b/modules/swagger-codegen/src/main/resources/objc/ResponseDeserializer-header.mustache new file mode 100644 index 00000000000..2dd038c13f0 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/objc/ResponseDeserializer-header.mustache @@ -0,0 +1,50 @@ +#import + +/** + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen + * Do not edit the class manually. + */ + +/** + * A key for deserialization ErrorDomain + */ +extern NSString *const {{classPrefix}}DeserializationErrorDomainKey; + +/** + * Code for deserialization type mismatch error + */ +extern NSInteger const {{classPrefix}}TypeMismatchErrorCode; + +/** + * Code for deserialization empty value error + */ +extern NSInteger const {{classPrefix}}EmptyValueOccurredErrorCode; + +/** + * Error code for unknown response + */ +extern NSInteger const {{classPrefix}}UnknownResponseObjectErrorCode; + +@protocol {{classPrefix}}ResponseDeserializer + +/** + * Deserializes the given data to Objective-C object. + * + * @param data The data will be deserialized. + * @param class The type of objective-c object. + * @param error The error + */ +- (id) deserialize:(id) data class:(NSString *) className error:(NSError**)error; + +@end + +@interface {{classPrefix}}ResponseDeserializer : NSObject <{{classPrefix}}ResponseDeserializer> + +/** + * If an null value occurs in dictionary or array if set to YES whole response will be invalid else will be ignored + * @default NO + */ +@property (nonatomic, assign) BOOL treatNullAsError; + +@end diff --git a/modules/swagger-codegen/src/main/resources/objc/Sanitizer-body.mustache b/modules/swagger-codegen/src/main/resources/objc/Sanitizer-body.mustache new file mode 100644 index 00000000000..74b166d75e9 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/objc/Sanitizer-body.mustache @@ -0,0 +1,82 @@ +#import "{{classPrefix}}Sanitizer.h" +#import "{{classPrefix}}Object.h" +#import "{{classPrefix}}QueryParamCollection.h" +#import + +@interface {{classPrefix}}Sanitizer () + +@end + +@implementation {{classPrefix}}Sanitizer + +- (id) sanitizeForSerialization:(id) object { + if (object == nil) { + return nil; + } + else if ([object isKindOfClass:[NSString class]] || [object isKindOfClass:[NSNumber class]] || [object isKindOfClass:[{{classPrefix}}QueryParamCollection class]]) { + return object; + } + else if ([object isKindOfClass:[NSDate class]]) { + return [object ISO8601String]; + } + else if ([object isKindOfClass:[NSArray class]]) { + NSArray *objectArray = object; + NSMutableArray *sanitizedObjs = [NSMutableArray arrayWithCapacity:[objectArray count]]; + [object enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { + id sanitizedObj = [self sanitizeForSerialization:obj]; + if (sanitizedObj) { + [sanitizedObjs addObject:sanitizedObj]; + } + }]; + return sanitizedObjs; + } + else if ([object isKindOfClass:[NSDictionary class]]) { + NSDictionary *objectDict = object; + NSMutableDictionary *sanitizedObjs = [NSMutableDictionary dictionaryWithCapacity:[objectDict count]]; + [object enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { + id sanitizedObj = [self sanitizeForSerialization:obj]; + if (sanitizedObj) { + sanitizedObjs[key] = sanitizedObj; + } + }]; + return sanitizedObjs; + } + else if ([object isKindOfClass:[{{classPrefix}}Object class]]) { + return [object toDictionary]; + } + else { + NSException *e = [NSException + exceptionWithName:@"InvalidObjectArgumentException" + reason:[NSString stringWithFormat:@"*** The argument object: %@ is invalid", object] + userInfo:nil]; + @throw e; + } +} + +- (NSString *) parameterToString:(id)param { + if ([param isKindOfClass:[NSString class]]) { + return param; + } + else if ([param isKindOfClass:[NSNumber class]]) { + return [param stringValue]; + } + else if ([param isKindOfClass:[NSDate class]]) { + return [param ISO8601String]; + } + else if ([param isKindOfClass:[NSArray class]]) { + NSMutableArray *mutableParam = [NSMutableArray array]; + [param enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { + [mutableParam addObject:[self parameterToString:obj]]; + }]; + return [mutableParam componentsJoinedByString:@","]; + } + else { + NSException *e = [NSException + exceptionWithName:@"InvalidObjectArgumentException" + reason:[NSString stringWithFormat:@"*** The argument object: %@ is invalid", param] + userInfo:nil]; + @throw e; + } +} + +@end diff --git a/modules/swagger-codegen/src/main/resources/objc/Sanitizer-header.mustache b/modules/swagger-codegen/src/main/resources/objc/Sanitizer-header.mustache new file mode 100644 index 00000000000..706a94c1d0e --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/objc/Sanitizer-header.mustache @@ -0,0 +1,29 @@ +#import + +/** + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen + * Do not edit the class manually. + */ + +@protocol {{classPrefix}}Sanitizer + +/** + * Sanitize object for request + * + * @param object The query/path/header/form/body param to be sanitized. + */ +- (id) sanitizeForSerialization:(id) object; + +/** + * Convert parameter to NSString + */ +- (NSString *) parameterToString: (id) param; + +@end + +@interface {{classPrefix}}Sanitizer : NSObject <{{classPrefix}}Sanitizer> + + + +@end diff --git a/modules/swagger-codegen/src/main/resources/objc/api_doc.mustache b/modules/swagger-codegen/src/main/resources/objc/api_doc.mustache index 3400300c8dc..c27f6425388 100644 --- a/modules/swagger-codegen/src/main/resources/objc/api_doc.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/api_doc.mustache @@ -31,8 +31,8 @@ Method | HTTP request | Description {{/isBasic}}{{#isApiKey}} // Configure API key authorization: (authentication scheme: {{{name}}}) [apiConfig setApiKey:@"YOUR_API_KEY" forApiKeyIdentifier:@"{{{keyParamName}}}"]; -// Uncomment below to setup prefix (e.g. BEARER) for API key, if needed -//[apiConfig setApiKeyPrefix:@"BEARER" forApiKeyIdentifier:@"{{{keyParamName}}}"]; +// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed +//[apiConfig setApiKeyPrefix:@"Bearer" forApiKeyIdentifier:@"{{{keyParamName}}}"]; {{/isApiKey}}{{#isOAuth}} // Configure OAuth2 access token for authorization: (authentication scheme: {{{name}}}) [apiConfig setAccessToken:@"YOUR_ACCESS_TOKEN"]; 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 ec5ab3b9f80..776cd55ccef 100644 --- a/modules/swagger-codegen/src/main/resources/objc/model-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/model-body.mustache @@ -6,13 +6,11 @@ - (instancetype)init { self = [super init]; - if (self) { // initalise property's default value, if any {{#vars}}{{#defaultValue}}self.{{name}} = {{{defaultValue}}}; {{/defaultValue}}{{/vars}} } - return self; } @@ -22,7 +20,6 @@ */ - (id)initWithDictionary:(NSDictionary *)dict error:(NSError *__autoreleasing *)err { - NSString * discriminatedClassName = [dict valueForKey:@"{{discriminator}}"]; if(discriminatedClassName == nil ){ @@ -45,8 +42,7 @@ * Maps json key to property name. * This method is used by `JSONModel`. */ -+ (JSONKeyMapper *)keyMapper -{ ++ (JSONKeyMapper *)keyMapper { return [[JSONKeyMapper alloc] initWithDictionary:@{ {{#vars}}@"{{baseName}}": @"{{name}}"{{#hasMore}}, {{/hasMore}}{{/vars}} }]; } @@ -55,24 +51,11 @@ * If `propertyName` is optional, then return `YES`, otherwise return `NO`. * This method is used by `JSONModel`. */ -+ (BOOL)propertyIsOptional:(NSString *)propertyName -{ ++ (BOOL)propertyIsOptional:(NSString *)propertyName { + NSArray *optionalProperties = @[{{#vars}}{{^required}}@"{{name}}"{{#hasMore}}, {{/hasMore}}{{/required}}{{/vars}}]; + return [optionalProperties containsObject:propertyName]; - if ([optionalProperties containsObject:propertyName]) { - return YES; - } - else { - return NO; - } -} - -/** - * Gets the string presentation of the object. - * This method will be called when logging model object using `NSLog`. - */ -- (NSString *)description { - return [[self toDictionary] description]; } {{/model}} diff --git a/modules/swagger-codegen/src/main/resources/perl/README.mustache b/modules/swagger-codegen/src/main/resources/perl/README.mustache index b312193f1cc..d47d482742d 100644 --- a/modules/swagger-codegen/src/main/resources/perl/README.mustache +++ b/modules/swagger-codegen/src/main/resources/perl/README.mustache @@ -257,8 +257,8 @@ ${{{moduleName}}}::Configuration::username = 'YOUR_USERNAME'; ${{{moduleName}}}::Configuration::password = 'YOUR_PASSWORD';{{/isBasic}}{{#isApiKey}} # Configure API key authorization: {{{name}}} ${{{moduleName}}}::Configuration::api_key->{'{{{keyParamName}}}'} = 'YOUR_API_KEY'; -# uncomment below to setup prefix (e.g. BEARER) for API key, if needed -#${{{moduleName}}}::Configuration::api_key_prefix->{'{{{keyParamName}}}'} = 'BEARER';{{/isApiKey}}{{#isOAuth}} +# uncomment below to setup prefix (e.g. Bearer) for API key, if needed +#${{{moduleName}}}::Configuration::api_key_prefix->{'{{{keyParamName}}}'} = 'Bearer';{{/isApiKey}}{{#isOAuth}} # Configure OAuth2 access token for authorization: {{{name}}} ${{{moduleName}}}::Configuration::access_token = 'YOUR_ACCESS_TOKEN';{{/isOAuth}}{{/authMethods}} {{/hasAuthMethods}} diff --git a/modules/swagger-codegen/src/main/resources/perl/api_doc.mustache b/modules/swagger-codegen/src/main/resources/perl/api_doc.mustache index c68934ece2a..17dc3903152 100644 --- a/modules/swagger-codegen/src/main/resources/perl/api_doc.mustache +++ b/modules/swagger-codegen/src/main/resources/perl/api_doc.mustache @@ -31,8 +31,8 @@ ${{{moduleName}}}::Configuration::username = 'YOUR_USERNAME'; ${{{moduleName}}}::Configuration::password = 'YOUR_PASSWORD';{{/isBasic}}{{#isApiKey}} # Configure API key authorization: {{{name}}} ${{{moduleName}}}::Configuration::api_key->{'{{{keyParamName}}}'} = 'YOUR_API_KEY'; -# uncomment below to setup prefix (e.g. BEARER) for API key, if needed -#${{{moduleName}}}::Configuration::api_key_prefix->{'{{{keyParamName}}}'} = "BEARER";{{/isApiKey}}{{#isOAuth}} +# uncomment below to setup prefix (e.g. Bearer) for API key, if needed +#${{{moduleName}}}::Configuration::api_key_prefix->{'{{{keyParamName}}}'} = "Bearer";{{/isApiKey}}{{#isOAuth}} # Configure OAuth2 access token for authorization: {{{name}}} ${{{moduleName}}}::Configuration::access_token = 'YOUR_ACCESS_TOKEN';{{/isOAuth}}{{/authMethods}} {{/hasAuthMethods}} diff --git a/modules/swagger-codegen/src/main/resources/php/README.mustache b/modules/swagger-codegen/src/main/resources/php/README.mustache index e64b0bf22c6..3049d013ca5 100644 --- a/modules/swagger-codegen/src/main/resources/php/README.mustache +++ b/modules/swagger-codegen/src/main/resources/php/README.mustache @@ -68,8 +68,8 @@ require_once(__DIR__ . '/vendor/autoload.php'); {{{invokerPackage}}}\Configuration::getDefaultConfiguration()->setPassword('YOUR_PASSWORD');{{/isBasic}}{{#isApiKey}} // Configure API key authorization: {{{name}}} {{{invokerPackage}}}\Configuration::getDefaultConfiguration()->setApiKey('{{{keyParamName}}}', 'YOUR_API_KEY'); -// Uncomment below to setup prefix (e.g. BEARER) for API key, if needed -// {{{invokerPackage}}}\Configuration::getDefaultConfiguration()->setApiKeyPrefix('{{{keyParamName}}}', 'BEARER');{{/isApiKey}}{{#isOAuth}} +// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed +// {{{invokerPackage}}}\Configuration::getDefaultConfiguration()->setApiKeyPrefix('{{{keyParamName}}}', 'Bearer');{{/isApiKey}}{{#isOAuth}} // Configure OAuth2 access token for authorization: {{{name}}} {{{invokerPackage}}}\Configuration::getDefaultConfiguration()->setAccessToken('YOUR_ACCESS_TOKEN');{{/isOAuth}}{{/authMethods}} {{/hasAuthMethods}} @@ -94,12 +94,12 @@ All URIs are relative to *{{basePath}}* Class | Method | HTTP request | Description ------------ | ------------- | ------------- | ------------- -{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}*{{classname}}* | [**{{operationId}}**]({{apiDocPath}}{{classname}}.md#{{operationIdLowerCase}}) | **{{httpMethod}}** {{path}} | {{#summary}}{{summary}}{{/summary}} +{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}*{{classname}}* | [**{{operationId}}**]({{apiDocPath}}/{{classname}}.md#{{operationIdLowerCase}}) | **{{httpMethod}}** {{path}} | {{#summary}}{{summary}}{{/summary}} {{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} ## Documentation For Models -{{#models}}{{#model}} - [{{{classname}}}]({{modelDocPath}}{{{classname}}}.md) +{{#models}}{{#model}} - [{{{classname}}}]({{modelDocPath}}/{{{classname}}}.md) {{/model}}{{/models}} ## Documentation For Authorization diff --git a/modules/swagger-codegen/src/main/resources/php/api.mustache b/modules/swagger-codegen/src/main/resources/php/api.mustache index c8b16b46052..cc74dfd3a2a 100644 --- a/modules/swagger-codegen/src/main/resources/php/api.mustache +++ b/modules/swagger-codegen/src/main/resources/php/api.mustache @@ -131,7 +131,7 @@ use \{{invokerPackage}}\ObjectSerializer; } {{/maxLength}} {{#minLength}} - if (strlen(${{paramName}}) > {{minLength}}) { + if (strlen(${{paramName}}) < {{minLength}}) { throw new \InvalidArgumentException('invalid length for "${{paramName}}" when calling {{classname}}.{{operationId}}, must be bigger than or equal to {{minLength}}.'); } {{/minLength}} diff --git a/modules/swagger-codegen/src/main/resources/php/api_doc.mustache b/modules/swagger-codegen/src/main/resources/php/api_doc.mustache index ba3529e969c..4cf01aa510b 100644 --- a/modules/swagger-codegen/src/main/resources/php/api_doc.mustache +++ b/modules/swagger-codegen/src/main/resources/php/api_doc.mustache @@ -27,8 +27,8 @@ require_once(__DIR__ . '/vendor/autoload.php'); {{{invokerPackage}}}\Configuration::getDefaultConfiguration()->setPassword('YOUR_PASSWORD');{{/isBasic}}{{#isApiKey}} // Configure API key authorization: {{{name}}} {{{invokerPackage}}}\Configuration::getDefaultConfiguration()->setApiKey('{{{keyParamName}}}', 'YOUR_API_KEY'); -// Uncomment below to setup prefix (e.g. BEARER) for API key, if needed -// {{{invokerPackage}}}\Configuration::getDefaultConfiguration()->setApiKeyPrefix('{{{keyParamName}}}', 'BEARER');{{/isApiKey}}{{#isOAuth}} +// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed +// {{{invokerPackage}}}\Configuration::getDefaultConfiguration()->setApiKeyPrefix('{{{keyParamName}}}', 'Bearer');{{/isApiKey}}{{#isOAuth}} // Configure OAuth2 access token for authorization: {{{name}}} {{{invokerPackage}}}\Configuration::getDefaultConfiguration()->setAccessToken('YOUR_ACCESS_TOKEN');{{/isOAuth}}{{/authMethods}} {{/hasAuthMethods}} @@ -50,23 +50,23 @@ try { {{^allParams}}This endpoint does not need any parameter.{{/allParams}}{{#allParams}}{{#-last}} Name | Type | Description | Notes ------------- | ------------- | ------------- | -------------{{/-last}}{{/allParams}} -{{#allParams}} **{{paramName}}** | {{#isFile}}**{{dataType}}**{{/isFile}}{{#isPrimitiveType}}**{{dataType}}**{{/isPrimitiveType}}{{^isPrimitiveType}}{{^isFile}}[**{{dataType}}**]({{baseType}}.md){{/isFile}}{{/isPrimitiveType}}| {{description}} | {{^required}}[optional] {{/required}}{{#defaultValue}}[default to {{defaultValue}}]{{/defaultValue}} +{{#allParams}} **{{paramName}}** | {{#isFile}}**{{dataType}}**{{/isFile}}{{#isPrimitiveType}}**{{dataType}}**{{/isPrimitiveType}}{{^isPrimitiveType}}{{^isFile}}[**{{dataType}}**](../Model/{{baseType}}.md){{/isFile}}{{/isPrimitiveType}}| {{description}} | {{^required}}[optional] {{/required}}{{#defaultValue}}[default to {{defaultValue}}]{{/defaultValue}} {{/allParams}} ### Return type -{{#returnType}}{{#returnTypeIsPrimitive}}**{{{returnType}}}**{{/returnTypeIsPrimitive}}{{^returnTypeIsPrimitive}}[**{{{returnType}}}**]({{returnBaseType}}.md){{/returnTypeIsPrimitive}}{{/returnType}}{{^returnType}}void (empty response body){{/returnType}} +{{#returnType}}{{#returnTypeIsPrimitive}}**{{{returnType}}}**{{/returnTypeIsPrimitive}}{{^returnTypeIsPrimitive}}[**{{{returnType}}}**](../Model/{{returnBaseType}}.md){{/returnTypeIsPrimitive}}{{/returnType}}{{^returnType}}void (empty response body){{/returnType}} ### Authorization -{{^authMethods}}No authorization required{{/authMethods}}{{#authMethods}}[{{{name}}}](../README.md#{{{name}}}){{^-last}}, {{/-last}}{{/authMethods}} +{{^authMethods}}No authorization required{{/authMethods}}{{#authMethods}}[{{{name}}}](../../README.md#{{{name}}}){{^-last}}, {{/-last}}{{/authMethods}} ### HTTP request headers - **Content-Type**: {{#consumes}}{{mediaType}}{{#hasMore}}, {{/hasMore}}{{/consumes}}{{^consumes}}Not defined{{/consumes}} - **Accept**: {{#produces}}{{mediaType}}{{#hasMore}}, {{/hasMore}}{{/produces}}{{^produces}}Not defined{{/produces}} -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) {{/operation}} {{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/php/composer.mustache b/modules/swagger-codegen/src/main/resources/php/composer.mustache index 6ab42751a57..062a3ddc6cc 100644 --- a/modules/swagger-codegen/src/main/resources/php/composer.mustache +++ b/modules/swagger-codegen/src/main/resources/php/composer.mustache @@ -29,5 +29,8 @@ }, "autoload": { "psr-4": { "{{escapedInvokerPackage}}\\" : "{{srcBasePath}}/" } + }, + "autoload-dev": { + "psr-4": { "{{escapedInvokerPackage}}\\" : "{{testBasePath}}/" } } } diff --git a/modules/swagger-codegen/src/main/resources/php/model.mustache b/modules/swagger-codegen/src/main/resources/php/model.mustache index 2a7894ab860..6dbf2544a17 100644 --- a/modules/swagger-codegen/src/main/resources/php/model.mustache +++ b/modules/swagger-codegen/src/main/resources/php/model.mustache @@ -36,6 +36,7 @@ namespace {{modelPackage}}; use \ArrayAccess; + /** * {{classname}} Class Doc Comment * @@ -46,7 +47,7 @@ use \ArrayAccess; * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 * @link https://github.com/swagger-api/swagger-codegen */ -class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}implements ArrayAccess +class {{classname}} {{#parentSchema}}extends {{{parent}}} {{/parentSchema}}implements ArrayAccess { /** * The original name of the model. @@ -62,9 +63,9 @@ class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}implements ArrayA {{#vars}}'{{name}}' => '{{{datatype}}}'{{#hasMore}}, {{/hasMore}}{{/vars}} ); - + static function swaggerTypes() { - return self::$swaggerTypes{{#parent}} + parent::swaggerTypes(){{/parent}}; + return self::$swaggerTypes{{#parentSchema}} + parent::swaggerTypes(){{/parentSchema}}; } /** @@ -75,9 +76,9 @@ class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}implements ArrayA {{#vars}}'{{name}}' => '{{baseName}}'{{#hasMore}}, {{/hasMore}}{{/vars}} ); - + static function attributeMap() { - return {{#parent}}parent::attributeMap() + {{/parent}}self::$attributeMap; + return {{#parentSchema}}parent::attributeMap() + {{/parentSchema}}self::$attributeMap; } /** @@ -88,9 +89,9 @@ class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}implements ArrayA {{#vars}}'{{name}}' => '{{setter}}'{{#hasMore}}, {{/hasMore}}{{/vars}} ); - + static function setters() { - return {{#parent}}parent::setters() + {{/parent}}self::$setters; + return {{#parentSchema}}parent::setters() + {{/parentSchema}}self::$setters; } /** @@ -103,7 +104,7 @@ class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}implements ArrayA ); static function getters() { - return {{#parent}}parent::getters() + {{/parent}}self::$getters; + return {{#parentSchema}}parent::getters() + {{/parentSchema}}self::$getters; } {{#vars}}{{#isEnum}}{{#allowableValues}}{{#enumVars}}const {{datatypeWithEnum}}_{{{name}}} = {{{value}}}; @@ -122,13 +123,11 @@ class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}implements ArrayA } {{/isEnum}}{{/vars}} - {{#vars}} /** - * ${{name}} {{#description}}{{{description}}}{{/description}} - * @var {{datatype}} + * Associative array for storing property values + * @var mixed[] */ - protected ${{name}}{{#defaultValue}} = {{{defaultValue}}}{{/defaultValue}}; - {{/vars}} + protected $container = array(); /** * Constructor @@ -136,25 +135,132 @@ class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}implements ArrayA */ public function __construct(array $data = null) { - {{#parent}}parent::__construct($data);{{/parent}} - {{#discriminator}}// Initialize discriminator property with the model name. - $discrimintor = array_search('{{discriminator}}', self::$attributeMap); - $this->{$discrimintor} = static::$swaggerModelName; - {{/discriminator}} + {{#parentSchema}} + parent::__construct($data); - if ($data != null) { - {{#vars}}$this->{{name}} = $data["{{name}}"];{{#hasMore}} - {{/hasMore}}{{/vars}} - } + {{/parentSchema}} + {{#vars}} + $this->container['{{name}}'] = isset($data['{{name}}']) ? $data['{{name}}'] : {{#defaultValue}}{{{defaultValue}}}{{/defaultValue}}{{^defaultValue}}null{{/defaultValue}}; + {{/vars}} + {{#discriminator}} + + // Initialize discriminator property with the model name. + $discrimintor = array_search('{{discriminator}}', self::$attributeMap); + $this->container[$discrimintor] = static::$swaggerModelName; + {{/discriminator}} } + + /** + * show all the invalid properties with reasons. + * + * @return array invalid properties with reasons + */ + public function list_invalid_properties() + { + $invalid_properties = array(); + {{#vars}} + {{#required}} + if ($this->container['{{name}}'] === null) { + $invalid_properties[] = "'${{name}}' can't be null"; + } + {{/required}} + {{#isEnum}} + $allowed_values = array({{#allowableValues}}{{#values}}"{{{this}}}"{{^-last}}, {{/-last}}{{/values}}{{/allowableValues}}); + if (!in_array($this->container['{{name}}'], $allowed_values)) { + $invalid_properties[] = "invalid value for '${{name}}', must be one of #{allowed_values}."; + } + {{/isEnum}} + {{#hasValidation}} + {{#maxLength}} + if (strlen($this->container['{{name}}']) > {{maxLength}}) { + $invalid_properties[] = "invalid value for '${{name}}', the character length must be smaller than or equal to {{{maxLength}}}."; + } + {{/maxLength}} + {{#minLength}} + if (strlen($this->container['{{name}}']) < {{minLength}}) { + $invalid_properties[] = "invalid value for '${{name}}', the character length must be bigger than or equal to {{{minLength}}}."; + } + {{/minLength}} + {{#maximum}} + if ($this->container['{{name}}'] > {{maximum}}) { + $invalid_properties[] = "invalid value for '${{name}}', must be smaller than or equal to {{maximum}}."; + } + {{/maximum}} + {{#minimum}} + if ($this->container['{{name}}'] < {{minimum}}) { + $invalid_properties[] = "invalid value for '${{name}}', must be bigger than or equal to {{minimum}}."; + } + {{/minimum}} + {{#pattern}} + if (!preg_match("{{pattern}}", $this->container['{{name}}'])) { + $invalid_properties[] = "invalid value for '${{name}}', must be conform to the pattern {{pattern}}."; + } + {{/pattern}} + {{/hasValidation}} + {{/vars}} + return $invalid_properties; + } + + /** + * validate all the properties in the model + * return true if all passed + * + * @return bool True if all properteis are valid + */ + public function valid() + { + {{#vars}} + {{#required}} + if ($this->container['{{name}}'] === null) { + return false; + } + {{/required}} + {{#isEnum}} + $allowed_values = array({{#allowableValues}}{{#values}}"{{{this}}}"{{^-last}}, {{/-last}}{{/values}}{{/allowableValues}}); + if (!in_array($this->container['{{name}}'], $allowed_values)) { + return false; + } + {{/isEnum}} + {{#hasValidation}} + {{#maxLength}} + if (strlen($this->container['{{name}}']) > {{maxLength}}) { + return false; + } + {{/maxLength}} + {{#minLength}} + if (strlen($this->container['{{name}}']) < {{minLength}}) { + return false; + } + {{/minLength}} + {{#maximum}} + if ($this->container['{{name}}'] > {{maximum}}) { + return false; + } + {{/maximum}} + {{#minimum}} + if ($this->container['{{name}}'] < {{minimum}}) { + return false; + } + {{/minimum}} + {{#pattern}} + if (!preg_match("{{pattern}}", $this->container['{{name}}'])) { + return false; + } + {{/pattern}} + {{/hasValidation}} + {{/vars}} + return true; + } + {{#vars}} + /** * Gets {{name}} * @return {{datatype}} */ public function {{getter}}() { - return $this->{{name}}; + return $this->container['{{name}}']; } /** @@ -164,11 +270,40 @@ class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}implements ArrayA */ public function {{setter}}(${{name}}) { - {{#isEnum}}$allowed_values = array({{#allowableValues}}{{#values}}"{{{this}}}"{{^-last}}, {{/-last}}{{/values}}{{/allowableValues}}); + {{#isEnum}} + $allowed_values = array({{#allowableValues}}{{#values}}'{{{this}}}'{{^-last}}, {{/-last}}{{/values}}{{/allowableValues}}); if (!in_array(${{{name}}}, $allowed_values)) { throw new \InvalidArgumentException("Invalid value for '{{name}}', must be one of {{#allowableValues}}{{#values}}'{{{this}}}'{{^-last}}, {{/-last}}{{/values}}{{/allowableValues}}"); - }{{/isEnum}} - $this->{{name}} = ${{name}}; + } + {{/isEnum}} + {{#hasValidation}} + {{#maxLength}} + if (strlen(${{name}}) > {{maxLength}}) { + throw new \InvalidArgumentException('invalid length for ${{name}} when calling {{classname}}.{{operationId}}, must be smaller than or equal to {{maxLength}}.'); + }{{/maxLength}} + {{#minLength}} + if (strlen(${{name}}) < {{minLength}}) { + throw new \InvalidArgumentException('invalid length for ${{name}} when calling {{classname}}.{{operationId}}, must be bigger than or equal to {{minLength}}.'); + } + {{/minLength}} + {{#maximum}} + if (${{name}} > {{maximum}}) { + throw new \InvalidArgumentException('invalid value for ${{name}} when calling {{classname}}.{{operationId}}, must be smaller than or equal to {{maximum}}.'); + } + {{/maximum}} + {{#minimum}} + if (${{name}} < {{minimum}}) { + throw new \InvalidArgumentException('invalid value for ${{name}} when calling {{classname}}.{{operationId}}, must be bigger than or equal to {{minimum}}.'); + } + {{/minimum}} + {{#pattern}} + if (!preg_match("{{pattern}}", ${{name}})) { + throw new \InvalidArgumentException('invalid value for ${{name}} when calling {{classname}}.{{operationId}}, must be conform to the pattern {{pattern}}.'); + } + {{/pattern}} + {{/hasValidation}} + $this->container['{{name}}'] = ${{name}}; + return $this; } {{/vars}} @@ -179,7 +314,7 @@ class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}implements ArrayA */ public function offsetExists($offset) { - return isset($this->$offset); + return isset($this->container[$offset]); } /** @@ -189,7 +324,7 @@ class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}implements ArrayA */ public function offsetGet($offset) { - return $this->$offset; + return isset($this->container[$offset]) ? $this->container[$offset] : null; } /** @@ -200,7 +335,11 @@ class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}implements ArrayA */ public function offsetSet($offset, $value) { - $this->$offset = $value; + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } } /** @@ -210,7 +349,7 @@ class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}implements ArrayA */ public function offsetUnset($offset) { - unset($this->$offset); + unset($this->container[$offset]); } /** diff --git a/modules/swagger-codegen/src/main/resources/python/README.mustache b/modules/swagger-codegen/src/main/resources/python/README.mustache index 8fe1045f661..08f2d835c4c 100644 --- a/modules/swagger-codegen/src/main/resources/python/README.mustache +++ b/modules/swagger-codegen/src/main/resources/python/README.mustache @@ -61,8 +61,8 @@ from pprint import pprint {{{packageName}}}.configuration.password = 'YOUR_PASSWORD'{{/isBasic}}{{#isApiKey}} # Configure API key authorization: {{{name}}} {{{packageName}}}.configuration.api_key['{{{keyParamName}}}'] = 'YOUR_API_KEY' -# Uncomment below to setup prefix (e.g. BEARER) for API key, if needed -# {{{packageName}}}.configuration.api_key_prefix['{{{keyParamName}}}'] = 'BEARER'{{/isApiKey}}{{#isOAuth}} +# Uncomment below to setup prefix (e.g. Bearer) for API key, if needed +# {{{packageName}}}.configuration.api_key_prefix['{{{keyParamName}}}'] = 'Bearer'{{/isApiKey}}{{#isOAuth}} # Configure OAuth2 access token for authorization: {{{name}}} {{{packageName}}}.configuration.access_token = 'YOUR_ACCESS_TOKEN'{{/isOAuth}}{{/authMethods}} {{/hasAuthMethods}} diff --git a/modules/swagger-codegen/src/main/resources/python/api.mustache b/modules/swagger-codegen/src/main/resources/python/api.mustache index 0967a2ec6b3..94458e3f724 100644 --- a/modules/swagger-codegen/src/main/resources/python/api.mustache +++ b/modules/swagger-codegen/src/main/resources/python/api.mustache @@ -21,6 +21,7 @@ from __future__ import absolute_import import sys import os +import re # python 2 and python 3 compatibility library from six import iteritems @@ -94,6 +95,31 @@ class {{classname}}(object): if ('{{paramName}}' not in params) or (params['{{paramName}}'] is None): raise ValueError("Missing the required parameter `{{paramName}}` when calling `{{operationId}}`") {{/required}} +{{/allParams}} + +{{#allParams}} +{{#hasValidation}} + {{#maxLength}} + if '{{paramName}}' in params and len(params['{{paramName}}']) > {{maxLength}}: + raise ValueError("Invalid value for parameter `{{paramName}}` when calling `{{operationId}}`, length must be less than or equal to `{{maxLength}}`") + {{/maxLength}} + {{#minLength}} + if '{{paramName}}' in params and len(params['{{paramName}}']) < {{minLength}}: + raise ValueError("Invalid value for parameter `{{paramName}}` when calling `{{operationId}}`, length must be greater than or equal to `{{minLength}}`") + {{/minLength}} + {{#maximum}} + if '{{paramName}}' in params and params['{{paramName}}'] > {{maximum}}: + raise ValueError("Invalid value for parameter `{{paramName}}` when calling `{{operationId}}`, must be a value less than or equal to `{{maximum}}`") + {{/maximum}} + {{#minimum}} + if '{{paramName}}' in params and params['{{paramName}}'] < {{minimum}}: + raise ValueError("Invalid value for parameter `{{paramName}}` when calling `{{operationId}}`, must be a value greater than or equal to `{{minimum}}`") + {{/minimum}} + {{#pattern}} + if '{{paramName}}' in params and not re.search('{{vendorExtensions.x-regex}}', params['{{paramName}}']{{#vendorExtensions.x-modifiers}}{{#-first}}, flags={{/-first}}re.{{.}}{{^-last}} | {{/-last}}{{/vendorExtensions.x-modifiers}}): + raise ValueError("Invalid value for parameter `{{paramName}}` when calling `{{operationId}}`, must conform to the pattern `{{pattern}}`") + {{/pattern}} +{{/hasValidation}} {{/allParams}} resource_path = '{{path}}'.replace('{format}', 'json') diff --git a/modules/swagger-codegen/src/main/resources/python/api_doc.mustache b/modules/swagger-codegen/src/main/resources/python/api_doc.mustache index 99a05f8c43d..8eb25a87b06 100644 --- a/modules/swagger-codegen/src/main/resources/python/api_doc.mustache +++ b/modules/swagger-codegen/src/main/resources/python/api_doc.mustache @@ -29,8 +29,8 @@ from pprint import pprint {{{packageName}}}.configuration.password = 'YOUR_PASSWORD'{{/isBasic}}{{#isApiKey}} # Configure API key authorization: {{{name}}} {{{packageName}}}.configuration.api_key['{{{keyParamName}}}'] = 'YOUR_API_KEY' -# Uncomment below to setup prefix (e.g. BEARER) for API key, if needed -# {{{packageName}}}.configuration.api_key_prefix['{{{keyParamName}}}'] = 'BEARER'{{/isApiKey}}{{#isOAuth}} +# Uncomment below to setup prefix (e.g. Bearer) for API key, if needed +# {{{packageName}}}.configuration.api_key_prefix['{{{keyParamName}}}'] = 'Bearer'{{/isApiKey}}{{#isOAuth}} # Configure OAuth2 access token for authorization: {{{name}}} {{{packageName}}}.configuration.access_token = 'YOUR_ACCESS_TOKEN'{{/isOAuth}}{{/authMethods}} {{/hasAuthMethods}} diff --git a/modules/swagger-codegen/src/main/resources/python/model.mustache b/modules/swagger-codegen/src/main/resources/python/model.mustache index bd33a997c3e..e62fa2cbf66 100644 --- a/modules/swagger-codegen/src/main/resources/python/model.mustache +++ b/modules/swagger-codegen/src/main/resources/python/model.mustache @@ -22,6 +22,7 @@ Copyright 2016 SmartBear Software {{#model}} from pprint import pformat from six import iteritems +import re class {{classname}}(object): @@ -79,7 +80,36 @@ class {{classname}}(object): "Invalid value for `{{name}}`, must be one of {0}" .format(allowed_values) ) - {{/isEnum}}self._{{name}} = {{name}} +{{/isEnum}} +{{^isEnum}} +{{#hasValidation}} + + if not {{name}}: + raise ValueError("Invalid value for `{{name}}`, must not be `None`") +{{#maxLength}} + if len({{name}}) > {{maxLength}}: + raise ValueError("Invalid value for `{{name}}`, length must be less than `{{maxLength}}`") +{{/maxLength}} +{{#minLength}} + if len({{name}}) < {{minLength}}: + raise ValueError("Invalid value for `{{name}}`, length must be greater than or equal to `{{minLength}}`") +{{/minLength}} +{{#maximum}} + if {{name}} > {{maximum}}: + raise ValueError("Invalid value for `{{name}}`, must be a value less than or equal to `{{maximum}}`") +{{/maximum}} +{{#minimum}} + if {{name}} < {{minimum}}: + raise ValueError("Invalid value for `{{name}}`, must be a value greater than or equal to `{{minimum}}`") +{{/minimum}} +{{#pattern}} + if not re.search('{{vendorExtensions.x-regex}}', {{name}}{{#vendorExtensions.x-modifiers}}{{#-first}}, flags={{/-first}}re.{{.}}{{^-last}} | {{/-last}}{{/vendorExtensions.x-modifiers}}): + raise ValueError("Invalid value for `{{name}}`, must be a follow pattern or equal to `{{pattern}}`") +{{/pattern}} +{{/hasValidation}} +{{/isEnum}} + + self._{{name}} = {{name}} {{/vars}} def to_dict(self): diff --git a/modules/swagger-codegen/src/main/resources/ruby/README.mustache b/modules/swagger-codegen/src/main/resources/ruby/README.mustache index f4bafd9b0ea..076192b75ce 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/README.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/README.mustache @@ -67,8 +67,8 @@ require '{{{gemName}}}' config.password = 'YOUR PASSWORD'{{/isBasic}}{{#isApiKey}} # Configure API key authorization: {{{name}}} config.api_key['{{{keyParamName}}}'] = 'YOUR API KEY' - # Uncomment the following line to set a prefix for the API key, e.g. 'BEARER' (defaults to nil) - #config.api_key_prefix['{{{keyParamName}}}'] = 'BEARER'{{/isApiKey}}{{#isOAuth}} + # Uncomment the following line to set a prefix for the API key, e.g. 'Bearer' (defaults to nil) + #config.api_key_prefix['{{{keyParamName}}}'] = 'Bearer'{{/isApiKey}}{{#isOAuth}} # Configure OAuth2 access token for authorization: {{{name}}} config.access_token = 'YOUR ACCESS TOKEN'{{/isOAuth}} {{/authMethods}}end diff --git a/modules/swagger-codegen/src/main/resources/ruby/api_client_spec.mustache b/modules/swagger-codegen/src/main/resources/ruby/api_client_spec.mustache new file mode 100644 index 00000000000..1ed497da21e --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/ruby/api_client_spec.mustache @@ -0,0 +1,273 @@ +require 'spec_helper' + +describe {{moduleName}}::ApiClient do + context 'initialization' do + context 'URL stuff' do + context 'host' do + it 'removes http from host' do + {{moduleName}}.configure { |c| c.host = 'http://example.com' } + expect({{moduleName}}::Configuration.default.host).to eq('example.com') + end + + it 'removes https from host' do + {{moduleName}}.configure { |c| c.host = 'https://wookiee.com' } + expect({{moduleName}}::ApiClient.default.config.host).to eq('wookiee.com') + end + + it 'removes trailing path from host' do + {{moduleName}}.configure { |c| c.host = 'hobo.com/v4' } + expect({{moduleName}}::Configuration.default.host).to eq('hobo.com') + end + end + + context 'base_path' do + it "prepends a slash to base_path" do + {{moduleName}}.configure { |c| c.base_path = 'v4/dog' } + expect({{moduleName}}::Configuration.default.base_path).to eq('/v4/dog') + end + + it "doesn't prepend a slash if one is already there" do + {{moduleName}}.configure { |c| c.base_path = '/v4/dog' } + expect({{moduleName}}::Configuration.default.base_path).to eq('/v4/dog') + end + + it "ends up as a blank string if nil" do + {{moduleName}}.configure { |c| c.base_path = nil } + expect({{moduleName}}::Configuration.default.base_path).to eq('') + end + end + end + end + + describe "#update_params_for_auth!" do + it "sets header api-key parameter with prefix" do + {{moduleName}}.configure do |c| + c.api_key_prefix['api_key'] = 'PREFIX' + c.api_key['api_key'] = 'special-key' + end + + api_client = {{moduleName}}::ApiClient.new + + config2 = {{moduleName}}::Configuration.new do |c| + c.api_key_prefix['api_key'] = 'PREFIX2' + c.api_key['api_key'] = 'special-key2' + end + api_client2 = {{moduleName}}::ApiClient.new(config2) + + auth_names = ['api_key', 'unknown'] + + header_params = {} + query_params = {} + api_client.update_params_for_auth! header_params, query_params, auth_names + expect(header_params).to eq({'api_key' => 'PREFIX special-key'}) + expect(query_params).to eq({}) + + header_params = {} + query_params = {} + api_client2.update_params_for_auth! header_params, query_params, auth_names + expect(header_params).to eq({'api_key' => 'PREFIX2 special-key2'}) + expect(query_params).to eq({}) + end + + it "sets header api-key parameter without prefix" do + {{moduleName}}.configure do |c| + c.api_key_prefix['api_key'] = nil + c.api_key['api_key'] = 'special-key' + end + + api_client = {{moduleName}}::ApiClient.new + + header_params = {} + query_params = {} + auth_names = ['api_key', 'unknown'] + api_client.update_params_for_auth! header_params, query_params, auth_names + expect(header_params).to eq({'api_key' => 'special-key'}) + expect(query_params).to eq({}) + end + end + + describe "timeout in #build_request" do + let(:config) { {{moduleName}}::Configuration.new } + let(:api_client) { {{moduleName}}::ApiClient.new(config) } + + it "defaults to 0" do + expect({{moduleName}}::Configuration.default.timeout).to eq(0) + expect(config.timeout).to eq(0) + + request = api_client.build_request(:get, '/test') + expect(request.options[:timeout]).to eq(0) + end + + it "can be customized" do + config.timeout = 100 + request = api_client.build_request(:get, '/test') + expect(request.options[:timeout]).to eq(100) + end + end + + describe "#deserialize" do + it "handles Array" do + api_client = {{moduleName}}::ApiClient.new + headers = {'Content-Type' => 'application/json'} + response = double('response', headers: headers, body: '[12, 34]') + data = api_client.deserialize(response, 'Array') + expect(data).to be_instance_of(Array) + expect(data).to eq([12, 34]) + end + + it "handles Array>" do + api_client = {{moduleName}}::ApiClient.new + headers = {'Content-Type' => 'application/json'} + response = double('response', headers: headers, body: '[[12, 34], [56]]') + data = api_client.deserialize(response, 'Array>') + expect(data).to be_instance_of(Array) + expect(data).to eq([[12, 34], [56]]) + end + + it "handles Hash" do + api_client = {{moduleName}}::ApiClient.new + headers = {'Content-Type' => 'application/json'} + response = double('response', headers: headers, body: '{"message": "Hello"}') + data = api_client.deserialize(response, 'Hash') + expect(data).to be_instance_of(Hash) + expect(data).to eq({:message => 'Hello'}) + end + + it "handles Hash" do + api_client = {{moduleName}}::ApiClient.new + headers = {'Content-Type' => 'application/json'} + response = double('response', headers: headers, body: '{"pet": {"id": 1}}') + data = api_client.deserialize(response, 'Hash') + expect(data).to be_instance_of(Hash) + expect(data.keys).to eq([:pet]) + + pet = data[:pet] + expect(pet).to be_instance_of({{moduleName}}::Pet) + expect(pet.id).to eq(1) + end + + it "handles Hash>" do + api_client = {{moduleName}}::ApiClient.new + headers = {'Content-Type' => 'application/json'} + response = double('response', headers: headers, body: '{"data": {"pet": {"id": 1}}}') + result = api_client.deserialize(response, 'Hash>') + expect(result).to be_instance_of(Hash) + expect(result.keys).to match_array([:data]) + + data = result[:data] + expect(data).to be_instance_of(Hash) + expect(data.keys).to match_array([:pet]) + + pet = data[:pet] + expect(pet).to be_instance_of({{moduleName}}::Pet) + expect(pet.id).to eq(1) + end + end + + describe "#object_to_hash" do + it "ignores nils and includes empty arrays" do + api_client = {{moduleName}}::ApiClient.new + pet = {{moduleName}}::Pet.new + pet.id = 1 + pet.name = '' + pet.status = nil + pet.photo_urls = nil + pet.tags = [] + expected = {id: 1, name: '', tags: []} + expect(api_client.object_to_hash(pet)).to eq(expected) + end + end + + describe "#build_collection_param" do + let(:param) { ['aa', 'bb', 'cc'] } + let(:api_client) { {{moduleName}}::ApiClient.new } + + it "works for csv" do + expect(api_client.build_collection_param(param, :csv)).to eq('aa,bb,cc') + end + + it "works for ssv" do + expect(api_client.build_collection_param(param, :ssv)).to eq('aa bb cc') + end + + it "works for tsv" do + expect(api_client.build_collection_param(param, :tsv)).to eq("aa\tbb\tcc") + end + + it "works for pipes" do + expect(api_client.build_collection_param(param, :pipes)).to eq('aa|bb|cc') + end + + it "works for multi" do + expect(api_client.build_collection_param(param, :multi)).to eq(['aa', 'bb', 'cc']) + end + + it "fails for invalid collection format" do + expect(proc { api_client.build_collection_param(param, :INVALID) }).to raise_error(RuntimeError, 'unknown collection format: :INVALID') + end + end + + describe "#json_mime?" do + let(:api_client) { {{moduleName}}::ApiClient.new } + + it "works" do + expect(api_client.json_mime?(nil)).to eq false + expect(api_client.json_mime?('')).to eq false + + expect(api_client.json_mime?('application/json')).to eq true + expect(api_client.json_mime?('application/json; charset=UTF8')).to eq true + expect(api_client.json_mime?('APPLICATION/JSON')).to eq true + + expect(api_client.json_mime?('application/xml')).to eq false + expect(api_client.json_mime?('text/plain')).to eq false + expect(api_client.json_mime?('application/jsonp')).to eq false + end + end + + describe "#select_header_accept" do + let(:api_client) { {{moduleName}}::ApiClient.new } + + it "works" do + expect(api_client.select_header_accept(nil)).to be_nil + expect(api_client.select_header_accept([])).to be_nil + + expect(api_client.select_header_accept(['application/json'])).to eq('application/json') + expect(api_client.select_header_accept(['application/xml', 'application/json; charset=UTF8'])).to eq('application/json; charset=UTF8') + expect(api_client.select_header_accept(['APPLICATION/JSON', 'text/html'])).to eq('APPLICATION/JSON') + + expect(api_client.select_header_accept(['application/xml'])).to eq('application/xml') + expect(api_client.select_header_accept(['text/html', 'application/xml'])).to eq('text/html,application/xml') + end + end + + describe "#select_header_content_type" do + let(:api_client) { {{moduleName}}::ApiClient.new } + + it "works" do + expect(api_client.select_header_content_type(nil)).to eq('application/json') + expect(api_client.select_header_content_type([])).to eq('application/json') + + expect(api_client.select_header_content_type(['application/json'])).to eq('application/json') + expect(api_client.select_header_content_type(['application/xml', 'application/json; charset=UTF8'])).to eq('application/json; charset=UTF8') + expect(api_client.select_header_content_type(['APPLICATION/JSON', 'text/html'])).to eq('APPLICATION/JSON') + expect(api_client.select_header_content_type(['application/xml'])).to eq('application/xml') + expect(api_client.select_header_content_type(['text/plain', 'application/xml'])).to eq('text/plain') + end + end + + describe "#sanitize_filename" do + let(:api_client) { {{moduleName}}::ApiClient.new } + + it "works" do + expect(api_client.sanitize_filename('sun')).to eq('sun') + expect(api_client.sanitize_filename('sun.gif')).to eq('sun.gif') + expect(api_client.sanitize_filename('../sun.gif')).to eq('sun.gif') + expect(api_client.sanitize_filename('/var/tmp/sun.gif')).to eq('sun.gif') + expect(api_client.sanitize_filename('./sun.gif')).to eq('sun.gif') + expect(api_client.sanitize_filename('..\sun.gif')).to eq('sun.gif') + expect(api_client.sanitize_filename('\var\tmp\sun.gif')).to eq('sun.gif') + expect(api_client.sanitize_filename('c:\var\tmp\sun.gif')).to eq('sun.gif') + expect(api_client.sanitize_filename('.\sun.gif')).to eq('sun.gif') + end + end +end diff --git a/modules/swagger-codegen/src/main/resources/ruby/api_doc.mustache b/modules/swagger-codegen/src/main/resources/ruby/api_doc.mustache index 169920a4bc3..a2cee7f9361 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/api_doc.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/api_doc.mustache @@ -29,8 +29,8 @@ require '{{{gemName}}}' config.password = 'YOUR PASSWORD'{{/isBasic}}{{#isApiKey}} # Configure API key authorization: {{{name}}} config.api_key['{{{keyParamName}}}'] = 'YOUR API KEY' - # Uncomment the following line to set a prefix for the API key, e.g. 'BEARER' (defaults to nil) - #config.api_key_prefix['{{{keyParamName}}}'] = 'BEARER'{{/isApiKey}}{{#isOAuth}} + # Uncomment the following line to set a prefix for the API key, e.g. 'Bearer' (defaults to nil) + #config.api_key_prefix['{{{keyParamName}}}'] = 'Bearer'{{/isApiKey}}{{#isOAuth}} # Configure OAuth2 access token for authorization: {{{name}}} config.access_token = 'YOUR ACCESS TOKEN'{{/isOAuth}} {{/authMethods}}end diff --git a/modules/swagger-codegen/src/main/resources/ruby/api_test.mustache b/modules/swagger-codegen/src/main/resources/ruby/api_test.mustache index 7e95c2d6446..d28f29e0c3a 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/api_test.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/api_test.mustache @@ -20,7 +20,7 @@ require 'json' describe 'test an instance of {{classname}}' do it 'should create an instact of {{classname}}' do - @instance.should be_a({{moduleName}}::{{classname}}) + expect(@instance).to be_instance_of({{moduleName}}::{{classname}}) end end @@ -34,11 +34,7 @@ require 'json' {{/required}}{{/allParams}} # @return [{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}nil{{/returnType}}] describe '{{operationId}} test' do it "should work" do - # assertion here - # should be_a() - # should be_nil - # should == - # should_not == + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end diff --git a/modules/swagger-codegen/src/main/resources/ruby/base_object_spec.mustache b/modules/swagger-codegen/src/main/resources/ruby/base_object_spec.mustache new file mode 100644 index 00000000000..7376cd1e84d --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/ruby/base_object_spec.mustache @@ -0,0 +1,109 @@ +require 'spec_helper' + +class ArrayMapObject < Petstore::Category + attr_accessor :int_arr, :pet_arr, :int_map, :pet_map, :int_arr_map, :pet_arr_map, :boolean_true_arr, :boolean_false_arr + + def self.attribute_map + { + :int_arr => :int_arr, + :pet_arr => :pet_arr, + :int_map => :int_map, + :pet_map => :pet_map, + :int_arr_map => :int_arr_map, + :pet_arr_map => :pet_arr_map, + :boolean_true_arr => :boolean_true_arr, + :boolean_false_arr => :boolean_false_arr, + } + end + + def self.swagger_types + { + :int_arr => :'Array', + :pet_arr => :'Array', + :int_map => :'Hash', + :pet_map => :'Hash', + :int_arr_map => :'Hash>', + :pet_arr_map => :'Hash>', + :boolean_true_arr => :'Array', + :boolean_false_arr => :'Array', + } + end +end + +describe 'BaseObject' do + describe 'boolean values' do + let(:obj) { Petstore::Cat.new({declawed: false}) } + + it 'should have values set' do + expect(obj.declawed).not_to be_nil + expect(obj.declawed).to eq(false) + end + end + + describe 'array and map properties' do + let(:obj) { ArrayMapObject.new } + + let(:data) do + {int_arr: [123, 456], + pet_arr: [{name: 'Kitty'}], + int_map: {'int' => 123}, + pet_map: {'pet' => {name: 'Kitty'}}, + int_arr_map: {'int_arr' => [123, 456]}, + pet_arr_map: {'pet_arr' => [{name: 'Kitty'}]}, + boolean_true_arr: [true, "true", "TruE", 1, "y", "yes", "1", "t", "T"], + boolean_false_arr: [false, "", 0, "0", "f", nil, "null"], + } + end + + it 'works for #build_from_hash' do + obj.build_from_hash(data) + + expect(obj.int_arr).to match_array([123, 456]) + + expect(obj.pet_arr).to be_instance_of(Array) + expect(obj.pet_arr).to be_instance_of(1) + + pet = obj.pet_arr.first + expect(pet).to be_instance_of(Petstore::Pet) + expect(pet.name).to eq('Kitty') + + expect(obj.int_map).to be_instance_of(Hash) + expect(obj.int_map).to eq({'int' => 123}) + + expect(obj.pet_map).to be_instance_of(Hash) + pet = obj.pet_map['pet'] + expect(pet).to be_instance_of(Petstore::Pet) + expect(pet.name).to eq('Kitty') + + expect(obj.int_arr_map).to be_instance_of(Hash) + arr = obj.int_arr_map['int_arr'] + expect(arr).to match_array([123, 456]) + + expect(obj.pet_arr_map).to be_instance_of(Hash) + arr = obj.pet_arr_map['pet_arr'] + expect(arr).to be_instance_of(Array) + expect(arr.size).to eq(1) + pet = arr.first + expect(pet).to be_instance_of(Petstore::Pet) + expect(pet.name).to eq('Kitty') + + expect(obj.boolean_true_arr).to be_instance_of(Array) + obj.boolean_true_arr.each do |b| + expect(b).to eq(true) + end + + expect(obj.boolean_false_arr).to be_instance_of(Array) + obj.boolean_false_arr.each do |b| + expect(b).to eq(false) + end + end + + it 'works for #to_hash' do + obj.build_from_hash(data) + expect_data = data.dup + expect_data[:boolean_true_arr].map! {true} + expect_data[:boolean_false_arr].map! {false} + expect(obj.to_hash).to eq(expect_data) + end + end +end diff --git a/modules/swagger-codegen/src/main/resources/ruby/configuration_spec.mustache b/modules/swagger-codegen/src/main/resources/ruby/configuration_spec.mustache new file mode 100644 index 00000000000..4c23a067175 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/ruby/configuration_spec.mustache @@ -0,0 +1,25 @@ +require 'spec_helper' + +describe {{moduleName}}::Configuration do + let(:config) { {{moduleName}}::Configuration.default } + + before(:each) do + {{moduleName}}.configure do |c| + c.host = 'petstore.swagger.io' + c.base_path = 'v2' + end + end + + describe '#base_url' do + it 'should have the default value' do + expect(config.base_url).to eq('http://petstore.swagger.io/v2') + end + + it 'should remove trailing slashes' do + [nil, '', '/', '//'].each do |base_path| + config.base_path = base_path + expect(config.base_url).to eq('http://petstore.swagger.io') + end + end + end +end diff --git a/modules/swagger-codegen/src/main/resources/ruby/model_test.mustache b/modules/swagger-codegen/src/main/resources/ruby/model_test.mustache index f5204447975..305a10d6467 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/model_test.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/model_test.mustache @@ -21,17 +21,13 @@ require 'date' describe 'test an instance of {{classname}}' do it 'should create an instact of {{classname}}' do - @instance.should be_a({{moduleName}}::{{classname}}) + expect(@instance).to be_instance_of({{moduleName}}::{{classname}}) end end {{#vars}} describe 'test attribute "{{{name}}}"' do it 'should work' do - # assertion here - # should be_a() - # should be_nil - # should == - # should_not == + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end diff --git a/modules/swagger-codegen/src/main/resources/ruby/rspec.mustache b/modules/swagger-codegen/src/main/resources/ruby/rspec.mustache new file mode 100644 index 00000000000..83e16f80447 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/ruby/rspec.mustache @@ -0,0 +1,2 @@ +--color +--require spec_helper diff --git a/modules/swagger-codegen/src/main/resources/ruby/spec_helper.mustache b/modules/swagger-codegen/src/main/resources/ruby/spec_helper.mustache new file mode 100644 index 00000000000..bc4187c3378 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/ruby/spec_helper.mustache @@ -0,0 +1,99 @@ +# load the gem +require '{{{gemName}}}' + +# The following was generated by the `rspec --init` command. Conventionally, all +# specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`. +# The generated `.rspec` file contains `--require spec_helper` which will cause +# this file to always be loaded, without a need to explicitly require it in any +# files. +# +# Given that it is always loaded, you are encouraged to keep this file as +# light-weight as possible. Requiring heavyweight dependencies from this file +# will add to the boot time of your test suite on EVERY test run, even for an +# individual file that may not need all of that loaded. Instead, consider making +# a separate helper file that requires the additional dependencies and performs +# the additional setup, and require it from the spec files that actually need +# it. +# +# The `.rspec` file also contains a few flags that are not defaults but that +# users commonly want. +# +# See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration +RSpec.configure do |config| + # rspec-expectations config goes here. You can use an alternate + # assertion/expectation library such as wrong or the stdlib/minitest + # assertions if you prefer. + config.expect_with :rspec do |expectations| + # This option will default to `true` in RSpec 4. It makes the `description` + # and `failure_message` of custom matchers include text for helper methods + # defined using `chain`, e.g.: + # be_bigger_than(2).and_smaller_than(4).description + # # => "be bigger than 2 and smaller than 4" + # ...rather than: + # # => "be bigger than 2" + expectations.include_chain_clauses_in_custom_matcher_descriptions = true + end + + # rspec-mocks config goes here. You can use an alternate test double + # library (such as bogus or mocha) by changing the `mock_with` option here. + config.mock_with :rspec do |mocks| + # Prevents you from mocking or stubbing a method that does not exist on + # a real object. This is generally recommended, and will default to + # `true` in RSpec 4. + mocks.verify_partial_doubles = true + end + +# The settings below are suggested to provide a good initial experience +# with RSpec, but feel free to customize to your heart's content. +=begin + # These two settings work together to allow you to limit a spec run + # to individual examples or groups you care about by tagging them with + # `:focus` metadata. When nothing is tagged with `:focus`, all examples + # get run. + config.filter_run :focus + config.run_all_when_everything_filtered = true + + # Allows RSpec to persist some state between runs in order to support + # the `--only-failures` and `--next-failure` CLI options. We recommend + # you configure your source control system to ignore this file. + config.example_status_persistence_file_path = "spec/examples.txt" + + # Limits the available syntax to the non-monkey patched syntax that is + # recommended. For more details, see: + # - http://rspec.info/blog/2012/06/rspecs-new-expectation-syntax/ + # - http://www.teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/ + # - http://rspec.info/blog/2014/05/notable-changes-in-rspec-3/#zero-monkey-patching-mode + config.disable_monkey_patching! + + # This setting enables warnings. It's recommended, but in some cases may + # be too noisy due to issues in dependencies. + config.warnings = true + + # Many RSpec users commonly either run the entire suite or an individual + # file, and it's useful to allow more verbose output when running an + # individual spec file. + if config.files_to_run.one? + # Use the documentation formatter for detailed output, + # unless a formatter has already been configured + # (e.g. via a command-line flag). + config.default_formatter = 'doc' + end + + # Print the 10 slowest examples and example groups at the + # end of the spec run, to help surface which specs are running + # particularly slow. + config.profile_examples = 10 + + # Run specs in random order to surface order dependencies. If you find an + # order dependency and want to debug it, you can fix the order by providing + # the seed, which is printed after each run. + # --seed 1234 + config.order = :random + + # Seed global randomization in this process using the `--seed` CLI option. + # Setting this allows you to use `--seed` to deterministically reproduce + # test failures related to randomization by passing the same `--seed` value + # as the one that triggered the failure. + Kernel.srand config.seed +=end +end 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 25e152a9e34..81163d686aa 100644 --- a/modules/swagger-codegen/src/main/resources/typescript-node/api.mustache +++ b/modules/swagger-codegen/src/main/resources/typescript-node/api.mustache @@ -1,6 +1,10 @@ import request = require('request'); -import promise = require('bluebird'); import http = require('http'); +{{^supportsES6}} +import promise = require('bluebird'); +{{/supportsES6}} + +let defaultBasePath = '{{basePath}}'; // =============================================== // This file is autogenerated - Please do not edit @@ -22,7 +26,7 @@ export class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}{ * {{{description}}} */ {{/description}} - "{{name}}": {{#isEnum}}{{classname}}.{{{datatypeWithEnum}}}{{/isEnum}}{{^isEnum}}{{{datatype}}}{{/isEnum}}; + '{{name}}': {{#isEnum}}{{classname}}.{{{datatypeWithEnum}}}{{/isEnum}}{{^isEnum}}{{{datatype}}}{{/isEnum}}; {{/vars}} } @@ -31,7 +35,7 @@ export namespace {{classname}} { {{#vars}} {{#isEnum}} export enum {{datatypeWithEnum}} { {{#allowableValues}}{{#values}} - {{.}} = '{{.}}'{{^-last}},{{/-last}}{{/values}}{{/allowableValues}} + {{datatypeWithEnum}}_{{.}} = '{{.}}'{{^-last}},{{/-last}}{{/values}}{{/allowableValues}} } {{/isEnum}} {{/vars}} @@ -105,7 +109,7 @@ export enum {{classname}}ApiKeys { } export class {{classname}} { - protected basePath = '{{basePath}}'; + protected basePath = defaultBasePath; protected defaultHeaders : any = {}; protected authentications = { @@ -182,7 +186,7 @@ export class {{classname}} { * {{notes}} {{#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}} }> { + public {{nickname}} ({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) : Promise<{ response: http.{{#supportsES6}}IncomingMessage{{/supportsES6}}{{^supportsES6}}ClientResponse{{/supportsES6}}; {{#returnType}}body: {{{returnType}}}; {{/returnType}}{{^returnType}}body?: any; {{/returnType}} }> { const localVarPath = this.basePath + '{{path}}'{{#pathParams}} .replace('{' + '{{baseName}}' + '}', String({{paramName}})){{/pathParams}}; let queryParameters: any = {}; @@ -216,8 +220,9 @@ export class {{classname}} { {{/isFile}} {{/formParams}} + {{^supportsES6}} let localVarDeferred = promise.defer<{ response: http.ClientResponse; {{#returnType}}body: {{{returnType}}}; {{/returnType}}{{^returnType}}body?: any; {{/returnType}} }>(); - + {{/supportsES6}} let requestOptions: request.Options = { method: '{{httpMethod}}', qs: queryParameters, @@ -227,7 +232,7 @@ export class {{classname}} { {{#bodyParam}} body: {{paramName}}, {{/bodyParam}} - } + }; {{#authMethods}} this.authentications.{{name}}.applyToRequest(requestOptions); @@ -242,7 +247,7 @@ export class {{classname}} { requestOptions.form = formParams; } } - + {{^supportsES6}} request(requestOptions, (error, response, body) => { if (error) { localVarDeferred.reject(error); @@ -254,8 +259,23 @@ export class {{classname}} { } } }); - return localVarDeferred.promise; + {{/supportsES6}} + {{#supportsES6}} + return new Promise<{ response: http.IncomingMessage; {{#returnType}}body: {{{returnType}}}; {{/returnType}}{{^returnType}}body?: any; {{/returnType}} }>((resolve, reject) => { + request(requestOptions, (error, response, body) => { + if (error) { + reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + resolve({ response: response, body: body }); + } else { + reject({ response: response, body: body }); + } + } + }); + }); + {{/supportsES6}} } {{/operation}} } diff --git a/modules/swagger-codegen/src/main/resources/typescript-node/tsconfig.mustache b/modules/swagger-codegen/src/main/resources/typescript-node/tsconfig.mustache index 2dd166566e9..1a3bd00183a 100644 --- a/modules/swagger-codegen/src/main/resources/typescript-node/tsconfig.mustache +++ b/modules/swagger-codegen/src/main/resources/typescript-node/tsconfig.mustache @@ -3,7 +3,7 @@ "module": "commonjs", "noImplicitAny": false, "suppressImplicitAnyIndexErrors": true, - "target": "ES5", + "target": "{{#supportsES6}}ES6{{/supportsES6}}{{^supportsES6}}ES5{{/supportsES6}}", "moduleResolution": "node", "removeComments": true, "sourceMap": true, diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/objc/ObjcModelTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/objc/ObjcModelTest.java index fed94aa04f6..84fb38d1dd3 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/objc/ObjcModelTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/objc/ObjcModelTest.java @@ -27,6 +27,31 @@ import java.util.Map; @SuppressWarnings("static-method") public class ObjcModelTest { + @Test(description = "convert a model with a advanced map property") + public void advancedMapPropertyTest() { + final Model model = new ModelImpl() + .description("a sample model") + .property("translations", new MapProperty() + .additionalProperties(new MapProperty().additionalProperties(new StringProperty()))) + .required("id"); + final DefaultCodegen codegen = new ObjcClientCodegen(); + final CodegenModel cm = codegen.fromModel("sample", model); + + Assert.assertEquals(cm.name, "sample"); + Assert.assertEquals(cm.classname, "SWGSample"); + Assert.assertEquals(cm.description, "a sample model"); + Assert.assertEquals(cm.vars.size(), 1); + + final CodegenProperty property1 = cm.vars.get(0); + Assert.assertEquals(property1.baseName, "translations"); + Assert.assertEquals(property1.datatype, "NSDictionary*>*"); + Assert.assertEquals(property1.name, "translations"); + Assert.assertEquals(property1.baseType, "NSDictionary"); + Assert.assertEquals(property1.containerType, "map"); + Assert.assertNull(property1.required); + Assert.assertTrue(property1.isContainer); + } + @Test(description = "convert a simple java model") public void simpleModelTest() { final Model model = new ModelImpl() @@ -108,7 +133,7 @@ public class ObjcModelTest { final CodegenProperty property2 = cm.vars.get(1); Assert.assertEquals(property2.baseName, "urls"); - Assert.assertEquals(property2.datatype, "NSArray* /* NSString */"); + Assert.assertEquals(property2.datatype, "NSArray*"); Assert.assertEquals(property2.name, "urls"); Assert.assertNull(property2.defaultValue); Assert.assertEquals(property2.baseType, "NSArray"); @@ -136,7 +161,7 @@ public class ObjcModelTest { final CodegenProperty property1 = cm.vars.get(0); Assert.assertEquals(property1.baseName, "translations"); - Assert.assertEquals(property1.datatype, "NSDictionary* /* NSString, NSString */"); + Assert.assertEquals(property1.datatype, "NSDictionary*"); Assert.assertEquals(property1.name, "translations"); Assert.assertEquals(property1.baseType, "NSDictionary"); Assert.assertEquals(property1.containerType, "map"); @@ -145,6 +170,7 @@ public class ObjcModelTest { Assert.assertTrue(property1.isPrimitiveType); } + @Test(description = "convert a model with complex property") public void complexPropertyTest() { final Model model = new ModelImpl() @@ -210,7 +236,7 @@ public class ObjcModelTest { final CodegenProperty property1 = cm.vars.get(0); Assert.assertEquals(property1.baseName, "children"); Assert.assertEquals(property1.complexType, "SWGChildren"); - Assert.assertEquals(property1.datatype, "NSDictionary* /* NSString, SWGChildren */"); + Assert.assertEquals(property1.datatype, "NSDictionary*"); Assert.assertEquals(property1.name, "children"); Assert.assertEquals(property1.baseType, "NSDictionary"); Assert.assertEquals(property1.containerType, "map"); diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/SpringBootServerOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/SpringBootServerOptionsProvider.java new file mode 100644 index 00000000000..af70fc1834a --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/SpringBootServerOptionsProvider.java @@ -0,0 +1,32 @@ +package io.swagger.codegen.options; + +import io.swagger.codegen.CodegenConstants; +import io.swagger.codegen.languages.SpringBootServerCodegen; + +import java.util.HashMap; +import java.util.Map; + +public class SpringBootServerOptionsProvider extends JavaOptionsProvider { + public static final String CONFIG_PACKAGE_VALUE = "configPackage"; + public static final String BASE_PACKAGE_VALUE = "basePackage"; + public static final String LIBRARY_VALUE = "j8-async"; //FIXME hidding value from super class + + @Override + public String getLanguage() { + return "springboot"; + } + + @Override + public Map createOptions() { + Map options = new HashMap(super.createOptions()); + options.put(SpringBootServerCodegen.CONFIG_PACKAGE, CONFIG_PACKAGE_VALUE); + options.put(SpringBootServerCodegen.BASE_PACKAGE, BASE_PACKAGE_VALUE); + options.put(CodegenConstants.LIBRARY, LIBRARY_VALUE); + return options; + } + + @Override + public boolean isServer() { + return true; + } +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/TypeScriptAngular2ClientOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/TypeScriptAngular2ClientOptionsProvider.java index f0bca356d6f..8b8077edfee 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/TypeScriptAngular2ClientOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/TypeScriptAngular2ClientOptionsProvider.java @@ -8,6 +8,7 @@ import io.swagger.codegen.CodegenConstants; import io.swagger.codegen.languages.TypeScriptAngular2ClientCodegen; public class TypeScriptAngular2ClientOptionsProvider implements OptionsProvider { + public static final String SUPPORTS_ES6_VALUE = "false"; public static final String SORT_PARAMS_VALUE = "false"; public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; private static final String MODEL_PROPERTY_NAMING_VALUE = "camelCase"; @@ -26,6 +27,7 @@ public class TypeScriptAngular2ClientOptionsProvider implements OptionsProvider return builder.put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) .put(CodegenConstants.MODEL_PROPERTY_NAMING, MODEL_PROPERTY_NAMING_VALUE) + .put(CodegenConstants.SUPPORTS_ES6, SUPPORTS_ES6_VALUE) .put(TypeScriptAngular2ClientCodegen.NPM_NAME, NMP_NAME) .put(TypeScriptAngular2ClientCodegen.NPM_VERSION, NMP_VERSION) .put(TypeScriptAngular2ClientCodegen.SNAPSHOT, Boolean.FALSE.toString()) diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/TypeScriptAngularClientOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/TypeScriptAngularClientOptionsProvider.java index 3899ed26b29..4fe0820d34e 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/TypeScriptAngularClientOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/TypeScriptAngularClientOptionsProvider.java @@ -7,6 +7,7 @@ import com.google.common.collect.ImmutableMap; import java.util.Map; public class TypeScriptAngularClientOptionsProvider implements OptionsProvider { + public static final String SUPPORTS_ES6_VALUE = "false"; public static final String SORT_PARAMS_VALUE = "false"; public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; public static final String MODEL_PROPERTY_NAMING_VALUE = "camelCase"; @@ -20,6 +21,7 @@ public class TypeScriptAngularClientOptionsProvider implements OptionsProvider { public Map createOptions() { ImmutableMap.Builder builder = new ImmutableMap.Builder(); return builder.put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) + .put(CodegenConstants.SUPPORTS_ES6, SUPPORTS_ES6_VALUE) .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) .put(CodegenConstants.MODEL_PROPERTY_NAMING, MODEL_PROPERTY_NAMING_VALUE) .build(); diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/TypeScriptFetchClientOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/TypeScriptFetchClientOptionsProvider.java new file mode 100644 index 00000000000..cc5be4fe456 --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/TypeScriptFetchClientOptionsProvider.java @@ -0,0 +1,38 @@ +package io.swagger.codegen.options; + +import com.google.common.collect.ImmutableMap; +import io.swagger.codegen.CodegenConstants; +import io.swagger.codegen.languages.TypeScriptFetchClientCodegen; + +import java.util.Map; + +public class TypeScriptFetchClientOptionsProvider implements OptionsProvider { + public static final String SORT_PARAMS_VALUE = "false"; + public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; + public static final Boolean SUPPORTS_ES6_VALUE = false; + public static final String MODEL_PROPERTY_NAMING_VALUE = "camelCase"; + private static final String NMP_NAME = "npmName"; + private static final String NMP_VERSION = "1.0.0"; + + @Override + public String getLanguage() { + return "typescript-fetch"; + } + + @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) + .put(CodegenConstants.MODEL_PROPERTY_NAMING, MODEL_PROPERTY_NAMING_VALUE) + .put(CodegenConstants.SUPPORTS_ES6, String.valueOf(SUPPORTS_ES6_VALUE)) + .put(TypeScriptFetchClientCodegen.NPM_NAME, NMP_NAME) + .put(TypeScriptFetchClientCodegen.NPM_VERSION, NMP_VERSION) + .build(); + } + + @Override + public boolean isServer() { + return false; + } +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/TypeScriptNodeClientOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/TypeScriptNodeClientOptionsProvider.java index bfbd3528e87..61868ef6faf 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/TypeScriptNodeClientOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/TypeScriptNodeClientOptionsProvider.java @@ -9,6 +9,7 @@ import io.swagger.codegen.languages.TypeScriptAngular2ClientCodegen; public class TypeScriptNodeClientOptionsProvider implements OptionsProvider { + public static final String SUPPORTS_ES6_VALUE = "false"; public static final String SORT_PARAMS_VALUE = "false"; public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; public static final String MODEL_PROPERTY_NAMING_VALUE = "camelCase"; @@ -26,6 +27,7 @@ public class TypeScriptNodeClientOptionsProvider implements OptionsProvider { public Map createOptions() { ImmutableMap.Builder builder = new ImmutableMap.Builder(); return builder.put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) + .put(CodegenConstants.SUPPORTS_ES6, SUPPORTS_ES6_VALUE) .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) .put(CodegenConstants.MODEL_PROPERTY_NAMING, MODEL_PROPERTY_NAMING_VALUE) .put(TypeScriptAngular2ClientCodegen.NPM_NAME, NMP_NAME) diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/springboot/SpringBootServerOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/springboot/SpringBootServerOptionsTest.java new file mode 100644 index 00000000000..a7ecdd9d974 --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/springboot/SpringBootServerOptionsTest.java @@ -0,0 +1,60 @@ +package io.swagger.codegen.springBoot; + +import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.java.JavaClientOptionsTest; +import io.swagger.codegen.languages.SpringBootServerCodegen; +import io.swagger.codegen.options.SpringBootServerOptionsProvider; + +import mockit.Expectations; +import mockit.Tested; + +public class SpringBootServerOptionsTest extends JavaClientOptionsTest { + + @Tested + private SpringBootServerCodegen clientCodegen; + + public SpringBootServerOptionsTest() { + super(new SpringBootServerOptionsProvider()); + } + + @Override + protected CodegenConfig getCodegenConfig() { + return clientCodegen; + } + + @SuppressWarnings("unused") + @Override + protected void setExpectations() { + new Expectations(clientCodegen) {{ + clientCodegen.setModelPackage(SpringBootServerOptionsProvider.MODEL_PACKAGE_VALUE); + times = 1; + clientCodegen.setApiPackage(SpringBootServerOptionsProvider.API_PACKAGE_VALUE); + times = 1; + clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(SpringBootServerOptionsProvider.SORT_PARAMS_VALUE)); + times = 1; + clientCodegen.setInvokerPackage(SpringBootServerOptionsProvider.INVOKER_PACKAGE_VALUE); + times = 1; + clientCodegen.setGroupId(SpringBootServerOptionsProvider.GROUP_ID_VALUE); + times = 1; + clientCodegen.setArtifactId(SpringBootServerOptionsProvider.ARTIFACT_ID_VALUE); + times = 1; + clientCodegen.setArtifactVersion(SpringBootServerOptionsProvider.ARTIFACT_VERSION_VALUE); + times = 1; + clientCodegen.setSourceFolder(SpringBootServerOptionsProvider.SOURCE_FOLDER_VALUE); + times = 1; + clientCodegen.setLocalVariablePrefix(SpringBootServerOptionsProvider.LOCAL_PREFIX_VALUE); + times = 1; + clientCodegen.setSerializableModel(Boolean.valueOf(SpringBootServerOptionsProvider.SERIALIZABLE_MODEL_VALUE)); + times = 1; + clientCodegen.setLibrary(SpringBootServerOptionsProvider.LIBRARY_VALUE); + times = 1; + clientCodegen.setFullJavaUtil(Boolean.valueOf(SpringBootServerOptionsProvider.FULL_JAVA_UTIL_VALUE)); + times = 1; + clientCodegen.setConfigPackage(SpringBootServerOptionsProvider.CONFIG_PACKAGE_VALUE); + times = 1; + clientCodegen.setBasePackage(SpringBootServerOptionsProvider.BASE_PACKAGE_VALUE); + times = 1; + + }}; + } +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/statichtml/StaticHtmlTagsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/statichtml/StaticHtmlTagsTest.java index ad84f8ca0c7..0ba3d9e2fee 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/statichtml/StaticHtmlTagsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/statichtml/StaticHtmlTagsTest.java @@ -12,7 +12,7 @@ import java.util.Set; import javax.annotation.Nullable; -import org.apache.commons.lang.StringUtils; +import org.apache.commons.lang3.StringUtils; import org.junit.rules.TemporaryFolder; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescriptangular/TypeScriptAngularClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescriptangular/TypeScriptAngularClientOptionsTest.java index 17d9c1ed205..70cfb3d250d 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescriptangular/TypeScriptAngularClientOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescriptangular/TypeScriptAngularClientOptionsTest.java @@ -30,6 +30,8 @@ public class TypeScriptAngularClientOptionsTest extends AbstractOptionsTest { times = 1; clientCodegen.setModelPropertyNaming(TypeScriptAngularClientOptionsProvider.MODEL_PROPERTY_NAMING_VALUE); times = 1; + clientCodegen.setSupportsES6(Boolean.valueOf(TypeScriptAngularClientOptionsProvider.SUPPORTS_ES6_VALUE)); + times = 1; }}; } } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescriptangular2/TypeScriptAngular2ClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescriptangular2/TypeScriptAngular2ClientOptionsTest.java index 4c56a7dfab2..74e575c4496 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescriptangular2/TypeScriptAngular2ClientOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescriptangular2/TypeScriptAngular2ClientOptionsTest.java @@ -30,6 +30,8 @@ public class TypeScriptAngular2ClientOptionsTest extends AbstractOptionsTest { times = 1; clientCodegen.setModelPropertyNaming(TypeScriptAngularClientOptionsProvider.MODEL_PROPERTY_NAMING_VALUE); times = 1; + clientCodegen.setSupportsES6(Boolean.valueOf(TypeScriptAngularClientOptionsProvider.SUPPORTS_ES6_VALUE)); + times = 1; }}; } } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescriptfetch/TypeScriptFetchClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescriptfetch/TypeScriptFetchClientOptionsTest.java new file mode 100644 index 00000000000..09f16799ad9 --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescriptfetch/TypeScriptFetchClientOptionsTest.java @@ -0,0 +1,36 @@ +package io.swagger.codegen.typescriptfetch; + +import io.swagger.codegen.AbstractOptionsTest; +import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.languages.TypeScriptFetchClientCodegen; +import io.swagger.codegen.options.TypeScriptFetchClientOptionsProvider; +import mockit.Expectations; +import mockit.Tested; + +public class TypeScriptFetchClientOptionsTest extends AbstractOptionsTest { + + @Tested + private TypeScriptFetchClientCodegen clientCodegen; + + public TypeScriptFetchClientOptionsTest() { + super(new TypeScriptFetchClientOptionsProvider()); + } + + @Override + protected CodegenConfig getCodegenConfig() { + return clientCodegen; + } + + @SuppressWarnings("unused") + @Override + protected void setExpectations() { + new Expectations(clientCodegen) {{ + clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(TypeScriptFetchClientOptionsProvider.SORT_PARAMS_VALUE)); + times = 1; + clientCodegen.setModelPropertyNaming(TypeScriptFetchClientOptionsProvider.MODEL_PROPERTY_NAMING_VALUE); + times = 1; + clientCodegen.setSupportsES6(TypeScriptFetchClientOptionsProvider.SUPPORTS_ES6_VALUE); + times = 1; + }}; + } +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescriptfetch/TypeScriptFetchModelTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescriptfetch/TypeScriptFetchModelTest.java new file mode 100644 index 00000000000..d2173fdb710 --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescriptfetch/TypeScriptFetchModelTest.java @@ -0,0 +1,177 @@ +package io.swagger.codegen.typescriptfetch; + +import com.google.common.collect.Sets; +import io.swagger.codegen.CodegenModel; +import io.swagger.codegen.CodegenProperty; +import io.swagger.codegen.DefaultCodegen; +import io.swagger.codegen.languages.TypeScriptFetchClientCodegen; +import io.swagger.models.ArrayModel; +import io.swagger.models.Model; +import io.swagger.models.ModelImpl; +import io.swagger.models.properties.*; +import org.testng.Assert; +import org.testng.annotations.Test; + +@SuppressWarnings("static-method") +public class TypeScriptFetchModelTest { + + @Test(description = "convert a simple TypeScript Angular model") + public void simpleModelTest() { + final Model model = new ModelImpl() + .description("a sample model") + .property("id", new LongProperty()) + .property("name", new StringProperty()) + .property("createdAt", new DateTimeProperty()) + .required("id") + .required("name"); + final DefaultCodegen codegen = new TypeScriptFetchClientCodegen(); + final CodegenModel cm = codegen.fromModel("sample", model); + + Assert.assertEquals(cm.name, "sample"); + Assert.assertEquals(cm.classname, "Sample"); + Assert.assertEquals(cm.description, "a sample model"); + Assert.assertEquals(cm.vars.size(), 3); + + final CodegenProperty property1 = cm.vars.get(0); + Assert.assertEquals(property1.baseName, "id"); + Assert.assertEquals(property1.datatype, "number"); + Assert.assertEquals(property1.name, "id"); + Assert.assertEquals(property1.defaultValue, "null"); + Assert.assertEquals(property1.baseType, "number"); + Assert.assertTrue(property1.hasMore); + Assert.assertTrue(property1.required); + Assert.assertTrue(property1.isNotContainer); + + final CodegenProperty property2 = cm.vars.get(1); + Assert.assertEquals(property2.baseName, "name"); + Assert.assertEquals(property2.datatype, "string"); + Assert.assertEquals(property2.name, "name"); + Assert.assertEquals(property2.defaultValue, "null"); + Assert.assertEquals(property2.baseType, "string"); + Assert.assertTrue(property2.hasMore); + Assert.assertTrue(property2.required); + Assert.assertTrue(property2.isNotContainer); + + final CodegenProperty property3 = cm.vars.get(2); + Assert.assertEquals(property3.baseName, "createdAt"); + Assert.assertEquals(property3.complexType, null); + Assert.assertEquals(property3.datatype, "Date"); + Assert.assertEquals(property3.name, "createdAt"); + Assert.assertEquals(property3.defaultValue, "null"); + Assert.assertNull(property3.hasMore); + Assert.assertNull(property3.required); + Assert.assertTrue(property3.isNotContainer); + } + + @Test(description = "convert a model with list property") + public void listPropertyTest() { + final Model model = new ModelImpl() + .description("a sample model") + .property("id", new LongProperty()) + .property("urls", new ArrayProperty().items(new StringProperty())) + .required("id"); + final DefaultCodegen codegen = new TypeScriptFetchClientCodegen(); + final CodegenModel cm = codegen.fromModel("sample", model); + + Assert.assertEquals(cm.name, "sample"); + Assert.assertEquals(cm.classname, "Sample"); + Assert.assertEquals(cm.description, "a sample model"); + Assert.assertEquals(cm.vars.size(), 2); + + final CodegenProperty property1 = cm.vars.get(0); + Assert.assertEquals(property1.baseName, "id"); + Assert.assertEquals(property1.datatype, "number"); + Assert.assertEquals(property1.name, "id"); + Assert.assertEquals(property1.defaultValue, "null"); + Assert.assertEquals(property1.baseType, "number"); + Assert.assertTrue(property1.hasMore); + Assert.assertTrue(property1.required); + Assert.assertTrue(property1.isNotContainer); + + final CodegenProperty property2 = cm.vars.get(1); + Assert.assertEquals(property2.baseName, "urls"); + Assert.assertEquals(property2.datatype, "Array"); + Assert.assertEquals(property2.name, "urls"); + Assert.assertEquals(property2.baseType, "Array"); + Assert.assertNull(property2.hasMore); + Assert.assertNull(property2.required); + Assert.assertTrue(property2.isContainer); + } + + @Test(description = "convert a model with complex property") + public void complexPropertyTest() { + final Model model = new ModelImpl() + .description("a sample model") + .property("children", new RefProperty("#/definitions/Children")); + final DefaultCodegen codegen = new TypeScriptFetchClientCodegen(); + final CodegenModel cm = codegen.fromModel("sample", model); + + Assert.assertEquals(cm.name, "sample"); + Assert.assertEquals(cm.classname, "Sample"); + Assert.assertEquals(cm.description, "a sample model"); + Assert.assertEquals(cm.vars.size(), 1); + + final CodegenProperty property1 = cm.vars.get(0); + Assert.assertEquals(property1.baseName, "children"); + Assert.assertEquals(property1.datatype, "Children"); + Assert.assertEquals(property1.name, "children"); + Assert.assertEquals(property1.defaultValue, "null"); + Assert.assertEquals(property1.baseType, "Children"); + Assert.assertNull(property1.required); + Assert.assertTrue(property1.isNotContainer); + } + + @Test(description = "convert a model with complex list property") + public void complexListPropertyTest() { + final Model model = new ModelImpl() + .description("a sample model") + .property("children", new ArrayProperty() + .items(new RefProperty("#/definitions/Children"))); + final DefaultCodegen codegen = new TypeScriptFetchClientCodegen(); + final CodegenModel cm = codegen.fromModel("sample", model); + + Assert.assertEquals(cm.name, "sample"); + Assert.assertEquals(cm.classname, "Sample"); + Assert.assertEquals(cm.description, "a sample model"); + Assert.assertEquals(cm.vars.size(), 1); + + final CodegenProperty property1 = cm.vars.get(0); + Assert.assertEquals(property1.baseName, "children"); + Assert.assertEquals(property1.complexType, "Children"); + Assert.assertEquals(property1.datatype, "Array"); + Assert.assertEquals(property1.name, "children"); + Assert.assertEquals(property1.baseType, "Array"); + Assert.assertNull(property1.required); + Assert.assertTrue(property1.isContainer); + } + + @Test(description = "convert an array model") + public void arrayModelTest() { + final Model model = new ArrayModel() + .description("an array model") + .items(new RefProperty("#/definitions/Children")); + final DefaultCodegen codegen = new TypeScriptFetchClientCodegen(); + final CodegenModel cm = codegen.fromModel("sample", model); + + Assert.assertEquals(cm.name, "sample"); + Assert.assertEquals(cm.classname, "Sample"); + Assert.assertEquals(cm.description, "an array model"); + Assert.assertEquals(cm.vars.size(), 0); + } + + @Test(description = "convert a map model") + public void mapModelTest() { + final Model model = new ModelImpl() + .description("a map model") + .additionalProperties(new RefProperty("#/definitions/Children")); + final DefaultCodegen codegen = new TypeScriptFetchClientCodegen(); + final CodegenModel cm = codegen.fromModel("sample", model); + + Assert.assertEquals(cm.name, "sample"); + Assert.assertEquals(cm.classname, "Sample"); + Assert.assertEquals(cm.description, "a map model"); + Assert.assertEquals(cm.vars.size(), 0); + Assert.assertEquals(cm.imports.size(), 1); + Assert.assertEquals(Sets.intersection(cm.imports, Sets.newHashSet("Children")).size(), 1); + } +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescriptnode/TypeScriptNodeClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescriptnode/TypeScriptNodeClientOptionsTest.java index 67b55de138a..72b55b0b39d 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescriptnode/TypeScriptNodeClientOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescriptnode/TypeScriptNodeClientOptionsTest.java @@ -30,6 +30,8 @@ public class TypeScriptNodeClientOptionsTest extends AbstractOptionsTest { times = 1; clientCodegen.setModelPropertyNaming(TypeScriptNodeClientOptionsProvider.MODEL_PROPERTY_NAMING_VALUE); times = 1; + clientCodegen.setSupportsES6(Boolean.valueOf(TypeScriptNodeClientOptionsProvider.SUPPORTS_ES6_VALUE)); + times = 1; }}; } } diff --git a/modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml b/modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml index cf95a2612e2..b9fa750d38a 100644 --- a/modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml +++ b/modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml @@ -1,6 +1,6 @@ swagger: '2.0' info: - description: 'This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose.' + description: 'This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: " \ ' version: 1.0.0 title: Swagger Petstore termsOfService: 'http://swagger.io/terms/' @@ -564,8 +564,16 @@ paths: post: tags: - fake - summary: Fake endpoint for testing various parameters - description: Fake endpoint for testing various parameters + summary: | + Fake endpoint for testing various parameters + 假端點 + 偽のエンドポイント + 가짜 엔드 포인트 + description: | + Fake endpoint for testing various parameters + 假端點 + 偽のエンドポイント + 가짜 엔드 포인트 operationId: testEndpointParameters produces: - application/xml @@ -810,6 +818,9 @@ definitions: format: int32 property: type: string + 123Number: + type: integer + readOnly: true xml: name: Name 200_response: @@ -842,6 +853,13 @@ definitions: properties: className: type: string + color: + type: string + default: 'red' + AnimalFarm: + type: array + items: + $ref: '#/definitions/Animal' format_test: type: object required: diff --git a/pom.xml b/pom.xml index 9ac1890ea91..1b5c3d7580f 100644 --- a/pom.xml +++ b/pom.xml @@ -567,7 +567,7 @@ 1.2 4.8.1 1.0.0 - 2.4 + 3.4 1.7.12 3.2.1 1.12 diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/.gitignore b/samples/client/petstore/csharp/SwaggerClient/.gitignore similarity index 100% rename from samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/.gitignore rename to samples/client/petstore/csharp/SwaggerClient/.gitignore diff --git a/samples/client/petstore/csharp/SwaggerClient/IO.Swagger.sln b/samples/client/petstore/csharp/SwaggerClient/IO.Swagger.sln new file mode 100644 index 00000000000..3c26ad6be49 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClient/IO.Swagger.sln @@ -0,0 +1,27 @@ +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 2012 +VisualStudioVersion = 12.0.0.0 +MinimumVisualStudioVersion = 10.0.0.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IO.Swagger", "src\IO.Swagger\IO.Swagger.csproj", "{C075FB79-0DDE-43E3-9FA5-E239EE9B9B5A}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IO.Swagger.Test", "src\IO.Swagger.Test\IO.Swagger.Test.csproj", "{19F1DEBC-DE5E-4517-8062-F000CD499087}" +EndProject +Global +GlobalSection(SolutionConfigurationPlatforms) = preSolution +Debug|Any CPU = Debug|Any CPU +Release|Any CPU = Release|Any CPU +EndGlobalSection +GlobalSection(ProjectConfigurationPlatforms) = postSolution +{C075FB79-0DDE-43E3-9FA5-E239EE9B9B5A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{C075FB79-0DDE-43E3-9FA5-E239EE9B9B5A}.Debug|Any CPU.Build.0 = Debug|Any CPU +{C075FB79-0DDE-43E3-9FA5-E239EE9B9B5A}.Release|Any CPU.ActiveCfg = Release|Any CPU +{C075FB79-0DDE-43E3-9FA5-E239EE9B9B5A}.Release|Any CPU.Build.0 = Release|Any CPU +{19F1DEBC-DE5E-4517-8062-F000CD499087}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{19F1DEBC-DE5E-4517-8062-F000CD499087}.Debug|Any CPU.Build.0 = Debug|Any CPU +{19F1DEBC-DE5E-4517-8062-F000CD499087}.Release|Any CPU.ActiveCfg = Release|Any CPU +{19F1DEBC-DE5E-4517-8062-F000CD499087}.Release|Any CPU.Build.0 = Release|Any CPU +EndGlobalSection +GlobalSection(SolutionProperties) = preSolution +HideSolutionNode = FALSE +EndGlobalSection +EndGlobal \ No newline at end of file diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/README.md b/samples/client/petstore/csharp/SwaggerClient/README.md similarity index 84% rename from samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/README.md rename to samples/client/petstore/csharp/SwaggerClient/README.md index aceb18e3396..c546b834c18 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/README.md +++ b/samples/client/petstore/csharp/SwaggerClient/README.md @@ -6,7 +6,7 @@ This C# SDK is automatically generated by the [Swagger Codegen](https://github.c - API version: 1.0.0 - SDK version: 1.0.0 -- Build date: 2016-04-27T22:04:12.906+08:00 +- Build date: 2016-05-10T17:39:13.582+08:00 - Build package: class io.swagger.codegen.languages.CSharpClientCodegen ## Frameworks supported @@ -27,14 +27,14 @@ NOTE: RestSharp versions greater than 105.1.0 have a bug which causes file uploa ## Installation Run the following command to generate the DLL -- [Mac/Linux] `/bin/sh compile-mono.sh` -- [Windows] `compile.bat` +- [Mac/Linux] `/bin/sh build.sh` +- [Windows] `build.bat` Then include the DLL (under the `bin` folder) in the C# project, and use the namespaces: ```csharp using IO.Swagger.Api; using IO.Swagger.Client; -using IO.Swagger.Model; +using Model; ``` ## Getting Started @@ -44,7 +44,7 @@ using System; using System.Diagnostics; using IO.Swagger.Api; using IO.Swagger.Client; -using IO.Swagger.Model; +using Model; namespace Example { @@ -54,7 +54,7 @@ namespace Example { var apiInstance = new FakeApi(); - var number = number_example; // string | None + var number = 3.4; // double? | None var _double = 1.2; // double? | None var _string = _string_example; // string | None var _byte = B; // byte[] | None @@ -69,7 +69,7 @@ namespace Example try { - // Fake endpoint for testing various parameters + // Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 apiInstance.TestEndpointParameters(number, _double, _string, _byte, integer, int32, int64, _float, binary, date, dateTime, password); } catch (Exception e) @@ -87,7 +87,7 @@ All URIs are relative to *http://petstore.swagger.io/v2* Class | Method | HTTP request | Description ------------ | ------------- | ------------- | ------------- -*FakeApi* | [**TestEndpointParameters**](docs/FakeApi.md#testendpointparameters) | **POST** /fake | Fake endpoint for testing various parameters +*FakeApi* | [**TestEndpointParameters**](docs/FakeApi.md#testendpointparameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 *PetApi* | [**AddPet**](docs/PetApi.md#addpet) | **POST** /pet | Add a new pet to the store *PetApi* | [**DeletePet**](docs/PetApi.md#deletepet) | **DELETE** /pet/{petId} | Deletes a pet *PetApi* | [**FindPetsByStatus**](docs/PetApi.md#findpetsbystatus) | **GET** /pet/findByStatus | Finds Pets by status @@ -112,22 +112,23 @@ Class | Method | HTTP request | Description ## Documentation for Models - - [IO.Swagger.Model.Animal](docs/Animal.md) - - [IO.Swagger.Model.ApiResponse](docs/ApiResponse.md) - - [IO.Swagger.Model.Cat](docs/Cat.md) - - [IO.Swagger.Model.Category](docs/Category.md) - - [IO.Swagger.Model.Dog](docs/Dog.md) - - [IO.Swagger.Model.EnumClass](docs/EnumClass.md) - - [IO.Swagger.Model.EnumTest](docs/EnumTest.md) - - [IO.Swagger.Model.FormatTest](docs/FormatTest.md) - - [IO.Swagger.Model.Model200Response](docs/Model200Response.md) - - [IO.Swagger.Model.ModelReturn](docs/ModelReturn.md) - - [IO.Swagger.Model.Name](docs/Name.md) - - [IO.Swagger.Model.Order](docs/Order.md) - - [IO.Swagger.Model.Pet](docs/Pet.md) - - [IO.Swagger.Model.SpecialModelName](docs/SpecialModelName.md) - - [IO.Swagger.Model.Tag](docs/Tag.md) - - [IO.Swagger.Model.User](docs/User.md) + - [Model.Animal](docs/Animal.md) + - [Model.AnimalFarm](docs/AnimalFarm.md) + - [Model.ApiResponse](docs/ApiResponse.md) + - [Model.Cat](docs/Cat.md) + - [Model.Category](docs/Category.md) + - [Model.Dog](docs/Dog.md) + - [Model.EnumClass](docs/EnumClass.md) + - [Model.EnumTest](docs/EnumTest.md) + - [Model.FormatTest](docs/FormatTest.md) + - [Model.Model200Response](docs/Model200Response.md) + - [Model.ModelReturn](docs/ModelReturn.md) + - [Model.Name](docs/Name.md) + - [Model.Order](docs/Order.md) + - [Model.Pet](docs/Pet.md) + - [Model.SpecialModelName](docs/SpecialModelName.md) + - [Model.Tag](docs/Tag.md) + - [Model.User](docs/User.md) ## Documentation for Authorization diff --git a/samples/client/petstore/csharp/SwaggerClient/build.bat b/samples/client/petstore/csharp/SwaggerClient/build.bat new file mode 100644 index 00000000000..80a13e48231 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClient/build.bat @@ -0,0 +1,14 @@ +@echo off + +SET CSCPATH=%SYSTEMROOT%\Microsoft.NET\Framework\v4.0.30319 + + +if not exist ".\nuget.exe" powershell -Command "(new-object System.Net.WebClient).DownloadFile('https://nuget.org/nuget.exe', '.\nuget.exe')" +.\nuget.exe install src\IO.Swagger\packages.config -o packages + +if not exist ".\bin" mkdir bin + +copy packages\Newtonsoft.Json.8.0.2\lib\net45\Newtonsoft.Json.dll bin\Newtonsoft.Json.dll +copy packages\RestSharp.105.1.0\lib\net45\RestSharp.dll bin\RestSharp.dll + +%CSCPATH%\csc /reference:bin\Newtonsoft.Json.dll;bin\RestSharp.dll /target:library /out:bin\IO.Swagger.dll /recurse:src\IO.Swagger\*.cs /doc:bin\IO.Swagger.xml diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/compile-mono.sh b/samples/client/petstore/csharp/SwaggerClient/build.sh old mode 100755 new mode 100644 similarity index 56% rename from samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/compile-mono.sh rename to samples/client/petstore/csharp/SwaggerClient/build.sh index d768c892f31..159673fd60c --- a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/compile-mono.sh +++ b/samples/client/petstore/csharp/SwaggerClient/build.sh @@ -4,17 +4,17 @@ netfx=${frameworkVersion#net} wget -nc https://nuget.org/nuget.exe; mozroots --import --sync -mono nuget.exe install vendor/packages.config -o vendor; +mono nuget.exe install src/IO.Swagger/packages.config -o packages; mkdir -p bin; -cp vendor/Newtonsoft.Json.8.0.2/lib/net45/Newtonsoft.Json.dll bin/Newtonsoft.Json.dll; -cp vendor/RestSharp.105.1.0/lib/net45/RestSharp.dll bin/RestSharp.dll; +cp packages/Newtonsoft.Json.8.0.2/lib/net45/Newtonsoft.Json.dll bin/Newtonsoft.Json.dll; +cp packages/RestSharp.105.1.0/lib/net45/RestSharp.dll bin/RestSharp.dll; mcs -sdk:${netfx} -r:bin/Newtonsoft.Json.dll,\ bin/RestSharp.dll,\ System.Runtime.Serialization.dll \ -target:library \ -out:bin/IO.Swagger.dll \ --recurse:'src/*.cs' \ +-recurse:'src/IO.Swagger/*.cs' \ -doc:bin/IO.Swagger.xml \ -platform:anycpu diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/docs/Animal.md b/samples/client/petstore/csharp/SwaggerClient/docs/Animal.md similarity index 85% rename from samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/docs/Animal.md rename to samples/client/petstore/csharp/SwaggerClient/docs/Animal.md index 46eb96c05f4..f461176159c 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/docs/Animal.md +++ b/samples/client/petstore/csharp/SwaggerClient/docs/Animal.md @@ -4,6 +4,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **ClassName** | **string** | | +**Color** | **string** | | [optional] [default to "red"] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore/csharp/SwaggerClient/docs/AnimalFarm.md b/samples/client/petstore/csharp/SwaggerClient/docs/AnimalFarm.md new file mode 100644 index 00000000000..4d1cccb0cef --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClient/docs/AnimalFarm.md @@ -0,0 +1,8 @@ +# IO.Swagger.Model.AnimalFarm +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/docs/ApiResponse.md b/samples/client/petstore/csharp/SwaggerClient/docs/ApiResponse.md similarity index 100% rename from samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/docs/ApiResponse.md rename to samples/client/petstore/csharp/SwaggerClient/docs/ApiResponse.md diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/docs/Cat.md b/samples/client/petstore/csharp/SwaggerClient/docs/Cat.md similarity index 86% rename from samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/docs/Cat.md rename to samples/client/petstore/csharp/SwaggerClient/docs/Cat.md index e0034d4ab5d..a88425f4307 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/docs/Cat.md +++ b/samples/client/petstore/csharp/SwaggerClient/docs/Cat.md @@ -4,6 +4,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **ClassName** | **string** | | +**Color** | **string** | | [optional] [default to "red"] **Declawed** | **bool?** | | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/docs/Category.md b/samples/client/petstore/csharp/SwaggerClient/docs/Category.md similarity index 100% rename from samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/docs/Category.md rename to samples/client/petstore/csharp/SwaggerClient/docs/Category.md diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/docs/Dog.md b/samples/client/petstore/csharp/SwaggerClient/docs/Dog.md similarity index 86% rename from samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/docs/Dog.md rename to samples/client/petstore/csharp/SwaggerClient/docs/Dog.md index 0acf4182d94..c3ee6d927b4 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/docs/Dog.md +++ b/samples/client/petstore/csharp/SwaggerClient/docs/Dog.md @@ -4,6 +4,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **ClassName** | **string** | | +**Color** | **string** | | [optional] [default to "red"] **Breed** | **string** | | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore/csharp/SwaggerClient/docs/EnumClass.md b/samples/client/petstore/csharp/SwaggerClient/docs/EnumClass.md new file mode 100644 index 00000000000..d936aad6f0b --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClient/docs/EnumClass.md @@ -0,0 +1,8 @@ +# IO.Swagger.Model.EnumClass +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp/SwaggerClient/docs/EnumTest.md b/samples/client/petstore/csharp/SwaggerClient/docs/EnumTest.md new file mode 100644 index 00000000000..f0f300021b5 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClient/docs/EnumTest.md @@ -0,0 +1,11 @@ +# IO.Swagger.Model.EnumTest +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**EnumString** | **string** | | [optional] +**EnumInteger** | **int?** | | [optional] +**EnumNumber** | **double?** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp/SwaggerClient/docs/FakeApi.md b/samples/client/petstore/csharp/SwaggerClient/docs/FakeApi.md new file mode 100644 index 00000000000..65b04a12ccb --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClient/docs/FakeApi.md @@ -0,0 +1,91 @@ +# IO.Swagger.Api.FakeApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**TestEndpointParameters**](FakeApi.md#testendpointparameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + + +# **TestEndpointParameters** +> void TestEndpointParameters (double? number, double? _double, string _string, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, byte[] binary = null, DateTime? date = null, DateTime? dateTime = null, string password = null) + +Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + +Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + +### Example +```csharp +using System; +using System.Diagnostics; +using IO.Swagger.Api; +using IO.Swagger.Client; +using IO.Swagger.Model; + +namespace Example +{ + public class TestEndpointParametersExample + { + public void main() + { + + var apiInstance = new FakeApi(); + var number = 3.4; // double? | None + var _double = 1.2; // double? | None + var _string = _string_example; // string | None + var _byte = B; // byte[] | None + var integer = 56; // int? | None (optional) + var int32 = 56; // int? | None (optional) + var int64 = 789; // long? | None (optional) + var _float = 3.4; // float? | None (optional) + var binary = B; // byte[] | None (optional) + var date = 2013-10-20; // DateTime? | None (optional) + var dateTime = 2013-10-20T19:20:30+01:00; // DateTime? | None (optional) + var password = password_example; // string | None (optional) + + try + { + // Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + apiInstance.TestEndpointParameters(number, _double, _string, _byte, integer, int32, int64, _float, binary, date, dateTime, password); + } + catch (Exception e) + { + Debug.Print("Exception when calling FakeApi.TestEndpointParameters: " + e.Message ); + } + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **number** | **double?**| None | + **_double** | **double?**| None | + **_string** | **string**| None | + **_byte** | **byte[]**| None | + **integer** | **int?**| None | [optional] + **int32** | **int?**| None | [optional] + **int64** | **long?**| None | [optional] + **_float** | **float?**| None | [optional] + **binary** | **byte[]**| None | [optional] + **date** | **DateTime?**| None | [optional] + **dateTime** | **DateTime?**| None | [optional] + **password** | **string**| None | [optional] + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/docs/FormatTest.md b/samples/client/petstore/csharp/SwaggerClient/docs/FormatTest.md similarity index 95% rename from samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/docs/FormatTest.md rename to samples/client/petstore/csharp/SwaggerClient/docs/FormatTest.md index c5dc3cf53f3..7ddfad04d05 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/docs/FormatTest.md +++ b/samples/client/petstore/csharp/SwaggerClient/docs/FormatTest.md @@ -14,6 +14,7 @@ Name | Type | Description | Notes **Binary** | **byte[]** | | [optional] **Date** | **DateTime?** | | **DateTime** | **DateTime?** | | [optional] +**Uuid** | **Guid?** | | [optional] **Password** | **string** | | [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/docs/Model200Response.md b/samples/client/petstore/csharp/SwaggerClient/docs/Model200Response.md similarity index 100% rename from samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/docs/Model200Response.md rename to samples/client/petstore/csharp/SwaggerClient/docs/Model200Response.md diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/docs/ModelReturn.md b/samples/client/petstore/csharp/SwaggerClient/docs/ModelReturn.md similarity index 100% rename from samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/docs/ModelReturn.md rename to samples/client/petstore/csharp/SwaggerClient/docs/ModelReturn.md diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/docs/Name.md b/samples/client/petstore/csharp/SwaggerClient/docs/Name.md similarity index 90% rename from samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/docs/Name.md rename to samples/client/petstore/csharp/SwaggerClient/docs/Name.md index 6cb961b6fcf..678132c8e4e 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/docs/Name.md +++ b/samples/client/petstore/csharp/SwaggerClient/docs/Name.md @@ -6,6 +6,7 @@ Name | Type | Description | Notes **_Name** | **int?** | | **SnakeCase** | **int?** | | [optional] **Property** | **string** | | [optional] +**_123Number** | **int?** | | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/docs/Order.md b/samples/client/petstore/csharp/SwaggerClient/docs/Order.md similarity index 100% rename from samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/docs/Order.md rename to samples/client/petstore/csharp/SwaggerClient/docs/Order.md diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/docs/Pet.md b/samples/client/petstore/csharp/SwaggerClient/docs/Pet.md similarity index 100% rename from samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/docs/Pet.md rename to samples/client/petstore/csharp/SwaggerClient/docs/Pet.md diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/docs/PetApi.md b/samples/client/petstore/csharp/SwaggerClient/docs/PetApi.md similarity index 99% rename from samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/docs/PetApi.md rename to samples/client/petstore/csharp/SwaggerClient/docs/PetApi.md index 6d05169a4cc..837859e4b7e 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/docs/PetApi.md +++ b/samples/client/petstore/csharp/SwaggerClient/docs/PetApi.md @@ -294,8 +294,8 @@ namespace Example // Configure API key authorization: api_key Configuration.Default.ApiKey.Add('api_key', 'YOUR_API_KEY'); - // Uncomment below to setup prefix (e.g. BEARER) for API key, if needed - // Configuration.Default.ApiKeyPrefix.Add('api_key', 'BEARER'); + // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed + // Configuration.Default.ApiKeyPrefix.Add('api_key', 'Bearer'); var apiInstance = new PetApi(); var petId = 789; // long? | ID of pet to return diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/docs/SpecialModelName.md b/samples/client/petstore/csharp/SwaggerClient/docs/SpecialModelName.md similarity index 100% rename from samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/docs/SpecialModelName.md rename to samples/client/petstore/csharp/SwaggerClient/docs/SpecialModelName.md diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/docs/StoreApi.md b/samples/client/petstore/csharp/SwaggerClient/docs/StoreApi.md similarity index 98% rename from samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/docs/StoreApi.md rename to samples/client/petstore/csharp/SwaggerClient/docs/StoreApi.md index f558166ecb0..a5d5ff0454d 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/docs/StoreApi.md +++ b/samples/client/petstore/csharp/SwaggerClient/docs/StoreApi.md @@ -94,8 +94,8 @@ namespace Example // Configure API key authorization: api_key Configuration.Default.ApiKey.Add('api_key', 'YOUR_API_KEY'); - // Uncomment below to setup prefix (e.g. BEARER) for API key, if needed - // Configuration.Default.ApiKeyPrefix.Add('api_key', 'BEARER'); + // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed + // Configuration.Default.ApiKeyPrefix.Add('api_key', 'Bearer'); var apiInstance = new StoreApi(); diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/docs/Tag.md b/samples/client/petstore/csharp/SwaggerClient/docs/Tag.md similarity index 100% rename from samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/docs/Tag.md rename to samples/client/petstore/csharp/SwaggerClient/docs/Tag.md diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/docs/User.md b/samples/client/petstore/csharp/SwaggerClient/docs/User.md similarity index 100% rename from samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/docs/User.md rename to samples/client/petstore/csharp/SwaggerClient/docs/User.md diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/docs/UserApi.md b/samples/client/petstore/csharp/SwaggerClient/docs/UserApi.md similarity index 100% rename from samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/docs/UserApi.md rename to samples/client/petstore/csharp/SwaggerClient/docs/UserApi.md diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/git_push.sh b/samples/client/petstore/csharp/SwaggerClient/git_push.sh similarity index 100% rename from samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/git_push.sh rename to samples/client/petstore/csharp/SwaggerClient/git_push.sh diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Api/FakeApiTests.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Api/FakeApiTests.cs new file mode 100644 index 00000000000..478311b649e --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Api/FakeApiTests.cs @@ -0,0 +1,80 @@ +using System; +using System.IO; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.Reflection; +using RestSharp; +using NUnit.Framework; + +using IO.Swagger.Client; +using IO.Swagger.Api; + +namespace IO.Swagger.Test +{ + /// + /// Class for testing FakeApi + /// + /// + /// This file is automatically generated by Swagger Codegen. + /// Please update the test case below to test the API endpoint. + /// + [TestFixture] + public class FakeApiTests + { + private FakeApi instance; + + /// + /// Setup before each unit test + /// + [SetUp] + public void Init() + { + instance = new FakeApi(); + } + + /// + /// Clean up after each unit test + /// + [TearDown] + public void Cleanup() + { + + } + + /// + /// Test an instance of FakeApi + /// + [Test] + public void InstanceTest() + { + Assert.IsInstanceOf (instance, "instance is a FakeApi"); + } + + + /// + /// Test TestEndpointParameters + /// + [Test] + public void TestEndpointParametersTest() + { + // TODO: add unit test for the method 'TestEndpointParameters' + double? number = null; // TODO: replace null with proper value + double? _double = null; // TODO: replace null with proper value + string _string = null; // TODO: replace null with proper value + byte[] _byte = null; // TODO: replace null with proper value + int? integer = null; // TODO: replace null with proper value + int? int32 = null; // TODO: replace null with proper value + long? int64 = null; // TODO: replace null with proper value + float? _float = null; // TODO: replace null with proper value + byte[] binary = null; // TODO: replace null with proper value + DateTime? date = null; // TODO: replace null with proper value + DateTime? dateTime = null; // TODO: replace null with proper value + string password = null; // TODO: replace null with proper value + instance.TestEndpointParameters(number, _double, _string, _byte, integer, int32, int64, _float, binary, date, dateTime, password); + + } + + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient.Test/PetApiTests.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Api/PetApiTests.cs similarity index 100% rename from samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient.Test/PetApiTests.cs rename to samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Api/PetApiTests.cs diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient.Test/StoreApiTests.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Api/StoreApiTests.cs similarity index 100% rename from samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient.Test/StoreApiTests.cs rename to samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Api/StoreApiTests.cs diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient.Test/UserApiTests.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Api/UserApiTests.cs similarity index 100% rename from samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient.Test/UserApiTests.cs rename to samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Api/UserApiTests.cs diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/IO.Swagger.Test.csproj b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/IO.Swagger.Test.csproj new file mode 100644 index 00000000000..743b0b97853 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/IO.Swagger.Test.csproj @@ -0,0 +1,73 @@ + + + + Debug + AnyCPU + {19F1DEBC-DE5E-4517-8062-F000CD499087} + Library + Properties + IO.Swagger.Test + IO.Swagger.Test + v4.5 + 512 + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + $(SolutionDir)\packages\Newtonsoft.Json.8.0.2\lib\net45\Newtonsoft.Json.dll + ..\packages\Newtonsoft.Json.8.0.2\lib\net45\Newtonsoft.Json.dll + ..\..\packages\Newtonsoft.Json.8.0.2\lib\net45\Newtonsoft.Json.dll + ..\..\vendor\Newtonsoft.Json.8.0.2\lib\net45\Newtonsoft.Json.dll + + + $(SolutionDir)\packages\RestSharp.105.1.0\lib\net45\RestSharp.dll + ..\packages\RestSharp.105.1.0\lib\net45\RestSharp.dll + ..\..\packages\RestSharp.105.1.0\lib\net45\RestSharp.dll + ..\..\vendor\RestSharp.105.1.0\lib\net45\RestSharp.dll + + + $(SolutionDir)\packages\NUnit.2.6.3\lib\nunit.framework.dll + ..\packages\NUnit.2.6.3\lib\nunit.framework.dll + ..\..\packages\NUnit.2.6.3\lib\nunit.framework.dll + ..\..\vendor\NUnit.2.6.3\lib\nunit.framework.dll + + + + + + + + + + + + {C075FB79-0DDE-43E3-9FA5-E239EE9B9B5A} + IO.Swagger + + + + diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/AnimalFarmTests.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/AnimalFarmTests.cs new file mode 100644 index 00000000000..5baa4d93485 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/AnimalFarmTests.cs @@ -0,0 +1,56 @@ +using NUnit.Framework; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using IO.Swagger.Api; +using IO.Swagger.Model; +using IO.Swagger.Client; +using System.Reflection; + +namespace IO.Swagger.Test +{ + /// + /// Class for testing AnimalFarm + /// + /// + /// This file is automatically generated by Swagger Codegen. + /// Please update the test case below to test the model. + /// + [TestFixture] + public class AnimalFarmTests + { + private AnimalFarm instance; + + /// + /// Setup before each test + /// + [SetUp] + public void Init() + { + instance = new AnimalFarm(); + } + + /// + /// Clean up after each test + /// + [TearDown] + public void Cleanup() + { + + } + + /// + /// Test an instance of AnimalFarm + /// + [Test] + public void AnimalFarmInstanceTest() + { + Assert.IsInstanceOf (instance, "instance is a AnimalFarm"); + } + + + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient.Test/AnimalTests.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/AnimalTests.cs similarity index 100% rename from samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient.Test/AnimalTests.cs rename to samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/AnimalTests.cs diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient.Test/ApiResponseTests.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/ApiResponseTests.cs similarity index 100% rename from samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient.Test/ApiResponseTests.cs rename to samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/ApiResponseTests.cs diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient.Test/CatTests.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/CatTests.cs similarity index 100% rename from samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient.Test/CatTests.cs rename to samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/CatTests.cs diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient.Test/CategoryTests.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/CategoryTests.cs similarity index 100% rename from samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient.Test/CategoryTests.cs rename to samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/CategoryTests.cs diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient.Test/DogTests.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/DogTests.cs similarity index 100% rename from samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient.Test/DogTests.cs rename to samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/DogTests.cs diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/EnumClassTests.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/EnumClassTests.cs new file mode 100644 index 00000000000..8c81c81fbb1 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/EnumClassTests.cs @@ -0,0 +1,56 @@ +using NUnit.Framework; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using IO.Swagger.Api; +using IO.Swagger.Model; +using IO.Swagger.Client; +using System.Reflection; + +namespace IO.Swagger.Test +{ + /// + /// Class for testing EnumClass + /// + /// + /// This file is automatically generated by Swagger Codegen. + /// Please update the test case below to test the model. + /// + [TestFixture] + public class EnumClassTests + { + private EnumClass instance; + + /// + /// Setup before each test + /// + [SetUp] + public void Init() + { + instance = new EnumClass(); + } + + /// + /// Clean up after each test + /// + [TearDown] + public void Cleanup() + { + + } + + /// + /// Test an instance of EnumClass + /// + [Test] + public void EnumClassInstanceTest() + { + Assert.IsInstanceOf (instance, "instance is a EnumClass"); + } + + + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/EnumTestTests.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/EnumTestTests.cs new file mode 100644 index 00000000000..2679b085233 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/EnumTestTests.cs @@ -0,0 +1,80 @@ +using NUnit.Framework; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using IO.Swagger.Api; +using IO.Swagger.Model; +using IO.Swagger.Client; +using System.Reflection; + +namespace IO.Swagger.Test +{ + /// + /// Class for testing EnumTest + /// + /// + /// This file is automatically generated by Swagger Codegen. + /// Please update the test case below to test the model. + /// + [TestFixture] + public class EnumTestTests + { + private EnumTest instance; + + /// + /// Setup before each test + /// + [SetUp] + public void Init() + { + instance = new EnumTest(); + } + + /// + /// Clean up after each test + /// + [TearDown] + public void Cleanup() + { + + } + + /// + /// Test an instance of EnumTest + /// + [Test] + public void EnumTestInstanceTest() + { + Assert.IsInstanceOf (instance, "instance is a EnumTest"); + } + + /// + /// Test the property 'EnumString' + /// + [Test] + public void EnumStringTest() + { + // TODO: unit test for the property 'EnumString' + } + /// + /// Test the property 'EnumInteger' + /// + [Test] + public void EnumIntegerTest() + { + // TODO: unit test for the property 'EnumInteger' + } + /// + /// Test the property 'EnumNumber' + /// + [Test] + public void EnumNumberTest() + { + // TODO: unit test for the property 'EnumNumber' + } + + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient.Test/FormatTestTests.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/FormatTestTests.cs similarity index 100% rename from samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient.Test/FormatTestTests.cs rename to samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/FormatTestTests.cs diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient.Test/Model200ResponseTests.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/Model200ResponseTests.cs similarity index 100% rename from samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient.Test/Model200ResponseTests.cs rename to samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/Model200ResponseTests.cs diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient.Test/ModelReturnTests.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/ModelReturnTests.cs similarity index 100% rename from samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient.Test/ModelReturnTests.cs rename to samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/ModelReturnTests.cs diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient.Test/NameTests.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/NameTests.cs similarity index 100% rename from samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient.Test/NameTests.cs rename to samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/NameTests.cs diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient.Test/OrderTests.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/OrderTests.cs similarity index 100% rename from samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient.Test/OrderTests.cs rename to samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/OrderTests.cs diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient.Test/PetTests.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/PetTests.cs similarity index 100% rename from samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient.Test/PetTests.cs rename to samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/PetTests.cs diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient.Test/SpecialModelNameTests.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/SpecialModelNameTests.cs similarity index 100% rename from samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient.Test/SpecialModelNameTests.cs rename to samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/SpecialModelNameTests.cs diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient.Test/TagTests.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/TagTests.cs similarity index 100% rename from samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient.Test/TagTests.cs rename to samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/TagTests.cs diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient.Test/UserTests.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/UserTests.cs similarity index 100% rename from samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient.Test/UserTests.cs rename to samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/UserTests.cs diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/packages.config b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/packages.config new file mode 100644 index 00000000000..a8a3491f63d --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/packages.config @@ -0,0 +1,6 @@ + + + + + + diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Api/FakeApi.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Api/FakeApi.cs new file mode 100644 index 00000000000..8b9fe2e52c8 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Api/FakeApi.cs @@ -0,0 +1,418 @@ +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using RestSharp; +using IO.Swagger.Client; + +namespace IO.Swagger.Api +{ + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public interface IFakeApi + { + #region Synchronous Operations + /// + /// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + /// + /// + /// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + /// + /// Thrown when fails to make API call + /// None + /// None + /// None + /// None + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// + void TestEndpointParameters (double? number, double? _double, string _string, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, byte[] binary = null, DateTime? date = null, DateTime? dateTime = null, string password = null); + + /// + /// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + /// + /// + /// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + /// + /// Thrown when fails to make API call + /// None + /// None + /// None + /// None + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// ApiResponse of Object(void) + ApiResponse TestEndpointParametersWithHttpInfo (double? number, double? _double, string _string, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, byte[] binary = null, DateTime? date = null, DateTime? dateTime = null, string password = null); + #endregion Synchronous Operations + #region Asynchronous Operations + /// + /// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + /// + /// + /// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + /// + /// Thrown when fails to make API call + /// None + /// None + /// None + /// None + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// Task of void + System.Threading.Tasks.Task TestEndpointParametersAsync (double? number, double? _double, string _string, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, byte[] binary = null, DateTime? date = null, DateTime? dateTime = null, string password = null); + + /// + /// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + /// + /// + /// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + /// + /// Thrown when fails to make API call + /// None + /// None + /// None + /// None + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// Task of ApiResponse + System.Threading.Tasks.Task> TestEndpointParametersAsyncWithHttpInfo (double? number, double? _double, string _string, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, byte[] binary = null, DateTime? date = null, DateTime? dateTime = null, string password = null); + #endregion Asynchronous Operations + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public class FakeApi : IFakeApi + { + /// + /// Initializes a new instance of the class. + /// + /// + public FakeApi(String basePath) + { + this.Configuration = new Configuration(new ApiClient(basePath)); + + // ensure API client has configuration ready + if (Configuration.ApiClient.Configuration == null) + { + this.Configuration.ApiClient.Configuration = this.Configuration; + } + } + + /// + /// Initializes a new instance of the class + /// using Configuration object + /// + /// An instance of Configuration + /// + public FakeApi(Configuration configuration = null) + { + if (configuration == null) // use the default one in Configuration + this.Configuration = Configuration.Default; + else + this.Configuration = configuration; + + // ensure API client has configuration ready + if (Configuration.ApiClient.Configuration == null) + { + this.Configuration.ApiClient.Configuration = this.Configuration; + } + } + + /// + /// Gets the base path of the API client. + /// + /// The base path + public String GetBasePath() + { + return this.Configuration.ApiClient.RestClient.BaseUrl.ToString(); + } + + /// + /// Sets the base path of the API client. + /// + /// The base path + [Obsolete("SetBasePath is deprecated, please do 'Configuraiton.ApiClient = new ApiClient(\"http://new-path\")' instead.")] + public void SetBasePath(String basePath) + { + // do nothing + } + + /// + /// Gets or sets the configuration object + /// + /// An instance of the Configuration + public Configuration Configuration {get; set;} + + /// + /// Gets the default header. + /// + /// Dictionary of HTTP header + [Obsolete("DefaultHeader is deprecated, please use Configuration.DefaultHeader instead.")] + public Dictionary DefaultHeader() + { + return this.Configuration.DefaultHeader; + } + + /// + /// Add default header. + /// + /// Header field name. + /// Header field value. + /// + [Obsolete("AddDefaultHeader is deprecated, please use Configuration.AddDefaultHeader instead.")] + public void AddDefaultHeader(string key, string value) + { + this.Configuration.AddDefaultHeader(key, value); + } + + /// + /// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + /// + /// Thrown when fails to make API call + /// None + /// None + /// None + /// None + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// + public void TestEndpointParameters (double? number, double? _double, string _string, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, byte[] binary = null, DateTime? date = null, DateTime? dateTime = null, string password = null) + { + TestEndpointParametersWithHttpInfo(number, _double, _string, _byte, integer, int32, int64, _float, binary, date, dateTime, password); + } + + /// + /// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + /// + /// Thrown when fails to make API call + /// None + /// None + /// None + /// None + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// ApiResponse of Object(void) + public ApiResponse TestEndpointParametersWithHttpInfo (double? number, double? _double, string _string, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, byte[] binary = null, DateTime? date = null, DateTime? dateTime = null, string password = null) + { + // verify the required parameter 'number' is set + if (number == null) + throw new ApiException(400, "Missing required parameter 'number' when calling FakeApi->TestEndpointParameters"); + // verify the required parameter '_double' is set + if (_double == null) + throw new ApiException(400, "Missing required parameter '_double' when calling FakeApi->TestEndpointParameters"); + // verify the required parameter '_string' is set + if (_string == null) + throw new ApiException(400, "Missing required parameter '_string' when calling FakeApi->TestEndpointParameters"); + // verify the required parameter '_byte' is set + if (_byte == null) + throw new ApiException(400, "Missing required parameter '_byte' when calling FakeApi->TestEndpointParameters"); + + var localVarPath = "/fake"; + var localVarPathParams = new Dictionary(); + var localVarQueryParams = new Dictionary(); + var localVarHeaderParams = new Dictionary(Configuration.DefaultHeader); + var localVarFormParams = new Dictionary(); + var localVarFileParams = new Dictionary(); + Object localVarPostBody = null; + + // to determine the Content-Type header + String[] localVarHttpContentTypes = new String[] { + }; + String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); + + // to determine the Accept header + String[] localVarHttpHeaderAccepts = new String[] { + "application/xml", + "application/json" + }; + String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); + if (localVarHttpHeaderAccept != null) + localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); + + // set "format" to json by default + // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json + localVarPathParams.Add("format", "json"); + if (integer != null) localVarFormParams.Add("integer", Configuration.ApiClient.ParameterToString(integer)); // form parameter + if (int32 != null) localVarFormParams.Add("int32", Configuration.ApiClient.ParameterToString(int32)); // form parameter + if (int64 != null) localVarFormParams.Add("int64", Configuration.ApiClient.ParameterToString(int64)); // form parameter + if (number != null) localVarFormParams.Add("number", Configuration.ApiClient.ParameterToString(number)); // form parameter + if (_float != null) localVarFormParams.Add("float", Configuration.ApiClient.ParameterToString(_float)); // form parameter + if (_double != null) localVarFormParams.Add("double", Configuration.ApiClient.ParameterToString(_double)); // form parameter + if (_string != null) localVarFormParams.Add("string", Configuration.ApiClient.ParameterToString(_string)); // form parameter + if (_byte != null) localVarFormParams.Add("byte", Configuration.ApiClient.ParameterToString(_byte)); // form parameter + if (binary != null) localVarFormParams.Add("binary", Configuration.ApiClient.ParameterToString(binary)); // form parameter + if (date != null) localVarFormParams.Add("date", Configuration.ApiClient.ParameterToString(date)); // form parameter + if (dateTime != null) localVarFormParams.Add("dateTime", Configuration.ApiClient.ParameterToString(dateTime)); // form parameter + if (password != null) localVarFormParams.Add("password", Configuration.ApiClient.ParameterToString(password)); // form parameter + + + // make the HTTP request + IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, + Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, + localVarPathParams, localVarHttpContentType); + + int localVarStatusCode = (int) localVarResponse.StatusCode; + + if (localVarStatusCode >= 400) + throw new ApiException (localVarStatusCode, "Error calling TestEndpointParameters: " + localVarResponse.Content, localVarResponse.Content); + else if (localVarStatusCode == 0) + throw new ApiException (localVarStatusCode, "Error calling TestEndpointParameters: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + + + return new ApiResponse(localVarStatusCode, + localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), + null); + } + + /// + /// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + /// + /// Thrown when fails to make API call + /// None + /// None + /// None + /// None + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// Task of void + public async System.Threading.Tasks.Task TestEndpointParametersAsync (double? number, double? _double, string _string, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, byte[] binary = null, DateTime? date = null, DateTime? dateTime = null, string password = null) + { + await TestEndpointParametersAsyncWithHttpInfo(number, _double, _string, _byte, integer, int32, int64, _float, binary, date, dateTime, password); + + } + + /// + /// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + /// + /// Thrown when fails to make API call + /// None + /// None + /// None + /// None + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// Task of ApiResponse + public async System.Threading.Tasks.Task> TestEndpointParametersAsyncWithHttpInfo (double? number, double? _double, string _string, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, byte[] binary = null, DateTime? date = null, DateTime? dateTime = null, string password = null) + { + // verify the required parameter 'number' is set + if (number == null) + throw new ApiException(400, "Missing required parameter 'number' when calling FakeApi->TestEndpointParameters"); + // verify the required parameter '_double' is set + if (_double == null) + throw new ApiException(400, "Missing required parameter '_double' when calling FakeApi->TestEndpointParameters"); + // verify the required parameter '_string' is set + if (_string == null) + throw new ApiException(400, "Missing required parameter '_string' when calling FakeApi->TestEndpointParameters"); + // verify the required parameter '_byte' is set + if (_byte == null) + throw new ApiException(400, "Missing required parameter '_byte' when calling FakeApi->TestEndpointParameters"); + + var localVarPath = "/fake"; + var localVarPathParams = new Dictionary(); + var localVarQueryParams = new Dictionary(); + var localVarHeaderParams = new Dictionary(Configuration.DefaultHeader); + var localVarFormParams = new Dictionary(); + var localVarFileParams = new Dictionary(); + Object localVarPostBody = null; + + // to determine the Content-Type header + String[] localVarHttpContentTypes = new String[] { + }; + String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); + + // to determine the Accept header + String[] localVarHttpHeaderAccepts = new String[] { + "application/xml", + "application/json" + }; + String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); + if (localVarHttpHeaderAccept != null) + localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); + + // set "format" to json by default + // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json + localVarPathParams.Add("format", "json"); + if (integer != null) localVarFormParams.Add("integer", Configuration.ApiClient.ParameterToString(integer)); // form parameter + if (int32 != null) localVarFormParams.Add("int32", Configuration.ApiClient.ParameterToString(int32)); // form parameter + if (int64 != null) localVarFormParams.Add("int64", Configuration.ApiClient.ParameterToString(int64)); // form parameter + if (number != null) localVarFormParams.Add("number", Configuration.ApiClient.ParameterToString(number)); // form parameter + if (_float != null) localVarFormParams.Add("float", Configuration.ApiClient.ParameterToString(_float)); // form parameter + if (_double != null) localVarFormParams.Add("double", Configuration.ApiClient.ParameterToString(_double)); // form parameter + if (_string != null) localVarFormParams.Add("string", Configuration.ApiClient.ParameterToString(_string)); // form parameter + if (_byte != null) localVarFormParams.Add("byte", Configuration.ApiClient.ParameterToString(_byte)); // form parameter + if (binary != null) localVarFormParams.Add("binary", Configuration.ApiClient.ParameterToString(binary)); // form parameter + if (date != null) localVarFormParams.Add("date", Configuration.ApiClient.ParameterToString(date)); // form parameter + if (dateTime != null) localVarFormParams.Add("dateTime", Configuration.ApiClient.ParameterToString(dateTime)); // form parameter + if (password != null) localVarFormParams.Add("password", Configuration.ApiClient.ParameterToString(password)); // form parameter + + + // make the HTTP request + IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath, + Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, + localVarPathParams, localVarHttpContentType); + + int localVarStatusCode = (int) localVarResponse.StatusCode; + + if (localVarStatusCode >= 400) + throw new ApiException (localVarStatusCode, "Error calling TestEndpointParameters: " + localVarResponse.Content, localVarResponse.Content); + else if (localVarStatusCode == 0) + throw new ApiException (localVarStatusCode, "Error calling TestEndpointParameters: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + + + return new ApiResponse(localVarStatusCode, + localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), + null); + } + + } +} diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/PetApi.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Api/PetApi.cs similarity index 99% rename from samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/PetApi.cs rename to samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Api/PetApi.cs index 75d8dd830c7..ada1bcbed30 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/PetApi.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Api/PetApi.cs @@ -512,7 +512,7 @@ namespace IO.Swagger.Api // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); - if (body.GetType() != typeof(byte[])) + if (body != null && body.GetType() != typeof(byte[])) { localVarPostBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter } @@ -597,7 +597,7 @@ namespace IO.Swagger.Api // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); - if (body.GetType() != typeof(byte[])) + if (body != null && body.GetType() != typeof(byte[])) { localVarPostBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter } @@ -1296,7 +1296,7 @@ namespace IO.Swagger.Api // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); - if (body.GetType() != typeof(byte[])) + if (body != null && body.GetType() != typeof(byte[])) { localVarPostBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter } @@ -1381,7 +1381,7 @@ namespace IO.Swagger.Api // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); - if (body.GetType() != typeof(byte[])) + if (body != null && body.GetType() != typeof(byte[])) { localVarPostBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter } diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/StoreApi.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Api/StoreApi.cs similarity index 99% rename from samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/StoreApi.cs rename to samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Api/StoreApi.cs index a2c32ea3f7e..bbe6343ee84 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/StoreApi.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Api/StoreApi.cs @@ -737,7 +737,7 @@ namespace IO.Swagger.Api // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); - if (body.GetType() != typeof(byte[])) + if (body != null && body.GetType() != typeof(byte[])) { localVarPostBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter } @@ -815,7 +815,7 @@ namespace IO.Swagger.Api // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); - if (body.GetType() != typeof(byte[])) + if (body != null && body.GetType() != typeof(byte[])) { localVarPostBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter } diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/UserApi.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Api/UserApi.cs similarity index 99% rename from samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/UserApi.cs rename to samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Api/UserApi.cs index a94b733e44b..f4b36e47e32 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/UserApi.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Api/UserApi.cs @@ -494,7 +494,7 @@ namespace IO.Swagger.Api // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); - if (body.GetType() != typeof(byte[])) + if (body != null && body.GetType() != typeof(byte[])) { localVarPostBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter } @@ -571,7 +571,7 @@ namespace IO.Swagger.Api // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); - if (body.GetType() != typeof(byte[])) + if (body != null && body.GetType() != typeof(byte[])) { localVarPostBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter } @@ -647,7 +647,7 @@ namespace IO.Swagger.Api // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); - if (body.GetType() != typeof(byte[])) + if (body != null && body.GetType() != typeof(byte[])) { localVarPostBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter } @@ -724,7 +724,7 @@ namespace IO.Swagger.Api // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); - if (body.GetType() != typeof(byte[])) + if (body != null && body.GetType() != typeof(byte[])) { localVarPostBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter } @@ -800,7 +800,7 @@ namespace IO.Swagger.Api // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); - if (body.GetType() != typeof(byte[])) + if (body != null && body.GetType() != typeof(byte[])) { localVarPostBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter } @@ -877,7 +877,7 @@ namespace IO.Swagger.Api // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); - if (body.GetType() != typeof(byte[])) + if (body != null && body.GetType() != typeof(byte[])) { localVarPostBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter } @@ -1519,7 +1519,7 @@ namespace IO.Swagger.Api // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (username != null) localVarPathParams.Add("username", Configuration.ApiClient.ParameterToString(username)); // path parameter - if (body.GetType() != typeof(byte[])) + if (body != null && body.GetType() != typeof(byte[])) { localVarPostBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter } @@ -1602,7 +1602,7 @@ namespace IO.Swagger.Api // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (username != null) localVarPathParams.Add("username", Configuration.ApiClient.ParameterToString(username)); // path parameter - if (body.GetType() != typeof(byte[])) + if (body != null && body.GetType() != typeof(byte[])) { localVarPostBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter } diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Client/ApiClient.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Client/ApiClient.cs similarity index 100% rename from samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Client/ApiClient.cs rename to samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Client/ApiClient.cs diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Client/ApiException.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Client/ApiException.cs similarity index 100% rename from samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Client/ApiException.cs rename to samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Client/ApiException.cs diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Client/ApiResponse.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Client/ApiResponse.cs similarity index 100% rename from samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Client/ApiResponse.cs rename to samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Client/ApiResponse.cs diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Client/Configuration.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Client/Configuration.cs similarity index 100% rename from samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Client/Configuration.cs rename to samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Client/Configuration.cs diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/IO.Swagger.csproj b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/IO.Swagger.csproj new file mode 100644 index 00000000000..ad86456ecea --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/IO.Swagger.csproj @@ -0,0 +1,61 @@ + + + + Debug + AnyCPU + {C075FB79-0DDE-43E3-9FA5-E239EE9B9B5A} + Library + Properties + Swagger Library + Swagger Library + v4.5 + 512 + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + $(SolutionDir)\packages\Newtonsoft.Json.8.0.2\lib\net45\Newtonsoft.Json.dll + ..\packages\Newtonsoft.Json.8.0.2\lib\net45\Newtonsoft.Json.dll + ..\..\packages\Newtonsoft.Json.8.0.2\lib\net45\Newtonsoft.Json.dll + ..\..\vendor\Newtonsoft.Json.8.0.2\lib\net45\Newtonsoft.Json.dll + + + $(SolutionDir)\packages\RestSharp.105.1.0\lib\net45\RestSharp.dll + ..\packages\RestSharp.105.1.0\lib\net45\RestSharp.dll + ..\..\packages\RestSharp.105.1.0\lib\net45\RestSharp.dll + ..\..\vendor\RestSharp.105.1.0\lib\net45\RestSharp.dll + + + + + + + + + + + diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Animal.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Animal.cs similarity index 79% rename from samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Animal.cs rename to samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Animal.cs index f5b9a3efee0..87a17aa4fae 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Animal.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Animal.cs @@ -21,7 +21,8 @@ namespace IO.Swagger.Model /// Initializes a new instance of the class. /// /// ClassName (required). - public Animal(string ClassName = null) + /// Color (default to "red"). + public Animal(string ClassName = null, string Color = null) { // to ensure "ClassName" is required (not null) if (ClassName == null) @@ -34,6 +35,16 @@ namespace IO.Swagger.Model } + // use default value if no "Color" provided + if (Color == null) + { + this.Color = "red"; + } + else + { + this.Color = Color; + } + } /// @@ -42,6 +53,11 @@ namespace IO.Swagger.Model [DataMember(Name="className", EmitDefaultValue=false)] public string ClassName { get; set; } /// + /// Gets or Sets Color + /// + [DataMember(Name="color", EmitDefaultValue=false)] + public string Color { get; set; } + /// /// Returns the string presentation of the object /// /// String presentation of the object @@ -50,6 +66,7 @@ namespace IO.Swagger.Model var sb = new StringBuilder(); sb.Append("class Animal {\n"); sb.Append(" ClassName: ").Append(ClassName).Append("\n"); +sb.Append(" Color: ").Append(Color).Append("\n"); sb.Append("}\n"); return sb.ToString(); } @@ -90,6 +107,11 @@ namespace IO.Swagger.Model this.ClassName == other.ClassName || this.ClassName != null && this.ClassName.Equals(other.ClassName) + ) && + ( + this.Color == other.Color || + this.Color != null && + this.Color.Equals(other.Color) ); } @@ -106,6 +128,8 @@ namespace IO.Swagger.Model // Suitable nullity checks etc, of course :) if (this.ClassName != null) hash = hash * 59 + this.ClassName.GetHashCode(); + if (this.Color != null) + hash = hash * 59 + this.Color.GetHashCode(); return hash; } } diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Task.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/AnimalFarm.cs similarity index 61% rename from samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Task.cs rename to samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/AnimalFarm.cs index b2182f2f712..76685fe8495 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Task.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/AnimalFarm.cs @@ -12,31 +12,20 @@ using Newtonsoft.Json.Converters; namespace IO.Swagger.Model { /// - /// + /// AnimalFarm /// [DataContract] - public partial class Task : IEquatable - { - + public partial class AnimalFarm : List, IEquatable + { /// - /// Initializes a new instance of the class. - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// - /// _Return. - - public Task(int? _Return = null) + public AnimalFarm() { - this._Return = _Return; + } - - /// - /// Gets or Sets _Return - /// - [DataMember(Name="return", EmitDefaultValue=false)] - public int? _Return { get; set; } - /// /// Returns the string presentation of the object /// @@ -44,10 +33,8 @@ namespace IO.Swagger.Model public override string ToString() { var sb = new StringBuilder(); - sb.Append("class Task {\n"); - sb.Append(" _Return: ").Append(_Return).Append("\n"); - - sb.Append("}\n"); + sb.Append("class AnimalFarm {\n"); + sb.Append("}\n"); return sb.ToString(); } @@ -55,7 +42,7 @@ namespace IO.Swagger.Model /// Returns the JSON string presentation of the object /// /// JSON string presentation of the object - public string ToJson() + public new string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } @@ -68,26 +55,21 @@ namespace IO.Swagger.Model public override bool Equals(object obj) { // credit: http://stackoverflow.com/a/10454552/677735 - return this.Equals(obj as Task); + return this.Equals(obj as AnimalFarm); } /// - /// Returns true if Task instances are equal + /// Returns true if AnimalFarm instances are equal /// - /// Instance of Task to be compared + /// Instance of AnimalFarm to be compared /// Boolean - public bool Equals(Task other) + public bool Equals(AnimalFarm other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; - return - ( - this._Return == other._Return || - this._Return != null && - this._Return.Equals(other._Return) - ); + return false; } /// @@ -101,13 +83,9 @@ namespace IO.Swagger.Model { int hash = 41; // Suitable nullity checks etc, of course :) - - if (this._Return != null) - hash = hash * 59 + this._Return.GetHashCode(); - return hash; } } - } + } diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/ApiResponse.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/ApiResponse.cs similarity index 100% rename from samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/ApiResponse.cs rename to samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/ApiResponse.cs diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Cat.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Cat.cs similarity index 81% rename from samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Cat.cs rename to samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Cat.cs index 74bd81aee05..fee880c5d82 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Cat.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Cat.cs @@ -21,8 +21,9 @@ namespace IO.Swagger.Model /// Initializes a new instance of the class. /// /// ClassName (required). + /// Color (default to "red"). /// Declawed. - public Cat(string ClassName = null, bool? Declawed = null) + public Cat(string ClassName = null, string Color = null, bool? Declawed = null) { // to ensure "ClassName" is required (not null) if (ClassName == null) @@ -35,6 +36,16 @@ namespace IO.Swagger.Model } + // use default value if no "Color" provided + if (Color == null) + { + this.Color = "red"; + } + else + { + this.Color = Color; + } + this.Declawed = Declawed; } @@ -45,6 +56,11 @@ namespace IO.Swagger.Model [DataMember(Name="className", EmitDefaultValue=false)] public string ClassName { get; set; } /// + /// Gets or Sets Color + /// + [DataMember(Name="color", EmitDefaultValue=false)] + public string Color { get; set; } + /// /// Gets or Sets Declawed /// [DataMember(Name="declawed", EmitDefaultValue=false)] @@ -58,6 +74,7 @@ namespace IO.Swagger.Model var sb = new StringBuilder(); sb.Append("class Cat {\n"); sb.Append(" ClassName: ").Append(ClassName).Append("\n"); +sb.Append(" Color: ").Append(Color).Append("\n"); sb.Append(" Declawed: ").Append(Declawed).Append("\n"); sb.Append("}\n"); return sb.ToString(); @@ -100,6 +117,11 @@ sb.Append(" Declawed: ").Append(Declawed).Append("\n"); this.ClassName != null && this.ClassName.Equals(other.ClassName) ) && + ( + this.Color == other.Color || + this.Color != null && + this.Color.Equals(other.Color) + ) && ( this.Declawed == other.Declawed || this.Declawed != null && @@ -120,6 +142,8 @@ sb.Append(" Declawed: ").Append(Declawed).Append("\n"); // Suitable nullity checks etc, of course :) if (this.ClassName != null) hash = hash * 59 + this.ClassName.GetHashCode(); + if (this.Color != null) + hash = hash * 59 + this.Color.GetHashCode(); if (this.Declawed != null) hash = hash * 59 + this.Declawed.GetHashCode(); return hash; diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Category.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Category.cs similarity index 100% rename from samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Category.cs rename to samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Category.cs diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Dog.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Dog.cs similarity index 81% rename from samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Dog.cs rename to samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Dog.cs index 6ab8c9ad69f..fb65e3e0c99 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Dog.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Dog.cs @@ -21,8 +21,9 @@ namespace IO.Swagger.Model /// Initializes a new instance of the class. /// /// ClassName (required). + /// Color (default to "red"). /// Breed. - public Dog(string ClassName = null, string Breed = null) + public Dog(string ClassName = null, string Color = null, string Breed = null) { // to ensure "ClassName" is required (not null) if (ClassName == null) @@ -35,6 +36,16 @@ namespace IO.Swagger.Model } + // use default value if no "Color" provided + if (Color == null) + { + this.Color = "red"; + } + else + { + this.Color = Color; + } + this.Breed = Breed; } @@ -45,6 +56,11 @@ namespace IO.Swagger.Model [DataMember(Name="className", EmitDefaultValue=false)] public string ClassName { get; set; } /// + /// Gets or Sets Color + /// + [DataMember(Name="color", EmitDefaultValue=false)] + public string Color { get; set; } + /// /// Gets or Sets Breed /// [DataMember(Name="breed", EmitDefaultValue=false)] @@ -58,6 +74,7 @@ namespace IO.Swagger.Model var sb = new StringBuilder(); sb.Append("class Dog {\n"); sb.Append(" ClassName: ").Append(ClassName).Append("\n"); +sb.Append(" Color: ").Append(Color).Append("\n"); sb.Append(" Breed: ").Append(Breed).Append("\n"); sb.Append("}\n"); return sb.ToString(); @@ -100,6 +117,11 @@ sb.Append(" Breed: ").Append(Breed).Append("\n"); this.ClassName != null && this.ClassName.Equals(other.ClassName) ) && + ( + this.Color == other.Color || + this.Color != null && + this.Color.Equals(other.Color) + ) && ( this.Breed == other.Breed || this.Breed != null && @@ -120,6 +142,8 @@ sb.Append(" Breed: ").Append(Breed).Append("\n"); // Suitable nullity checks etc, of course :) if (this.ClassName != null) hash = hash * 59 + this.ClassName.GetHashCode(); + if (this.Color != null) + hash = hash * 59 + this.Color.GetHashCode(); if (this.Breed != null) hash = hash * 59 + this.Breed.GetHashCode(); return hash; diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/EnumClass.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/EnumClass.cs new file mode 100644 index 00000000000..1fb5f0b6626 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/EnumClass.cs @@ -0,0 +1,40 @@ +using System; +using System.Linq; +using System.IO; +using System.Text; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Runtime.Serialization; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; + +namespace IO.Swagger.Model +{ + /// + /// Gets or Sets EnumClass + /// + [JsonConverter(typeof(StringEnumConverter))] + public enum EnumClass + { + + /// + /// Enum Abc for "_abc" + /// + [EnumMember(Value = "_abc")] + Abc, + + /// + /// Enum efg for "-efg" + /// + [EnumMember(Value = "-efg")] + efg, + + /// + /// Enum xyz for "(xyz)" + /// + [EnumMember(Value = "(xyz)")] + xyz + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/EnumTest.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/EnumTest.cs new file mode 100644 index 00000000000..f8bebd6b2d7 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/EnumTest.cs @@ -0,0 +1,199 @@ +using System; +using System.Linq; +using System.IO; +using System.Text; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Runtime.Serialization; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; + +namespace IO.Swagger.Model +{ + /// + /// EnumTest + /// + [DataContract] + public partial class EnumTest : IEquatable + { + /// + /// Gets or Sets EnumString + /// + [JsonConverter(typeof(StringEnumConverter))] + public enum EnumStringEnum + { + + /// + /// Enum Upper for "UPPER" + /// + [EnumMember(Value = "UPPER")] + Upper, + + /// + /// Enum Lower for "lower" + /// + [EnumMember(Value = "lower")] + Lower + } + + /// + /// Gets or Sets EnumInteger + /// + [JsonConverter(typeof(StringEnumConverter))] + public enum EnumIntegerEnum + { + + /// + /// Enum NUMBER_1 for 1 + /// + [EnumMember(Value = "1")] + NUMBER_1 = 1, + + /// + /// Enum NUMBER_MINUS_1 for -1 + /// + [EnumMember(Value = "-1")] + NUMBER_MINUS_1 = -1 + } + + /// + /// Gets or Sets EnumNumber + /// + [JsonConverter(typeof(StringEnumConverter))] + public enum EnumNumberEnum + { + + /// + /// Enum NUMBER_1_DOT_1 for 1.1 + /// + [EnumMember(Value = "1.1")] + NUMBER_1_DOT_1, + + /// + /// Enum NUMBER_MINUS_1_DOT_2 for -1.2 + /// + [EnumMember(Value = "-1.2")] + NUMBER_MINUS_1_DOT_2 + } + + /// + /// Gets or Sets EnumString + /// + [DataMember(Name="enum_string", EmitDefaultValue=false)] + public EnumStringEnum? EnumString { get; set; } + /// + /// Gets or Sets EnumInteger + /// + [DataMember(Name="enum_integer", EmitDefaultValue=false)] + public EnumIntegerEnum? EnumInteger { get; set; } + /// + /// Gets or Sets EnumNumber + /// + [DataMember(Name="enum_number", EmitDefaultValue=false)] + public EnumNumberEnum? EnumNumber { get; set; } + /// + /// Initializes a new instance of the class. + /// + /// EnumString. + /// EnumInteger. + /// EnumNumber. + public EnumTest(EnumStringEnum? EnumString = null, EnumIntegerEnum? EnumInteger = null, EnumNumberEnum? EnumNumber = null) + { + + + this.EnumString = EnumString; + + this.EnumInteger = EnumInteger; + + this.EnumNumber = EnumNumber; + + } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + var sb = new StringBuilder(); + sb.Append("class EnumTest {\n"); + sb.Append(" EnumString: ").Append(EnumString).Append("\n"); +sb.Append(" EnumInteger: ").Append(EnumInteger).Append("\n"); +sb.Append(" EnumNumber: ").Append(EnumNumber).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public string ToJson() + { + return JsonConvert.SerializeObject(this, Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object obj) + { + // credit: http://stackoverflow.com/a/10454552/677735 + return this.Equals(obj as EnumTest); + } + + /// + /// Returns true if EnumTest instances are equal + /// + /// Instance of EnumTest to be compared + /// Boolean + public bool Equals(EnumTest other) + { + // credit: http://stackoverflow.com/a/10454552/677735 + if (other == null) + return false; + + return + ( + this.EnumString == other.EnumString || + this.EnumString != null && + this.EnumString.Equals(other.EnumString) + ) && + ( + this.EnumInteger == other.EnumInteger || + this.EnumInteger != null && + this.EnumInteger.Equals(other.EnumInteger) + ) && + ( + this.EnumNumber == other.EnumNumber || + this.EnumNumber != null && + this.EnumNumber.Equals(other.EnumNumber) + ); + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + // credit: http://stackoverflow.com/a/263416/677735 + unchecked // Overflow is fine, just wrap + { + int hash = 41; + // Suitable nullity checks etc, of course :) + if (this.EnumString != null) + hash = hash * 59 + this.EnumString.GetHashCode(); + if (this.EnumInteger != null) + hash = hash * 59 + this.EnumInteger.GetHashCode(); + if (this.EnumNumber != null) + hash = hash * 59 + this.EnumNumber.GetHashCode(); + return hash; + } + } + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/FormatTest.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/FormatTest.cs similarity index 94% rename from samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/FormatTest.cs rename to samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/FormatTest.cs index c5a99d45af0..33301f02a95 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/FormatTest.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/FormatTest.cs @@ -31,8 +31,9 @@ namespace IO.Swagger.Model /// Binary. /// Date (required). /// DateTime. + /// Uuid. /// Password (required). - public FormatTest(int? Integer = null, int? Int32 = null, long? Int64 = null, double? Number = null, float? _Float = null, double? _Double = null, string _String = null, byte[] _Byte = null, byte[] Binary = null, DateTime? Date = null, DateTime? DateTime = null, string Password = null) + public FormatTest(int? Integer = null, int? Int32 = null, long? Int64 = null, double? Number = null, float? _Float = null, double? _Double = null, string _String = null, byte[] _Byte = null, byte[] Binary = null, DateTime? Date = null, DateTime? DateTime = null, Guid? Uuid = null, string Password = null) { // to ensure "Number" is required (not null) if (Number == null) @@ -88,6 +89,8 @@ namespace IO.Swagger.Model this.DateTime = DateTime; + this.Uuid = Uuid; + } /// @@ -146,6 +149,11 @@ namespace IO.Swagger.Model [DataMember(Name="dateTime", EmitDefaultValue=false)] public DateTime? DateTime { get; set; } /// + /// Gets or Sets Uuid + /// + [DataMember(Name="uuid", EmitDefaultValue=false)] + public Guid? Uuid { get; set; } + /// /// Gets or Sets Password /// [DataMember(Name="password", EmitDefaultValue=false)] @@ -169,6 +177,7 @@ sb.Append(" _Byte: ").Append(_Byte).Append("\n"); sb.Append(" Binary: ").Append(Binary).Append("\n"); sb.Append(" Date: ").Append(Date).Append("\n"); sb.Append(" DateTime: ").Append(DateTime).Append("\n"); +sb.Append(" Uuid: ").Append(Uuid).Append("\n"); sb.Append(" Password: ").Append(Password).Append("\n"); sb.Append("}\n"); return sb.ToString(); @@ -261,6 +270,11 @@ sb.Append(" Password: ").Append(Password).Append("\n"); this.DateTime != null && this.DateTime.Equals(other.DateTime) ) && + ( + this.Uuid == other.Uuid || + this.Uuid != null && + this.Uuid.Equals(other.Uuid) + ) && ( this.Password == other.Password || this.Password != null && @@ -301,6 +315,8 @@ sb.Append(" Password: ").Append(Password).Append("\n"); hash = hash * 59 + this.Date.GetHashCode(); if (this.DateTime != null) hash = hash * 59 + this.DateTime.GetHashCode(); + if (this.Uuid != null) + hash = hash * 59 + this.Uuid.GetHashCode(); if (this.Password != null) hash = hash * 59 + this.Password.GetHashCode(); return hash; diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Model200Response.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Model200Response.cs similarity index 100% rename from samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Model200Response.cs rename to samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Model200Response.cs diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/ModelReturn.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/ModelReturn.cs similarity index 100% rename from samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/ModelReturn.cs rename to samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/ModelReturn.cs diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Name.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Name.cs similarity index 89% rename from samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Name.cs rename to samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Name.cs index b0e819fec20..25273ffb97b 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Name.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Name.cs @@ -55,6 +55,11 @@ namespace IO.Swagger.Model [DataMember(Name="property", EmitDefaultValue=false)] public string Property { get; set; } /// + /// Gets or Sets _123Number + /// + [DataMember(Name="123Number", EmitDefaultValue=false)] + public int? _123Number { get; private set; } + /// /// Returns the string presentation of the object /// /// String presentation of the object @@ -65,6 +70,7 @@ namespace IO.Swagger.Model sb.Append(" _Name: ").Append(_Name).Append("\n"); sb.Append(" SnakeCase: ").Append(SnakeCase).Append("\n"); sb.Append(" Property: ").Append(Property).Append("\n"); +sb.Append(" _123Number: ").Append(_123Number).Append("\n"); sb.Append("}\n"); return sb.ToString(); } @@ -115,6 +121,11 @@ sb.Append(" Property: ").Append(Property).Append("\n"); this.Property == other.Property || this.Property != null && this.Property.Equals(other.Property) + ) && + ( + this._123Number == other._123Number || + this._123Number != null && + this._123Number.Equals(other._123Number) ); } @@ -135,6 +146,8 @@ sb.Append(" Property: ").Append(Property).Append("\n"); hash = hash * 59 + this.SnakeCase.GetHashCode(); if (this.Property != null) hash = hash * 59 + this.Property.GetHashCode(); + if (this._123Number != null) + hash = hash * 59 + this._123Number.GetHashCode(); return hash; } } diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Order.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Order.cs similarity index 100% rename from samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Order.cs rename to samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Order.cs diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Pet.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Pet.cs similarity index 100% rename from samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Pet.cs rename to samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Pet.cs diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/SpecialModelName.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/SpecialModelName.cs similarity index 100% rename from samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/SpecialModelName.cs rename to samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/SpecialModelName.cs diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Tag.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Tag.cs similarity index 100% rename from samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Tag.cs rename to samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Tag.cs diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/User.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/User.cs similarity index 100% rename from samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/User.cs rename to samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/User.cs diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Properties/AssemblyInfo.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Properties/AssemblyInfo.cs similarity index 100% rename from samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Properties/AssemblyInfo.cs rename to samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Properties/AssemblyInfo.cs diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/vendor/packages.config b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/packages.config similarity index 100% rename from samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/vendor/packages.config rename to samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/packages.config diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient.Test/InlineResponse200Tests.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient.Test/InlineResponse200Tests.cs deleted file mode 100644 index a4930b02df3..00000000000 --- a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient.Test/InlineResponse200Tests.cs +++ /dev/null @@ -1,104 +0,0 @@ -using NUnit.Framework; - -using System; -using System.Linq; -using System.IO; -using System.Collections.Generic; -using IO.Swagger.Api; -using IO.Swagger.Model; -using IO.Swagger.Client; -using System.Reflection; - -namespace IO.Swagger.Test -{ - /// - /// Class for testing InlineResponse200 - /// - /// - /// This file is automatically generated by Swagger Codegen. - /// Please update the test case below to test the model. - /// - [TestFixture] - public class InlineResponse200Tests - { - private InlineResponse200 instance; - - /// - /// Setup before each test - /// - [SetUp] - public void Init() - { - instance = new InlineResponse200(); - } - - /// - /// Clean up after each test - /// - [TearDown] - public void Cleanup() - { - - } - - /// - /// Test an instance of InlineResponse200 - /// - [Test] - public void InlineResponse200InstanceTest() - { - Assert.IsInstanceOf (instance, "instance is a InlineResponse200"); - } - - /// - /// Test the property 'PhotoUrls' - /// - [Test] - public void PhotoUrlsTest() - { - // TODO: unit test for the property 'PhotoUrls' - } - /// - /// Test the property 'Name' - /// - [Test] - public void NameTest() - { - // TODO: unit test for the property 'Name' - } - /// - /// Test the property 'Id' - /// - [Test] - public void IdTest() - { - // TODO: unit test for the property 'Id' - } - /// - /// Test the property 'Category' - /// - [Test] - public void CategoryTest() - { - // TODO: unit test for the property 'Category' - } - /// - /// Test the property 'Tags' - /// - [Test] - public void TagsTest() - { - // TODO: unit test for the property 'Tags' - } - /// - /// Test the property 'Status' - /// - [Test] - public void StatusTest() - { - // TODO: unit test for the property 'Status' - } - - } - -} diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/README.mustache b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/README.mustache deleted file mode 100644 index d5f5ce413b3..00000000000 --- a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/README.mustache +++ /dev/null @@ -1,184 +0,0 @@ - - the C# library for the Swagger Petstore - - This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters - -This SDK is automatically generated by the [Swagger Codegen](https://github.com/swagger-api/swagger-codegen) project: - -- API version: 1.0.0 -- Package version: -- Build date: 2016-04-14T06:55:47.468-04:00 -- Build package: class io.swagger.codegen.languages.CSharpClientCodegen - -## Frameworks supported -- .NET 4.0 or later -- Windows Phone 7.1 (Mango) - -## Dependencies -- [RestSharp] (https://www.nuget.org/packages/RestSharp) - 105.1.0 or later -- [Json.NET] (https://www.nuget.org/packages/Newtonsoft.Json/) - 7.0.0 or later - -The DLLs included in the package may not be the latest version. We recommned using [NuGet] (https://docs.nuget.org/consume/installing-nuget) to obtain the latest version of the packages: -``` -Install-Package RestSharp -Install-Package Newtonsoft.Json -``` - -NOTE: RestSharp versions greater than 105.1.0 have a bug which causes file uploads to fail. See [RestSharp#742](https://github.com/restsharp/RestSharp/issues/742) - -## Installation -Run the following command to generate the DLL -- [Mac/Linux] compile-mono.sh -- [Windows] compile.bat - -Then include the DLL (under the `bin` folder) in the C# project - - -```csharp -using System; -using System.Diagnostics; -using IO.Swagger.Api; -using IO.Swagger.Client; -using IO.Swagger.Module; - -namespace Example -{ -public class Example -{ -public void main(){ - - // Configure OAuth2 access token for authorization: petstore_auth - Configuration.Default.AccessToken = 'YOUR_ACCESS_TOKEN'; - // Configure API key authorization: test_api_client_id - Configuration.Default.ApiKey.Add('x-test_api_client_id', 'YOUR_API_KEY'); - // Uncomment below to setup prefix (e.g. BEARER) for API key, if needed - // Configuration.Default.ApiKeyPrefix.Add('x-test_api_client_id', 'BEARER'); - // Configure API key authorization: test_api_client_secret - Configuration.Default.ApiKey.Add('x-test_api_client_secret', 'YOUR_API_KEY'); - // Uncomment below to setup prefix (e.g. BEARER) for API key, if needed - // Configuration.Default.ApiKeyPrefix.Add('x-test_api_client_secret', 'BEARER'); - // Configure API key authorization: api_key - Configuration.Default.ApiKey.Add('api_key', 'YOUR_API_KEY'); - // Uncomment below to setup prefix (e.g. BEARER) for API key, if needed - // Configuration.Default.ApiKeyPrefix.Add('api_key', 'BEARER'); - // Configure HTTP basic authorization: test_http_basic - Configuration.Default.Username = 'YOUR_USERNAME'; - Configuration.Default.Password = 'YOUR_PASSWORD'; - // Configure API key authorization: test_api_key_query - Configuration.Default.ApiKey.Add('test_api_key_query', 'YOUR_API_KEY'); - // Uncomment below to setup prefix (e.g. BEARER) for API key, if needed - // Configuration.Default.ApiKeyPrefix.Add('test_api_key_query', 'BEARER'); - // Configure API key authorization: test_api_key_header - Configuration.Default.ApiKey.Add('test_api_key_header', 'YOUR_API_KEY'); - // Uncomment below to setup prefix (e.g. BEARER) for API key, if needed - // Configuration.Default.ApiKeyPrefix.Add('test_api_key_header', 'BEARER'); - -var apiInstance = new (); - -try { -apiInstance.(); -} catch (Exception e) { -Debug.Print("Exception when calling .: " + e.Message ); -} -} -} -} -``` - -## Documentation for API Endpoints - -All URIs are relative to *http://petstore.swagger.io/v2* - -Class | Method | HTTP request | Description ------------- | ------------- | ------------- | ------------- -*::PetApi* | [**AddPet**](docs/PetApi.md#AddPet) | **POST** /pet | Add a new pet to the store -*::PetApi* | [**AddPetUsingByteArray**](docs/PetApi.md#AddPetUsingByteArray) | **POST** /pet?testing_byte_array=true | Fake endpoint to test byte array in body parameter for adding a new pet to the store -*::PetApi* | [**DeletePet**](docs/PetApi.md#DeletePet) | **DELETE** /pet/{petId} | Deletes a pet -*::PetApi* | [**FindPetsByStatus**](docs/PetApi.md#FindPetsByStatus) | **GET** /pet/findByStatus | Finds Pets by status -*::PetApi* | [**FindPetsByTags**](docs/PetApi.md#FindPetsByTags) | **GET** /pet/findByTags | Finds Pets by tags -*::PetApi* | [**GetPetById**](docs/PetApi.md#GetPetById) | **GET** /pet/{petId} | Find pet by ID -*::PetApi* | [**GetPetByIdInObject**](docs/PetApi.md#GetPetByIdInObject) | **GET** /pet/{petId}?response=inline_arbitrary_object | Fake endpoint to test inline arbitrary object return by 'Find pet by ID' -*::PetApi* | [**PetPetIdtestingByteArraytrueGet**](docs/PetApi.md#PetPetIdtestingByteArraytrueGet) | **GET** /pet/{petId}?testing_byte_array=true | Fake endpoint to test byte array return by 'Find pet by ID' -*::PetApi* | [**UpdatePet**](docs/PetApi.md#UpdatePet) | **PUT** /pet | Update an existing pet -*::PetApi* | [**UpdatePetWithForm**](docs/PetApi.md#UpdatePetWithForm) | **POST** /pet/{petId} | Updates a pet in the store with form data -*::PetApi* | [**UploadFile**](docs/PetApi.md#UploadFile) | **POST** /pet/{petId}/uploadImage | uploads an image -*::StoreApi* | [**DeleteOrder**](docs/StoreApi.md#DeleteOrder) | **DELETE** /store/order/{orderId} | Delete purchase order by ID -*::StoreApi* | [**FindOrdersByStatus**](docs/StoreApi.md#FindOrdersByStatus) | **GET** /store/findByStatus | Finds orders by status -*::StoreApi* | [**GetInventory**](docs/StoreApi.md#GetInventory) | **GET** /store/inventory | Returns pet inventories by status -*::StoreApi* | [**GetInventoryInObject**](docs/StoreApi.md#GetInventoryInObject) | **GET** /store/inventory?response=arbitrary_object | Fake endpoint to test arbitrary object return by 'Get inventory' -*::StoreApi* | [**GetOrderById**](docs/StoreApi.md#GetOrderById) | **GET** /store/order/{orderId} | Find purchase order by ID -*::StoreApi* | [**PlaceOrder**](docs/StoreApi.md#PlaceOrder) | **POST** /store/order | Place an order for a pet -*::UserApi* | [**CreateUser**](docs/UserApi.md#CreateUser) | **POST** /user | Create user -*::UserApi* | [**CreateUsersWithArrayInput**](docs/UserApi.md#CreateUsersWithArrayInput) | **POST** /user/createWithArray | Creates list of users with given input array -*::UserApi* | [**CreateUsersWithListInput**](docs/UserApi.md#CreateUsersWithListInput) | **POST** /user/createWithList | Creates list of users with given input array -*::UserApi* | [**DeleteUser**](docs/UserApi.md#DeleteUser) | **DELETE** /user/{username} | Delete user -*::UserApi* | [**GetUserByName**](docs/UserApi.md#GetUserByName) | **GET** /user/{username} | Get user by user name -*::UserApi* | [**LoginUser**](docs/UserApi.md#LoginUser) | **GET** /user/login | Logs user into the system -*::UserApi* | [**LogoutUser**](docs/UserApi.md#LogoutUser) | **GET** /user/logout | Logs out current logged in user session -*::UserApi* | [**UpdateUser**](docs/UserApi.md#UpdateUser) | **PUT** /user/{username} | Updated user - - -## Documentation for Models - - - [::Animal](docs/Animal.md) - - [::Cat](docs/Cat.md) - - [::Category](docs/Category.md) - - [::Dog](docs/Dog.md) - - [::FormatTest](docs/FormatTest.md) - - [::InlineResponse200](docs/InlineResponse200.md) - - [::Model200Response](docs/Model200Response.md) - - [::ModelReturn](docs/ModelReturn.md) - - [::Name](docs/Name.md) - - [::Order](docs/Order.md) - - [::Pet](docs/Pet.md) - - [::SpecialModelName](docs/SpecialModelName.md) - - [::Tag](docs/Tag.md) - - [::User](docs/User.md) - - -## Documentation for Authorization - - -### petstore_auth - -- **Type**: OAuth -- **Flow**: implicit -- **Authorization URL**: http://petstore.swagger.io/api/oauth/dialog -- **Scopes**: - - write:pets: modify pets in your account - - read:pets: read your pets - -### test_api_client_id - -- **Type**: API key -- **API key parameter name**: x-test_api_client_id -- **Location**: HTTP header - -### test_api_client_secret - -- **Type**: API key -- **API key parameter name**: x-test_api_client_secret -- **Location**: HTTP header - -### api_key - -- **Type**: API key -- **API key parameter name**: api_key -- **Location**: HTTP header - -### test_http_basic - -- **Type**: HTTP basic authentication - -### test_api_key_query - -- **Type**: API key -- **API key parameter name**: test_api_key_query -- **Location**: URL query string - -### test_api_key_header - -- **Type**: API key -- **API key parameter name**: test_api_key_header -- **Location**: HTTP header - - diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/bin/Newtonsoft.Json.dll b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/bin/Newtonsoft.Json.dll deleted file mode 100644 index 4d42dd9c5fe..00000000000 Binary files a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/bin/Newtonsoft.Json.dll and /dev/null differ diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/bin/RestSharp.dll b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/bin/RestSharp.dll deleted file mode 100644 index 59d82f94198..00000000000 Binary files a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/bin/RestSharp.dll and /dev/null differ diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/compile.bat b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/compile.bat deleted file mode 100644 index 8d07d021131..00000000000 --- a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/compile.bat +++ /dev/null @@ -1,14 +0,0 @@ -@echo off - -SET CSCPATH=%SYSTEMROOT%\Microsoft.NET\Framework\v4.0.30319 - - -if not exist ".\nuget.exe" powershell -Command "(new-object System.Net.WebClient).DownloadFile('https://nuget.org/nuget.exe', '.\nuget.exe')" -.\nuget.exe install vendor/packages.config -o vendor - -if not exist ".\bin" mkdir bin - -copy vendor\Newtonsoft.Json.8.0.2\lib\net45\Newtonsoft.Json.dll bin\Newtonsoft.Json.dll -copy vendor\RestSharp.105.1.0\lib\net45\RestSharp.dll bin\RestSharp.dll - -%CSCPATH%\csc /reference:bin\Newtonsoft.Json.dll;bin\RestSharp.dll /target:library /out:bin\IO.Swagger.dll /recurse:src\*.cs /doc:bin\IO.Swagger.xml diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/docs/InlineResponse200.md b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/docs/InlineResponse200.md deleted file mode 100644 index 6380096b06b..00000000000 --- a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/docs/InlineResponse200.md +++ /dev/null @@ -1,14 +0,0 @@ -# InlineResponse200 - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**PhotoUrls** | **List<string>** | | [optional] -**Name** | **string** | | [optional] -**Id** | **long?** | | -**Category** | **Object** | | [optional] -**Tags** | [**List<Tag>**](Tag.md) | | [optional] -**Status** | **string** | pet status in the store | [optional] - - diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/petstore b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/petstore deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/InlineResponse200.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/InlineResponse200.cs deleted file mode 100644 index 32d3db25e58..00000000000 --- a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/InlineResponse200.cs +++ /dev/null @@ -1,235 +0,0 @@ -using System; -using System.Linq; -using System.IO; -using System.Text; -using System.Collections; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.ComponentModel; -using System.Runtime.Serialization; -using Newtonsoft.Json; -using Newtonsoft.Json.Converters; - -namespace IO.Swagger.Model -{ - /// - /// InlineResponse200 - /// - [DataContract] - public partial class InlineResponse200 : IEquatable - { - /// - /// pet status in the store - /// - /// pet status in the store - [JsonConverter(typeof(StringEnumConverter))] - public enum StatusEnum - { - - /// - /// Enum Available for "available" - /// - [EnumMember(Value = "available")] - Available, - - /// - /// Enum Pending for "pending" - /// - [EnumMember(Value = "pending")] - Pending, - - /// - /// Enum Sold for "sold" - /// - [EnumMember(Value = "sold")] - Sold - } - - - /// - /// pet status in the store - /// - /// pet status in the store - [DataMember(Name="status", EmitDefaultValue=false)] - public StatusEnum? Status { get; set; } - - /// - /// Initializes a new instance of the class. - /// Initializes a new instance of the class. - /// - /// Tags. - /// Id (required). - /// Category. - /// pet status in the store. - /// Name. - /// PhotoUrls. - - public InlineResponse200(List Tags = null, long? Id = null, Object Category = null, StatusEnum? Status = null, string Name = null, List PhotoUrls = null) - { - // to ensure "Id" is required (not null) - if (Id == null) - { - throw new InvalidDataException("Id is a required property for InlineResponse200 and cannot be null"); - } - else - { - this.Id = Id; - } - this.Tags = Tags; - this.Category = Category; - this.Status = Status; - this.Name = Name; - this.PhotoUrls = PhotoUrls; - - } - - - /// - /// Gets or Sets Tags - /// - [DataMember(Name="tags", EmitDefaultValue=false)] - public List Tags { get; set; } - - /// - /// Gets or Sets Id - /// - [DataMember(Name="id", EmitDefaultValue=false)] - public long? Id { get; set; } - - /// - /// Gets or Sets Category - /// - [DataMember(Name="category", EmitDefaultValue=false)] - public Object Category { get; set; } - - /// - /// Gets or Sets Name - /// - [DataMember(Name="name", EmitDefaultValue=false)] - public string Name { get; set; } - - /// - /// Gets or Sets PhotoUrls - /// - [DataMember(Name="photoUrls", EmitDefaultValue=false)] - public List PhotoUrls { get; set; } - - /// - /// Returns the string presentation of the object - /// - /// String presentation of the object - public override string ToString() - { - var sb = new StringBuilder(); - sb.Append("class InlineResponse200 {\n"); - sb.Append(" Tags: ").Append(Tags).Append("\n"); - sb.Append(" Id: ").Append(Id).Append("\n"); - sb.Append(" Category: ").Append(Category).Append("\n"); - sb.Append(" Status: ").Append(Status).Append("\n"); - sb.Append(" Name: ").Append(Name).Append("\n"); - sb.Append(" PhotoUrls: ").Append(PhotoUrls).Append("\n"); - - sb.Append("}\n"); - return sb.ToString(); - } - - /// - /// Returns the JSON string presentation of the object - /// - /// JSON string presentation of the object - public string ToJson() - { - return JsonConvert.SerializeObject(this, Formatting.Indented); - } - - /// - /// Returns true if objects are equal - /// - /// Object to be compared - /// Boolean - public override bool Equals(object obj) - { - // credit: http://stackoverflow.com/a/10454552/677735 - return this.Equals(obj as InlineResponse200); - } - - /// - /// Returns true if InlineResponse200 instances are equal - /// - /// Instance of InlineResponse200 to be compared - /// Boolean - public bool Equals(InlineResponse200 other) - { - // credit: http://stackoverflow.com/a/10454552/677735 - if (other == null) - return false; - - return - ( - this.Tags == other.Tags || - this.Tags != null && - this.Tags.SequenceEqual(other.Tags) - ) && - ( - this.Id == other.Id || - this.Id != null && - this.Id.Equals(other.Id) - ) && - ( - this.Category == other.Category || - this.Category != null && - this.Category.Equals(other.Category) - ) && - ( - this.Status == other.Status || - this.Status != null && - this.Status.Equals(other.Status) - ) && - ( - this.Name == other.Name || - this.Name != null && - this.Name.Equals(other.Name) - ) && - ( - this.PhotoUrls == other.PhotoUrls || - this.PhotoUrls != null && - this.PhotoUrls.SequenceEqual(other.PhotoUrls) - ); - } - - /// - /// Gets the hash code - /// - /// Hash code - public override int GetHashCode() - { - // credit: http://stackoverflow.com/a/263416/677735 - unchecked // Overflow is fine, just wrap - { - int hash = 41; - // Suitable nullity checks etc, of course :) - - if (this.Tags != null) - hash = hash * 59 + this.Tags.GetHashCode(); - - if (this.Id != null) - hash = hash * 59 + this.Id.GetHashCode(); - - if (this.Category != null) - hash = hash * 59 + this.Category.GetHashCode(); - - if (this.Status != null) - hash = hash * 59 + this.Status.GetHashCode(); - - if (this.Name != null) - hash = hash * 59 + this.Name.GetHashCode(); - - if (this.PhotoUrls != null) - hash = hash * 59 + this.PhotoUrls.GetHashCode(); - - return hash; - } - } - } - -} diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/ObjectReturn.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/ObjectReturn.cs deleted file mode 100644 index 1ea3dea45c5..00000000000 --- a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/ObjectReturn.cs +++ /dev/null @@ -1,113 +0,0 @@ -using System; -using System.Linq; -using System.IO; -using System.Text; -using System.Collections; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Runtime.Serialization; -using Newtonsoft.Json; -using Newtonsoft.Json.Converters; - -namespace IO.Swagger.Model -{ - /// - /// - /// - [DataContract] - public partial class ObjectReturn : IEquatable - { - - /// - /// Initializes a new instance of the class. - /// Initializes a new instance of the class. - /// - /// _Return. - - public ObjectReturn(int? _Return = null) - { - this._Return = _Return; - - } - - - /// - /// Gets or Sets _Return - /// - [DataMember(Name="return", EmitDefaultValue=false)] - public int? _Return { get; set; } - - /// - /// Returns the string presentation of the object - /// - /// String presentation of the object - public override string ToString() - { - var sb = new StringBuilder(); - sb.Append("class ObjectReturn {\n"); - sb.Append(" _Return: ").Append(_Return).Append("\n"); - - sb.Append("}\n"); - return sb.ToString(); - } - - /// - /// Returns the JSON string presentation of the object - /// - /// JSON string presentation of the object - public string ToJson() - { - return JsonConvert.SerializeObject(this, Formatting.Indented); - } - - /// - /// Returns true if objects are equal - /// - /// Object to be compared - /// Boolean - public override bool Equals(object obj) - { - // credit: http://stackoverflow.com/a/10454552/677735 - return this.Equals(obj as ObjectReturn); - } - - /// - /// Returns true if ObjectReturn instances are equal - /// - /// Instance of ObjectReturn to be compared - /// Boolean - public bool Equals(ObjectReturn other) - { - // credit: http://stackoverflow.com/a/10454552/677735 - if (other == null) - return false; - - return - ( - this._Return == other._Return || - this._Return != null && - this._Return.Equals(other._Return) - ); - } - - /// - /// Gets the hash code - /// - /// Hash code - public override int GetHashCode() - { - // credit: http://stackoverflow.com/a/263416/677735 - unchecked // Overflow is fine, just wrap - { - int hash = 41; - // Suitable nullity checks etc, of course :) - - if (this._Return != null) - hash = hash * 59 + this._Return.GetHashCode(); - - return hash; - } - } - - } -} diff --git a/samples/client/petstore/csharp/SwaggerClientTest/SwaggerClientTest.csproj b/samples/client/petstore/csharp/SwaggerClientTest/SwaggerClientTest.csproj index 389c142e1bd..c7be212db66 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/SwaggerClientTest.csproj +++ b/samples/client/petstore/csharp/SwaggerClientTest/SwaggerClientTest.csproj @@ -30,7 +30,10 @@ - Lib\SwaggerClient\bin\Newtonsoft.Json.dll + packages\Newtonsoft.Json.8.0.2\lib\net45\Newtonsoft.Json.dll + + + packages\RestSharp.105.1.0\lib\net45\RestSharp.dll @@ -38,56 +41,31 @@ packages\NUnit.2.6.4\lib\nunit.framework.dll - - Lib\SwaggerClient\bin\RestSharp.dll - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + - - + - \ No newline at end of file + + + {0862164F-97E9-4226-B458-E09905B21F2F} + IO.Swagger + + + diff --git a/samples/client/petstore/csharp/SwaggerClientTest/SwaggerClientTest.sln b/samples/client/petstore/csharp/SwaggerClientTest/SwaggerClientTest.sln index dfb6e762ce2..5274859c30a 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/SwaggerClientTest.sln +++ b/samples/client/petstore/csharp/SwaggerClientTest/SwaggerClientTest.sln @@ -3,12 +3,18 @@ Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 2012 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SwaggerClientTest", "SwaggerClientTest.csproj", "{1011E844-3414-4D65-BF1F-7C8CE0167174}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IO.Swagger", "..\SwaggerClient\src\IO.Swagger\IO.Swagger.csproj", "{0862164F-97E9-4226-B458-E09905B21F2F}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution + {0862164F-97E9-4226-B458-E09905B21F2F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {0862164F-97E9-4226-B458-E09905B21F2F}.Debug|Any CPU.Build.0 = Debug|Any CPU + {0862164F-97E9-4226-B458-E09905B21F2F}.Release|Any CPU.ActiveCfg = Release|Any CPU + {0862164F-97E9-4226-B458-E09905B21F2F}.Release|Any CPU.Build.0 = Release|Any CPU {1011E844-3414-4D65-BF1F-7C8CE0167174}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {1011E844-3414-4D65-BF1F-7C8CE0167174}.Debug|Any CPU.Build.0 = Debug|Any CPU {1011E844-3414-4D65-BF1F-7C8CE0167174}.Release|Any CPU.ActiveCfg = Release|Any CPU diff --git a/samples/client/petstore/csharp/SwaggerClientTest/SwaggerClientTest.userprefs b/samples/client/petstore/csharp/SwaggerClientTest/SwaggerClientTest.userprefs index eb976117be8..b87503528b6 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/SwaggerClientTest.userprefs +++ b/samples/client/petstore/csharp/SwaggerClientTest/SwaggerClientTest.userprefs @@ -1,11 +1,11 @@  - + - - - - + + + + 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 new file mode 100644 index 00000000000..fe5b5e6a930 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.csproj.FilesWrittenAbsolute.txt @@ -0,0 +1,11 @@ +/Users/williamcheng/Code/swagger-api/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/.NETFramework,Version=v4.5.AssemblyAttribute.cs +/Users/williamcheng/Code/swagger-api/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.swagger-logo.png +/Users/williamcheng/Code/swagger-api/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/SwaggerClientTest.dll.mdb +/Users/williamcheng/Code/swagger-api/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/SwaggerClientTest.dll +/Users/williamcheng/Code/swagger-api/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.dll +/Users/williamcheng/Code/swagger-api/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.dll.mdb +/Users/williamcheng/Code/swagger-api/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/Newtonsoft.Json.dll +/Users/williamcheng/Code/swagger-api/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/RestSharp.dll +/Users/williamcheng/Code/swagger-api/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/nunit.framework.dll +/Users/williamcheng/Code/swagger-api/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/Swagger Library.dll +/Users/williamcheng/Code/swagger-api/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/Swagger Library.dll.mdb diff --git a/samples/client/petstore/csharp/SwaggerClientTest/packages.config b/samples/client/petstore/csharp/SwaggerClientTest/packages.config index 09300da2fcd..0a536655794 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/packages.config +++ b/samples/client/petstore/csharp/SwaggerClientTest/packages.config @@ -1,4 +1,6 @@  + + \ No newline at end of file diff --git a/samples/client/petstore/csharp/SwaggerClientTest/packages/repositories.config b/samples/client/petstore/csharp/SwaggerClientTest/packages/repositories.config index ba8d0d576a8..c109c8ad2e5 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/packages/repositories.config +++ b/samples/client/petstore/csharp/SwaggerClientTest/packages/repositories.config @@ -1,4 +1,5 @@ - - - + + + + \ No newline at end of file diff --git a/samples/client/petstore/go/go-petstore/README.md b/samples/client/petstore/go/go-petstore/README.md index 9130ec599b6..9f725fb007b 100644 --- a/samples/client/petstore/go/go-petstore/README.md +++ b/samples/client/petstore/go/go-petstore/README.md @@ -7,7 +7,7 @@ This API client was generated by the [swagger-codegen](https://github.com/swagge - API version: 1.0.0 - Package version: 1.0.0 -- Build date: 2016-05-02T15:51:26.331+01:00 +- Build date: 2016-05-03T10:14:09.589-07:00 - Build package: class io.swagger.codegen.languages.GoClientCodegen ## Installation diff --git a/samples/client/petstore/go/go-petstore/pet_api.go b/samples/client/petstore/go/go-petstore/pet_api.go index 0e252159fd0..f70ceaa65f0 100644 --- a/samples/client/petstore/go/go-petstore/pet_api.go +++ b/samples/client/petstore/go/go-petstore/pet_api.go @@ -36,7 +36,7 @@ func NewPetApiWithBasePath(basePath string) *PetApi { * @param body Pet object that needs to be added to the store * @return void */ -func (a PetApi) AddPet(body Pet) (APIResponse, error) { +func (a PetApi) AddPet(body Pet) (*APIResponse, error) { var httpMethod = "Post" // create path and map variables @@ -44,7 +44,7 @@ func (a PetApi) AddPet(body Pet) (APIResponse, error) { // verify the required parameter 'body' is set if &body == nil { - return *NewAPIResponseWithError("400 - Bad Request"), errors.New("Missing required parameter 'body' when calling PetApi->AddPet") + return nil, errors.New("Missing required parameter 'body' when calling PetApi->AddPet") } headerParams := make(map[string]string) @@ -89,10 +89,10 @@ func (a PetApi) AddPet(body Pet) (APIResponse, error) { httpResponse, err := a.Configuration.APIClient.CallAPI(path, httpMethod, postBody, headerParams, queryParams, formParams, fileName, fileBytes) if err != nil { - return *NewAPIResponse(httpResponse.RawResponse), err + return NewAPIResponse(httpResponse.RawResponse), err } - return *NewAPIResponse(httpResponse.RawResponse), err + return NewAPIResponse(httpResponse.RawResponse), err } /** @@ -103,7 +103,7 @@ func (a PetApi) AddPet(body Pet) (APIResponse, error) { * @param apiKey * @return void */ -func (a PetApi) DeletePet(petId int64, apiKey string) (APIResponse, error) { +func (a PetApi) DeletePet(petId int64, apiKey string) (*APIResponse, error) { var httpMethod = "Delete" // create path and map variables @@ -112,7 +112,7 @@ func (a PetApi) DeletePet(petId int64, apiKey string) (APIResponse, error) { // verify the required parameter 'petId' is set if &petId == nil { - return *NewAPIResponseWithError("400 - Bad Request"), errors.New("Missing required parameter 'petId' when calling PetApi->DeletePet") + return nil, errors.New("Missing required parameter 'petId' when calling PetApi->DeletePet") } headerParams := make(map[string]string) @@ -158,10 +158,10 @@ func (a PetApi) DeletePet(petId int64, apiKey string) (APIResponse, error) { httpResponse, err := a.Configuration.APIClient.CallAPI(path, httpMethod, postBody, headerParams, queryParams, formParams, fileName, fileBytes) if err != nil { - return *NewAPIResponse(httpResponse.RawResponse), err + return NewAPIResponse(httpResponse.RawResponse), err } - return *NewAPIResponse(httpResponse.RawResponse), err + return NewAPIResponse(httpResponse.RawResponse), err } /** @@ -171,7 +171,7 @@ func (a PetApi) DeletePet(petId int64, apiKey string) (APIResponse, error) { * @param status Status values that need to be considered for filter * @return []Pet */ -func (a PetApi) FindPetsByStatus(status []string) ([]Pet, APIResponse, error) { +func (a PetApi) FindPetsByStatus(status []string) ([]Pet, *APIResponse, error) { var httpMethod = "Get" // create path and map variables @@ -179,7 +179,7 @@ func (a PetApi) FindPetsByStatus(status []string) ([]Pet, APIResponse, error) { // verify the required parameter 'status' is set if &status == nil { - return *new([]Pet), *NewAPIResponseWithError("400 - Bad Request"), errors.New("Missing required parameter 'status' when calling PetApi->FindPetsByStatus") + return *new([]Pet), nil, errors.New("Missing required parameter 'status' when calling PetApi->FindPetsByStatus") } headerParams := make(map[string]string) @@ -224,10 +224,10 @@ func (a PetApi) FindPetsByStatus(status []string) ([]Pet, APIResponse, error) { var successPayload = new([]Pet) httpResponse, err := a.Configuration.APIClient.CallAPI(path, httpMethod, postBody, headerParams, queryParams, formParams, fileName, fileBytes) if err != nil { - return *successPayload, *NewAPIResponse(httpResponse.RawResponse), err + return *successPayload, NewAPIResponse(httpResponse.RawResponse), err } err = json.Unmarshal(httpResponse.Body(), &successPayload) - return *successPayload, *NewAPIResponse(httpResponse.RawResponse), err + return *successPayload, NewAPIResponse(httpResponse.RawResponse), err } /** @@ -237,7 +237,7 @@ func (a PetApi) FindPetsByStatus(status []string) ([]Pet, APIResponse, error) { * @param tags Tags to filter by * @return []Pet */ -func (a PetApi) FindPetsByTags(tags []string) ([]Pet, APIResponse, error) { +func (a PetApi) FindPetsByTags(tags []string) ([]Pet, *APIResponse, error) { var httpMethod = "Get" // create path and map variables @@ -245,7 +245,7 @@ func (a PetApi) FindPetsByTags(tags []string) ([]Pet, APIResponse, error) { // verify the required parameter 'tags' is set if &tags == nil { - return *new([]Pet), *NewAPIResponseWithError("400 - Bad Request"), errors.New("Missing required parameter 'tags' when calling PetApi->FindPetsByTags") + return *new([]Pet), nil, errors.New("Missing required parameter 'tags' when calling PetApi->FindPetsByTags") } headerParams := make(map[string]string) @@ -290,10 +290,10 @@ func (a PetApi) FindPetsByTags(tags []string) ([]Pet, APIResponse, error) { var successPayload = new([]Pet) httpResponse, err := a.Configuration.APIClient.CallAPI(path, httpMethod, postBody, headerParams, queryParams, formParams, fileName, fileBytes) if err != nil { - return *successPayload, *NewAPIResponse(httpResponse.RawResponse), err + return *successPayload, NewAPIResponse(httpResponse.RawResponse), err } err = json.Unmarshal(httpResponse.Body(), &successPayload) - return *successPayload, *NewAPIResponse(httpResponse.RawResponse), err + return *successPayload, NewAPIResponse(httpResponse.RawResponse), err } /** @@ -301,9 +301,9 @@ func (a PetApi) FindPetsByTags(tags []string) ([]Pet, APIResponse, error) { * Returns a single pet * * @param petId ID of pet to return - * @return Pet + * @return *Pet */ -func (a PetApi) GetPetById(petId int64) (Pet, APIResponse, error) { +func (a PetApi) GetPetById(petId int64) (*Pet, *APIResponse, error) { var httpMethod = "Get" // create path and map variables @@ -312,7 +312,7 @@ func (a PetApi) GetPetById(petId int64) (Pet, APIResponse, error) { // verify the required parameter 'petId' is set if &petId == nil { - return *new(Pet), *NewAPIResponseWithError("400 - Bad Request"), errors.New("Missing required parameter 'petId' when calling PetApi->GetPetById") + return new(Pet), nil, errors.New("Missing required parameter 'petId' when calling PetApi->GetPetById") } headerParams := make(map[string]string) @@ -353,10 +353,10 @@ func (a PetApi) GetPetById(petId int64) (Pet, APIResponse, error) { var successPayload = new(Pet) httpResponse, err := a.Configuration.APIClient.CallAPI(path, httpMethod, postBody, headerParams, queryParams, formParams, fileName, fileBytes) if err != nil { - return *successPayload, *NewAPIResponse(httpResponse.RawResponse), err + return successPayload, NewAPIResponse(httpResponse.RawResponse), err } err = json.Unmarshal(httpResponse.Body(), &successPayload) - return *successPayload, *NewAPIResponse(httpResponse.RawResponse), err + return successPayload, NewAPIResponse(httpResponse.RawResponse), err } /** @@ -366,7 +366,7 @@ func (a PetApi) GetPetById(petId int64) (Pet, APIResponse, error) { * @param body Pet object that needs to be added to the store * @return void */ -func (a PetApi) UpdatePet(body Pet) (APIResponse, error) { +func (a PetApi) UpdatePet(body Pet) (*APIResponse, error) { var httpMethod = "Put" // create path and map variables @@ -374,7 +374,7 @@ func (a PetApi) UpdatePet(body Pet) (APIResponse, error) { // verify the required parameter 'body' is set if &body == nil { - return *NewAPIResponseWithError("400 - Bad Request"), errors.New("Missing required parameter 'body' when calling PetApi->UpdatePet") + return nil, errors.New("Missing required parameter 'body' when calling PetApi->UpdatePet") } headerParams := make(map[string]string) @@ -419,10 +419,10 @@ func (a PetApi) UpdatePet(body Pet) (APIResponse, error) { httpResponse, err := a.Configuration.APIClient.CallAPI(path, httpMethod, postBody, headerParams, queryParams, formParams, fileName, fileBytes) if err != nil { - return *NewAPIResponse(httpResponse.RawResponse), err + return NewAPIResponse(httpResponse.RawResponse), err } - return *NewAPIResponse(httpResponse.RawResponse), err + return NewAPIResponse(httpResponse.RawResponse), err } /** @@ -434,7 +434,7 @@ func (a PetApi) UpdatePet(body Pet) (APIResponse, error) { * @param status Updated status of the pet * @return void */ -func (a PetApi) UpdatePetWithForm(petId int64, name string, status string) (APIResponse, error) { +func (a PetApi) UpdatePetWithForm(petId int64, name string, status string) (*APIResponse, error) { var httpMethod = "Post" // create path and map variables @@ -443,7 +443,7 @@ func (a PetApi) UpdatePetWithForm(petId int64, name string, status string) (APIR // verify the required parameter 'petId' is set if &petId == nil { - return *NewAPIResponseWithError("400 - Bad Request"), errors.New("Missing required parameter 'petId' when calling PetApi->UpdatePetWithForm") + return nil, errors.New("Missing required parameter 'petId' when calling PetApi->UpdatePetWithForm") } headerParams := make(map[string]string) @@ -488,10 +488,10 @@ func (a PetApi) UpdatePetWithForm(petId int64, name string, status string) (APIR httpResponse, err := a.Configuration.APIClient.CallAPI(path, httpMethod, postBody, headerParams, queryParams, formParams, fileName, fileBytes) if err != nil { - return *NewAPIResponse(httpResponse.RawResponse), err + return NewAPIResponse(httpResponse.RawResponse), err } - return *NewAPIResponse(httpResponse.RawResponse), err + return NewAPIResponse(httpResponse.RawResponse), err } /** @@ -501,9 +501,9 @@ func (a PetApi) UpdatePetWithForm(petId int64, name string, status string) (APIR * @param petId ID of pet to update * @param additionalMetadata Additional data to pass to server * @param file file to upload - * @return ModelApiResponse + * @return *ModelApiResponse */ -func (a PetApi) UploadFile(petId int64, additionalMetadata string, file *os.File) (ModelApiResponse, APIResponse, error) { +func (a PetApi) UploadFile(petId int64, additionalMetadata string, file *os.File) (*ModelApiResponse, *APIResponse, error) { var httpMethod = "Post" // create path and map variables @@ -512,7 +512,7 @@ func (a PetApi) UploadFile(petId int64, additionalMetadata string, file *os.File // verify the required parameter 'petId' is set if &petId == nil { - return *new(ModelApiResponse), *NewAPIResponseWithError("400 - Bad Request"), errors.New("Missing required parameter 'petId' when calling PetApi->UploadFile") + return new(ModelApiResponse), nil, errors.New("Missing required parameter 'petId' when calling PetApi->UploadFile") } headerParams := make(map[string]string) @@ -559,9 +559,9 @@ func (a PetApi) UploadFile(petId int64, additionalMetadata string, file *os.File var successPayload = new(ModelApiResponse) httpResponse, err := a.Configuration.APIClient.CallAPI(path, httpMethod, postBody, headerParams, queryParams, formParams, fileName, fileBytes) if err != nil { - return *successPayload, *NewAPIResponse(httpResponse.RawResponse), err + return successPayload, NewAPIResponse(httpResponse.RawResponse), err } err = json.Unmarshal(httpResponse.Body(), &successPayload) - return *successPayload, *NewAPIResponse(httpResponse.RawResponse), err + return successPayload, NewAPIResponse(httpResponse.RawResponse), err } diff --git a/samples/client/petstore/go/go-petstore/store_api.go b/samples/client/petstore/go/go-petstore/store_api.go index d2848305114..56af7223639 100644 --- a/samples/client/petstore/go/go-petstore/store_api.go +++ b/samples/client/petstore/go/go-petstore/store_api.go @@ -34,7 +34,7 @@ func NewStoreApiWithBasePath(basePath string) *StoreApi { * @param orderId ID of the order that needs to be deleted * @return void */ -func (a StoreApi) DeleteOrder(orderId string) (APIResponse, error) { +func (a StoreApi) DeleteOrder(orderId string) (*APIResponse, error) { var httpMethod = "Delete" // create path and map variables @@ -43,7 +43,7 @@ func (a StoreApi) DeleteOrder(orderId string) (APIResponse, error) { // verify the required parameter 'orderId' is set if &orderId == nil { - return *NewAPIResponseWithError("400 - Bad Request"), errors.New("Missing required parameter 'orderId' when calling StoreApi->DeleteOrder") + return nil, errors.New("Missing required parameter 'orderId' when calling StoreApi->DeleteOrder") } headerParams := make(map[string]string) @@ -80,19 +80,19 @@ func (a StoreApi) DeleteOrder(orderId string) (APIResponse, error) { httpResponse, err := a.Configuration.APIClient.CallAPI(path, httpMethod, postBody, headerParams, queryParams, formParams, fileName, fileBytes) if err != nil { - return *NewAPIResponse(httpResponse.RawResponse), err + return NewAPIResponse(httpResponse.RawResponse), err } - return *NewAPIResponse(httpResponse.RawResponse), err + return NewAPIResponse(httpResponse.RawResponse), err } /** * Returns pet inventories by status * Returns a map of status codes to quantities * - * @return map[string]int32 + * @return *map[string]int32 */ -func (a StoreApi) GetInventory() (map[string]int32, APIResponse, error) { +func (a StoreApi) GetInventory() (*map[string]int32, *APIResponse, error) { var httpMethod = "Get" // create path and map variables @@ -136,10 +136,10 @@ func (a StoreApi) GetInventory() (map[string]int32, APIResponse, error) { var successPayload = new(map[string]int32) httpResponse, err := a.Configuration.APIClient.CallAPI(path, httpMethod, postBody, headerParams, queryParams, formParams, fileName, fileBytes) if err != nil { - return *successPayload, *NewAPIResponse(httpResponse.RawResponse), err + return successPayload, NewAPIResponse(httpResponse.RawResponse), err } err = json.Unmarshal(httpResponse.Body(), &successPayload) - return *successPayload, *NewAPIResponse(httpResponse.RawResponse), err + return successPayload, NewAPIResponse(httpResponse.RawResponse), err } /** @@ -147,9 +147,9 @@ func (a StoreApi) GetInventory() (map[string]int32, APIResponse, error) { * 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 + * @return *Order */ -func (a StoreApi) GetOrderById(orderId int64) (Order, APIResponse, error) { +func (a StoreApi) GetOrderById(orderId int64) (*Order, *APIResponse, error) { var httpMethod = "Get" // create path and map variables @@ -158,7 +158,7 @@ func (a StoreApi) GetOrderById(orderId int64) (Order, APIResponse, error) { // verify the required parameter 'orderId' is set if &orderId == nil { - return *new(Order), *NewAPIResponseWithError("400 - Bad Request"), errors.New("Missing required parameter 'orderId' when calling StoreApi->GetOrderById") + return new(Order), nil, errors.New("Missing required parameter 'orderId' when calling StoreApi->GetOrderById") } headerParams := make(map[string]string) @@ -195,10 +195,10 @@ func (a StoreApi) GetOrderById(orderId int64) (Order, APIResponse, error) { var successPayload = new(Order) httpResponse, err := a.Configuration.APIClient.CallAPI(path, httpMethod, postBody, headerParams, queryParams, formParams, fileName, fileBytes) if err != nil { - return *successPayload, *NewAPIResponse(httpResponse.RawResponse), err + return successPayload, NewAPIResponse(httpResponse.RawResponse), err } err = json.Unmarshal(httpResponse.Body(), &successPayload) - return *successPayload, *NewAPIResponse(httpResponse.RawResponse), err + return successPayload, NewAPIResponse(httpResponse.RawResponse), err } /** @@ -206,9 +206,9 @@ func (a StoreApi) GetOrderById(orderId int64) (Order, APIResponse, error) { * * * @param body order placed for purchasing the pet - * @return Order + * @return *Order */ -func (a StoreApi) PlaceOrder(body Order) (Order, APIResponse, error) { +func (a StoreApi) PlaceOrder(body Order) (*Order, *APIResponse, error) { var httpMethod = "Post" // create path and map variables @@ -216,7 +216,7 @@ func (a StoreApi) PlaceOrder(body Order) (Order, APIResponse, error) { // verify the required parameter 'body' is set if &body == nil { - return *new(Order), *NewAPIResponseWithError("400 - Bad Request"), errors.New("Missing required parameter 'body' when calling StoreApi->PlaceOrder") + return new(Order), nil, errors.New("Missing required parameter 'body' when calling StoreApi->PlaceOrder") } headerParams := make(map[string]string) @@ -256,9 +256,9 @@ func (a StoreApi) PlaceOrder(body Order) (Order, APIResponse, error) { var successPayload = new(Order) httpResponse, err := a.Configuration.APIClient.CallAPI(path, httpMethod, postBody, headerParams, queryParams, formParams, fileName, fileBytes) if err != nil { - return *successPayload, *NewAPIResponse(httpResponse.RawResponse), err + return successPayload, NewAPIResponse(httpResponse.RawResponse), err } err = json.Unmarshal(httpResponse.Body(), &successPayload) - return *successPayload, *NewAPIResponse(httpResponse.RawResponse), err + return successPayload, NewAPIResponse(httpResponse.RawResponse), err } diff --git a/samples/client/petstore/go/go-petstore/user_api.go b/samples/client/petstore/go/go-petstore/user_api.go index ce23df39d69..1ed8b9a599a 100644 --- a/samples/client/petstore/go/go-petstore/user_api.go +++ b/samples/client/petstore/go/go-petstore/user_api.go @@ -34,7 +34,7 @@ func NewUserApiWithBasePath(basePath string) *UserApi { * @param body Created user object * @return void */ -func (a UserApi) CreateUser(body User) (APIResponse, error) { +func (a UserApi) CreateUser(body User) (*APIResponse, error) { var httpMethod = "Post" // create path and map variables @@ -42,7 +42,7 @@ func (a UserApi) CreateUser(body User) (APIResponse, error) { // verify the required parameter 'body' is set if &body == nil { - return *NewAPIResponseWithError("400 - Bad Request"), errors.New("Missing required parameter 'body' when calling UserApi->CreateUser") + return nil, errors.New("Missing required parameter 'body' when calling UserApi->CreateUser") } headerParams := make(map[string]string) @@ -82,10 +82,10 @@ func (a UserApi) CreateUser(body User) (APIResponse, error) { httpResponse, err := a.Configuration.APIClient.CallAPI(path, httpMethod, postBody, headerParams, queryParams, formParams, fileName, fileBytes) if err != nil { - return *NewAPIResponse(httpResponse.RawResponse), err + return NewAPIResponse(httpResponse.RawResponse), err } - return *NewAPIResponse(httpResponse.RawResponse), err + return NewAPIResponse(httpResponse.RawResponse), err } /** @@ -95,7 +95,7 @@ func (a UserApi) CreateUser(body User) (APIResponse, error) { * @param body List of user object * @return void */ -func (a UserApi) CreateUsersWithArrayInput(body []User) (APIResponse, error) { +func (a UserApi) CreateUsersWithArrayInput(body []User) (*APIResponse, error) { var httpMethod = "Post" // create path and map variables @@ -103,7 +103,7 @@ func (a UserApi) CreateUsersWithArrayInput(body []User) (APIResponse, error) { // verify the required parameter 'body' is set if &body == nil { - return *NewAPIResponseWithError("400 - Bad Request"), errors.New("Missing required parameter 'body' when calling UserApi->CreateUsersWithArrayInput") + return nil, errors.New("Missing required parameter 'body' when calling UserApi->CreateUsersWithArrayInput") } headerParams := make(map[string]string) @@ -143,10 +143,10 @@ func (a UserApi) CreateUsersWithArrayInput(body []User) (APIResponse, error) { httpResponse, err := a.Configuration.APIClient.CallAPI(path, httpMethod, postBody, headerParams, queryParams, formParams, fileName, fileBytes) if err != nil { - return *NewAPIResponse(httpResponse.RawResponse), err + return NewAPIResponse(httpResponse.RawResponse), err } - return *NewAPIResponse(httpResponse.RawResponse), err + return NewAPIResponse(httpResponse.RawResponse), err } /** @@ -156,7 +156,7 @@ func (a UserApi) CreateUsersWithArrayInput(body []User) (APIResponse, error) { * @param body List of user object * @return void */ -func (a UserApi) CreateUsersWithListInput(body []User) (APIResponse, error) { +func (a UserApi) CreateUsersWithListInput(body []User) (*APIResponse, error) { var httpMethod = "Post" // create path and map variables @@ -164,7 +164,7 @@ func (a UserApi) CreateUsersWithListInput(body []User) (APIResponse, error) { // verify the required parameter 'body' is set if &body == nil { - return *NewAPIResponseWithError("400 - Bad Request"), errors.New("Missing required parameter 'body' when calling UserApi->CreateUsersWithListInput") + return nil, errors.New("Missing required parameter 'body' when calling UserApi->CreateUsersWithListInput") } headerParams := make(map[string]string) @@ -204,10 +204,10 @@ func (a UserApi) CreateUsersWithListInput(body []User) (APIResponse, error) { httpResponse, err := a.Configuration.APIClient.CallAPI(path, httpMethod, postBody, headerParams, queryParams, formParams, fileName, fileBytes) if err != nil { - return *NewAPIResponse(httpResponse.RawResponse), err + return NewAPIResponse(httpResponse.RawResponse), err } - return *NewAPIResponse(httpResponse.RawResponse), err + return NewAPIResponse(httpResponse.RawResponse), err } /** @@ -217,7 +217,7 @@ func (a UserApi) CreateUsersWithListInput(body []User) (APIResponse, error) { * @param username The name that needs to be deleted * @return void */ -func (a UserApi) DeleteUser(username string) (APIResponse, error) { +func (a UserApi) DeleteUser(username string) (*APIResponse, error) { var httpMethod = "Delete" // create path and map variables @@ -226,7 +226,7 @@ func (a UserApi) DeleteUser(username string) (APIResponse, error) { // verify the required parameter 'username' is set if &username == nil { - return *NewAPIResponseWithError("400 - Bad Request"), errors.New("Missing required parameter 'username' when calling UserApi->DeleteUser") + return nil, errors.New("Missing required parameter 'username' when calling UserApi->DeleteUser") } headerParams := make(map[string]string) @@ -263,10 +263,10 @@ func (a UserApi) DeleteUser(username string) (APIResponse, error) { httpResponse, err := a.Configuration.APIClient.CallAPI(path, httpMethod, postBody, headerParams, queryParams, formParams, fileName, fileBytes) if err != nil { - return *NewAPIResponse(httpResponse.RawResponse), err + return NewAPIResponse(httpResponse.RawResponse), err } - return *NewAPIResponse(httpResponse.RawResponse), err + return NewAPIResponse(httpResponse.RawResponse), err } /** @@ -274,9 +274,9 @@ func (a UserApi) DeleteUser(username string) (APIResponse, error) { * * * @param username The name that needs to be fetched. Use user1 for testing. - * @return User + * @return *User */ -func (a UserApi) GetUserByName(username string) (User, APIResponse, error) { +func (a UserApi) GetUserByName(username string) (*User, *APIResponse, error) { var httpMethod = "Get" // create path and map variables @@ -285,7 +285,7 @@ func (a UserApi) GetUserByName(username string) (User, APIResponse, error) { // verify the required parameter 'username' is set if &username == nil { - return *new(User), *NewAPIResponseWithError("400 - Bad Request"), errors.New("Missing required parameter 'username' when calling UserApi->GetUserByName") + return new(User), nil, errors.New("Missing required parameter 'username' when calling UserApi->GetUserByName") } headerParams := make(map[string]string) @@ -322,10 +322,10 @@ func (a UserApi) GetUserByName(username string) (User, APIResponse, error) { var successPayload = new(User) httpResponse, err := a.Configuration.APIClient.CallAPI(path, httpMethod, postBody, headerParams, queryParams, formParams, fileName, fileBytes) if err != nil { - return *successPayload, *NewAPIResponse(httpResponse.RawResponse), err + return successPayload, NewAPIResponse(httpResponse.RawResponse), err } err = json.Unmarshal(httpResponse.Body(), &successPayload) - return *successPayload, *NewAPIResponse(httpResponse.RawResponse), err + return successPayload, NewAPIResponse(httpResponse.RawResponse), err } /** @@ -334,9 +334,9 @@ func (a UserApi) GetUserByName(username string) (User, APIResponse, error) { * * @param username The user name for login * @param password The password for login in clear text - * @return string + * @return *string */ -func (a UserApi) LoginUser(username string, password string) (string, APIResponse, error) { +func (a UserApi) LoginUser(username string, password string) (*string, *APIResponse, error) { var httpMethod = "Get" // create path and map variables @@ -344,11 +344,11 @@ func (a UserApi) LoginUser(username string, password string) (string, APIRespons // verify the required parameter 'username' is set if &username == nil { - return *new(string), *NewAPIResponseWithError("400 - Bad Request"), errors.New("Missing required parameter 'username' when calling UserApi->LoginUser") + return new(string), nil, errors.New("Missing required parameter 'username' when calling UserApi->LoginUser") } // verify the required parameter 'password' is set if &password == nil { - return *new(string), *NewAPIResponseWithError("400 - Bad Request"), errors.New("Missing required parameter 'password' when calling UserApi->LoginUser") + return new(string), nil, errors.New("Missing required parameter 'password' when calling UserApi->LoginUser") } headerParams := make(map[string]string) @@ -391,10 +391,10 @@ func (a UserApi) LoginUser(username string, password string) (string, APIRespons var successPayload = new(string) httpResponse, err := a.Configuration.APIClient.CallAPI(path, httpMethod, postBody, headerParams, queryParams, formParams, fileName, fileBytes) if err != nil { - return *successPayload, *NewAPIResponse(httpResponse.RawResponse), err + return successPayload, NewAPIResponse(httpResponse.RawResponse), err } err = json.Unmarshal(httpResponse.Body(), &successPayload) - return *successPayload, *NewAPIResponse(httpResponse.RawResponse), err + return successPayload, NewAPIResponse(httpResponse.RawResponse), err } /** @@ -403,7 +403,7 @@ func (a UserApi) LoginUser(username string, password string) (string, APIRespons * * @return void */ -func (a UserApi) LogoutUser() (APIResponse, error) { +func (a UserApi) LogoutUser() (*APIResponse, error) { var httpMethod = "Get" // create path and map variables @@ -444,10 +444,10 @@ func (a UserApi) LogoutUser() (APIResponse, error) { httpResponse, err := a.Configuration.APIClient.CallAPI(path, httpMethod, postBody, headerParams, queryParams, formParams, fileName, fileBytes) if err != nil { - return *NewAPIResponse(httpResponse.RawResponse), err + return NewAPIResponse(httpResponse.RawResponse), err } - return *NewAPIResponse(httpResponse.RawResponse), err + return NewAPIResponse(httpResponse.RawResponse), err } /** @@ -458,7 +458,7 @@ func (a UserApi) LogoutUser() (APIResponse, error) { * @param body Updated user object * @return void */ -func (a UserApi) UpdateUser(username string, body User) (APIResponse, error) { +func (a UserApi) UpdateUser(username string, body User) (*APIResponse, error) { var httpMethod = "Put" // create path and map variables @@ -467,11 +467,11 @@ func (a UserApi) UpdateUser(username string, body User) (APIResponse, error) { // verify the required parameter 'username' is set if &username == nil { - return *NewAPIResponseWithError("400 - Bad Request"), errors.New("Missing required parameter 'username' when calling UserApi->UpdateUser") + return nil, errors.New("Missing required parameter 'username' when calling UserApi->UpdateUser") } // verify the required parameter 'body' is set if &body == nil { - return *NewAPIResponseWithError("400 - Bad Request"), errors.New("Missing required parameter 'body' when calling UserApi->UpdateUser") + return nil, errors.New("Missing required parameter 'body' when calling UserApi->UpdateUser") } headerParams := make(map[string]string) @@ -511,9 +511,9 @@ func (a UserApi) UpdateUser(username string, body User) (APIResponse, error) { httpResponse, err := a.Configuration.APIClient.CallAPI(path, httpMethod, postBody, headerParams, queryParams, formParams, fileName, fileBytes) if err != nil { - return *NewAPIResponse(httpResponse.RawResponse), err + return NewAPIResponse(httpResponse.RawResponse), err } - return *NewAPIResponse(httpResponse.RawResponse), err + return NewAPIResponse(httpResponse.RawResponse), err } diff --git a/samples/client/petstore/go/pet_api_test.go b/samples/client/petstore/go/pet_api_test.go index 5b18e3a7675..fdda15acbe5 100644 --- a/samples/client/petstore/go/pet_api_test.go +++ b/samples/client/petstore/go/pet_api_test.go @@ -3,8 +3,8 @@ package main import ( sw "./go-petstore" "github.com/stretchr/testify/assert" - "testing" "os" + "testing" ) func TestAddPet(t *testing.T) { @@ -20,7 +20,7 @@ func TestAddPet(t *testing.T) { } if apiResponse.Response.StatusCode != 200 { t.Log(apiResponse.Response) - } + } } func TestFindPetsByStatusWithMissingParam(t *testing.T) { @@ -34,7 +34,7 @@ func TestFindPetsByStatusWithMissingParam(t *testing.T) { } if apiResponse.Response.StatusCode != 200 { t.Log(apiResponse) - } + } } func TestGetPetById(t *testing.T) { @@ -54,7 +54,7 @@ func TestGetPetById(t *testing.T) { } if apiResponse.Response.StatusCode != 200 { t.Log(apiResponse.Response) - } + } } func TestGetPetByIdWithInvalidID(t *testing.T) { @@ -69,7 +69,7 @@ func TestGetPetByIdWithInvalidID(t *testing.T) { } if apiResponse.Response.StatusCode != 200 { t.Log(apiResponse.Response) - } + } } func TestUpdatePetWithForm(t *testing.T) { @@ -88,26 +88,30 @@ func TestUpdatePetWithForm(t *testing.T) { func TestFindPetsByStatus(t *testing.T) { s := sw.NewPetApi() - resp, apiResponse, err := s.FindPetsByStatus([]string {"pending"}) + resp, apiResponse, err := s.FindPetsByStatus([]string{"available"}) if err != nil { t.Errorf("Error while getting pet by id") t.Log(err) t.Log(apiResponse) } else { - t.Log(apiResponse) if len(resp) == 0 { t.Errorf("Error no pets returned") + } else { + assert := assert.New(t) + for i := 0; i < len(resp); i++ { + assert.Equal(resp[i].Status, "available", "Pet status should be `available`") + } } - if apiResponse.Response.StatusCode != 200 { - t.Log(apiResponse.Response) - } + if apiResponse.Response.StatusCode != 200 { + t.Log(apiResponse.Response) + } } } func TestUploadFile(t *testing.T) { s := sw.NewPetApi() - file, _ := os.Open("../python/testfiles/foo.png") + file, _ := os.Open("../python/testfiles/foo.png") _, apiResponse, err := s.UploadFile(12830, "golang", file) @@ -115,6 +119,7 @@ func TestUploadFile(t *testing.T) { t.Errorf("Error while uploading file") t.Log(err) } + if apiResponse.Response.StatusCode != 200 { t.Log(apiResponse.Response) } diff --git a/samples/client/petstore/java/default/docs/AnimalFarm.md b/samples/client/petstore/java/default/docs/AnimalFarm.md new file mode 100644 index 00000000000..c7c7f1ddcce --- /dev/null +++ b/samples/client/petstore/java/default/docs/AnimalFarm.md @@ -0,0 +1,9 @@ + +# AnimalFarm + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + + + diff --git a/samples/client/petstore/java/default/docs/EnumClass.md b/samples/client/petstore/java/default/docs/EnumClass.md index de0bc8a95ac..c746edc3cb1 100644 --- a/samples/client/petstore/java/default/docs/EnumClass.md +++ b/samples/client/petstore/java/default/docs/EnumClass.md @@ -3,6 +3,12 @@ ## Enum -* `{values=[_abc, -efg, (xyz)], enumVars=[{name=_ABC, value="_abc"}, {name=_EFG, value="-efg"}, {name=_XYZ_, value="(xyz)"}]}` + +* `_ABC` (value: `"_abc"`) + +* `_EFG` (value: `"-efg"`) + +* `_XYZ_` (value: `"(xyz)"`) + diff --git a/samples/client/petstore/java/default/docs/FakeApi.md b/samples/client/petstore/java/default/docs/FakeApi.md index f642566c8e7..b4e5f34974a 100644 --- a/samples/client/petstore/java/default/docs/FakeApi.md +++ b/samples/client/petstore/java/default/docs/FakeApi.md @@ -4,16 +4,16 @@ All URIs are relative to *http://petstore.swagger.io/v2* Method | HTTP request | Description ------------- | ------------- | ------------- -[**testEndpointParameters**](FakeApi.md#testEndpointParameters) | **POST** /fake | Fake endpoint for testing various parameters +[**testEndpointParameters**](FakeApi.md#testEndpointParameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 # **testEndpointParameters** > testEndpointParameters(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password) -Fake endpoint for testing various parameters +Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 -Fake endpoint for testing various parameters +Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 ### Example ```java @@ -23,7 +23,7 @@ Fake endpoint for testing various parameters FakeApi apiInstance = new FakeApi(); -String number = "number_example"; // String | None +BigDecimal number = new BigDecimal(); // BigDecimal | None Double _double = 3.4D; // Double | None String string = "string_example"; // String | None byte[] _byte = B; // byte[] | None @@ -47,7 +47,7 @@ try { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **number** | **String**| None | + **number** | **BigDecimal**| None | **_double** | **Double**| None | **string** | **String**| None | **_byte** | **byte[]**| None | diff --git a/samples/client/petstore/java/default/docs/FormatTest.md b/samples/client/petstore/java/default/docs/FormatTest.md index 5e54362e535..dc2b559dad2 100644 --- a/samples/client/petstore/java/default/docs/FormatTest.md +++ b/samples/client/petstore/java/default/docs/FormatTest.md @@ -15,6 +15,7 @@ Name | Type | Description | Notes **binary** | **byte[]** | | [optional] **date** | [**Date**](Date.md) | | **dateTime** | [**Date**](Date.md) | | [optional] +**uuid** | **String** | | [optional] **password** | **String** | | diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/FakeApi.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/FakeApi.java index ddfaff67d0f..40ee5e2774f 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/FakeApi.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/FakeApi.java @@ -5,9 +5,12 @@ import com.sun.jersey.api.client.GenericType; import io.swagger.client.ApiException; import io.swagger.client.ApiClient; import io.swagger.client.Configuration; +import io.swagger.client.model.*; import io.swagger.client.Pair; import java.util.Date; +import java.math.BigDecimal; + import java.util.ArrayList; import java.util.HashMap; @@ -35,8 +38,8 @@ public class FakeApi { } /** - * Fake endpoint for testing various parameters - * Fake endpoint for testing various parameters + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 * @param number None (required) * @param _double None (required) * @param string None (required) @@ -51,7 +54,7 @@ public class FakeApi { * @param password None (optional) * @throws ApiException if fails to make API call */ - public void testEndpointParameters(String number, Double _double, String string, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, byte[] binary, Date date, Date dateTime, String password) throws ApiException { + public void testEndpointParameters(BigDecimal number, Double _double, String string, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, byte[] binary, Date date, Date dateTime, String password) throws ApiException { Object localVarPostBody = null; // verify the required parameter 'number' is set 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 c4ff05ec24f..0816f9a2961 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 @@ -5,12 +5,14 @@ import com.sun.jersey.api.client.GenericType; import io.swagger.client.ApiException; import io.swagger.client.ApiClient; import io.swagger.client.Configuration; +import io.swagger.client.model.*; import io.swagger.client.Pair; import io.swagger.client.model.Pet; import java.io.File; import io.swagger.client.model.ModelApiResponse; + import java.util.ArrayList; import java.util.HashMap; import java.util.List; 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 59a1a58266e..4714c3ca2d3 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 @@ -5,10 +5,12 @@ import com.sun.jersey.api.client.GenericType; import io.swagger.client.ApiException; import io.swagger.client.ApiClient; import io.swagger.client.Configuration; +import io.swagger.client.model.*; import io.swagger.client.Pair; import io.swagger.client.model.Order; + import java.util.ArrayList; import java.util.HashMap; import java.util.List; 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 7ab75eabd34..6369d9daa4d 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 @@ -5,10 +5,12 @@ import com.sun.jersey.api.client.GenericType; import io.swagger.client.ApiException; import io.swagger.client.ApiClient; import io.swagger.client.Configuration; +import io.swagger.client.model.*; import io.swagger.client.Pair; import io.swagger.client.model.User; + import java.util.ArrayList; import java.util.HashMap; import java.util.List; diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Animal.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Animal.java index 559e19848f9..365f0110b78 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Animal.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Animal.java @@ -1,5 +1,6 @@ package io.swagger.client.model; +import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/AnimalFarm.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/AnimalFarm.java new file mode 100644 index 00000000000..647e3a893e1 --- /dev/null +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/AnimalFarm.java @@ -0,0 +1,54 @@ +package io.swagger.client.model; + +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.Objects; +import io.swagger.client.model.Animal; +import java.util.ArrayList; +import java.util.List; + + +/** + * AnimalFarm + */ + +public class AnimalFarm extends ArrayList { + + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + return true; + } + + @Override + public int hashCode() { + return Objects.hash(super.hashCode()); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class AnimalFarm {\n"); + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Cat.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Cat.java index 305b4806f4a..21c54aff204 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Cat.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Cat.java @@ -1,5 +1,6 @@ package io.swagger.client.model; +import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; 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 b97a241ff8c..c6cb703a89e 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 @@ -1,5 +1,6 @@ package io.swagger.client.model; +import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Dog.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Dog.java index f72a7f046ab..ed5581058c6 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Dog.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Dog.java @@ -1,5 +1,6 @@ package io.swagger.client.model; +import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/EnumClass.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/EnumClass.java index 716bfbbc85e..42434e297ff 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/EnumClass.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/EnumClass.java @@ -1,5 +1,6 @@ package io.swagger.client.model; +import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonValue; diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/EnumTest.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/EnumTest.java index 806628ebd56..1c8657fd3ec 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/EnumTest.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/EnumTest.java @@ -1,5 +1,6 @@ package io.swagger.client.model; +import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonValue; diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/FormatTest.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/FormatTest.java index f10a0749f5e..c01974880ae 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/FormatTest.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/FormatTest.java @@ -1,5 +1,6 @@ package io.swagger.client.model; +import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Model200Response.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Model200Response.java index e62ec1f3281..b2809525c7f 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Model200Response.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Model200Response.java @@ -1,5 +1,6 @@ package io.swagger.client.model; +import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/ModelApiResponse.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/ModelApiResponse.java index 719f9b676fd..32fb86dd323 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/ModelApiResponse.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/ModelApiResponse.java @@ -1,5 +1,6 @@ package io.swagger.client.model; +import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/ModelReturn.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/ModelReturn.java index fa6b2b8b90c..a076d16f964 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/ModelReturn.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/ModelReturn.java @@ -1,5 +1,6 @@ package io.swagger.client.model; +import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Name.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Name.java index b9953ebac0a..60b26b55658 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Name.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Name.java @@ -1,5 +1,6 @@ package io.swagger.client.model; +import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; 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 00372f26f93..ed5739592a3 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 @@ -1,5 +1,6 @@ package io.swagger.client.model; +import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonValue; 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 a3e34c8570f..da8b76ad024 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 @@ -1,5 +1,6 @@ package io.swagger.client.model; +import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonValue; diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/SpecialModelName.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/SpecialModelName.java index 1a38a0edea9..24e57756cb2 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/SpecialModelName.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/SpecialModelName.java @@ -1,5 +1,6 @@ package io.swagger.client.model; +import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; 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 f76224dd489..9d3bdd8cb9e 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 @@ -1,5 +1,6 @@ package io.swagger.client.model; +import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; 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 017a72b2ee5..f23553660de 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 @@ -1,5 +1,6 @@ package io.swagger.client.model; +import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; diff --git a/samples/client/petstore/java/feign/git_push.sh b/samples/client/petstore/java/feign/git_push.sh index 1a36388db02..ed374619b13 100644 --- a/samples/client/petstore/java/feign/git_push.sh +++ b/samples/client/petstore/java/feign/git_push.sh @@ -8,12 +8,12 @@ git_repo_id=$2 release_note=$3 if [ "$git_user_id" = "" ]; then - git_user_id="YOUR_GIT_USR_ID" + git_user_id="GIT_USER_ID" echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" fi if [ "$git_repo_id" = "" ]; then - git_repo_id="YOUR_GIT_REPO_ID" + git_repo_id="GIT_REPO_ID" echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" fi diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/FakeApi.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/FakeApi.java index b92a064d3e5..b1dc92805ab 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/FakeApi.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/FakeApi.java @@ -2,6 +2,7 @@ package io.swagger.client.api; import io.swagger.client.ApiClient; +import java.math.BigDecimal; import java.util.Date; import java.util.ArrayList; @@ -10,7 +11,7 @@ import java.util.List; import java.util.Map; import feign.*; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-27T23:17:22.230+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-06T18:35:05.435+08:00") public interface FakeApi extends ApiClient.Api { @@ -36,5 +37,5 @@ public interface FakeApi extends ApiClient.Api { "Content-type: application/x-www-form-urlencoded", "Accepts: application/json", }) - void testEndpointParameters(@Param("number") String number, @Param("_double") Double _double, @Param("string") String string, @Param("_byte") byte[] _byte, @Param("integer") Integer integer, @Param("int32") Integer int32, @Param("int64") Long int64, @Param("_float") Float _float, @Param("binary") byte[] binary, @Param("date") Date date, @Param("dateTime") Date dateTime, @Param("password") String password); + void testEndpointParameters(@Param("number") BigDecimal number, @Param("_double") Double _double, @Param("string") String string, @Param("_byte") byte[] _byte, @Param("integer") Integer integer, @Param("int32") Integer int32, @Param("int64") Long int64, @Param("_float") Float _float, @Param("binary") byte[] binary, @Param("date") Date date, @Param("dateTime") Date dateTime, @Param("password") String password); } diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/AnimalFarm.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/AnimalFarm.java new file mode 100644 index 00000000000..f38bf504d50 --- /dev/null +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/AnimalFarm.java @@ -0,0 +1,53 @@ +package io.swagger.client.model; + +import java.util.Objects; +import io.swagger.client.model.Animal; +import java.util.ArrayList; +import java.util.List; + + +/** + * AnimalFarm + */ +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-06T18:35:05.435+08:00") +public class AnimalFarm extends ArrayList { + + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + return true; + } + + @Override + public int hashCode() { + return Objects.hash(super.hashCode()); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class AnimalFarm {\n"); + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/FormatTest.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/FormatTest.java index 53aa13638a7..072decf8079 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/FormatTest.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/FormatTest.java @@ -11,7 +11,7 @@ import java.util.Date; /** * FormatTest */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-27T23:17:22.230+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-06T18:35:05.435+08:00") public class FormatTest { private Integer integer = null; @@ -25,6 +25,7 @@ public class FormatTest { private byte[] binary = null; private Date date = null; private Date dateTime = null; + private String uuid = null; private String password = null; @@ -225,6 +226,23 @@ public class FormatTest { } + /** + **/ + public FormatTest uuid(String uuid) { + this.uuid = uuid; + return this; + } + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("uuid") + public String getUuid() { + return uuid; + } + public void setUuid(String uuid) { + this.uuid = uuid; + } + + /** **/ public FormatTest password(String password) { @@ -262,12 +280,13 @@ public class FormatTest { Objects.equals(this.binary, formatTest.binary) && Objects.equals(this.date, formatTest.date) && Objects.equals(this.dateTime, formatTest.dateTime) && + Objects.equals(this.uuid, formatTest.uuid) && Objects.equals(this.password, formatTest.password); } @Override public int hashCode() { - return Objects.hash(integer, int32, int64, number, _float, _double, string, _byte, binary, date, dateTime, password); + return Objects.hash(integer, int32, int64, number, _float, _double, string, _byte, binary, date, dateTime, uuid, password); } @Override @@ -286,6 +305,7 @@ public class FormatTest { sb.append(" binary: ").append(toIndentedString(binary)).append("\n"); sb.append(" date: ").append(toIndentedString(date)).append("\n"); sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); + sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); sb.append(" password: ").append(toIndentedString(password)).append("\n"); sb.append("}"); return sb.toString(); diff --git a/samples/client/petstore/java/jersey2/docs/AnimalFarm.md b/samples/client/petstore/java/jersey2/docs/AnimalFarm.md new file mode 100644 index 00000000000..c7c7f1ddcce --- /dev/null +++ b/samples/client/petstore/java/jersey2/docs/AnimalFarm.md @@ -0,0 +1,9 @@ + +# AnimalFarm + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + + + diff --git a/samples/client/petstore/java/jersey2/docs/EnumClass.md b/samples/client/petstore/java/jersey2/docs/EnumClass.md new file mode 100644 index 00000000000..c746edc3cb1 --- /dev/null +++ b/samples/client/petstore/java/jersey2/docs/EnumClass.md @@ -0,0 +1,14 @@ + +# EnumClass + +## Enum + + +* `_ABC` (value: `"_abc"`) + +* `_EFG` (value: `"-efg"`) + +* `_XYZ_` (value: `"(xyz)"`) + + + diff --git a/samples/client/petstore/java/jersey2/docs/EnumTest.md b/samples/client/petstore/java/jersey2/docs/EnumTest.md new file mode 100644 index 00000000000..deb1951c552 --- /dev/null +++ b/samples/client/petstore/java/jersey2/docs/EnumTest.md @@ -0,0 +1,36 @@ + +# EnumTest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**enumString** | [**EnumStringEnum**](#EnumStringEnum) | | [optional] +**enumInteger** | [**EnumIntegerEnum**](#EnumIntegerEnum) | | [optional] +**enumNumber** | [**EnumNumberEnum**](#EnumNumberEnum) | | [optional] + + + +## Enum: EnumStringEnum +Name | Value +---- | ----- +UPPER | "UPPER" +LOWER | "lower" + + + +## Enum: EnumIntegerEnum +Name | Value +---- | ----- +NUMBER_1 | 1 +NUMBER_MINUS_1 | -1 + + + +## Enum: EnumNumberEnum +Name | Value +---- | ----- +NUMBER_1_DOT_1 | 1.1 +NUMBER_MINUS_1_DOT_2 | -1.2 + + + diff --git a/samples/client/petstore/java/jersey2/docs/FakeApi.md b/samples/client/petstore/java/jersey2/docs/FakeApi.md new file mode 100644 index 00000000000..c1fdd310321 --- /dev/null +++ b/samples/client/petstore/java/jersey2/docs/FakeApi.md @@ -0,0 +1,75 @@ +# FakeApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**testEndpointParameters**](FakeApi.md#testEndpointParameters) | **POST** /fake | Fake endpoint for testing various parameters + + + +# **testEndpointParameters** +> testEndpointParameters(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password) + +Fake endpoint for testing various parameters + +Fake endpoint for testing various parameters + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.FakeApi; + + +FakeApi apiInstance = new FakeApi(); +BigDecimal number = new BigDecimal(); // BigDecimal | None +Double _double = 3.4D; // Double | None +String string = "string_example"; // String | None +byte[] _byte = B; // byte[] | None +Integer integer = 56; // Integer | None +Integer int32 = 56; // Integer | None +Long int64 = 789L; // Long | None +Float _float = 3.4F; // Float | None +byte[] binary = B; // byte[] | None +Date date = new Date(); // Date | None +Date dateTime = new Date(); // Date | None +String password = "password_example"; // String | None +try { + apiInstance.testEndpointParameters(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password); +} catch (ApiException e) { + System.err.println("Exception when calling FakeApi#testEndpointParameters"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **number** | **BigDecimal**| None | + **_double** | **Double**| None | + **string** | **String**| None | + **_byte** | **byte[]**| None | + **integer** | **Integer**| None | [optional] + **int32** | **Integer**| None | [optional] + **int64** | **Long**| None | [optional] + **_float** | **Float**| None | [optional] + **binary** | **byte[]**| None | [optional] + **date** | **Date**| None | [optional] + **dateTime** | **Date**| None | [optional] + **password** | **String**| None | [optional] + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + diff --git a/samples/client/petstore/java/jersey2/docs/FormatTest.md b/samples/client/petstore/java/jersey2/docs/FormatTest.md index 8e400e7bcd7..dc2b559dad2 100644 --- a/samples/client/petstore/java/jersey2/docs/FormatTest.md +++ b/samples/client/petstore/java/jersey2/docs/FormatTest.md @@ -11,11 +11,12 @@ Name | Type | Description | Notes **_float** | **Float** | | [optional] **_double** | **Double** | | [optional] **string** | **String** | | [optional] -**_byte** | **byte[]** | | [optional] +**_byte** | **byte[]** | | **binary** | **byte[]** | | [optional] -**date** | [**Date**](Date.md) | | [optional] +**date** | [**Date**](Date.md) | | **dateTime** | [**Date**](Date.md) | | [optional] -**password** | **String** | | [optional] +**uuid** | **String** | | [optional] +**password** | **String** | | diff --git a/samples/client/petstore/java/jersey2/docs/Order.md b/samples/client/petstore/java/jersey2/docs/Order.md index b1709c14eee..29ca3ddbc6b 100644 --- a/samples/client/petstore/java/jersey2/docs/Order.md +++ b/samples/client/petstore/java/jersey2/docs/Order.md @@ -16,9 +16,9 @@ Name | Type | Description | Notes ## Enum: StatusEnum Name | Value ---- | ----- -PLACED | placed -APPROVED | approved -DELIVERED | delivered +PLACED | "placed" +APPROVED | "approved" +DELIVERED | "delivered" diff --git a/samples/client/petstore/java/jersey2/docs/Pet.md b/samples/client/petstore/java/jersey2/docs/Pet.md index 20a1c298dd6..5b63109ef92 100644 --- a/samples/client/petstore/java/jersey2/docs/Pet.md +++ b/samples/client/petstore/java/jersey2/docs/Pet.md @@ -16,9 +16,9 @@ Name | Type | Description | Notes ## Enum: StatusEnum Name | Value ---- | ----- -AVAILABLE | available -PENDING | pending -SOLD | sold +AVAILABLE | "available" +PENDING | "pending" +SOLD | "sold" diff --git a/samples/client/petstore/java/jersey2/git_push.sh b/samples/client/petstore/java/jersey2/git_push.sh index 1a36388db02..ed374619b13 100644 --- a/samples/client/petstore/java/jersey2/git_push.sh +++ b/samples/client/petstore/java/jersey2/git_push.sh @@ -8,12 +8,12 @@ git_repo_id=$2 release_note=$3 if [ "$git_user_id" = "" ]; then - git_user_id="YOUR_GIT_USR_ID" + git_user_id="GIT_USER_ID" echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" fi if [ "$git_repo_id" = "" ]; then - git_repo_id="YOUR_GIT_REPO_ID" + git_repo_id="GIT_REPO_ID" echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" fi diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/FakeApi.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/FakeApi.java new file mode 100644 index 00000000000..33c74e7a51c --- /dev/null +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/FakeApi.java @@ -0,0 +1,128 @@ +package io.swagger.client.api; + +import io.swagger.client.ApiException; +import io.swagger.client.ApiClient; +import io.swagger.client.Configuration; +import io.swagger.client.Pair; + +import javax.ws.rs.core.GenericType; + +import java.math.BigDecimal; +import java.util.Date; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-06T18:35:03.551+08:00") +public class FakeApi { + private ApiClient apiClient; + + public FakeApi() { + this(Configuration.getDefaultApiClient()); + } + + public FakeApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /** + * Fake endpoint for testing various parameters + * Fake endpoint for testing various parameters + * @param number None (required) + * @param _double None (required) + * @param string None (required) + * @param _byte None (required) + * @param integer None (optional) + * @param int32 None (optional) + * @param int64 None (optional) + * @param _float None (optional) + * @param binary None (optional) + * @param date None (optional) + * @param dateTime None (optional) + * @param password None (optional) + * @throws ApiException if fails to make API call + */ + public void testEndpointParameters(BigDecimal number, Double _double, String string, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, byte[] binary, Date date, Date dateTime, String password) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'number' is set + if (number == null) { + throw new ApiException(400, "Missing the required parameter 'number' when calling testEndpointParameters"); + } + + // verify the required parameter '_double' is set + if (_double == null) { + throw new ApiException(400, "Missing the required parameter '_double' when calling testEndpointParameters"); + } + + // verify the required parameter 'string' is set + if (string == null) { + throw new ApiException(400, "Missing the required parameter 'string' when calling testEndpointParameters"); + } + + // verify the required parameter '_byte' is set + if (_byte == null) { + throw new ApiException(400, "Missing the required parameter '_byte' when calling testEndpointParameters"); + } + + // create path and map variables + String localVarPath = "/fake".replaceAll("\\{format\\}","json"); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + if (integer != null) + localVarFormParams.put("integer", integer); +if (int32 != null) + localVarFormParams.put("int32", int32); +if (int64 != null) + localVarFormParams.put("int64", int64); +if (number != null) + localVarFormParams.put("number", number); +if (_float != null) + localVarFormParams.put("float", _float); +if (_double != null) + localVarFormParams.put("double", _double); +if (string != null) + localVarFormParams.put("string", string); +if (_byte != null) + localVarFormParams.put("byte", _byte); +if (binary != null) + localVarFormParams.put("binary", binary); +if (date != null) + localVarFormParams.put("date", date); +if (dateTime != null) + localVarFormParams.put("dateTime", dateTime); +if (password != null) + localVarFormParams.put("password", password); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + + apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); + } +} diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Animal.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Animal.java index 1a3029ec922..0781e60a4d4 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Animal.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Animal.java @@ -9,7 +9,7 @@ import io.swagger.annotations.ApiModelProperty; /** * Animal */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-12T23:06:12.393+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-06T18:35:03.551+08:00") public class Animal { private String className = null; @@ -31,7 +31,6 @@ public class Animal { this.className = className; } - @Override public boolean equals(java.lang.Object o) { diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/AnimalFarm.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/AnimalFarm.java new file mode 100644 index 00000000000..04767c63252 --- /dev/null +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/AnimalFarm.java @@ -0,0 +1,53 @@ +package io.swagger.client.model; + +import java.util.Objects; +import io.swagger.client.model.Animal; +import java.util.ArrayList; +import java.util.List; + + +/** + * AnimalFarm + */ +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-06T18:35:03.551+08:00") +public class AnimalFarm extends ArrayList { + + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + return true; + } + + @Override + public int hashCode() { + return Objects.hash(super.hashCode()); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class AnimalFarm {\n"); + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Cat.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Cat.java index c877047cd45..8acadb9a2f6 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Cat.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Cat.java @@ -10,7 +10,7 @@ import io.swagger.client.model.Animal; /** * Cat */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-12T23:06:12.393+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-06T18:35:03.551+08:00") public class Cat extends Animal { private String className = null; @@ -33,7 +33,7 @@ public class Cat extends Animal { this.className = className; } - + /** **/ public Cat declawed(Boolean declawed) { @@ -50,7 +50,6 @@ public class Cat extends Animal { this.declawed = declawed; } - @Override public boolean equals(java.lang.Object o) { 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 b9cb4951346..763fcccf2a7 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Category.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Category.java @@ -9,7 +9,7 @@ import io.swagger.annotations.ApiModelProperty; /** * Category */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-12T23:06:12.393+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-06T18:35:03.551+08:00") public class Category { private Long id = null; @@ -32,7 +32,7 @@ public class Category { this.id = id; } - + /** **/ public Category name(String name) { @@ -49,7 +49,6 @@ public class Category { this.name = name; } - @Override public boolean equals(java.lang.Object o) { diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Dog.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Dog.java index 15d3ce320b2..a9e7e2acce0 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Dog.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Dog.java @@ -10,7 +10,7 @@ import io.swagger.client.model.Animal; /** * Dog */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-12T23:06:12.393+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-06T18:35:03.551+08:00") public class Dog extends Animal { private String className = null; @@ -33,7 +33,7 @@ public class Dog extends Animal { this.className = className; } - + /** **/ public Dog breed(String breed) { @@ -50,7 +50,6 @@ public class Dog extends Animal { this.breed = breed; } - @Override public boolean equals(java.lang.Object o) { diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/EnumTest.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/EnumTest.java index 6b8ee8102be..8152b440599 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/EnumTest.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/EnumTest.java @@ -10,7 +10,7 @@ import io.swagger.annotations.ApiModelProperty; /** * EnumTest */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-12T23:06:12.393+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-06T18:35:03.551+08:00") public class EnumTest { @@ -97,7 +97,7 @@ public class EnumTest { this.enumString = enumString; } - + /** **/ public EnumTest enumInteger(EnumIntegerEnum enumInteger) { @@ -114,7 +114,7 @@ public class EnumTest { this.enumInteger = enumInteger; } - + /** **/ public EnumTest enumNumber(EnumNumberEnum enumNumber) { @@ -131,7 +131,6 @@ public class EnumTest { this.enumNumber = enumNumber; } - @Override public boolean equals(java.lang.Object o) { diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/FormatTest.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/FormatTest.java index 774ce0ebcfe..4098e37a8a9 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/FormatTest.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/FormatTest.java @@ -8,10 +8,10 @@ import java.math.BigDecimal; import java.util.Date; - - - -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-23T12:58:40.273+08:00") +/** + * FormatTest + */ +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-06T18:35:03.551+08:00") public class FormatTest { private Integer integer = null; @@ -25,10 +25,13 @@ public class FormatTest { private byte[] binary = null; private Date date = null; private Date dateTime = null; + private String uuid = null; private String password = null; /** + * minimum: 10.0 + * maximum: 100.0 **/ public FormatTest integer(Integer integer) { this.integer = integer; @@ -46,6 +49,8 @@ public class FormatTest { /** + * minimum: 20.0 + * maximum: 200.0 **/ public FormatTest int32(Integer int32) { this.int32 = int32; @@ -80,6 +85,8 @@ public class FormatTest { /** + * minimum: 32.1 + * maximum: 543.2 **/ public FormatTest number(BigDecimal number) { this.number = number; @@ -97,6 +104,8 @@ public class FormatTest { /** + * minimum: 54.3 + * maximum: 987.6 **/ public FormatTest _float(Float _float) { this._float = _float; @@ -114,6 +123,8 @@ public class FormatTest { /** + * minimum: 67.8 + * maximum: 123.4 **/ public FormatTest _double(Double _double) { this._double = _double; @@ -154,7 +165,7 @@ public class FormatTest { return this; } - @ApiModelProperty(example = "null", value = "") + @ApiModelProperty(example = "null", required = true, value = "") @JsonProperty("byte") public byte[] getByte() { return _byte; @@ -188,7 +199,7 @@ public class FormatTest { return this; } - @ApiModelProperty(example = "null", value = "") + @ApiModelProperty(example = "null", required = true, value = "") @JsonProperty("date") public Date getDate() { return date; @@ -215,6 +226,23 @@ public class FormatTest { } + /** + **/ + public FormatTest uuid(String uuid) { + this.uuid = uuid; + return this; + } + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("uuid") + public String getUuid() { + return uuid; + } + public void setUuid(String uuid) { + this.uuid = uuid; + } + + /** **/ public FormatTest password(String password) { @@ -222,7 +250,7 @@ public class FormatTest { return this; } - @ApiModelProperty(example = "null", value = "") + @ApiModelProperty(example = "null", required = true, value = "") @JsonProperty("password") public String getPassword() { return password; @@ -252,12 +280,13 @@ public class FormatTest { Objects.equals(this.binary, formatTest.binary) && Objects.equals(this.date, formatTest.date) && Objects.equals(this.dateTime, formatTest.dateTime) && + Objects.equals(this.uuid, formatTest.uuid) && Objects.equals(this.password, formatTest.password); } @Override public int hashCode() { - return Objects.hash(integer, int32, int64, number, _float, _double, string, _byte, binary, date, dateTime, password); + return Objects.hash(integer, int32, int64, number, _float, _double, string, _byte, binary, date, dateTime, uuid, password); } @Override @@ -276,6 +305,7 @@ public class FormatTest { sb.append(" binary: ").append(toIndentedString(binary)).append("\n"); sb.append(" date: ").append(toIndentedString(date)).append("\n"); sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); + sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); sb.append(" password: ").append(toIndentedString(password)).append("\n"); sb.append("}"); return sb.toString(); diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Model200Response.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Model200Response.java index 36f04c225f6..0101cd5e8e3 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Model200Response.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Model200Response.java @@ -7,9 +7,10 @@ import io.swagger.annotations.ApiModelProperty; /** - * Model200Response + * Model for testing model name starting with number */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-12T23:06:12.393+08:00") +@ApiModel(description = "Model for testing model name starting with number") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-06T18:35:03.551+08:00") public class Model200Response { private Integer name = null; @@ -31,7 +32,6 @@ public class Model200Response { this.name = name; } - @Override public boolean equals(java.lang.Object o) { diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ModelApiResponse.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ModelApiResponse.java index 5a3f9254bae..af6f23fd782 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ModelApiResponse.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ModelApiResponse.java @@ -6,10 +6,10 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - - - -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-23T12:58:40.273+08:00") +/** + * ModelApiResponse + */ +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-06T18:35:03.551+08:00") public class ModelApiResponse { private Integer code = null; diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ModelReturn.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ModelReturn.java index 62224f3b2c3..827c22bef67 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ModelReturn.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ModelReturn.java @@ -7,9 +7,10 @@ import io.swagger.annotations.ApiModelProperty; /** - * ModelReturn + * Model for testing reserved words */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-12T23:06:12.393+08:00") +@ApiModel(description = "Model for testing reserved words") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-06T18:35:03.551+08:00") public class ModelReturn { private Integer _return = null; @@ -31,7 +32,6 @@ public class ModelReturn { this._return = _return; } - @Override public boolean equals(java.lang.Object o) { diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Name.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Name.java index 92bf36a7952..b7209d46b19 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Name.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Name.java @@ -7,13 +7,15 @@ import io.swagger.annotations.ApiModelProperty; /** - * Name + * Model for testing model name same as property name */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-12T23:06:12.393+08:00") +@ApiModel(description = "Model for testing model name same as property name") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-06T18:35:03.551+08:00") public class Name { private Integer name = null; private Integer snakeCase = null; + private String property = null; /** @@ -23,7 +25,7 @@ public class Name { return this; } - @ApiModelProperty(example = "null", value = "") + @ApiModelProperty(example = "null", required = true, value = "") @JsonProperty("name") public Integer getName() { return name; @@ -32,24 +34,30 @@ public class Name { this.name = name; } - - /** - **/ - public Name snakeCase(Integer snakeCase) { - this.snakeCase = snakeCase; - return this; - } - + @ApiModelProperty(example = "null", value = "") @JsonProperty("snake_case") public Integer getSnakeCase() { return snakeCase; } - public void setSnakeCase(Integer snakeCase) { - this.snakeCase = snakeCase; + + + /** + **/ + public Name property(String property) { + this.property = property; + return this; + } + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("property") + public String getProperty() { + return property; + } + public void setProperty(String property) { + this.property = property; } - @Override public boolean equals(java.lang.Object o) { @@ -61,12 +69,13 @@ public class Name { } Name name = (Name) o; return Objects.equals(this.name, name.name) && - Objects.equals(this.snakeCase, name.snakeCase); + Objects.equals(this.snakeCase, name.snakeCase) && + Objects.equals(this.property, name.property); } @Override public int hashCode() { - return Objects.hash(name, snakeCase); + return Objects.hash(name, snakeCase, property); } @Override @@ -76,6 +85,7 @@ public class Name { sb.append(" name: ").append(toIndentedString(name)).append("\n"); sb.append(" snakeCase: ").append(toIndentedString(snakeCase)).append("\n"); + sb.append(" property: ").append(toIndentedString(property)).append("\n"); sb.append("}"); return sb.toString(); } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Order.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Order.java index 116f07dc14d..322b2b832cb 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Order.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Order.java @@ -11,7 +11,7 @@ import java.util.Date; /** * Order */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-12T23:06:12.393+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-06T18:35:03.551+08:00") public class Order { private Long id = null; @@ -40,17 +40,27 @@ public class Order { } } - private StatusEnum status = StatusEnum.PLACED; - private Boolean complete = null; + private StatusEnum status = null; + private Boolean complete = false; + /** + **/ + public Order id(Long id) { + this.id = id; + return this; + } + @ApiModelProperty(example = "null", value = "") @JsonProperty("id") public Long getId() { return id; } + public void setId(Long id) { + this.id = id; + } + - /** **/ public Order petId(Long petId) { @@ -67,7 +77,7 @@ public class Order { this.petId = petId; } - + /** **/ public Order quantity(Integer quantity) { @@ -84,7 +94,7 @@ public class Order { this.quantity = quantity; } - + /** **/ public Order shipDate(Date shipDate) { @@ -101,7 +111,7 @@ public class Order { this.shipDate = shipDate; } - + /** * Order Status **/ @@ -119,7 +129,7 @@ public class Order { this.status = status; } - + /** **/ public Order complete(Boolean complete) { @@ -136,7 +146,6 @@ public class Order { this.complete = complete; } - @Override public boolean equals(java.lang.Object o) { 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 82dc1e9a1a4..07becbd4107 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Pet.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Pet.java @@ -14,7 +14,7 @@ import java.util.List; /** * Pet */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-12T23:06:12.393+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-06T18:35:03.551+08:00") public class Pet { private Long id = null; @@ -63,7 +63,7 @@ public class Pet { this.id = id; } - + /** **/ public Pet category(Category category) { @@ -80,7 +80,7 @@ public class Pet { this.category = category; } - + /** **/ public Pet name(String name) { @@ -97,7 +97,7 @@ public class Pet { this.name = name; } - + /** **/ public Pet photoUrls(List photoUrls) { @@ -114,7 +114,7 @@ public class Pet { this.photoUrls = photoUrls; } - + /** **/ public Pet tags(List tags) { @@ -131,7 +131,7 @@ public class Pet { this.tags = tags; } - + /** * pet status in the store **/ @@ -149,7 +149,6 @@ public class Pet { this.status = status; } - @Override public boolean equals(java.lang.Object o) { diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/SpecialModelName.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/SpecialModelName.java index 12e360e83a4..fccd55df94d 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/SpecialModelName.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/SpecialModelName.java @@ -9,7 +9,7 @@ import io.swagger.annotations.ApiModelProperty; /** * SpecialModelName */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-12T23:06:12.393+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-06T18:35:03.551+08:00") public class SpecialModelName { private Long specialPropertyName = null; @@ -31,7 +31,6 @@ public class SpecialModelName { this.specialPropertyName = specialPropertyName; } - @Override public boolean equals(java.lang.Object o) { 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 0c579b9ed7e..417f95d4a2f 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Tag.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Tag.java @@ -9,7 +9,7 @@ import io.swagger.annotations.ApiModelProperty; /** * Tag */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-12T23:06:12.393+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-06T18:35:03.551+08:00") public class Tag { private Long id = null; @@ -32,7 +32,7 @@ public class Tag { this.id = id; } - + /** **/ public Tag name(String name) { @@ -49,7 +49,6 @@ public class Tag { this.name = name; } - @Override public boolean equals(java.lang.Object o) { 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 48933177c5f..bf361b5a765 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/User.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/User.java @@ -9,7 +9,7 @@ import io.swagger.annotations.ApiModelProperty; /** * User */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-12T23:06:12.393+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-06T18:35:03.551+08:00") public class User { private Long id = null; @@ -38,7 +38,7 @@ public class User { this.id = id; } - + /** **/ public User username(String username) { @@ -55,7 +55,7 @@ public class User { this.username = username; } - + /** **/ public User firstName(String firstName) { @@ -72,7 +72,7 @@ public class User { this.firstName = firstName; } - + /** **/ public User lastName(String lastName) { @@ -89,7 +89,7 @@ public class User { this.lastName = lastName; } - + /** **/ public User email(String email) { @@ -106,7 +106,7 @@ public class User { this.email = email; } - + /** **/ public User password(String password) { @@ -123,7 +123,7 @@ public class User { this.password = password; } - + /** **/ public User phone(String phone) { @@ -140,7 +140,7 @@ public class User { this.phone = phone; } - + /** * User Status **/ @@ -158,7 +158,6 @@ public class User { this.userStatus = userStatus; } - @Override public boolean equals(java.lang.Object o) { diff --git a/samples/client/petstore/java/okhttp-gson/docs/AnimalFarm.md b/samples/client/petstore/java/okhttp-gson/docs/AnimalFarm.md new file mode 100644 index 00000000000..c7c7f1ddcce --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/docs/AnimalFarm.md @@ -0,0 +1,9 @@ + +# AnimalFarm + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + + + diff --git a/samples/client/petstore/java/okhttp-gson/docs/EnumClass.md b/samples/client/petstore/java/okhttp-gson/docs/EnumClass.md index d03195a19a4..c746edc3cb1 100644 --- a/samples/client/petstore/java/okhttp-gson/docs/EnumClass.md +++ b/samples/client/petstore/java/okhttp-gson/docs/EnumClass.md @@ -4,11 +4,11 @@ ## Enum -* `_ABC` (value: `"_abc"`) +* `_ABC` (value: `"_abc"`) -* `_EFG` (value: `"-efg"`) +* `_EFG` (value: `"-efg"`) -* `_XYZ_` (value: `"(xyz)"`) +* `_XYZ_` (value: `"(xyz)"`) diff --git a/samples/client/petstore/java/okhttp-gson/docs/FakeApi.md b/samples/client/petstore/java/okhttp-gson/docs/FakeApi.md index f642566c8e7..c1fdd310321 100644 --- a/samples/client/petstore/java/okhttp-gson/docs/FakeApi.md +++ b/samples/client/petstore/java/okhttp-gson/docs/FakeApi.md @@ -23,7 +23,7 @@ Fake endpoint for testing various parameters FakeApi apiInstance = new FakeApi(); -String number = "number_example"; // String | None +BigDecimal number = new BigDecimal(); // BigDecimal | None Double _double = 3.4D; // Double | None String string = "string_example"; // String | None byte[] _byte = B; // byte[] | None @@ -47,7 +47,7 @@ try { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **number** | **String**| None | + **number** | **BigDecimal**| None | **_double** | **Double**| None | **string** | **String**| None | **_byte** | **byte[]**| None | diff --git a/samples/client/petstore/java/okhttp-gson/docs/FormatTest.md b/samples/client/petstore/java/okhttp-gson/docs/FormatTest.md index 5e54362e535..dc2b559dad2 100644 --- a/samples/client/petstore/java/okhttp-gson/docs/FormatTest.md +++ b/samples/client/petstore/java/okhttp-gson/docs/FormatTest.md @@ -15,6 +15,7 @@ Name | Type | Description | Notes **binary** | **byte[]** | | [optional] **date** | [**Date**](Date.md) | | **dateTime** | [**Date**](Date.md) | | [optional] +**uuid** | **String** | | [optional] **password** | **String** | | diff --git a/samples/client/petstore/java/okhttp-gson/git_push.sh b/samples/client/petstore/java/okhttp-gson/git_push.sh index 1a36388db02..ed374619b13 100644 --- a/samples/client/petstore/java/okhttp-gson/git_push.sh +++ b/samples/client/petstore/java/okhttp-gson/git_push.sh @@ -8,12 +8,12 @@ git_repo_id=$2 release_note=$3 if [ "$git_user_id" = "" ]; then - git_user_id="YOUR_GIT_USR_ID" + git_user_id="GIT_USER_ID" echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" fi if [ "$git_repo_id" = "" ]; then - git_repo_id="YOUR_GIT_REPO_ID" + git_repo_id="GIT_REPO_ID" echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" fi diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/FakeApi.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/FakeApi.java index dd6d8236607..e021970cdb7 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/FakeApi.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/FakeApi.java @@ -17,6 +17,7 @@ import com.squareup.okhttp.Response; import java.io.IOException; +import java.math.BigDecimal; import java.util.Date; import java.lang.reflect.Type; @@ -45,7 +46,7 @@ public class FakeApi { } /* Build call for testEndpointParameters */ - private Call testEndpointParametersCall(String number, Double _double, String string, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, byte[] binary, Date date, Date dateTime, String password, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + private Call testEndpointParametersCall(BigDecimal number, Double _double, String string, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, byte[] binary, Date date, Date dateTime, String password, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object localVarPostBody = null; // verify the required parameter 'number' is set @@ -147,7 +148,7 @@ public class FakeApi { * @param password None (optional) * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ - public void testEndpointParameters(String number, Double _double, String string, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, byte[] binary, Date date, Date dateTime, String password) throws ApiException { + public void testEndpointParameters(BigDecimal number, Double _double, String string, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, byte[] binary, Date date, Date dateTime, String password) throws ApiException { testEndpointParametersWithHttpInfo(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password); } @@ -169,7 +170,7 @@ public class FakeApi { * @return ApiResponse * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ - public ApiResponse testEndpointParametersWithHttpInfo(String number, Double _double, String string, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, byte[] binary, Date date, Date dateTime, String password) throws ApiException { + public ApiResponse testEndpointParametersWithHttpInfo(BigDecimal number, Double _double, String string, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, byte[] binary, Date date, Date dateTime, String password) throws ApiException { Call call = testEndpointParametersCall(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password, null, null); return apiClient.execute(call); } @@ -193,7 +194,7 @@ public class FakeApi { * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object */ - public Call testEndpointParametersAsync(String number, Double _double, String string, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, byte[] binary, Date date, Date dateTime, String password, final ApiCallback callback) throws ApiException { + public Call testEndpointParametersAsync(BigDecimal number, Double _double, String string, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, byte[] binary, Date date, Date dateTime, String password, final ApiCallback callback) throws ApiException { ProgressResponseBody.ProgressListener progressListener = null; ProgressRequestBody.ProgressRequestListener progressRequestListener = null; diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/AnimalFarm.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/AnimalFarm.java new file mode 100644 index 00000000000..8be2f1ecd0d --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/AnimalFarm.java @@ -0,0 +1,53 @@ +package io.swagger.client.model; + +import java.util.Objects; +import io.swagger.client.model.Animal; +import java.util.ArrayList; +import java.util.List; + +import com.google.gson.annotations.SerializedName; + + +/** + * AnimalFarm + */ +public class AnimalFarm extends ArrayList { + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + return true; + } + + @Override + public int hashCode() { + return Objects.hash(super.hashCode()); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class AnimalFarm {\n"); + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/FormatTest.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/FormatTest.java index 0fc4082d119..af3fec2a2ea 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/FormatTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/FormatTest.java @@ -47,6 +47,9 @@ public class FormatTest { @SerializedName("dateTime") private Date dateTime = null; + @SerializedName("uuid") + private String uuid = null; + @SerializedName("password") private String password = null; @@ -170,6 +173,16 @@ public class FormatTest { this.dateTime = dateTime; } + /** + **/ + @ApiModelProperty(value = "") + public String getUuid() { + return uuid; + } + public void setUuid(String uuid) { + this.uuid = uuid; + } + /** **/ @ApiModelProperty(required = true, value = "") @@ -201,12 +214,13 @@ public class FormatTest { Objects.equals(this.binary, formatTest.binary) && Objects.equals(this.date, formatTest.date) && Objects.equals(this.dateTime, formatTest.dateTime) && + Objects.equals(this.uuid, formatTest.uuid) && Objects.equals(this.password, formatTest.password); } @Override public int hashCode() { - return Objects.hash(integer, int32, int64, number, _float, _double, string, _byte, binary, date, dateTime, password); + return Objects.hash(integer, int32, int64, number, _float, _double, string, _byte, binary, date, dateTime, uuid, password); } @Override @@ -225,6 +239,7 @@ public class FormatTest { sb.append(" binary: ").append(toIndentedString(binary)).append("\n"); sb.append(" date: ").append(toIndentedString(date)).append("\n"); sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); + sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); sb.append(" password: ").append(toIndentedString(password)).append("\n"); sb.append("}"); return sb.toString(); diff --git a/samples/client/petstore/java/retrofit/git_push.sh b/samples/client/petstore/java/retrofit/git_push.sh index 1a36388db02..ed374619b13 100644 --- a/samples/client/petstore/java/retrofit/git_push.sh +++ b/samples/client/petstore/java/retrofit/git_push.sh @@ -8,12 +8,12 @@ git_repo_id=$2 release_note=$3 if [ "$git_user_id" = "" ]; then - git_user_id="YOUR_GIT_USR_ID" + git_user_id="GIT_USER_ID" echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" fi if [ "$git_repo_id" = "" ]; then - git_repo_id="YOUR_GIT_REPO_ID" + git_repo_id="GIT_REPO_ID" echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" fi diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/FakeApi.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/FakeApi.java index 03f5b9aff1b..89fb9ddba73 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/FakeApi.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/FakeApi.java @@ -6,6 +6,7 @@ import retrofit.Callback; import retrofit.http.*; import retrofit.mime.*; +import java.math.BigDecimal; import java.util.Date; import java.util.ArrayList; @@ -36,7 +37,7 @@ public interface FakeApi { @FormUrlEncoded @POST("/fake") Void testEndpointParameters( - @Field("number") String number, @Field("double") Double _double, @Field("string") String string, @Field("byte") byte[] _byte, @Field("integer") Integer integer, @Field("int32") Integer int32, @Field("int64") Long int64, @Field("float") Float _float, @Field("binary") byte[] binary, @Field("date") Date date, @Field("dateTime") Date dateTime, @Field("password") String password + @Field("number") BigDecimal number, @Field("double") Double _double, @Field("string") String string, @Field("byte") byte[] _byte, @Field("integer") Integer integer, @Field("int32") Integer int32, @Field("int64") Long int64, @Field("float") Float _float, @Field("binary") byte[] binary, @Field("date") Date date, @Field("dateTime") Date dateTime, @Field("password") String password ); /** @@ -61,6 +62,6 @@ public interface FakeApi { @FormUrlEncoded @POST("/fake") void testEndpointParameters( - @Field("number") String number, @Field("double") Double _double, @Field("string") String string, @Field("byte") byte[] _byte, @Field("integer") Integer integer, @Field("int32") Integer int32, @Field("int64") Long int64, @Field("float") Float _float, @Field("binary") byte[] binary, @Field("date") Date date, @Field("dateTime") Date dateTime, @Field("password") String password, Callback cb + @Field("number") BigDecimal number, @Field("double") Double _double, @Field("string") String string, @Field("byte") byte[] _byte, @Field("integer") Integer integer, @Field("int32") Integer int32, @Field("int64") Long int64, @Field("float") Float _float, @Field("binary") byte[] binary, @Field("date") Date date, @Field("dateTime") Date dateTime, @Field("password") String password, Callback cb ); } diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/AnimalFarm.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/AnimalFarm.java new file mode 100644 index 00000000000..c7d37b1512c --- /dev/null +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/AnimalFarm.java @@ -0,0 +1,53 @@ +package io.swagger.client.model; + +import java.util.Objects; +import io.swagger.client.model.Animal; +import java.util.ArrayList; +import java.util.List; + +import com.google.gson.annotations.SerializedName; + + + + + +public class AnimalFarm extends ArrayList { + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + AnimalFarm animalFarm = (AnimalFarm) o; + return true; + } + + @Override + public int hashCode() { + return Objects.hash(); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class AnimalFarm {\n"); + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/FormatTest.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/FormatTest.java index 40d1ca0ecea..694335531fd 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/FormatTest.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/FormatTest.java @@ -47,6 +47,9 @@ public class FormatTest { @SerializedName("dateTime") private Date dateTime = null; + @SerializedName("uuid") + private String uuid = null; + @SerializedName("password") private String password = null; @@ -170,6 +173,16 @@ public class FormatTest { this.dateTime = dateTime; } + /** + **/ + @ApiModelProperty(value = "") + public String getUuid() { + return uuid; + } + public void setUuid(String uuid) { + this.uuid = uuid; + } + /** **/ @ApiModelProperty(required = true, value = "") @@ -201,12 +214,13 @@ public class FormatTest { Objects.equals(binary, formatTest.binary) && Objects.equals(date, formatTest.date) && Objects.equals(dateTime, formatTest.dateTime) && + Objects.equals(uuid, formatTest.uuid) && Objects.equals(password, formatTest.password); } @Override public int hashCode() { - return Objects.hash(integer, int32, int64, number, _float, _double, string, _byte, binary, date, dateTime, password); + return Objects.hash(integer, int32, int64, number, _float, _double, string, _byte, binary, date, dateTime, uuid, password); } @Override @@ -225,6 +239,7 @@ public class FormatTest { sb.append(" binary: ").append(toIndentedString(binary)).append("\n"); sb.append(" date: ").append(toIndentedString(date)).append("\n"); sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); + sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); sb.append(" password: ").append(toIndentedString(password)).append("\n"); sb.append("}"); return sb.toString(); diff --git a/samples/client/petstore/java/retrofit2/git_push.sh b/samples/client/petstore/java/retrofit2/git_push.sh index 1a36388db02..ed374619b13 100644 --- a/samples/client/petstore/java/retrofit2/git_push.sh +++ b/samples/client/petstore/java/retrofit2/git_push.sh @@ -8,12 +8,12 @@ git_repo_id=$2 release_note=$3 if [ "$git_user_id" = "" ]; then - git_user_id="YOUR_GIT_USR_ID" + git_user_id="GIT_USER_ID" echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" fi if [ "$git_repo_id" = "" ]; then - git_repo_id="YOUR_GIT_REPO_ID" + git_repo_id="GIT_REPO_ID" echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" fi diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/FakeApi.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/FakeApi.java index dc732e67ae7..28db89beefd 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/FakeApi.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/FakeApi.java @@ -8,6 +8,7 @@ import retrofit2.http.*; import okhttp3.RequestBody; +import java.math.BigDecimal; import java.util.Date; import java.util.ArrayList; @@ -37,7 +38,7 @@ public interface FakeApi { @FormUrlEncoded @POST("fake") Call testEndpointParameters( - @Field("number") String number, @Field("double") Double _double, @Field("string") String string, @Field("byte") byte[] _byte, @Field("integer") Integer integer, @Field("int32") Integer int32, @Field("int64") Long int64, @Field("float") Float _float, @Field("binary") byte[] binary, @Field("date") Date date, @Field("dateTime") Date dateTime, @Field("password") String password + @Field("number") BigDecimal number, @Field("double") Double _double, @Field("string") String string, @Field("byte") byte[] _byte, @Field("integer") Integer integer, @Field("int32") Integer int32, @Field("int64") Long int64, @Field("float") Float _float, @Field("binary") byte[] binary, @Field("date") Date date, @Field("dateTime") Date dateTime, @Field("password") String password ); } diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/AnimalFarm.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/AnimalFarm.java new file mode 100644 index 00000000000..c7d37b1512c --- /dev/null +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/AnimalFarm.java @@ -0,0 +1,53 @@ +package io.swagger.client.model; + +import java.util.Objects; +import io.swagger.client.model.Animal; +import java.util.ArrayList; +import java.util.List; + +import com.google.gson.annotations.SerializedName; + + + + + +public class AnimalFarm extends ArrayList { + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + AnimalFarm animalFarm = (AnimalFarm) o; + return true; + } + + @Override + public int hashCode() { + return Objects.hash(); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class AnimalFarm {\n"); + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/FormatTest.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/FormatTest.java index 40d1ca0ecea..694335531fd 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/FormatTest.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/FormatTest.java @@ -47,6 +47,9 @@ public class FormatTest { @SerializedName("dateTime") private Date dateTime = null; + @SerializedName("uuid") + private String uuid = null; + @SerializedName("password") private String password = null; @@ -170,6 +173,16 @@ public class FormatTest { this.dateTime = dateTime; } + /** + **/ + @ApiModelProperty(value = "") + public String getUuid() { + return uuid; + } + public void setUuid(String uuid) { + this.uuid = uuid; + } + /** **/ @ApiModelProperty(required = true, value = "") @@ -201,12 +214,13 @@ public class FormatTest { Objects.equals(binary, formatTest.binary) && Objects.equals(date, formatTest.date) && Objects.equals(dateTime, formatTest.dateTime) && + Objects.equals(uuid, formatTest.uuid) && Objects.equals(password, formatTest.password); } @Override public int hashCode() { - return Objects.hash(integer, int32, int64, number, _float, _double, string, _byte, binary, date, dateTime, password); + return Objects.hash(integer, int32, int64, number, _float, _double, string, _byte, binary, date, dateTime, uuid, password); } @Override @@ -225,6 +239,7 @@ public class FormatTest { sb.append(" binary: ").append(toIndentedString(binary)).append("\n"); sb.append(" date: ").append(toIndentedString(date)).append("\n"); sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); + sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); sb.append(" password: ").append(toIndentedString(password)).append("\n"); sb.append("}"); return sb.toString(); diff --git a/samples/client/petstore/java/retrofit2rx/git_push.sh b/samples/client/petstore/java/retrofit2rx/git_push.sh index 1a36388db02..ed374619b13 100644 --- a/samples/client/petstore/java/retrofit2rx/git_push.sh +++ b/samples/client/petstore/java/retrofit2rx/git_push.sh @@ -8,12 +8,12 @@ git_repo_id=$2 release_note=$3 if [ "$git_user_id" = "" ]; then - git_user_id="YOUR_GIT_USR_ID" + git_user_id="GIT_USER_ID" echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" fi if [ "$git_repo_id" = "" ]; then - git_repo_id="YOUR_GIT_REPO_ID" + git_repo_id="GIT_REPO_ID" echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" fi diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/AnimalFarm.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/AnimalFarm.java new file mode 100644 index 00000000000..c7d37b1512c --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/AnimalFarm.java @@ -0,0 +1,53 @@ +package io.swagger.client.model; + +import java.util.Objects; +import io.swagger.client.model.Animal; +import java.util.ArrayList; +import java.util.List; + +import com.google.gson.annotations.SerializedName; + + + + + +public class AnimalFarm extends ArrayList { + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + AnimalFarm animalFarm = (AnimalFarm) o; + return true; + } + + @Override + public int hashCode() { + return Objects.hash(); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class AnimalFarm {\n"); + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/FormatTest.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/FormatTest.java index 4106b15caaf..694335531fd 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/FormatTest.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/FormatTest.java @@ -5,7 +5,6 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.math.BigDecimal; import java.util.Date; -import java.util.UUID; import com.google.gson.annotations.SerializedName; @@ -49,7 +48,7 @@ public class FormatTest { private Date dateTime = null; @SerializedName("uuid") - private UUID uuid = null; + private String uuid = null; @SerializedName("password") private String password = null; @@ -177,10 +176,10 @@ public class FormatTest { /** **/ @ApiModelProperty(value = "") - public UUID getUuid() { + public String getUuid() { return uuid; } - public void setUuid(UUID uuid) { + public void setUuid(String uuid) { this.uuid = uuid; } diff --git a/samples/client/petstore/javascript-promise/README.md b/samples/client/petstore/javascript-promise/README.md index f1d10a435b6..ba181cae089 100644 --- a/samples/client/petstore/javascript-promise/README.md +++ b/samples/client/petstore/javascript-promise/README.md @@ -1,12 +1,12 @@ # swagger-petstore SwaggerPetstore - JavaScript client for swagger-petstore -This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. This SDK is automatically generated by the [Swagger Codegen](https://github.com/swagger-api/swagger-codegen) project: - API version: 1.0.0 - Package version: 1.0.0 -- Build date: 2016-05-01T12:08:53.092+08:00 +- Build date: 2016-05-06T17:51:36.114+08:00 - Build package: class io.swagger.codegen.languages.JavascriptClientCodegen ## Installation @@ -53,18 +53,27 @@ Please follow the [installation](#installation) instruction and execute the foll ```javascript var SwaggerPetstore = require('swagger-petstore'); -var defaultClient = SwaggerPetstore.ApiClient.default; +var api = new SwaggerPetstore.FakeApi() -// Configure OAuth2 access token for authorization: petstore_auth -var petstore_auth = defaultClient.authentications['petstore_auth']; -petstore_auth.accessToken = "YOUR ACCESS TOKEN" +var _number = 3.4; // {Number} None -var api = new SwaggerPetstore.PetApi() +var _double = 1.2; // {Number} None + +var _string = "_string_example"; // {String} None + +var _byte = "B"; // {String} None var opts = { - 'body': new SwaggerPetstore.Pet() // {Pet} Pet object that needs to be added to the store + 'integer': 56, // {Integer} None + 'int32': 56, // {Integer} None + 'int64': 789, // {Integer} None + '_float': 3.4, // {Number} None + 'binary': "B", // {String} None + '_date': new Date("2013-10-20"), // {Date} None + 'dateTime': new Date("2013-10-20T19:20:30+01:00"), // {Date} None + 'password': "password_example" // {String} None }; -api.addPet(opts).then(function() { +api.testEndpointParameters(_number, _double, _string, _byte, opts).then(function() { console.log('API called successfully.'); }, function(error) { console.error(error); @@ -79,6 +88,7 @@ All URIs are relative to *http://petstore.swagger.io/v2* Class | Method | HTTP request | Description ------------ | ------------- | ------------- | ------------- +*SwaggerPetstore.FakeApi* | [**testEndpointParameters**](docs/FakeApi.md#testEndpointParameters) | **POST** /fake | Fake endpoint for testing various parameters *SwaggerPetstore.PetApi* | [**addPet**](docs/PetApi.md#addPet) | **POST** /pet | Add a new pet to the store *SwaggerPetstore.PetApi* | [**deletePet**](docs/PetApi.md#deletePet) | **DELETE** /pet/{petId} | Deletes a pet *SwaggerPetstore.PetApi* | [**findPetsByStatus**](docs/PetApi.md#findPetsByStatus) | **GET** /pet/findByStatus | Finds Pets by status @@ -103,9 +113,21 @@ Class | Method | HTTP request | Description ## Documentation for Models + - [SwaggerPetstore.Animal](docs/Animal.md) + - [SwaggerPetstore.AnimalFarm](docs/AnimalFarm.md) + - [SwaggerPetstore.ApiResponse](docs/ApiResponse.md) + - [SwaggerPetstore.Cat](docs/Cat.md) - [SwaggerPetstore.Category](docs/Category.md) + - [SwaggerPetstore.Dog](docs/Dog.md) + - [SwaggerPetstore.EnumClass](docs/EnumClass.md) + - [SwaggerPetstore.EnumTest](docs/EnumTest.md) + - [SwaggerPetstore.FormatTest](docs/FormatTest.md) + - [SwaggerPetstore.Model200Response](docs/Model200Response.md) + - [SwaggerPetstore.ModelReturn](docs/ModelReturn.md) + - [SwaggerPetstore.Name](docs/Name.md) - [SwaggerPetstore.Order](docs/Order.md) - [SwaggerPetstore.Pet](docs/Pet.md) + - [SwaggerPetstore.SpecialModelName](docs/SpecialModelName.md) - [SwaggerPetstore.Tag](docs/Tag.md) - [SwaggerPetstore.User](docs/User.md) @@ -113,12 +135,6 @@ Class | Method | HTTP request | Description ## Documentation for Authorization -### api_key - -- **Type**: API key -- **API key parameter name**: api_key -- **Location**: HTTP header - ### petstore_auth - **Type**: OAuth @@ -128,3 +144,9 @@ Class | Method | HTTP request | Description - write:pets: modify pets in your account - read:pets: read your pets +### api_key + +- **Type**: API key +- **API key parameter name**: api_key +- **Location**: HTTP header + diff --git a/samples/client/petstore/javascript-promise/docs/AnimalFarm.md b/samples/client/petstore/javascript-promise/docs/AnimalFarm.md new file mode 100644 index 00000000000..b72739a44c4 --- /dev/null +++ b/samples/client/petstore/javascript-promise/docs/AnimalFarm.md @@ -0,0 +1,7 @@ +# SwaggerPetstore.AnimalFarm + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + + diff --git a/samples/client/petstore/javascript-promise/docs/ApiResponse.md b/samples/client/petstore/javascript-promise/docs/ApiResponse.md new file mode 100644 index 00000000000..0ee678b84af --- /dev/null +++ b/samples/client/petstore/javascript-promise/docs/ApiResponse.md @@ -0,0 +1,10 @@ +# SwaggerPetstore.ApiResponse + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**code** | **Integer** | | [optional] +**type** | **String** | | [optional] +**message** | **String** | | [optional] + + diff --git a/samples/client/petstore/javascript-promise/docs/EnumClass.md b/samples/client/petstore/javascript-promise/docs/EnumClass.md new file mode 100644 index 00000000000..04b89362941 --- /dev/null +++ b/samples/client/petstore/javascript-promise/docs/EnumClass.md @@ -0,0 +1,12 @@ +# SwaggerPetstore.EnumClass + +## Enum + + +* `_abc` (value: `"_abc"`) + +* `-efg` (value: `"-efg"`) + +* `(xyz)` (value: `"(xyz)"`) + + diff --git a/samples/client/petstore/javascript-promise/docs/EnumTest.md b/samples/client/petstore/javascript-promise/docs/EnumTest.md new file mode 100644 index 00000000000..22c4da11b9d --- /dev/null +++ b/samples/client/petstore/javascript-promise/docs/EnumTest.md @@ -0,0 +1,43 @@ +# SwaggerPetstore.EnumTest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**enumString** | **String** | | [optional] +**enumInteger** | **Integer** | | [optional] +**enumNumber** | **Number** | | [optional] + + + +## Enum: EnumStringEnum + + +* `UPPER` (value: `"UPPER"`) + +* `lower` (value: `"lower"`) + + + + + +## Enum: EnumIntegerEnum + + +* `1` (value: `1`) + +* `-1` (value: `-1`) + + + + + +## Enum: EnumNumberEnum + + +* `1.1` (value: `1.1`) + +* `-1.2` (value: `-1.2`) + + + + diff --git a/samples/client/petstore/javascript-promise/docs/FakeApi.md b/samples/client/petstore/javascript-promise/docs/FakeApi.md new file mode 100644 index 00000000000..83925c1266d --- /dev/null +++ b/samples/client/petstore/javascript-promise/docs/FakeApi.md @@ -0,0 +1,79 @@ +# SwaggerPetstore.FakeApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**testEndpointParameters**](FakeApi.md#testEndpointParameters) | **POST** /fake | Fake endpoint for testing various parameters + + + +# **testEndpointParameters** +> testEndpointParameters(_number, _double, _string, _byte, opts) + +Fake endpoint for testing various parameters + +Fake endpoint for testing various parameters + +### Example +```javascript +var SwaggerPetstore = require('swagger-petstore'); + +var apiInstance = new SwaggerPetstore.FakeApi(); + +var _number = 3.4; // Number | None + +var _double = 1.2; // Number | None + +var _string = "_string_example"; // String | None + +var _byte = "B"; // String | None + +var opts = { + 'integer': 56, // Integer | None + 'int32': 56, // Integer | None + 'int64': 789, // Integer | None + '_float': 3.4, // Number | None + 'binary': "B", // String | None + '_date': new Date("2013-10-20"), // Date | None + 'dateTime': new Date("2013-10-20T19:20:30+01:00"), // Date | None + 'password': "password_example" // String | None +}; +apiInstance.testEndpointParameters(_number, _double, _string, _byte, opts).then(function() { + console.log('API called successfully.'); +}, function(error) { + console.error(error); +}); + +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **_number** | **Number**| None | + **_double** | **Number**| None | + **_string** | **String**| None | + **_byte** | **String**| None | + **integer** | **Integer**| None | [optional] + **int32** | **Integer**| None | [optional] + **int64** | **Integer**| None | [optional] + **_float** | **Number**| None | [optional] + **binary** | **String**| None | [optional] + **_date** | **Date**| None | [optional] + **dateTime** | **Date**| None | [optional] + **password** | **String**| None | [optional] + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + diff --git a/samples/client/petstore/javascript-promise/docs/FormatTest.md b/samples/client/petstore/javascript-promise/docs/FormatTest.md index 57a4fb132d5..9600904ee6d 100644 --- a/samples/client/petstore/javascript-promise/docs/FormatTest.md +++ b/samples/client/petstore/javascript-promise/docs/FormatTest.md @@ -10,9 +10,11 @@ Name | Type | Description | Notes **_float** | **Number** | | [optional] **_double** | **Number** | | [optional] **_string** | **String** | | [optional] -**_byte** | **String** | | [optional] +**_byte** | **String** | | **binary** | **String** | | [optional] -**_date** | **Date** | | [optional] -**dateTime** | **String** | | [optional] +**_date** | **Date** | | +**dateTime** | **Date** | | [optional] +**uuid** | **String** | | [optional] +**password** | **String** | | diff --git a/samples/client/petstore/javascript-promise/docs/InlineResponse200.md b/samples/client/petstore/javascript-promise/docs/InlineResponse200.md deleted file mode 100644 index bbb11067e9a..00000000000 --- a/samples/client/petstore/javascript-promise/docs/InlineResponse200.md +++ /dev/null @@ -1,13 +0,0 @@ -# SwaggerPetstore.InlineResponse200 - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**tags** | [**[Tag]**](Tag.md) | | [optional] -**id** | **Integer** | | -**category** | **Object** | | [optional] -**status** | **String** | pet status in the store | [optional] -**name** | **String** | | [optional] -**photoUrls** | **[String]** | | [optional] - - diff --git a/samples/client/petstore/javascript-promise/docs/Name.md b/samples/client/petstore/javascript-promise/docs/Name.md index f0e693f2f56..3bdb76be085 100644 --- a/samples/client/petstore/javascript-promise/docs/Name.md +++ b/samples/client/petstore/javascript-promise/docs/Name.md @@ -5,5 +5,6 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **name** | **Integer** | | **snakeCase** | **Integer** | | [optional] +**property** | **String** | | [optional] diff --git a/samples/client/petstore/javascript-promise/docs/Order.md b/samples/client/petstore/javascript-promise/docs/Order.md index b34b67d3a56..95ee5946ed2 100644 --- a/samples/client/petstore/javascript-promise/docs/Order.md +++ b/samples/client/petstore/javascript-promise/docs/Order.md @@ -8,6 +8,19 @@ Name | Type | Description | Notes **quantity** | **Integer** | | [optional] **shipDate** | **Date** | | [optional] **status** | **String** | Order Status | [optional] -**complete** | **Boolean** | | [optional] +**complete** | **Boolean** | | [optional] [default to false] + + + +## Enum: StatusEnum + + +* `placed` (value: `"placed"`) + +* `approved` (value: `"approved"`) + +* `delivered` (value: `"delivered"`) + + diff --git a/samples/client/petstore/javascript-promise/docs/Pet.md b/samples/client/petstore/javascript-promise/docs/Pet.md index f1b049dcadd..a08333731c0 100644 --- a/samples/client/petstore/javascript-promise/docs/Pet.md +++ b/samples/client/petstore/javascript-promise/docs/Pet.md @@ -11,3 +11,16 @@ Name | Type | Description | Notes **status** | **String** | pet status in the store | [optional] + +## Enum: StatusEnum + + +* `available` (value: `"available"`) + +* `pending` (value: `"pending"`) + +* `sold` (value: `"sold"`) + + + + diff --git a/samples/client/petstore/javascript-promise/docs/PetApi.md b/samples/client/petstore/javascript-promise/docs/PetApi.md index 0a0513875eb..af66741523b 100644 --- a/samples/client/petstore/javascript-promise/docs/PetApi.md +++ b/samples/client/petstore/javascript-promise/docs/PetApi.md @@ -16,7 +16,7 @@ Method | HTTP request | Description # **addPet** -> addPet(opts) +> addPet(body) Add a new pet to the store @@ -33,10 +33,9 @@ petstore_auth.accessToken = 'YOUR ACCESS TOKEN'; var apiInstance = new SwaggerPetstore.PetApi(); -var opts = { - 'body': new SwaggerPetstore.Pet() // Pet | Pet object that needs to be added to the store -}; -apiInstance.addPet(opts).then(function() { +var body = new SwaggerPetstore.Pet(); // Pet | Pet object that needs to be added to the store + +apiInstance.addPet(body).then(function() { console.log('API called successfully.'); }, function(error) { console.error(error); @@ -48,7 +47,7 @@ apiInstance.addPet(opts).then(function() { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **body** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | [optional] + **body** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | ### Return type @@ -61,7 +60,7 @@ null (empty response body) ### HTTP request headers - **Content-Type**: application/json, application/xml - - **Accept**: application/json, application/xml + - **Accept**: application/xml, application/json # **deletePet** @@ -113,15 +112,15 @@ null (empty response body) ### HTTP request headers - **Content-Type**: Not defined - - **Accept**: application/json, application/xml + - **Accept**: application/xml, application/json # **findPetsByStatus** -> [Pet] findPetsByStatus(opts) +> [Pet] findPetsByStatus(status) Finds Pets by status -Multiple status values can be provided with comma seperated strings +Multiple status values can be provided with comma separated strings ### Example ```javascript @@ -134,10 +133,9 @@ petstore_auth.accessToken = 'YOUR ACCESS TOKEN'; var apiInstance = new SwaggerPetstore.PetApi(); -var opts = { - 'status': ["available"] // [String] | Status values that need to be considered for filter -}; -apiInstance.findPetsByStatus(opts).then(function(data) { +var status = ["status_example"]; // [String] | Status values that need to be considered for filter + +apiInstance.findPetsByStatus(status).then(function(data) { console.log('API called successfully. Returned data: ' + data); }, function(error) { console.error(error); @@ -149,7 +147,7 @@ apiInstance.findPetsByStatus(opts).then(function(data) { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **status** | [**[String]**](String.md)| Status values that need to be considered for filter | [optional] [default to available] + **status** | [**[String]**](String.md)| Status values that need to be considered for filter | ### Return type @@ -162,15 +160,15 @@ Name | Type | Description | Notes ### HTTP request headers - **Content-Type**: Not defined - - **Accept**: application/json, application/xml + - **Accept**: application/xml, application/json # **findPetsByTags** -> [Pet] findPetsByTags(opts) +> [Pet] findPetsByTags(tags) Finds Pets by tags -Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. +Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. ### Example ```javascript @@ -183,10 +181,9 @@ petstore_auth.accessToken = 'YOUR ACCESS TOKEN'; var apiInstance = new SwaggerPetstore.PetApi(); -var opts = { - 'tags': ["tags_example"] // [String] | Tags to filter by -}; -apiInstance.findPetsByTags(opts).then(function(data) { +var tags = ["tags_example"]; // [String] | Tags to filter by + +apiInstance.findPetsByTags(tags).then(function(data) { console.log('API called successfully. Returned data: ' + data); }, function(error) { console.error(error); @@ -198,7 +195,7 @@ apiInstance.findPetsByTags(opts).then(function(data) { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **tags** | [**[String]**](String.md)| Tags to filter by | [optional] + **tags** | [**[String]**](String.md)| Tags to filter by | ### Return type @@ -211,7 +208,7 @@ Name | Type | Description | Notes ### HTTP request headers - **Content-Type**: Not defined - - **Accept**: application/json, application/xml + - **Accept**: application/xml, application/json # **getPetById** @@ -219,7 +216,7 @@ Name | Type | Description | Notes Find pet by ID -Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions +Returns a single pet ### Example ```javascript @@ -232,13 +229,9 @@ api_key.apiKey = 'YOUR API KEY'; // Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null) //api_key.apiKeyPrefix = 'Token'; -// Configure OAuth2 access token for authorization: petstore_auth -var petstore_auth = defaultClient.authentications['petstore_auth']; -petstore_auth.accessToken = 'YOUR ACCESS TOKEN'; - var apiInstance = new SwaggerPetstore.PetApi(); -var petId = 789; // Integer | ID of pet that needs to be fetched +var petId = 789; // Integer | ID of pet to return apiInstance.getPetById(petId).then(function(data) { console.log('API called successfully. Returned data: ' + data); @@ -252,7 +245,7 @@ apiInstance.getPetById(petId).then(function(data) { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **petId** | **Integer**| ID of pet that needs to be fetched | + **petId** | **Integer**| ID of pet to return | ### Return type @@ -260,16 +253,16 @@ Name | Type | Description | Notes ### Authorization -[api_key](../README.md#api_key), [petstore_auth](../README.md#petstore_auth) +[api_key](../README.md#api_key) ### HTTP request headers - **Content-Type**: Not defined - - **Accept**: application/json, application/xml + - **Accept**: application/xml, application/json # **updatePet** -> updatePet(opts) +> updatePet(body) Update an existing pet @@ -286,10 +279,9 @@ petstore_auth.accessToken = 'YOUR ACCESS TOKEN'; var apiInstance = new SwaggerPetstore.PetApi(); -var opts = { - 'body': new SwaggerPetstore.Pet() // Pet | Pet object that needs to be added to the store -}; -apiInstance.updatePet(opts).then(function() { +var body = new SwaggerPetstore.Pet(); // Pet | Pet object that needs to be added to the store + +apiInstance.updatePet(body).then(function() { console.log('API called successfully.'); }, function(error) { console.error(error); @@ -301,7 +293,7 @@ apiInstance.updatePet(opts).then(function() { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **body** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | [optional] + **body** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | ### Return type @@ -314,7 +306,7 @@ null (empty response body) ### HTTP request headers - **Content-Type**: application/json, application/xml - - **Accept**: application/json, application/xml + - **Accept**: application/xml, application/json # **updatePetWithForm** @@ -335,7 +327,7 @@ petstore_auth.accessToken = 'YOUR ACCESS TOKEN'; var apiInstance = new SwaggerPetstore.PetApi(); -var petId = "petId_example"; // String | ID of pet that needs to be updated +var petId = 789; // Integer | ID of pet that needs to be updated var opts = { 'name': "name_example", // String | Updated name of the pet @@ -353,7 +345,7 @@ apiInstance.updatePetWithForm(petId, opts).then(function() { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **petId** | **String**| ID of pet that needs to be updated | + **petId** | **Integer**| ID of pet that needs to be updated | **name** | **String**| Updated name of the pet | [optional] **status** | **String**| Updated status of the pet | [optional] @@ -368,11 +360,11 @@ null (empty response body) ### HTTP request headers - **Content-Type**: application/x-www-form-urlencoded - - **Accept**: application/json, application/xml + - **Accept**: application/xml, application/json # **uploadFile** -> uploadFile(petId, opts) +> ApiResponse uploadFile(petId, opts) uploads an image @@ -395,8 +387,8 @@ var opts = { 'additionalMetadata': "additionalMetadata_example", // String | Additional data to pass to server 'file': "/path/to/file.txt" // File | file to upload }; -apiInstance.uploadFile(petId, opts).then(function() { - console.log('API called successfully.'); +apiInstance.uploadFile(petId, opts).then(function(data) { + console.log('API called successfully. Returned data: ' + data); }, function(error) { console.error(error); }); @@ -413,7 +405,7 @@ Name | Type | Description | Notes ### Return type -null (empty response body) +[**ApiResponse**](ApiResponse.md) ### Authorization @@ -422,5 +414,5 @@ null (empty response body) ### HTTP request headers - **Content-Type**: multipart/form-data - - **Accept**: application/json, application/xml + - **Accept**: application/json diff --git a/samples/client/petstore/javascript-promise/docs/StoreApi.md b/samples/client/petstore/javascript-promise/docs/StoreApi.md index ce57b57bc4f..0d96cfc9e34 100644 --- a/samples/client/petstore/javascript-promise/docs/StoreApi.md +++ b/samples/client/petstore/javascript-promise/docs/StoreApi.md @@ -51,7 +51,7 @@ No authorization required ### HTTP request headers - **Content-Type**: Not defined - - **Accept**: application/json, application/xml + - **Accept**: application/xml, application/json # **getInventory** @@ -95,7 +95,7 @@ This endpoint does not need any parameter. ### HTTP request headers - **Content-Type**: Not defined - - **Accept**: application/json, application/xml + - **Accept**: application/json # **getOrderById** @@ -111,7 +111,7 @@ var SwaggerPetstore = require('swagger-petstore'); var apiInstance = new SwaggerPetstore.StoreApi(); -var orderId = "orderId_example"; // String | ID of pet that needs to be fetched +var orderId = 789; // Integer | ID of pet that needs to be fetched apiInstance.getOrderById(orderId).then(function(data) { console.log('API called successfully. Returned data: ' + data); @@ -125,7 +125,7 @@ apiInstance.getOrderById(orderId).then(function(data) { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **orderId** | **String**| ID of pet that needs to be fetched | + **orderId** | **Integer**| ID of pet that needs to be fetched | ### Return type @@ -138,11 +138,11 @@ No authorization required ### HTTP request headers - **Content-Type**: Not defined - - **Accept**: application/json, application/xml + - **Accept**: application/xml, application/json # **placeOrder** -> Order placeOrder(opts) +> Order placeOrder(body) Place an order for a pet @@ -154,10 +154,9 @@ var SwaggerPetstore = require('swagger-petstore'); var apiInstance = new SwaggerPetstore.StoreApi(); -var opts = { - 'body': new SwaggerPetstore.Order() // Order | order placed for purchasing the pet -}; -apiInstance.placeOrder(opts).then(function(data) { +var body = new SwaggerPetstore.Order(); // Order | order placed for purchasing the pet + +apiInstance.placeOrder(body).then(function(data) { console.log('API called successfully. Returned data: ' + data); }, function(error) { console.error(error); @@ -169,7 +168,7 @@ apiInstance.placeOrder(opts).then(function(data) { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **body** | [**Order**](Order.md)| order placed for purchasing the pet | [optional] + **body** | [**Order**](Order.md)| order placed for purchasing the pet | ### Return type @@ -182,5 +181,5 @@ No authorization required ### HTTP request headers - **Content-Type**: Not defined - - **Accept**: application/json, application/xml + - **Accept**: application/xml, application/json diff --git a/samples/client/petstore/javascript-promise/docs/UserApi.md b/samples/client/petstore/javascript-promise/docs/UserApi.md index 99b56e9cf3d..2634d41e611 100644 --- a/samples/client/petstore/javascript-promise/docs/UserApi.md +++ b/samples/client/petstore/javascript-promise/docs/UserApi.md @@ -16,7 +16,7 @@ Method | HTTP request | Description # **createUser** -> createUser(opts) +> createUser(body) Create user @@ -28,10 +28,9 @@ var SwaggerPetstore = require('swagger-petstore'); var apiInstance = new SwaggerPetstore.UserApi(); -var opts = { - 'body': new SwaggerPetstore.User() // User | Created user object -}; -apiInstance.createUser(opts).then(function() { +var body = new SwaggerPetstore.User(); // User | Created user object + +apiInstance.createUser(body).then(function() { console.log('API called successfully.'); }, function(error) { console.error(error); @@ -43,7 +42,7 @@ apiInstance.createUser(opts).then(function() { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **body** | [**User**](User.md)| Created user object | [optional] + **body** | [**User**](User.md)| Created user object | ### Return type @@ -56,11 +55,11 @@ No authorization required ### HTTP request headers - **Content-Type**: Not defined - - **Accept**: application/json, application/xml + - **Accept**: application/xml, application/json # **createUsersWithArrayInput** -> createUsersWithArrayInput(opts) +> createUsersWithArrayInput(body) Creates list of users with given input array @@ -72,10 +71,9 @@ var SwaggerPetstore = require('swagger-petstore'); var apiInstance = new SwaggerPetstore.UserApi(); -var opts = { - 'body': [new SwaggerPetstore.User()] // [User] | List of user object -}; -apiInstance.createUsersWithArrayInput(opts).then(function() { +var body = [new SwaggerPetstore.User()]; // [User] | List of user object + +apiInstance.createUsersWithArrayInput(body).then(function() { console.log('API called successfully.'); }, function(error) { console.error(error); @@ -87,7 +85,7 @@ apiInstance.createUsersWithArrayInput(opts).then(function() { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **body** | [**[User]**](User.md)| List of user object | [optional] + **body** | [**[User]**](User.md)| List of user object | ### Return type @@ -100,11 +98,11 @@ No authorization required ### HTTP request headers - **Content-Type**: Not defined - - **Accept**: application/json, application/xml + - **Accept**: application/xml, application/json # **createUsersWithListInput** -> createUsersWithListInput(opts) +> createUsersWithListInput(body) Creates list of users with given input array @@ -116,10 +114,9 @@ var SwaggerPetstore = require('swagger-petstore'); var apiInstance = new SwaggerPetstore.UserApi(); -var opts = { - 'body': [new SwaggerPetstore.User()] // [User] | List of user object -}; -apiInstance.createUsersWithListInput(opts).then(function() { +var body = [new SwaggerPetstore.User()]; // [User] | List of user object + +apiInstance.createUsersWithListInput(body).then(function() { console.log('API called successfully.'); }, function(error) { console.error(error); @@ -131,7 +128,7 @@ apiInstance.createUsersWithListInput(opts).then(function() { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **body** | [**[User]**](User.md)| List of user object | [optional] + **body** | [**[User]**](User.md)| List of user object | ### Return type @@ -144,7 +141,7 @@ No authorization required ### HTTP request headers - **Content-Type**: Not defined - - **Accept**: application/json, application/xml + - **Accept**: application/xml, application/json # **deleteUser** @@ -187,7 +184,7 @@ No authorization required ### HTTP request headers - **Content-Type**: Not defined - - **Accept**: application/json, application/xml + - **Accept**: application/xml, application/json # **getUserByName** @@ -230,11 +227,11 @@ No authorization required ### HTTP request headers - **Content-Type**: Not defined - - **Accept**: application/json, application/xml + - **Accept**: application/xml, application/json # **loginUser** -> 'String' loginUser(opts) +> 'String' loginUser(username, password) Logs user into the system @@ -246,11 +243,11 @@ var SwaggerPetstore = require('swagger-petstore'); var apiInstance = new SwaggerPetstore.UserApi(); -var opts = { - 'username': "username_example", // String | The user name for login - 'password': "password_example" // String | The password for login in clear text -}; -apiInstance.loginUser(opts).then(function(data) { +var username = "username_example"; // String | The user name for login + +var password = "password_example"; // String | The password for login in clear text + +apiInstance.loginUser(username, password).then(function(data) { console.log('API called successfully. Returned data: ' + data); }, function(error) { console.error(error); @@ -262,8 +259,8 @@ apiInstance.loginUser(opts).then(function(data) { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **username** | **String**| The user name for login | [optional] - **password** | **String**| The password for login in clear text | [optional] + **username** | **String**| The user name for login | + **password** | **String**| The password for login in clear text | ### Return type @@ -276,7 +273,7 @@ No authorization required ### HTTP request headers - **Content-Type**: Not defined - - **Accept**: application/json, application/xml + - **Accept**: application/xml, application/json # **logoutUser** @@ -313,11 +310,11 @@ No authorization required ### HTTP request headers - **Content-Type**: Not defined - - **Accept**: application/json, application/xml + - **Accept**: application/xml, application/json # **updateUser** -> updateUser(username, opts) +> updateUser(username, body) Updated user @@ -331,10 +328,9 @@ var apiInstance = new SwaggerPetstore.UserApi(); var username = "username_example"; // String | name that need to be deleted -var opts = { - 'body': new SwaggerPetstore.User() // User | Updated user object -}; -apiInstance.updateUser(username, opts).then(function() { +var body = new SwaggerPetstore.User(); // User | Updated user object + +apiInstance.updateUser(username, body).then(function() { console.log('API called successfully.'); }, function(error) { console.error(error); @@ -347,7 +343,7 @@ apiInstance.updateUser(username, opts).then(function() { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **username** | **String**| name that need to be deleted | - **body** | [**User**](User.md)| Updated user object | [optional] + **body** | [**User**](User.md)| Updated user object | ### Return type @@ -360,5 +356,5 @@ No authorization required ### HTTP request headers - **Content-Type**: Not defined - - **Accept**: application/json, application/xml + - **Accept**: application/xml, application/json diff --git a/samples/client/petstore/javascript-promise/package.json b/samples/client/petstore/javascript-promise/package.json index 72a48ac71de..8ff02a78ae3 100644 --- a/samples/client/petstore/javascript-promise/package.json +++ b/samples/client/petstore/javascript-promise/package.json @@ -1,7 +1,7 @@ { "name": "swagger-petstore", "version": "1.0.0", - "description": "This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters", + "description": "This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose.", "license": "Apache 2.0", "main": "src/index.js", "scripts": { diff --git a/samples/client/petstore/javascript-promise/src/ApiClient.js b/samples/client/petstore/javascript-promise/src/ApiClient.js index ac0b172ff22..4033ad41e00 100644 --- a/samples/client/petstore/javascript-promise/src/ApiClient.js +++ b/samples/client/petstore/javascript-promise/src/ApiClient.js @@ -40,8 +40,8 @@ * @type {Array.} */ this.authentications = { - 'api_key': {type: 'apiKey', 'in': 'header', name: 'api_key'}, - 'petstore_auth': {type: 'oauth2'} + 'petstore_auth': {type: 'oauth2'}, + 'api_key': {type: 'apiKey', 'in': 'header', name: 'api_key'} }; /** * The default HTTP headers to be included for all API calls. diff --git a/samples/client/petstore/javascript-promise/src/api/FakeApi.js b/samples/client/petstore/javascript-promise/src/api/FakeApi.js new file mode 100644 index 00000000000..84d262725a2 --- /dev/null +++ b/samples/client/petstore/javascript-promise/src/api/FakeApi.js @@ -0,0 +1,113 @@ +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(['ApiClient'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + module.exports = factory(require('../ApiClient')); + } else { + // Browser globals (root is window) + if (!root.SwaggerPetstore) { + root.SwaggerPetstore = {}; + } + root.SwaggerPetstore.FakeApi = factory(root.SwaggerPetstore.ApiClient); + } +}(this, function(ApiClient) { + 'use strict'; + + /** + * Fake service. + * @module api/FakeApi + * @version 1.0.0 + */ + + /** + * Constructs a new FakeApi. + * @alias module:api/FakeApi + * @class + * @param {module:ApiClient} apiClient Optional API client implementation to use, + * default to {@link module:ApiClient#instance} if unspecified. + */ + var exports = function(apiClient) { + this.apiClient = apiClient || ApiClient.instance; + + + + /** + * Fake endpoint for testing various parameters + * Fake endpoint for testing various parameters + * @param {Number} _number None + * @param {Number} _double None + * @param {String} _string None + * @param {String} _byte None + * @param {Object} opts Optional parameters + * @param {Integer} opts.integer None + * @param {Integer} opts.int32 None + * @param {Integer} opts.int64 None + * @param {Number} opts._float None + * @param {String} opts.binary None + * @param {Date} opts._date None + * @param {Date} opts.dateTime None + * @param {String} opts.password None + */ + this.testEndpointParameters = function(_number, _double, _string, _byte, opts) { + opts = opts || {}; + var postBody = null; + + // verify the required parameter '_number' is set + if (_number == undefined || _number == null) { + throw "Missing the required parameter '_number' when calling testEndpointParameters"; + } + + // verify the required parameter '_double' is set + if (_double == undefined || _double == null) { + throw "Missing the required parameter '_double' when calling testEndpointParameters"; + } + + // verify the required parameter '_string' is set + if (_string == undefined || _string == null) { + throw "Missing the required parameter '_string' when calling testEndpointParameters"; + } + + // verify the required parameter '_byte' is set + if (_byte == undefined || _byte == null) { + throw "Missing the required parameter '_byte' when calling testEndpointParameters"; + } + + + var pathParams = { + }; + var queryParams = { + }; + var headerParams = { + }; + var formParams = { + 'integer': opts['integer'], + 'int32': opts['int32'], + 'int64': opts['int64'], + 'number': _number, + 'float': opts['_float'], + 'double': _double, + 'string': _string, + 'byte': _byte, + 'binary': opts['binary'], + 'date': opts['_date'], + 'dateTime': opts['dateTime'], + 'password': opts['password'] + }; + + var authNames = []; + var contentTypes = []; + var accepts = ['application/xml', 'application/json']; + var returnType = null; + + return this.apiClient.callApi( + '/fake', 'POST', + pathParams, queryParams, headerParams, formParams, postBody, + authNames, contentTypes, accepts, returnType + ); + } + }; + + return exports; +})); diff --git a/samples/client/petstore/javascript-promise/src/api/PetApi.js b/samples/client/petstore/javascript-promise/src/api/PetApi.js index 1b0855e5287..572fe19dbf2 100644 --- a/samples/client/petstore/javascript-promise/src/api/PetApi.js +++ b/samples/client/petstore/javascript-promise/src/api/PetApi.js @@ -1,18 +1,18 @@ (function(root, factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. - define(['ApiClient', 'model/Pet'], factory); + define(['ApiClient', 'model/Pet', 'model/ApiResponse'], factory); } else if (typeof module === 'object' && module.exports) { // CommonJS-like environments that support module.exports, like Node. - module.exports = factory(require('../ApiClient'), require('../model/Pet')); + module.exports = factory(require('../ApiClient'), require('../model/Pet'), require('../model/ApiResponse')); } else { // Browser globals (root is window) if (!root.SwaggerPetstore) { root.SwaggerPetstore = {}; } - root.SwaggerPetstore.PetApi = factory(root.SwaggerPetstore.ApiClient, root.SwaggerPetstore.Pet); + root.SwaggerPetstore.PetApi = factory(root.SwaggerPetstore.ApiClient, root.SwaggerPetstore.Pet, root.SwaggerPetstore.ApiResponse); } -}(this, function(ApiClient, Pet) { +}(this, function(ApiClient, Pet, ApiResponse) { 'use strict'; /** @@ -36,12 +36,15 @@ /** * Add a new pet to the store * - * @param {Object} opts Optional parameters - * @param {module:model/Pet} opts.body Pet object that needs to be added to the store + * @param {module:model/Pet} body Pet object that needs to be added to the store */ - this.addPet = function(opts) { - opts = opts || {}; - var postBody = opts['body']; + this.addPet = function(body) { + var postBody = body; + + // verify the required parameter 'body' is set + if (body == undefined || body == null) { + throw "Missing the required parameter 'body' when calling addPet"; + } var pathParams = { @@ -55,7 +58,7 @@ var authNames = ['petstore_auth']; var contentTypes = ['application/json', 'application/xml']; - var accepts = ['application/json', 'application/xml']; + var accepts = ['application/xml', 'application/json']; var returnType = null; return this.apiClient.callApi( @@ -96,7 +99,7 @@ var authNames = ['petstore_auth']; var contentTypes = []; - var accepts = ['application/json', 'application/xml']; + var accepts = ['application/xml', 'application/json']; var returnType = null; return this.apiClient.callApi( @@ -109,20 +112,23 @@ /** * Finds Pets by status - * Multiple status values can be provided with comma seperated strings - * @param {Object} opts Optional parameters - * @param {Array.} opts.status Status values that need to be considered for filter (default to available) + * Multiple status values can be provided with comma separated strings + * @param {Array.} status Status values that need to be considered for filter * data is of type: {Array.} */ - this.findPetsByStatus = function(opts) { - opts = opts || {}; + this.findPetsByStatus = function(status) { var postBody = null; + // verify the required parameter 'status' is set + if (status == undefined || status == null) { + throw "Missing the required parameter 'status' when calling findPetsByStatus"; + } + var pathParams = { }; var queryParams = { - 'status': this.apiClient.buildCollectionParam(opts['status'], 'multi') + 'status': this.apiClient.buildCollectionParam(status, 'csv') }; var headerParams = { }; @@ -131,7 +137,7 @@ var authNames = ['petstore_auth']; var contentTypes = []; - var accepts = ['application/json', 'application/xml']; + var accepts = ['application/xml', 'application/json']; var returnType = [Pet]; return this.apiClient.callApi( @@ -144,20 +150,23 @@ /** * Finds Pets by tags - * Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. - * @param {Object} opts Optional parameters - * @param {Array.} opts.tags Tags to filter by + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * @param {Array.} tags Tags to filter by * data is of type: {Array.} */ - this.findPetsByTags = function(opts) { - opts = opts || {}; + this.findPetsByTags = function(tags) { var postBody = null; + // verify the required parameter 'tags' is set + if (tags == undefined || tags == null) { + throw "Missing the required parameter 'tags' when calling findPetsByTags"; + } + var pathParams = { }; var queryParams = { - 'tags': this.apiClient.buildCollectionParam(opts['tags'], 'multi') + 'tags': this.apiClient.buildCollectionParam(tags, 'csv') }; var headerParams = { }; @@ -166,7 +175,7 @@ var authNames = ['petstore_auth']; var contentTypes = []; - var accepts = ['application/json', 'application/xml']; + var accepts = ['application/xml', 'application/json']; var returnType = [Pet]; return this.apiClient.callApi( @@ -179,8 +188,8 @@ /** * 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 + * Returns a single pet + * @param {Integer} petId ID of pet to return * data is of type: {module:model/Pet} */ this.getPetById = function(petId) { @@ -202,9 +211,9 @@ var formParams = { }; - var authNames = ['api_key', 'petstore_auth']; + var authNames = ['api_key']; var contentTypes = []; - var accepts = ['application/json', 'application/xml']; + var accepts = ['application/xml', 'application/json']; var returnType = Pet; return this.apiClient.callApi( @@ -218,12 +227,15 @@ /** * Update an existing pet * - * @param {Object} opts Optional parameters - * @param {module:model/Pet} opts.body Pet object that needs to be added to the store + * @param {module:model/Pet} body Pet object that needs to be added to the store */ - this.updatePet = function(opts) { - opts = opts || {}; - var postBody = opts['body']; + this.updatePet = function(body) { + var postBody = body; + + // verify the required parameter 'body' is set + if (body == undefined || body == null) { + throw "Missing the required parameter 'body' when calling updatePet"; + } var pathParams = { @@ -237,7 +249,7 @@ var authNames = ['petstore_auth']; var contentTypes = ['application/json', 'application/xml']; - var accepts = ['application/json', 'application/xml']; + var accepts = ['application/xml', 'application/json']; var returnType = null; return this.apiClient.callApi( @@ -251,7 +263,7 @@ /** * Updates a pet in the store with form data * - * @param {String} petId ID of pet that needs to be updated + * @param {Integer} petId ID of pet that needs to be updated * @param {Object} opts Optional parameters * @param {String} opts.name Updated name of the pet * @param {String} opts.status Updated status of the pet @@ -280,7 +292,7 @@ var authNames = ['petstore_auth']; var contentTypes = ['application/x-www-form-urlencoded']; - var accepts = ['application/json', 'application/xml']; + var accepts = ['application/xml', 'application/json']; var returnType = null; return this.apiClient.callApi( @@ -298,6 +310,7 @@ * @param {Object} opts Optional parameters * @param {String} opts.additionalMetadata Additional data to pass to server * @param {File} opts.file file to upload + * data is of type: {module:model/ApiResponse} */ this.uploadFile = function(petId, opts) { opts = opts || {}; @@ -323,8 +336,8 @@ var authNames = ['petstore_auth']; var contentTypes = ['multipart/form-data']; - var accepts = ['application/json', 'application/xml']; - var returnType = null; + var accepts = ['application/json']; + var returnType = ApiResponse; return this.apiClient.callApi( '/pet/{petId}/uploadImage', 'POST', diff --git a/samples/client/petstore/javascript-promise/src/api/StoreApi.js b/samples/client/petstore/javascript-promise/src/api/StoreApi.js index 6c6f7ea5dc4..f8b889256b2 100644 --- a/samples/client/petstore/javascript-promise/src/api/StoreApi.js +++ b/samples/client/petstore/javascript-promise/src/api/StoreApi.js @@ -59,7 +59,7 @@ var authNames = []; var contentTypes = []; - var accepts = ['application/json', 'application/xml']; + var accepts = ['application/xml', 'application/json']; var returnType = null; return this.apiClient.callApi( @@ -90,7 +90,7 @@ var authNames = ['api_key']; var contentTypes = []; - var accepts = ['application/json', 'application/xml']; + var accepts = ['application/json']; var returnType = {'String': 'Integer'}; return this.apiClient.callApi( @@ -104,7 +104,7 @@ /** * 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 {Integer} orderId ID of pet that needs to be fetched * data is of type: {module:model/Order} */ this.getOrderById = function(orderId) { @@ -128,7 +128,7 @@ var authNames = []; var contentTypes = []; - var accepts = ['application/json', 'application/xml']; + var accepts = ['application/xml', 'application/json']; var returnType = Order; return this.apiClient.callApi( @@ -142,13 +142,16 @@ /** * Place an order for a pet * - * @param {Object} opts Optional parameters - * @param {module:model/Order} opts.body order placed for purchasing the pet + * @param {module:model/Order} body order placed for purchasing the pet * data is of type: {module:model/Order} */ - this.placeOrder = function(opts) { - opts = opts || {}; - var postBody = opts['body']; + this.placeOrder = function(body) { + var postBody = body; + + // verify the required parameter 'body' is set + if (body == undefined || body == null) { + throw "Missing the required parameter 'body' when calling placeOrder"; + } var pathParams = { @@ -162,7 +165,7 @@ var authNames = []; var contentTypes = []; - var accepts = ['application/json', 'application/xml']; + var accepts = ['application/xml', 'application/json']; var returnType = Order; return this.apiClient.callApi( diff --git a/samples/client/petstore/javascript-promise/src/api/UserApi.js b/samples/client/petstore/javascript-promise/src/api/UserApi.js index e58ee580d3b..ff8f745735d 100644 --- a/samples/client/petstore/javascript-promise/src/api/UserApi.js +++ b/samples/client/petstore/javascript-promise/src/api/UserApi.js @@ -36,12 +36,15 @@ /** * Create user * This can only be done by the logged in user. - * @param {Object} opts Optional parameters - * @param {module:model/User} opts.body Created user object + * @param {module:model/User} body Created user object */ - this.createUser = function(opts) { - opts = opts || {}; - var postBody = opts['body']; + this.createUser = function(body) { + var postBody = body; + + // verify the required parameter 'body' is set + if (body == undefined || body == null) { + throw "Missing the required parameter 'body' when calling createUser"; + } var pathParams = { @@ -55,7 +58,7 @@ var authNames = []; var contentTypes = []; - var accepts = ['application/json', 'application/xml']; + var accepts = ['application/xml', 'application/json']; var returnType = null; return this.apiClient.callApi( @@ -69,12 +72,15 @@ /** * Creates list of users with given input array * - * @param {Object} opts Optional parameters - * @param {Array.} opts.body List of user object + * @param {Array.} body List of user object */ - this.createUsersWithArrayInput = function(opts) { - opts = opts || {}; - var postBody = opts['body']; + this.createUsersWithArrayInput = function(body) { + var postBody = body; + + // verify the required parameter 'body' is set + if (body == undefined || body == null) { + throw "Missing the required parameter 'body' when calling createUsersWithArrayInput"; + } var pathParams = { @@ -88,7 +94,7 @@ var authNames = []; var contentTypes = []; - var accepts = ['application/json', 'application/xml']; + var accepts = ['application/xml', 'application/json']; var returnType = null; return this.apiClient.callApi( @@ -102,12 +108,15 @@ /** * Creates list of users with given input array * - * @param {Object} opts Optional parameters - * @param {Array.} opts.body List of user object + * @param {Array.} body List of user object */ - this.createUsersWithListInput = function(opts) { - opts = opts || {}; - var postBody = opts['body']; + this.createUsersWithListInput = function(body) { + var postBody = body; + + // verify the required parameter 'body' is set + if (body == undefined || body == null) { + throw "Missing the required parameter 'body' when calling createUsersWithListInput"; + } var pathParams = { @@ -121,7 +130,7 @@ var authNames = []; var contentTypes = []; - var accepts = ['application/json', 'application/xml']; + var accepts = ['application/xml', 'application/json']; var returnType = null; return this.apiClient.callApi( @@ -158,7 +167,7 @@ var authNames = []; var contentTypes = []; - var accepts = ['application/json', 'application/xml']; + var accepts = ['application/xml', 'application/json']; var returnType = null; return this.apiClient.callApi( @@ -196,7 +205,7 @@ var authNames = []; var contentTypes = []; - var accepts = ['application/json', 'application/xml']; + var accepts = ['application/xml', 'application/json']; var returnType = User; return this.apiClient.callApi( @@ -210,21 +219,29 @@ /** * Logs user into the system * - * @param {Object} opts Optional parameters - * @param {String} opts.username The user name for login - * @param {String} opts.password The password for login in clear text + * @param {String} username The user name for login + * @param {String} password The password for login in clear text * data is of type: {'String'} */ - this.loginUser = function(opts) { - opts = opts || {}; + this.loginUser = function(username, password) { var postBody = null; + // verify the required parameter 'username' is set + if (username == undefined || username == null) { + throw "Missing the required parameter 'username' when calling loginUser"; + } + + // verify the required parameter 'password' is set + if (password == undefined || password == null) { + throw "Missing the required parameter 'password' when calling loginUser"; + } + var pathParams = { }; var queryParams = { - 'username': opts['username'], - 'password': opts['password'] + 'username': username, + 'password': password }; var headerParams = { }; @@ -233,7 +250,7 @@ var authNames = []; var contentTypes = []; - var accepts = ['application/json', 'application/xml']; + var accepts = ['application/xml', 'application/json']; var returnType = 'String'; return this.apiClient.callApi( @@ -263,7 +280,7 @@ var authNames = []; var contentTypes = []; - var accepts = ['application/json', 'application/xml']; + var accepts = ['application/xml', 'application/json']; var returnType = null; return this.apiClient.callApi( @@ -278,18 +295,21 @@ * Updated user * This can only be done by the logged in user. * @param {String} username name that need to be deleted - * @param {Object} opts Optional parameters - * @param {module:model/User} opts.body Updated user object + * @param {module:model/User} body Updated user object */ - this.updateUser = function(username, opts) { - opts = opts || {}; - var postBody = opts['body']; + this.updateUser = function(username, body) { + var postBody = body; // verify the required parameter 'username' is set if (username == undefined || username == null) { throw "Missing the required parameter 'username' when calling updateUser"; } + // verify the required parameter 'body' is set + if (body == undefined || body == null) { + throw "Missing the required parameter 'body' when calling updateUser"; + } + var pathParams = { 'username': username @@ -303,7 +323,7 @@ var authNames = []; var contentTypes = []; - var accepts = ['application/json', 'application/xml']; + var accepts = ['application/xml', 'application/json']; var returnType = null; return this.apiClient.callApi( diff --git a/samples/client/petstore/javascript-promise/src/index.js b/samples/client/petstore/javascript-promise/src/index.js index b0d17b3ef3a..727b4782f45 100644 --- a/samples/client/petstore/javascript-promise/src/index.js +++ b/samples/client/petstore/javascript-promise/src/index.js @@ -1,16 +1,16 @@ (function(factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. - define(['ApiClient', 'model/Category', 'model/Order', 'model/Pet', 'model/Tag', 'model/User', 'api/PetApi', 'api/StoreApi', 'api/UserApi'], factory); + define(['ApiClient', 'model/Animal', 'model/AnimalFarm', 'model/ApiResponse', 'model/Cat', 'model/Category', 'model/Dog', 'model/EnumClass', 'model/EnumTest', 'model/FormatTest', 'model/Model200Response', 'model/ModelReturn', 'model/Name', 'model/Order', 'model/Pet', 'model/SpecialModelName', 'model/Tag', 'model/User', 'api/FakeApi', 'api/PetApi', 'api/StoreApi', 'api/UserApi'], factory); } else if (typeof module === 'object' && module.exports) { // CommonJS-like environments that support module.exports, like Node. - module.exports = factory(require('./ApiClient'), require('./model/Category'), require('./model/Order'), require('./model/Pet'), require('./model/Tag'), require('./model/User'), require('./api/PetApi'), require('./api/StoreApi'), require('./api/UserApi')); + module.exports = factory(require('./ApiClient'), require('./model/Animal'), require('./model/AnimalFarm'), require('./model/ApiResponse'), require('./model/Cat'), require('./model/Category'), require('./model/Dog'), require('./model/EnumClass'), require('./model/EnumTest'), require('./model/FormatTest'), require('./model/Model200Response'), require('./model/ModelReturn'), require('./model/Name'), require('./model/Order'), require('./model/Pet'), require('./model/SpecialModelName'), require('./model/Tag'), require('./model/User'), require('./api/FakeApi'), require('./api/PetApi'), require('./api/StoreApi'), require('./api/UserApi')); } -}(function(ApiClient, Category, Order, Pet, Tag, User, PetApi, StoreApi, UserApi) { +}(function(ApiClient, Animal, AnimalFarm, ApiResponse, Cat, Category, Dog, EnumClass, EnumTest, FormatTest, Model200Response, ModelReturn, Name, Order, Pet, SpecialModelName, Tag, User, FakeApi, PetApi, StoreApi, UserApi) { 'use strict'; /** - * This is a sample server Petstore server. You can find out more about Swagger at <a href=\"http://swagger.io\">http://swagger.io</a> or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters.
+ * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose..
* The index module provides access to constructors for all the classes which comprise the public API. *

* An AMD (recommended!) or CommonJS application will generally do something equivalent to the following: @@ -46,11 +46,66 @@ * @property {module:ApiClient} */ ApiClient: ApiClient, + /** + * The Animal model constructor. + * @property {module:model/Animal} + */ + Animal: Animal, + /** + * The AnimalFarm model constructor. + * @property {module:model/AnimalFarm} + */ + AnimalFarm: AnimalFarm, + /** + * The ApiResponse model constructor. + * @property {module:model/ApiResponse} + */ + ApiResponse: ApiResponse, + /** + * The Cat model constructor. + * @property {module:model/Cat} + */ + Cat: Cat, /** * The Category model constructor. * @property {module:model/Category} */ Category: Category, + /** + * The Dog model constructor. + * @property {module:model/Dog} + */ + Dog: Dog, + /** + * The EnumClass model constructor. + * @property {module:model/EnumClass} + */ + EnumClass: EnumClass, + /** + * The EnumTest model constructor. + * @property {module:model/EnumTest} + */ + EnumTest: EnumTest, + /** + * The FormatTest model constructor. + * @property {module:model/FormatTest} + */ + FormatTest: FormatTest, + /** + * The Model200Response model constructor. + * @property {module:model/Model200Response} + */ + Model200Response: Model200Response, + /** + * The ModelReturn model constructor. + * @property {module:model/ModelReturn} + */ + ModelReturn: ModelReturn, + /** + * The Name model constructor. + * @property {module:model/Name} + */ + Name: Name, /** * The Order model constructor. * @property {module:model/Order} @@ -61,6 +116,11 @@ * @property {module:model/Pet} */ Pet: Pet, + /** + * The SpecialModelName model constructor. + * @property {module:model/SpecialModelName} + */ + SpecialModelName: SpecialModelName, /** * The Tag model constructor. * @property {module:model/Tag} @@ -71,6 +131,11 @@ * @property {module:model/User} */ User: User, + /** + * The FakeApi service constructor. + * @property {module:api/FakeApi} + */ + FakeApi: FakeApi, /** * The PetApi service constructor. * @property {module:api/PetApi} diff --git a/samples/client/petstore/javascript-promise/src/model/Animal.js b/samples/client/petstore/javascript-promise/src/model/Animal.js index 674471a30ee..e42874c669b 100644 --- a/samples/client/petstore/javascript-promise/src/model/Animal.js +++ b/samples/client/petstore/javascript-promise/src/model/Animal.js @@ -1,7 +1,7 @@ (function(root, factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. - define(['../ApiClient'], factory); + define(['ApiClient'], factory); } else if (typeof module === 'object' && module.exports) { // CommonJS-like environments that support module.exports, like Node. module.exports = factory(require('../ApiClient')); @@ -15,6 +15,9 @@ }(this, function(ApiClient) { 'use strict'; + + + /** * The Animal model module. * @module model/Animal @@ -28,8 +31,9 @@ * @param className */ var exports = function(className) { + var _this = this; - this['className'] = className; + _this['className'] = className; }; /** @@ -40,7 +44,7 @@ * @return {module:model/Animal} The populated Animal instance. */ exports.constructFromObject = function(data, obj) { - if (data) { + if (data) { obj = obj || new exports(); if (data.hasOwnProperty('className')) { @@ -50,7 +54,6 @@ return obj; } - /** * @member {String} className */ @@ -61,3 +64,5 @@ return exports; })); + + diff --git a/samples/client/petstore/javascript-promise/src/model/AnimalFarm.js b/samples/client/petstore/javascript-promise/src/model/AnimalFarm.js new file mode 100644 index 00000000000..d5f6aa2a424 --- /dev/null +++ b/samples/client/petstore/javascript-promise/src/model/AnimalFarm.js @@ -0,0 +1,64 @@ +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(['ApiClient', 'model/Animal'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + module.exports = factory(require('../ApiClient'), require('./Animal')); + } else { + // Browser globals (root is window) + if (!root.SwaggerPetstore) { + root.SwaggerPetstore = {}; + } + root.SwaggerPetstore.AnimalFarm = factory(root.SwaggerPetstore.ApiClient, root.SwaggerPetstore.Animal); + } +}(this, function(ApiClient, Animal) { + 'use strict'; + + + + + /** + * The AnimalFarm model module. + * @module model/AnimalFarm + * @version 1.0.0 + */ + + /** + * Constructs a new AnimalFarm. + * @alias module:model/AnimalFarm + * @class + * @extends Array + */ + var exports = function() { + var _this = this; + _this = new Array(); + Object.setPrototypeOf(_this, exports); + + return _this; + }; + + /** + * Constructs a AnimalFarm from a plain JavaScript object, optionally creating a new instance. + * Copies all relevant properties from data to obj if supplied or a new instance if not. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @param {module:model/AnimalFarm} obj Optional instance to populate. + * @return {module:model/AnimalFarm} The populated AnimalFarm instance. + */ + exports.constructFromObject = function(data, obj) { + if (data) { + obj = obj || new exports(); + ApiClient.constructFromObject(data, obj, Animal); + + } + return obj; + } + + + + + + return exports; +})); + + diff --git a/samples/client/petstore/javascript-promise/src/model/ApiResponse.js b/samples/client/petstore/javascript-promise/src/model/ApiResponse.js new file mode 100644 index 00000000000..6d4c970264b --- /dev/null +++ b/samples/client/petstore/javascript-promise/src/model/ApiResponse.js @@ -0,0 +1,83 @@ +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(['ApiClient'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + module.exports = factory(require('../ApiClient')); + } else { + // Browser globals (root is window) + if (!root.SwaggerPetstore) { + root.SwaggerPetstore = {}; + } + root.SwaggerPetstore.ApiResponse = factory(root.SwaggerPetstore.ApiClient); + } +}(this, function(ApiClient) { + 'use strict'; + + + + + /** + * The ApiResponse model module. + * @module model/ApiResponse + * @version 1.0.0 + */ + + /** + * Constructs a new ApiResponse. + * @alias module:model/ApiResponse + * @class + */ + var exports = function() { + var _this = this; + + + + + }; + + /** + * Constructs a ApiResponse from a plain JavaScript object, optionally creating a new instance. + * Copies all relevant properties from data to obj if supplied or a new instance if not. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @param {module:model/ApiResponse} obj Optional instance to populate. + * @return {module:model/ApiResponse} The populated ApiResponse instance. + */ + exports.constructFromObject = function(data, obj) { + if (data) { + obj = obj || new exports(); + + if (data.hasOwnProperty('code')) { + obj['code'] = ApiClient.convertToType(data['code'], 'Integer'); + } + if (data.hasOwnProperty('type')) { + obj['type'] = ApiClient.convertToType(data['type'], 'String'); + } + if (data.hasOwnProperty('message')) { + obj['message'] = ApiClient.convertToType(data['message'], 'String'); + } + } + return obj; + } + + /** + * @member {Integer} code + */ + exports.prototype['code'] = undefined; + /** + * @member {String} type + */ + exports.prototype['type'] = undefined; + /** + * @member {String} message + */ + exports.prototype['message'] = undefined; + + + + + return exports; +})); + + diff --git a/samples/client/petstore/javascript-promise/src/model/Cat.js b/samples/client/petstore/javascript-promise/src/model/Cat.js index c878af6edec..a6b25bc6d58 100644 --- a/samples/client/petstore/javascript-promise/src/model/Cat.js +++ b/samples/client/petstore/javascript-promise/src/model/Cat.js @@ -1,7 +1,7 @@ (function(root, factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. - define(['../ApiClient', './Animal'], factory); + define(['ApiClient', 'model/Animal'], factory); } else if (typeof module === 'object' && module.exports) { // CommonJS-like environments that support module.exports, like Node. module.exports = factory(require('../ApiClient'), require('./Animal')); @@ -15,6 +15,9 @@ }(this, function(ApiClient, Animal) { 'use strict'; + + + /** * The Cat model module. * @module model/Cat @@ -29,7 +32,8 @@ * @param className */ var exports = function(className) { - Animal.call(this, className); + var _this = this; + Animal.call(_this, className); }; @@ -41,7 +45,7 @@ * @return {module:model/Cat} The populated Cat instance. */ exports.constructFromObject = function(data, obj) { - if (data) { + if (data) { obj = obj || new exports(); Animal.constructFromObject(data, obj); if (data.hasOwnProperty('declawed')) { @@ -54,7 +58,6 @@ exports.prototype = Object.create(Animal.prototype); exports.prototype.constructor = exports; - /** * @member {Boolean} declawed */ @@ -65,3 +68,5 @@ return exports; })); + + diff --git a/samples/client/petstore/javascript-promise/src/model/Category.js b/samples/client/petstore/javascript-promise/src/model/Category.js index 9956525e037..9e2e19ac5bb 100644 --- a/samples/client/petstore/javascript-promise/src/model/Category.js +++ b/samples/client/petstore/javascript-promise/src/model/Category.js @@ -15,6 +15,9 @@ }(this, function(ApiClient) { 'use strict'; + + + /** * The Category model module. * @module model/Category @@ -54,12 +57,10 @@ return obj; } - /** * @member {Integer} id */ exports.prototype['id'] = undefined; - /** * @member {String} name */ @@ -70,3 +71,5 @@ return exports; })); + + diff --git a/samples/client/petstore/javascript-promise/src/model/Dog.js b/samples/client/petstore/javascript-promise/src/model/Dog.js index e5e55581a70..ee17ae3467f 100644 --- a/samples/client/petstore/javascript-promise/src/model/Dog.js +++ b/samples/client/petstore/javascript-promise/src/model/Dog.js @@ -1,7 +1,7 @@ (function(root, factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. - define(['../ApiClient', './Animal'], factory); + define(['ApiClient', 'model/Animal'], factory); } else if (typeof module === 'object' && module.exports) { // CommonJS-like environments that support module.exports, like Node. module.exports = factory(require('../ApiClient'), require('./Animal')); @@ -15,6 +15,9 @@ }(this, function(ApiClient, Animal) { 'use strict'; + + + /** * The Dog model module. * @module model/Dog @@ -29,7 +32,8 @@ * @param className */ var exports = function(className) { - Animal.call(this, className); + var _this = this; + Animal.call(_this, className); }; @@ -41,7 +45,7 @@ * @return {module:model/Dog} The populated Dog instance. */ exports.constructFromObject = function(data, obj) { - if (data) { + if (data) { obj = obj || new exports(); Animal.constructFromObject(data, obj); if (data.hasOwnProperty('breed')) { @@ -54,7 +58,6 @@ exports.prototype = Object.create(Animal.prototype); exports.prototype.constructor = exports; - /** * @member {String} breed */ @@ -65,3 +68,5 @@ return exports; })); + + diff --git a/samples/client/petstore/javascript-promise/src/model/EnumClass.js b/samples/client/petstore/javascript-promise/src/model/EnumClass.js new file mode 100644 index 00000000000..e9bf5219ee5 --- /dev/null +++ b/samples/client/petstore/javascript-promise/src/model/EnumClass.js @@ -0,0 +1,44 @@ +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(['ApiClient'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + module.exports = factory(require('../ApiClient')); + } else { + // Browser globals (root is window) + if (!root.SwaggerPetstore) { + root.SwaggerPetstore = {}; + } + root.SwaggerPetstore.EnumClass = factory(root.SwaggerPetstore.ApiClient); + } +}(this, function(ApiClient) { + 'use strict'; + + + /** + * Enum class EnumClass. + * @enum {} + * @readonly + */ + var exports = { + /** + * value: "_abc" + * @const + */ + "_abc": "_abc", + /** + * value: "-efg" + * @const + */ + "-efg": "-efg", + /** + * value: "(xyz)" + * @const + */ + "(xyz)": "(xyz)" }; + + return exports; +})); + + diff --git a/samples/client/petstore/javascript-promise/src/model/EnumTest.js b/samples/client/petstore/javascript-promise/src/model/EnumTest.js new file mode 100644 index 00000000000..6f8f0de3836 --- /dev/null +++ b/samples/client/petstore/javascript-promise/src/model/EnumTest.js @@ -0,0 +1,131 @@ +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(['ApiClient'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + module.exports = factory(require('../ApiClient')); + } else { + // Browser globals (root is window) + if (!root.SwaggerPetstore) { + root.SwaggerPetstore = {}; + } + root.SwaggerPetstore.EnumTest = factory(root.SwaggerPetstore.ApiClient); + } +}(this, function(ApiClient) { + 'use strict'; + + + + + /** + * The EnumTest model module. + * @module model/EnumTest + * @version 1.0.0 + */ + + /** + * Constructs a new EnumTest. + * @alias module:model/EnumTest + * @class + */ + var exports = function() { + var _this = this; + + + + + }; + + /** + * Constructs a EnumTest from a plain JavaScript object, optionally creating a new instance. + * Copies all relevant properties from data to obj if supplied or a new instance if not. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @param {module:model/EnumTest} obj Optional instance to populate. + * @return {module:model/EnumTest} The populated EnumTest instance. + */ + exports.constructFromObject = function(data, obj) { + if (data) { + obj = obj || new exports(); + + if (data.hasOwnProperty('enum_string')) { + obj['enum_string'] = ApiClient.convertToType(data['enum_string'], 'String'); + } + if (data.hasOwnProperty('enum_integer')) { + obj['enum_integer'] = ApiClient.convertToType(data['enum_integer'], 'Integer'); + } + if (data.hasOwnProperty('enum_number')) { + obj['enum_number'] = ApiClient.convertToType(data['enum_number'], 'Number'); + } + } + return obj; + } + + /** + * @member {module:model/EnumTest.EnumStringEnum} enum_string + */ + exports.prototype['enum_string'] = undefined; + /** + * @member {module:model/EnumTest.EnumIntegerEnum} enum_integer + */ + exports.prototype['enum_integer'] = undefined; + /** + * @member {module:model/EnumTest.EnumNumberEnum} enum_number + */ + exports.prototype['enum_number'] = undefined; + + + /** + * Allowed values for the enum_string property. + * @enum {String} + * @readonly + */ + exports.EnumStringEnum = { + /** + * value: "UPPER" + * @const + */ + "UPPER": "UPPER", + /** + * value: "lower" + * @const + */ + "lower": "lower" }; + /** + * Allowed values for the enum_integer property. + * @enum {Integer} + * @readonly + */ + exports.EnumIntegerEnum = { + /** + * value: 1 + * @const + */ + "1": 1, + /** + * value: -1 + * @const + */ + "-1": -1 }; + /** + * Allowed values for the enum_number property. + * @enum {Number} + * @readonly + */ + exports.EnumNumberEnum = { + /** + * value: 1.1 + * @const + */ + "1.1": 1.1, + /** + * value: -1.2 + * @const + */ + "-1.2": -1.2 }; + + + return exports; +})); + + diff --git a/samples/client/petstore/javascript-promise/src/model/FormatTest.js b/samples/client/petstore/javascript-promise/src/model/FormatTest.js index 46a9bc854fc..ed9e0cfcaf8 100644 --- a/samples/client/petstore/javascript-promise/src/model/FormatTest.js +++ b/samples/client/petstore/javascript-promise/src/model/FormatTest.js @@ -1,7 +1,7 @@ (function(root, factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. - define(['../ApiClient'], factory); + define(['ApiClient'], factory); } else if (typeof module === 'object' && module.exports) { // CommonJS-like environments that support module.exports, like Node. module.exports = factory(require('../ApiClient')); @@ -15,6 +15,9 @@ }(this, function(ApiClient) { 'use strict'; + + + /** * The FormatTest model module. * @module model/FormatTest @@ -26,20 +29,26 @@ * @alias module:model/FormatTest * @class * @param _number + * @param _byte + * @param _date + * @param password */ - var exports = function(_number) { + var exports = function(_number, _byte, _date, password) { + var _this = this; - this['number'] = _number; - - + _this['number'] = _number; + _this['byte'] = _byte; + + _this['date'] = _date; + _this['password'] = password; }; /** @@ -50,7 +59,7 @@ * @return {module:model/FormatTest} The populated FormatTest instance. */ exports.constructFromObject = function(data, obj) { - if (data) { + if (data) { obj = obj || new exports(); if (data.hasOwnProperty('integer')) { @@ -84,70 +93,75 @@ obj['date'] = ApiClient.convertToType(data['date'], 'Date'); } if (data.hasOwnProperty('dateTime')) { - obj['dateTime'] = ApiClient.convertToType(data['dateTime'], 'String'); + obj['dateTime'] = ApiClient.convertToType(data['dateTime'], 'Date'); + } + if (data.hasOwnProperty('uuid')) { + obj['uuid'] = ApiClient.convertToType(data['uuid'], 'String'); + } + if (data.hasOwnProperty('password')) { + obj['password'] = ApiClient.convertToType(data['password'], 'String'); } } return obj; } - /** * @member {Integer} integer */ exports.prototype['integer'] = undefined; - /** * @member {Integer} int32 */ exports.prototype['int32'] = undefined; - /** * @member {Integer} int64 */ exports.prototype['int64'] = undefined; - /** * @member {Number} number */ exports.prototype['number'] = undefined; - /** * @member {Number} float */ exports.prototype['float'] = undefined; - /** * @member {Number} double */ exports.prototype['double'] = undefined; - /** * @member {String} string */ exports.prototype['string'] = undefined; - /** * @member {String} byte */ exports.prototype['byte'] = undefined; - /** * @member {String} binary */ exports.prototype['binary'] = undefined; - /** * @member {Date} date */ exports.prototype['date'] = undefined; - /** - * @member {String} dateTime + * @member {Date} dateTime */ exports.prototype['dateTime'] = undefined; + /** + * @member {String} uuid + */ + exports.prototype['uuid'] = undefined; + /** + * @member {String} password + */ + exports.prototype['password'] = undefined; return exports; })); + + diff --git a/samples/client/petstore/javascript-promise/src/model/InlineResponse200.js b/samples/client/petstore/javascript-promise/src/model/InlineResponse200.js deleted file mode 100644 index f2abaf1bd1b..00000000000 --- a/samples/client/petstore/javascript-promise/src/model/InlineResponse200.js +++ /dev/null @@ -1,132 +0,0 @@ -(function(root, factory) { - if (typeof define === 'function' && define.amd) { - // AMD. Register as an anonymous module. - define(['ApiClient', 'model/Tag'], factory); - } else if (typeof module === 'object' && module.exports) { - // CommonJS-like environments that support module.exports, like Node. - module.exports = factory(require('../ApiClient'), require('./Tag')); - } else { - // Browser globals (root is window) - if (!root.SwaggerPetstore) { - root.SwaggerPetstore = {}; - } - root.SwaggerPetstore.InlineResponse200 = factory(root.SwaggerPetstore.ApiClient, root.SwaggerPetstore.Tag); - } -}(this, function(ApiClient, Tag) { - 'use strict'; - - /** - * The InlineResponse200 model module. - * @module model/InlineResponse200 - * @version 1.0.0 - */ - - /** - * Constructs a new InlineResponse200. - * @alias module:model/InlineResponse200 - * @class - * @param id - */ - var exports = function(id) { - - - this['id'] = id; - - - - - }; - - /** - * Constructs a InlineResponse200 from a plain JavaScript object, optionally creating a new instance. - * Copies all relevant properties from data to obj if supplied or a new instance if not. - * @param {Object} data The plain JavaScript object bearing properties of interest. - * @param {module:model/InlineResponse200} obj Optional instance to populate. - * @return {module:model/InlineResponse200} The populated InlineResponse200 instance. - */ - exports.constructFromObject = function(data, obj) { - if (data) { - obj = obj || new exports(); - - if (data.hasOwnProperty('tags')) { - obj['tags'] = ApiClient.convertToType(data['tags'], [Tag]); - } - if (data.hasOwnProperty('id')) { - obj['id'] = ApiClient.convertToType(data['id'], 'Integer'); - } - if (data.hasOwnProperty('category')) { - obj['category'] = ApiClient.convertToType(data['category'], Object); - } - if (data.hasOwnProperty('status')) { - obj['status'] = ApiClient.convertToType(data['status'], 'String'); - } - if (data.hasOwnProperty('name')) { - obj['name'] = ApiClient.convertToType(data['name'], 'String'); - } - if (data.hasOwnProperty('photoUrls')) { - obj['photoUrls'] = ApiClient.convertToType(data['photoUrls'], ['String']); - } - } - return obj; - } - - - /** - * @member {Array.} tags - */ - exports.prototype['tags'] = undefined; - - /** - * @member {Integer} id - */ - exports.prototype['id'] = undefined; - - /** - * @member {Object} category - */ - exports.prototype['category'] = undefined; - - /** - * pet status in the store - * @member {module:model/InlineResponse200.StatusEnum} status - */ - exports.prototype['status'] = undefined; - - /** - * @member {String} name - */ - exports.prototype['name'] = undefined; - - /** - * @member {Array.} photoUrls - */ - exports.prototype['photoUrls'] = undefined; - - - /** - * Allowed values for the status property. - * @enum {String} - * @readonly - */ - exports.StatusEnum = { - /** - * value: available - * @const - */ - AVAILABLE: "available", - - /** - * value: pending - * @const - */ - PENDING: "pending", - - /** - * value: sold - * @const - */ - SOLD: "sold" - }; - - return exports; -})); diff --git a/samples/client/petstore/javascript-promise/src/model/Model200Response.js b/samples/client/petstore/javascript-promise/src/model/Model200Response.js index 8381185d9d0..1d83d420287 100644 --- a/samples/client/petstore/javascript-promise/src/model/Model200Response.js +++ b/samples/client/petstore/javascript-promise/src/model/Model200Response.js @@ -15,6 +15,9 @@ }(this, function(ApiClient) { 'use strict'; + + + /** * The Model200Response model module. * @module model/Model200Response @@ -28,6 +31,7 @@ * @class */ var exports = function() { + var _this = this; }; @@ -40,7 +44,7 @@ * @return {module:model/Model200Response} The populated Model200Response instance. */ exports.constructFromObject = function(data, obj) { - if (data) { + if (data) { obj = obj || new exports(); if (data.hasOwnProperty('name')) { @@ -50,7 +54,6 @@ return obj; } - /** * @member {Integer} name */ @@ -61,3 +64,5 @@ return exports; })); + + diff --git a/samples/client/petstore/javascript-promise/src/model/ModelReturn.js b/samples/client/petstore/javascript-promise/src/model/ModelReturn.js index 9549db64d46..d0236e77b17 100644 --- a/samples/client/petstore/javascript-promise/src/model/ModelReturn.js +++ b/samples/client/petstore/javascript-promise/src/model/ModelReturn.js @@ -15,6 +15,9 @@ }(this, function(ApiClient) { 'use strict'; + + + /** * The ModelReturn model module. * @module model/ModelReturn @@ -28,6 +31,7 @@ * @class */ var exports = function() { + var _this = this; }; @@ -40,7 +44,7 @@ * @return {module:model/ModelReturn} The populated ModelReturn instance. */ exports.constructFromObject = function(data, obj) { - if (data) { + if (data) { obj = obj || new exports(); if (data.hasOwnProperty('return')) { @@ -50,7 +54,6 @@ return obj; } - /** * @member {Integer} return */ @@ -61,3 +64,5 @@ return exports; })); + + diff --git a/samples/client/petstore/javascript-promise/src/model/Name.js b/samples/client/petstore/javascript-promise/src/model/Name.js index 08a5a34c29a..93d1d55deb2 100644 --- a/samples/client/petstore/javascript-promise/src/model/Name.js +++ b/samples/client/petstore/javascript-promise/src/model/Name.js @@ -15,6 +15,9 @@ }(this, function(ApiClient) { 'use strict'; + + + /** * The Name model module. * @module model/Name @@ -29,8 +32,10 @@ * @param name */ var exports = function(name) { + var _this = this; + + _this['name'] = name; - this['name'] = name; }; @@ -42,7 +47,7 @@ * @return {module:model/Name} The populated Name instance. */ exports.constructFromObject = function(data, obj) { - if (data) { + if (data) { obj = obj || new exports(); if (data.hasOwnProperty('name')) { @@ -51,23 +56,30 @@ if (data.hasOwnProperty('snake_case')) { obj['snake_case'] = ApiClient.convertToType(data['snake_case'], 'Integer'); } + if (data.hasOwnProperty('property')) { + obj['property'] = ApiClient.convertToType(data['property'], 'String'); + } } return obj; } - /** * @member {Integer} name */ exports.prototype['name'] = undefined; - /** * @member {Integer} snake_case */ exports.prototype['snake_case'] = undefined; + /** + * @member {String} property + */ + exports.prototype['property'] = undefined; return exports; })); + + diff --git a/samples/client/petstore/javascript-promise/src/model/Order.js b/samples/client/petstore/javascript-promise/src/model/Order.js index 664908b77a9..57f77d84ccd 100644 --- a/samples/client/petstore/javascript-promise/src/model/Order.js +++ b/samples/client/petstore/javascript-promise/src/model/Order.js @@ -15,6 +15,9 @@ }(this, function(ApiClient) { 'use strict'; + + + /** * The Order model module. * @module model/Order @@ -70,37 +73,32 @@ return obj; } - /** * @member {Integer} id */ exports.prototype['id'] = undefined; - /** * @member {Integer} petId */ exports.prototype['petId'] = undefined; - /** * @member {Integer} quantity */ exports.prototype['quantity'] = undefined; - /** * @member {Date} shipDate */ exports.prototype['shipDate'] = undefined; - /** * Order Status * @member {module:model/Order.StatusEnum} status */ exports.prototype['status'] = undefined; - /** * @member {Boolean} complete + * @default false */ - exports.prototype['complete'] = undefined; + exports.prototype['complete'] = false; /** @@ -108,25 +106,25 @@ * @enum {String} * @readonly */ - exports.StatusEnum = { + exports.StatusEnum = { /** - * value: placed + * value: "placed" * @const */ - PLACED: "placed", - + "placed": "placed", /** - * value: approved + * value: "approved" * @const */ - APPROVED: "approved", - + "approved": "approved", /** - * value: delivered + * value: "delivered" * @const */ - DELIVERED: "delivered" - }; + "delivered": "delivered" }; + return exports; })); + + diff --git a/samples/client/petstore/javascript-promise/src/model/Pet.js b/samples/client/petstore/javascript-promise/src/model/Pet.js index ae907d35ca2..fe14361dbf2 100644 --- a/samples/client/petstore/javascript-promise/src/model/Pet.js +++ b/samples/client/petstore/javascript-promise/src/model/Pet.js @@ -15,6 +15,9 @@ }(this, function(ApiClient, Category, Tag) { 'use strict'; + + + /** * The Pet model module. * @module model/Pet @@ -72,32 +75,26 @@ return obj; } - /** * @member {Integer} id */ exports.prototype['id'] = undefined; - /** * @member {module:model/Category} category */ exports.prototype['category'] = undefined; - /** * @member {String} name */ exports.prototype['name'] = undefined; - /** * @member {Array.} photoUrls */ exports.prototype['photoUrls'] = undefined; - /** * @member {Array.} tags */ exports.prototype['tags'] = undefined; - /** * pet status in the store * @member {module:model/Pet.StatusEnum} status @@ -110,25 +107,25 @@ * @enum {String} * @readonly */ - exports.StatusEnum = { + exports.StatusEnum = { /** - * value: available + * value: "available" * @const */ - AVAILABLE: "available", - + "available": "available", /** - * value: pending + * value: "pending" * @const */ - PENDING: "pending", - + "pending": "pending", /** - * value: sold + * value: "sold" * @const */ - SOLD: "sold" - }; + "sold": "sold" }; + return exports; })); + + diff --git a/samples/client/petstore/javascript-promise/src/model/SpecialModelName.js b/samples/client/petstore/javascript-promise/src/model/SpecialModelName.js index 8694196cdd9..d5a0e992a73 100644 --- a/samples/client/petstore/javascript-promise/src/model/SpecialModelName.js +++ b/samples/client/petstore/javascript-promise/src/model/SpecialModelName.js @@ -15,6 +15,9 @@ }(this, function(ApiClient) { 'use strict'; + + + /** * The SpecialModelName model module. * @module model/SpecialModelName @@ -27,6 +30,7 @@ * @class */ var exports = function() { + var _this = this; }; @@ -39,7 +43,7 @@ * @return {module:model/SpecialModelName} The populated SpecialModelName instance. */ exports.constructFromObject = function(data, obj) { - if (data) { + if (data) { obj = obj || new exports(); if (data.hasOwnProperty('$special[property.name]')) { @@ -49,7 +53,6 @@ return obj; } - /** * @member {Integer} $special[property.name] */ @@ -60,3 +63,5 @@ return exports; })); + + diff --git a/samples/client/petstore/javascript-promise/src/model/Tag.js b/samples/client/petstore/javascript-promise/src/model/Tag.js index d9ab35fb8b5..443d312b76a 100644 --- a/samples/client/petstore/javascript-promise/src/model/Tag.js +++ b/samples/client/petstore/javascript-promise/src/model/Tag.js @@ -15,6 +15,9 @@ }(this, function(ApiClient) { 'use strict'; + + + /** * The Tag model module. * @module model/Tag @@ -54,12 +57,10 @@ return obj; } - /** * @member {Integer} id */ exports.prototype['id'] = undefined; - /** * @member {String} name */ @@ -70,3 +71,5 @@ return exports; })); + + diff --git a/samples/client/petstore/javascript-promise/src/model/User.js b/samples/client/petstore/javascript-promise/src/model/User.js index 3bc6aaab630..2360c7c6314 100644 --- a/samples/client/petstore/javascript-promise/src/model/User.js +++ b/samples/client/petstore/javascript-promise/src/model/User.js @@ -15,6 +15,9 @@ }(this, function(ApiClient) { 'use strict'; + + + /** * The User model module. * @module model/User @@ -78,42 +81,34 @@ return obj; } - /** * @member {Integer} id */ exports.prototype['id'] = undefined; - /** * @member {String} username */ exports.prototype['username'] = undefined; - /** * @member {String} firstName */ exports.prototype['firstName'] = undefined; - /** * @member {String} lastName */ exports.prototype['lastName'] = undefined; - /** * @member {String} email */ exports.prototype['email'] = undefined; - /** * @member {String} password */ exports.prototype['password'] = undefined; - /** * @member {String} phone */ exports.prototype['phone'] = undefined; - /** * User Status * @member {Integer} userStatus @@ -125,3 +120,5 @@ return exports; })); + + diff --git a/samples/client/petstore/javascript-promise/test/api/PetApiTest.js b/samples/client/petstore/javascript-promise/test/api/PetApiTest.js index 1119546014d..98debb8ea19 100644 --- a/samples/client/petstore/javascript-promise/test/api/PetApiTest.js +++ b/samples/client/petstore/javascript-promise/test/api/PetApiTest.js @@ -49,7 +49,7 @@ var createRandomPet = function() { describe('PetApi', function() { it('should create and get pet', function(done) { var pet = createRandomPet(); - api.addPet({body: pet}) + api.addPet(pet) .then(function() { return api.getPetById(pet.id) }) @@ -63,7 +63,7 @@ describe('PetApi', function() { .to.be(getProperty(getProperty(pet, "getCategory", "category"), "getName", "name")); api.deletePet(pet.id); - done(); + done(); }); }); }); diff --git a/samples/client/petstore/javascript/README.md b/samples/client/petstore/javascript/README.md index 651e1e6047f..1bf60abb9c3 100644 --- a/samples/client/petstore/javascript/README.md +++ b/samples/client/petstore/javascript/README.md @@ -6,7 +6,7 @@ This SDK is automatically generated by the [Swagger Codegen](https://github.com/ - API version: 1.0.0 - Package version: 1.0.0 -- Build date: 2016-05-03T11:05:41.851+08:00 +- Build date: 2016-05-06T18:34:50.267+08:00 - Build package: class io.swagger.codegen.languages.JavascriptClientCodegen ## Installation @@ -117,6 +117,7 @@ Class | Method | HTTP request | Description ## Documentation for Models - [SwaggerPetstore.Animal](docs/Animal.md) + - [SwaggerPetstore.AnimalFarm](docs/AnimalFarm.md) - [SwaggerPetstore.ApiResponse](docs/ApiResponse.md) - [SwaggerPetstore.Cat](docs/Cat.md) - [SwaggerPetstore.Category](docs/Category.md) @@ -137,12 +138,6 @@ Class | Method | HTTP request | Description ## Documentation for Authorization -### api_key - -- **Type**: API key -- **API key parameter name**: api_key -- **Location**: HTTP header - ### petstore_auth - **Type**: OAuth @@ -152,3 +147,9 @@ Class | Method | HTTP request | Description - write:pets: modify pets in your account - read:pets: read your pets +### api_key + +- **Type**: API key +- **API key parameter name**: api_key +- **Location**: HTTP header + diff --git a/samples/client/petstore/javascript/docs/AnimalFarm.md b/samples/client/petstore/javascript/docs/AnimalFarm.md new file mode 100644 index 00000000000..b72739a44c4 --- /dev/null +++ b/samples/client/petstore/javascript/docs/AnimalFarm.md @@ -0,0 +1,7 @@ +# SwaggerPetstore.AnimalFarm + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + + diff --git a/samples/client/petstore/javascript/docs/EnumClass.md b/samples/client/petstore/javascript/docs/EnumClass.md index 5159ccfb454..04b89362941 100644 --- a/samples/client/petstore/javascript/docs/EnumClass.md +++ b/samples/client/petstore/javascript/docs/EnumClass.md @@ -1,7 +1,12 @@ # SwaggerPetstore.EnumClass -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- +## Enum + + +* `_abc` (value: `"_abc"`) + +* `-efg` (value: `"-efg"`) + +* `(xyz)` (value: `"(xyz)"`) diff --git a/samples/client/petstore/javascript/docs/EnumTest.md b/samples/client/petstore/javascript/docs/EnumTest.md index 724eea8a25e..22c4da11b9d 100644 --- a/samples/client/petstore/javascript/docs/EnumTest.md +++ b/samples/client/petstore/javascript/docs/EnumTest.md @@ -8,3 +8,36 @@ Name | Type | Description | Notes **enumNumber** | **Number** | | [optional] + +## Enum: EnumStringEnum + + +* `UPPER` (value: `"UPPER"`) + +* `lower` (value: `"lower"`) + + + + + +## Enum: EnumIntegerEnum + + +* `1` (value: `1`) + +* `-1` (value: `-1`) + + + + + +## Enum: EnumNumberEnum + + +* `1.1` (value: `1.1`) + +* `-1.2` (value: `-1.2`) + + + + diff --git a/samples/client/petstore/javascript/docs/InlineResponse200.md b/samples/client/petstore/javascript/docs/InlineResponse200.md deleted file mode 100644 index bbb11067e9a..00000000000 --- a/samples/client/petstore/javascript/docs/InlineResponse200.md +++ /dev/null @@ -1,13 +0,0 @@ -# SwaggerPetstore.InlineResponse200 - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**tags** | [**[Tag]**](Tag.md) | | [optional] -**id** | **Integer** | | -**category** | **Object** | | [optional] -**status** | **String** | pet status in the store | [optional] -**name** | **String** | | [optional] -**photoUrls** | **[String]** | | [optional] - - diff --git a/samples/client/petstore/javascript/docs/Order.md b/samples/client/petstore/javascript/docs/Order.md index 10503b58206..95ee5946ed2 100644 --- a/samples/client/petstore/javascript/docs/Order.md +++ b/samples/client/petstore/javascript/docs/Order.md @@ -11,3 +11,16 @@ Name | Type | Description | Notes **complete** | **Boolean** | | [optional] [default to false] + +## Enum: StatusEnum + + +* `placed` (value: `"placed"`) + +* `approved` (value: `"approved"`) + +* `delivered` (value: `"delivered"`) + + + + diff --git a/samples/client/petstore/javascript/docs/Pet.md b/samples/client/petstore/javascript/docs/Pet.md index f1b049dcadd..a08333731c0 100644 --- a/samples/client/petstore/javascript/docs/Pet.md +++ b/samples/client/petstore/javascript/docs/Pet.md @@ -11,3 +11,16 @@ Name | Type | Description | Notes **status** | **String** | pet status in the store | [optional] + +## Enum: StatusEnum + + +* `available` (value: `"available"`) + +* `pending` (value: `"pending"`) + +* `sold` (value: `"sold"`) + + + + diff --git a/samples/client/petstore/javascript/src/ApiClient.js b/samples/client/petstore/javascript/src/ApiClient.js index d45704dcdac..2598dd8d9ea 100644 --- a/samples/client/petstore/javascript/src/ApiClient.js +++ b/samples/client/petstore/javascript/src/ApiClient.js @@ -40,8 +40,8 @@ * @type {Array.} */ this.authentications = { - 'api_key': {type: 'apiKey', 'in': 'header', name: 'api_key'}, - 'petstore_auth': {type: 'oauth2'} + 'petstore_auth': {type: 'oauth2'}, + 'api_key': {type: 'apiKey', 'in': 'header', name: 'api_key'} }; /** * The default HTTP headers to be included for all API calls. diff --git a/samples/client/petstore/javascript/src/index.js b/samples/client/petstore/javascript/src/index.js index 2c3fb27ef65..727b4782f45 100644 --- a/samples/client/petstore/javascript/src/index.js +++ b/samples/client/petstore/javascript/src/index.js @@ -1,12 +1,12 @@ (function(factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. - define(['ApiClient', 'model/Animal', 'model/ApiResponse', 'model/Cat', 'model/Category', 'model/Dog', 'model/EnumClass', 'model/EnumTest', 'model/FormatTest', 'model/Model200Response', 'model/ModelReturn', 'model/Name', 'model/Order', 'model/Pet', 'model/SpecialModelName', 'model/Tag', 'model/User', 'api/FakeApi', 'api/PetApi', 'api/StoreApi', 'api/UserApi'], factory); + define(['ApiClient', 'model/Animal', 'model/AnimalFarm', 'model/ApiResponse', 'model/Cat', 'model/Category', 'model/Dog', 'model/EnumClass', 'model/EnumTest', 'model/FormatTest', 'model/Model200Response', 'model/ModelReturn', 'model/Name', 'model/Order', 'model/Pet', 'model/SpecialModelName', 'model/Tag', 'model/User', 'api/FakeApi', 'api/PetApi', 'api/StoreApi', 'api/UserApi'], factory); } else if (typeof module === 'object' && module.exports) { // CommonJS-like environments that support module.exports, like Node. - module.exports = factory(require('./ApiClient'), require('./model/Animal'), require('./model/ApiResponse'), require('./model/Cat'), require('./model/Category'), require('./model/Dog'), require('./model/EnumClass'), require('./model/EnumTest'), require('./model/FormatTest'), require('./model/Model200Response'), require('./model/ModelReturn'), require('./model/Name'), require('./model/Order'), require('./model/Pet'), require('./model/SpecialModelName'), require('./model/Tag'), require('./model/User'), require('./api/FakeApi'), require('./api/PetApi'), require('./api/StoreApi'), require('./api/UserApi')); + module.exports = factory(require('./ApiClient'), require('./model/Animal'), require('./model/AnimalFarm'), require('./model/ApiResponse'), require('./model/Cat'), require('./model/Category'), require('./model/Dog'), require('./model/EnumClass'), require('./model/EnumTest'), require('./model/FormatTest'), require('./model/Model200Response'), require('./model/ModelReturn'), require('./model/Name'), require('./model/Order'), require('./model/Pet'), require('./model/SpecialModelName'), require('./model/Tag'), require('./model/User'), require('./api/FakeApi'), require('./api/PetApi'), require('./api/StoreApi'), require('./api/UserApi')); } -}(function(ApiClient, Animal, ApiResponse, Cat, Category, Dog, EnumClass, EnumTest, FormatTest, Model200Response, ModelReturn, Name, Order, Pet, SpecialModelName, Tag, User, FakeApi, PetApi, StoreApi, UserApi) { +}(function(ApiClient, Animal, AnimalFarm, ApiResponse, Cat, Category, Dog, EnumClass, EnumTest, FormatTest, Model200Response, ModelReturn, Name, Order, Pet, SpecialModelName, Tag, User, FakeApi, PetApi, StoreApi, UserApi) { 'use strict'; /** @@ -51,6 +51,11 @@ * @property {module:model/Animal} */ Animal: Animal, + /** + * The AnimalFarm model constructor. + * @property {module:model/AnimalFarm} + */ + AnimalFarm: AnimalFarm, /** * The ApiResponse model constructor. * @property {module:model/ApiResponse} diff --git a/samples/client/petstore/javascript/src/model/AnimalFarm.js b/samples/client/petstore/javascript/src/model/AnimalFarm.js new file mode 100644 index 00000000000..d5f6aa2a424 --- /dev/null +++ b/samples/client/petstore/javascript/src/model/AnimalFarm.js @@ -0,0 +1,64 @@ +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(['ApiClient', 'model/Animal'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + module.exports = factory(require('../ApiClient'), require('./Animal')); + } else { + // Browser globals (root is window) + if (!root.SwaggerPetstore) { + root.SwaggerPetstore = {}; + } + root.SwaggerPetstore.AnimalFarm = factory(root.SwaggerPetstore.ApiClient, root.SwaggerPetstore.Animal); + } +}(this, function(ApiClient, Animal) { + 'use strict'; + + + + + /** + * The AnimalFarm model module. + * @module model/AnimalFarm + * @version 1.0.0 + */ + + /** + * Constructs a new AnimalFarm. + * @alias module:model/AnimalFarm + * @class + * @extends Array + */ + var exports = function() { + var _this = this; + _this = new Array(); + Object.setPrototypeOf(_this, exports); + + return _this; + }; + + /** + * Constructs a AnimalFarm from a plain JavaScript object, optionally creating a new instance. + * Copies all relevant properties from data to obj if supplied or a new instance if not. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @param {module:model/AnimalFarm} obj Optional instance to populate. + * @return {module:model/AnimalFarm} The populated AnimalFarm instance. + */ + exports.constructFromObject = function(data, obj) { + if (data) { + obj = obj || new exports(); + ApiClient.constructFromObject(data, obj, Animal); + + } + return obj; + } + + + + + + return exports; +})); + + diff --git a/samples/client/petstore/javascript/src/model/EnumClass.js b/samples/client/petstore/javascript/src/model/EnumClass.js index 2ff3398113a..e9bf5219ee5 100644 --- a/samples/client/petstore/javascript/src/model/EnumClass.js +++ b/samples/client/petstore/javascript/src/model/EnumClass.js @@ -21,19 +21,19 @@ * @enum {} * @readonly */ - exports.EnumClass = { + var exports = { /** - * value: _abc + * value: "_abc" * @const */ "_abc": "_abc", /** - * value: -efg + * value: "-efg" * @const */ "-efg": "-efg", /** - * value: (xyz) + * value: "(xyz)" * @const */ "(xyz)": "(xyz)" }; diff --git a/samples/client/petstore/javascript/src/model/InlineResponse200.js b/samples/client/petstore/javascript/src/model/InlineResponse200.js deleted file mode 100644 index f2abaf1bd1b..00000000000 --- a/samples/client/petstore/javascript/src/model/InlineResponse200.js +++ /dev/null @@ -1,132 +0,0 @@ -(function(root, factory) { - if (typeof define === 'function' && define.amd) { - // AMD. Register as an anonymous module. - define(['ApiClient', 'model/Tag'], factory); - } else if (typeof module === 'object' && module.exports) { - // CommonJS-like environments that support module.exports, like Node. - module.exports = factory(require('../ApiClient'), require('./Tag')); - } else { - // Browser globals (root is window) - if (!root.SwaggerPetstore) { - root.SwaggerPetstore = {}; - } - root.SwaggerPetstore.InlineResponse200 = factory(root.SwaggerPetstore.ApiClient, root.SwaggerPetstore.Tag); - } -}(this, function(ApiClient, Tag) { - 'use strict'; - - /** - * The InlineResponse200 model module. - * @module model/InlineResponse200 - * @version 1.0.0 - */ - - /** - * Constructs a new InlineResponse200. - * @alias module:model/InlineResponse200 - * @class - * @param id - */ - var exports = function(id) { - - - this['id'] = id; - - - - - }; - - /** - * Constructs a InlineResponse200 from a plain JavaScript object, optionally creating a new instance. - * Copies all relevant properties from data to obj if supplied or a new instance if not. - * @param {Object} data The plain JavaScript object bearing properties of interest. - * @param {module:model/InlineResponse200} obj Optional instance to populate. - * @return {module:model/InlineResponse200} The populated InlineResponse200 instance. - */ - exports.constructFromObject = function(data, obj) { - if (data) { - obj = obj || new exports(); - - if (data.hasOwnProperty('tags')) { - obj['tags'] = ApiClient.convertToType(data['tags'], [Tag]); - } - if (data.hasOwnProperty('id')) { - obj['id'] = ApiClient.convertToType(data['id'], 'Integer'); - } - if (data.hasOwnProperty('category')) { - obj['category'] = ApiClient.convertToType(data['category'], Object); - } - if (data.hasOwnProperty('status')) { - obj['status'] = ApiClient.convertToType(data['status'], 'String'); - } - if (data.hasOwnProperty('name')) { - obj['name'] = ApiClient.convertToType(data['name'], 'String'); - } - if (data.hasOwnProperty('photoUrls')) { - obj['photoUrls'] = ApiClient.convertToType(data['photoUrls'], ['String']); - } - } - return obj; - } - - - /** - * @member {Array.} tags - */ - exports.prototype['tags'] = undefined; - - /** - * @member {Integer} id - */ - exports.prototype['id'] = undefined; - - /** - * @member {Object} category - */ - exports.prototype['category'] = undefined; - - /** - * pet status in the store - * @member {module:model/InlineResponse200.StatusEnum} status - */ - exports.prototype['status'] = undefined; - - /** - * @member {String} name - */ - exports.prototype['name'] = undefined; - - /** - * @member {Array.} photoUrls - */ - exports.prototype['photoUrls'] = undefined; - - - /** - * Allowed values for the status property. - * @enum {String} - * @readonly - */ - exports.StatusEnum = { - /** - * value: available - * @const - */ - AVAILABLE: "available", - - /** - * value: pending - * @const - */ - PENDING: "pending", - - /** - * value: sold - * @const - */ - SOLD: "sold" - }; - - return exports; -})); diff --git a/samples/client/petstore/objc/README.md b/samples/client/petstore/objc/README.md index bd0f24851a7..f4b3f2f2f76 100644 --- a/samples/client/petstore/objc/README.md +++ b/samples/client/petstore/objc/README.md @@ -6,7 +6,7 @@ This ObjC package is automatically generated by the [Swagger Codegen](https://gi - API version: 1.0.0 - Package version: -- Build date: 2016-04-25T18:52:19.055+02:00 +- Build date: 2016-05-08T12:06:01.121+02:00 - Build package: class io.swagger.codegen.languages.ObjcClientCodegen ## Requirements @@ -19,7 +19,7 @@ The SDK requires [**ARC (Automatic Reference Counting)**](http://stackoverflow.c Add the following to the Podfile: ```ruby -pod 'SwaggerClient', :git => 'https://github.com/YOUR_GIT_USR_ID/YOUR_GIT_REPO_ID.git' +pod 'SwaggerClient', :git => 'https://github.com/GIT_USER_ID/GIT_REPO_ID.git' ``` To specify a particular branch, append `, :branch => 'branch-name-here'` diff --git a/samples/client/petstore/objc/SwaggerClient/SWG200Response.h b/samples/client/petstore/objc/SwaggerClient/SWG200Response.h deleted file mode 100644 index c576bc204ad..00000000000 --- a/samples/client/petstore/objc/SwaggerClient/SWG200Response.h +++ /dev/null @@ -1,20 +0,0 @@ -#import -#import "SWGObject.h" - -/** - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen - * Do not edit the class manually. - */ - - - -@protocol SWG200Response -@end - -@interface SWG200Response : SWGObject - - -@property(nonatomic) NSNumber* name; - -@end diff --git a/samples/client/petstore/objc/SwaggerClient/SWG200Response.m b/samples/client/petstore/objc/SwaggerClient/SWG200Response.m deleted file mode 100644 index 9cafc782f1a..00000000000 --- a/samples/client/petstore/objc/SwaggerClient/SWG200Response.m +++ /dev/null @@ -1,51 +0,0 @@ -#import "SWG200Response.h" - -@implementation SWG200Response - -- (instancetype)init { - self = [super init]; - - if (self) { - // initalise property's default value, if any - - } - - return self; -} - - -/** - * Maps json key to property name. - * This method is used by `JSONModel`. - */ -+ (JSONKeyMapper *)keyMapper -{ - return [[JSONKeyMapper alloc] initWithDictionary:@{ @"name": @"name" }]; -} - -/** - * Indicates whether the property with the given name is optional. - * If `propertyName` is optional, then return `YES`, otherwise return `NO`. - * This method is used by `JSONModel`. - */ -+ (BOOL)propertyIsOptional:(NSString *)propertyName -{ - NSArray *optionalProperties = @[@"name"]; - - if ([optionalProperties containsObject:propertyName]) { - return YES; - } - else { - return NO; - } -} - -/** - * Gets the string presentation of the object. - * This method will be called when logging model object using `NSLog`. - */ -- (NSString *)description { - return [[self toDictionary] description]; -} - -@end diff --git a/samples/client/petstore/objc/SwaggerClient/SWGApiClient.h b/samples/client/petstore/objc/SwaggerClient/SWGApiClient.h index 5d40ef2f5f0..82472ab20bf 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGApiClient.h +++ b/samples/client/petstore/objc/SwaggerClient/SWGApiClient.h @@ -1,11 +1,12 @@ #import #import -#import +#import #import "SWGJSONResponseSerializer.h" #import "SWGJSONRequestSerializer.h" #import "SWGQueryParamCollection.h" #import "SWGConfiguration.h" - +#import "SWGResponseDeserializer.h" +#import "SWGSanitizer.h" /** * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen @@ -29,22 +30,14 @@ */ extern NSString *const SWGResponseObjectErrorKey; -/** - * A key for deserialization ErrorDomain - */ -extern NSString *const SWGDeserializationErrorDomainKey; - -/** - * Code for deserialization type mismatch error - */ -extern NSInteger const SWGTypeMismatchErrorCode; - /** * Log debug message macro */ -#define SWGDebugLog(format, ...) [SWGApiClient debugLog:[NSString stringWithFormat:@"%s", __PRETTY_FUNCTION__] message: format, ##__VA_ARGS__]; +#ifndef SWGDebugLog + #define SWGDebugLog(format, ...) [SWGApiClient debugLog:[NSString stringWithFormat:@"%s", __PRETTY_FUNCTION__] message: format, ##__VA_ARGS__]; +#endif -@interface SWGApiClient : AFHTTPRequestOperationManager +@interface SWGApiClient : AFHTTPSessionManager @property(nonatomic, assign) NSURLRequestCachePolicy cachePolicy; @property(nonatomic, assign) NSTimeInterval timeoutInterval; @@ -53,6 +46,9 @@ extern NSInteger const SWGTypeMismatchErrorCode; /// In order to ensure the HTTPResponseHeaders are correct, it is recommended to initialize one SWGApiClient instance per thread. @property(nonatomic, readonly) NSDictionary* HTTPResponseHeaders; +@property(nonatomic, strong) id responseDeserializer; + +@property(nonatomic, strong) id sanitizer; /** * Clears Cache */ @@ -84,7 +80,7 @@ extern NSInteger const SWGTypeMismatchErrorCode; * * @return The client offline state */ -+(bool) getOfflineState; ++(BOOL) getOfflineState; /** * Sets the client reachability, this may be overridden by the reachability manager if reachability changes @@ -180,24 +176,17 @@ extern NSInteger const SWGTypeMismatchErrorCode; queryParams:(NSDictionary **)querys WithAuthSettings:(NSArray *)authSettings; -/** - * Deserializes the given data to Objective-C object. - * - * @param data The data will be deserialized. - * @param class The type of objective-c object. - * @param error The error - */ -- (id) deserialize:(id) data class:(NSString *) class error:(NSError**)error; - /** * Logs request and response * - * @param operation AFHTTPRequestOperation for the HTTP request. + * @param response NSURLResponse for the HTTP request. + * @param responseObject response object of the HTTP request. * @param request The HTTP request. * @param error The error of the HTTP request. */ -- (void)logResponse:(AFHTTPRequestOperation *)operation - forRequest:(NSURLRequest *)request +- (void)logResponse:(NSURLResponse *)response + responseObject:(id)responseObject + request:(NSURLRequest *)request error:(NSError *)error; /** @@ -230,13 +219,6 @@ extern NSInteger const SWGTypeMismatchErrorCode; responseType:(NSString *) responseType completionBlock:(void (^)(id, NSError *))completionBlock; -/** - * Sanitize object for request - * - * @param object The query/path/header/form/body param to be sanitized. - */ -- (id) sanitizeForSerialization:(id) object; - /** * Custom security policy * @@ -244,11 +226,6 @@ extern NSInteger const SWGTypeMismatchErrorCode; */ - (AFSecurityPolicy *) customSecurityPolicy; -/** - * Convert parameter to NSString - */ -- (NSString *) parameterToString: (id) param; - /** * Log debug message */ diff --git a/samples/client/petstore/objc/SwaggerClient/SWGApiClient.m b/samples/client/petstore/objc/SwaggerClient/SWGApiClient.m index ecdf4aaafb2..1246dff7fca 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGApiClient.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGApiClient.m @@ -2,10 +2,6 @@ NSString *const SWGResponseObjectErrorKey = @"SWGResponseObject"; -NSString *const SWGDeserializationErrorDomainKey = @"SWGDeserializationErrorDomainKey"; - -NSInteger const SWGTypeMismatchErrorCode = 143553; - static long requestId = 0; static bool offlineState = false; static NSMutableSet * queuedRequests = nil; @@ -14,6 +10,30 @@ static AFNetworkReachabilityStatus reachabilityStatus = AFNetworkReachabilitySta static void (^reachabilityChangeBlock)(int); +static NSDictionary * SWG__headerFieldsForResponse(NSURLResponse *response) { + if(![response isKindOfClass:[NSHTTPURLResponse class]]) { + return nil; + } + return ((NSHTTPURLResponse*)response).allHeaderFields; +} + +static NSString * SWG__fileNameForResponse(NSURLResponse *response) { + NSDictionary * headers = SWG__headerFieldsForResponse(response); + if(!headers[@"Content-Disposition"]) { + return [NSString stringWithFormat:@"%@", [[NSProcessInfo processInfo] globallyUniqueString]]; + } + NSString *pattern = @"filename=['\"]?([^'\"\\s]+)['\"]?"; + NSRegularExpression *regexp = [NSRegularExpression regularExpressionWithPattern:pattern + options:NSRegularExpressionCaseInsensitive + error:nil]; + NSString *contentDispositionHeader = headers[@"Content-Disposition"]; + NSTextCheckingResult *match = [regexp firstMatchInString:contentDispositionHeader + options:0 + range:NSMakeRange(0, [contentDispositionHeader length])]; + return [contentDispositionHeader substringWithRange:[match rangeAtIndex:1]]; +} + + @interface SWGApiClient () @property (readwrite, nonatomic) NSDictionary *HTTPResponseHeaders; @@ -33,6 +53,8 @@ static void (^reachabilityChangeBlock)(int); self.requestSerializer = [AFJSONRequestSerializer serializer]; self.responseSerializer = [AFJSONResponseSerializer serializer]; self.securityPolicy = [self customSecurityPolicy]; + self.responseDeserializer = [[SWGResponseDeserializer alloc] init]; + self.sanitizer = [[SWGSanitizer alloc] init]; // configure reachability [self configureCacheReachibility]; } @@ -99,14 +121,12 @@ static void (^reachabilityChangeBlock)(int); va_end(args); } -- (void)logResponse:(AFHTTPRequestOperation *)operation - forRequest:(NSURLRequest *)request - error:(NSError*)error { +- (void)logResponse:(NSURLResponse *)response responseObject:(id)responseObject request:(NSURLRequest *)request error:(NSError *)error { NSString *message = [NSString stringWithFormat:@"\n[DEBUG] HTTP request body \n~BEGIN~\n %@\n~END~\n"\ "[DEBUG] HTTP response body \n~BEGIN~\n %@\n~END~\n", [[NSString alloc] initWithData:request.HTTPBody encoding:NSUTF8StringEncoding], - operation.responseString]; + responseObject]; SWGDebugLog(message); } @@ -222,20 +242,14 @@ static void (^reachabilityChangeBlock)(int); -(Boolean) executeRequestWithId:(NSNumber*) requestId { NSSet* matchingItems = [queuedRequests objectsPassingTest:^BOOL(id obj, BOOL *stop) { - if ([obj intValue] == [requestId intValue]) { - return YES; - } - else { - return NO; - } + return [obj intValue] == [requestId intValue]; }]; if (matchingItems.count == 1) { SWGDebugLog(@"removed request id %@", requestId); [queuedRequests removeObject:requestId]; return YES; - } - else { + } else { return NO; } } @@ -246,7 +260,7 @@ static void (^reachabilityChangeBlock)(int); return reachabilityStatus; } -+(bool) getOfflineState { ++(BOOL) getOfflineState { return offlineState; } @@ -257,29 +271,8 @@ static void (^reachabilityChangeBlock)(int); - (void) configureCacheReachibility { [self.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) { reachabilityStatus = status; - switch (status) { - case AFNetworkReachabilityStatusUnknown: - SWGDebugLog(@"reachability changed to AFNetworkReachabilityStatusUnknown"); - [SWGApiClient setOfflineState:true]; - break; - - case AFNetworkReachabilityStatusNotReachable: - SWGDebugLog(@"reachability changed to AFNetworkReachabilityStatusNotReachable"); - [SWGApiClient setOfflineState:true]; - break; - - case AFNetworkReachabilityStatusReachableViaWWAN: - SWGDebugLog(@"reachability changed to AFNetworkReachabilityStatusReachableViaWWAN"); - [SWGApiClient setOfflineState:false]; - break; - - case AFNetworkReachabilityStatusReachableViaWiFi: - SWGDebugLog(@"reachability changed to AFNetworkReachabilityStatusReachableViaWiFi"); - [SWGApiClient setOfflineState:false]; - break; - default: - break; - } + SWGDebugLog(@"reachability changed to %@",AFStringFromNetworkReachabilityStatus(status)); + [SWGApiClient setOfflineState:status == AFNetworkReachabilityStatusUnknown || status == AFNetworkReachabilityStatusNotReachable]; // call the reachability block, if configured if (reachabilityChangeBlock != nil) { @@ -290,245 +283,65 @@ static void (^reachabilityChangeBlock)(int); [self.reachabilityManager startMonitoring]; } -#pragma mark - Deserialize methods - -- (id) deserialize:(id) data class:(NSString *) class error:(NSError **) error { - // return nil if data is nil or class is nil - if (!data || !class) { - return nil; - } - - // remove "*" from class, if ends with "*" - if ([class hasSuffix:@"*"]) { - class = [class substringToIndex:[class length] - 1]; - } - - // pure object - if ([class isEqualToString:@"NSObject"]) { - return data; - } - - NSRegularExpression *regexp = nil; - NSTextCheckingResult *match = nil; - NSMutableArray *resultArray = nil; - NSMutableDictionary *resultDict = nil; - NSString *innerType = nil; - - // list of models - NSString *arrayOfModelsPat = @"NSArray<(.+)>"; - regexp = [NSRegularExpression regularExpressionWithPattern:arrayOfModelsPat - options:NSRegularExpressionCaseInsensitive - error:nil]; - - match = [regexp firstMatchInString:class - options:0 - range:NSMakeRange(0, [class length])]; - - if (match) { - if(![data isKindOfClass: [NSArray class]]) { - if(error) { - NSDictionary * userInfo = @{NSLocalizedDescriptionKey : NSLocalizedString(@"Received response is not an array", nil)}; - *error = [NSError errorWithDomain:SWGDeserializationErrorDomainKey code:SWGTypeMismatchErrorCode userInfo:userInfo]; - } - return nil; - } - NSArray *dataArray = data; - innerType = [class substringWithRange:[match rangeAtIndex:1]]; - - resultArray = [NSMutableArray arrayWithCapacity:[dataArray count]]; - [data enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { - id arrObj = [self deserialize:obj class:innerType error:error]; - if(arrObj) { - [resultArray addObject:arrObj]; - } else { - * stop = YES; - } - }]; - - return resultArray; - } - - // list of primitives - NSString *arrayOfPrimitivesPat = @"NSArray\\* /\\* (.+) \\*/"; - regexp = [NSRegularExpression regularExpressionWithPattern:arrayOfPrimitivesPat - options:NSRegularExpressionCaseInsensitive - error:nil]; - match = [regexp firstMatchInString:class - options:0 - range:NSMakeRange(0, [class length])]; - - if (match) { - NSArray *dataArray = data; - innerType = [class substringWithRange:[match rangeAtIndex:1]]; - - resultArray = [NSMutableArray arrayWithCapacity:[dataArray count]]; - [data enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { - id arrObj = [self deserialize:obj class:innerType error:error]; - if(arrObj) { - [resultArray addObject:arrObj]; - } else { - * stop = YES; - } - }]; - - return resultArray; - } - - // map - NSString *dictPat = @"NSDictionary\\* /\\* (.+?), (.+) \\*/"; - regexp = [NSRegularExpression regularExpressionWithPattern:dictPat - options:NSRegularExpressionCaseInsensitive - error:nil]; - match = [regexp firstMatchInString:class - options:0 - range:NSMakeRange(0, [class length])]; - - if (match) { - NSDictionary *dataDict = data; - NSString *valueType = [class substringWithRange:[match rangeAtIndex:2]]; - - resultDict = [NSMutableDictionary dictionaryWithCapacity:[dataDict count]]; - [data enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { - id dicObj = [self deserialize:obj class:valueType error:error]; - if(dicObj) { - [resultDict setValue:dicObj forKey:key]; - } else { - * stop = YES; - } - }]; - - return resultDict; - } - - // primitives - NSArray *primitiveTypes = @[@"NSString", @"NSDate", @"NSNumber"]; - - if ([primitiveTypes containsObject:class]) { - if ([class isEqualToString:@"NSString"]) { - return [NSString stringWithString:data]; - } - else if ([class isEqualToString:@"NSDate"]) { - return [NSDate dateWithISO8601String:data]; - } - else if ([class isEqualToString:@"NSNumber"]) { - // NSNumber from NSNumber - if ([data isKindOfClass:[NSNumber class]]) { - return data; - } - else if ([data isKindOfClass:[NSString class]]) { - // NSNumber (NSCFBoolean) from NSString - if ([[data lowercaseString] isEqualToString:@"true"] || [[data lowercaseString] isEqualToString:@"false"]) { - return [NSNumber numberWithBool:[data boolValue]]; - // NSNumber from NSString - } else { - NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init]; - formatter.numberStyle = NSNumberFormatterDecimalStyle; - return [formatter numberFromString:data]; - } - } - } - } - - // model - Class ModelClass = NSClassFromString(class); - if ([ModelClass instancesRespondToSelector:@selector(initWithDictionary:error:)]) { - return [(JSONModel *) [ModelClass alloc] initWithDictionary:data error:error]; - } - - return nil; -} - #pragma mark - Operation Methods - (void) operationWithCompletionBlock: (NSURLRequest *)request requestId: (NSNumber *) requestId completionBlock: (void (^)(id, NSError *))completionBlock { - AFHTTPRequestOperation *op = [self HTTPRequestOperationWithRequest:request - success:^(AFHTTPRequestOperation *operation, id response) { - 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]) { - NSMutableDictionary *userInfo = [error.userInfo mutableCopy]; - if (operation.responseObject) { - // Add in the (parsed) response body. - userInfo[SWGResponseObjectErrorKey] = operation.responseObject; - } - NSError *augmentedError = [error initWithDomain:error.domain code:error.code userInfo:userInfo]; - [self logResponse:nil forRequest:request error:augmentedError]; - - NSDictionary *responseHeaders = [[operation response] allHeaderFields]; - self.HTTPResponseHeaders = responseHeaders; - - completionBlock(nil, augmentedError); - } - }]; - - [self.operationQueue addOperation:op]; + __weak __typeof(self)weakSelf = self; + NSURLSessionDataTask* op = [self dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) { + __strong __typeof(weakSelf)strongSelf = weakSelf; + if (![strongSelf executeRequestWithId:requestId]) { + return; + } + [strongSelf logResponse:response responseObject:responseObject request:request error:error]; + strongSelf.HTTPResponseHeaders = SWG__headerFieldsForResponse(response); + if(!error) { + completionBlock(responseObject, nil); + return; + } + NSMutableDictionary *userInfo = [error.userInfo mutableCopy]; + if (responseObject) { + // Add in the (parsed) response body. + userInfo[SWGResponseObjectErrorKey] = responseObject; + } + NSError *augmentedError = [error initWithDomain:error.domain code:error.code userInfo:userInfo]; + completionBlock(nil, augmentedError); + }]; + [op resume]; } - (void) downloadOperationWithCompletionBlock: (NSURLRequest *)request requestId: (NSNumber *) requestId completionBlock: (void (^)(id, NSError *))completionBlock { - AFHTTPRequestOperation *op = [self HTTPRequestOperationWithRequest:request - success:^(AFHTTPRequestOperation *operation, id responseObject) { - SWGConfiguration *config = [SWGConfiguration sharedConfig]; - NSString *directory = nil; - if (config.tempFolderPath) { - directory = config.tempFolderPath; - } - else { - directory = NSTemporaryDirectory(); - } + __weak __typeof(self)weakSelf = self; + NSURLSessionDataTask* op = [self dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) { + __strong __typeof(weakSelf)strongSelf = weakSelf; + if (![strongSelf executeRequestWithId:requestId]) { + return; + } + strongSelf.HTTPResponseHeaders = SWG__headerFieldsForResponse(response); + [strongSelf logResponse:response responseObject:responseObject request:request error:error]; + if(error) { + NSMutableDictionary *userInfo = [error.userInfo mutableCopy]; + if (responseObject) { + userInfo[SWGResponseObjectErrorKey] = responseObject; + } + NSError *augmentedError = [error initWithDomain:error.domain code:error.code userInfo:userInfo]; + completionBlock(nil, augmentedError); + } + SWGConfiguration *config = [SWGConfiguration sharedConfig]; + NSString *directory = config.tempFolderPath ?: NSTemporaryDirectory(); + NSString * filename = SWG__fileNameForResponse(response); - NSDictionary *headers = operation.response.allHeaderFields; - NSString *filename = nil; - if ([headers objectForKey:@"Content-Disposition"]) { + NSString *filepath = [directory stringByAppendingPathComponent:filename]; + NSURL *file = [NSURL fileURLWithPath:filepath]; - NSString *pattern = @"filename=['\"]?([^'\"\\s]+)['\"]?"; - NSRegularExpression *regexp = [NSRegularExpression regularExpressionWithPattern:pattern - options:NSRegularExpressionCaseInsensitive - error:nil]; - NSString *contentDispositionHeader = [headers objectForKey:@"Content-Disposition"]; - NSTextCheckingResult *match = [regexp firstMatchInString:contentDispositionHeader - options:0 - range:NSMakeRange(0, [contentDispositionHeader length])]; - filename = [contentDispositionHeader substringWithRange:[match rangeAtIndex:1]]; - } - else { - filename = [NSString stringWithFormat:@"%@", [[NSProcessInfo processInfo] globallyUniqueString]]; - } + [responseObject writeToURL:file atomically:YES]; - NSString *filepath = [directory stringByAppendingPathComponent:filename]; - NSURL *file = [NSURL fileURLWithPath:filepath]; - - [operation.responseData writeToURL:file atomically:YES]; - self.HTTPResponseHeaders = headers; - completionBlock(file, nil); - } failure:^(AFHTTPRequestOperation *operation, NSError *error) { - - if ([self executeRequestWithId:requestId]) { - NSMutableDictionary *userInfo = [error.userInfo mutableCopy]; - if (operation.responseObject) { - userInfo[SWGResponseObjectErrorKey] = operation.responseObject; - } - - NSError *augmentedError = [error initWithDomain:error.domain code:error.code userInfo:userInfo]; - - - [self logResponse:nil forRequest:request error:augmentedError]; - - NSDictionary *responseHeaders = [[operation response] allHeaderFields]; - self.HTTPResponseHeaders = responseHeaders; - completionBlock(nil, augmentedError); - } - }]; - - [self.operationQueue addOperation:op]; + completionBlock(file, nil); + }]; + [op resume]; } #pragma mark - Perform Request Methods @@ -569,11 +382,11 @@ static void (^reachabilityChangeBlock)(int); } // sanitize parameters - pathParams = [self sanitizeForSerialization:pathParams]; - queryParams = [self sanitizeForSerialization:queryParams]; - headerParams = [self sanitizeForSerialization:headerParams]; - formParams = [self sanitizeForSerialization:formParams]; - body = [self sanitizeForSerialization:body]; + pathParams = [self.sanitizer sanitizeForSerialization:pathParams]; + queryParams = [self.sanitizer sanitizeForSerialization:queryParams]; + headerParams = [self.sanitizer sanitizeForSerialization:headerParams]; + formParams = [self.sanitizer sanitizeForSerialization:formParams]; + body = [self.sanitizer sanitizeForSerialization:body]; // auth setting [self updateHeaderParams:&headerParams queryParams:&queryParams WithAuthSettings:authSettings]; @@ -593,12 +406,13 @@ static void (^reachabilityChangeBlock)(int); NSString* urlString = [[NSURL URLWithString:pathWithQueryParams relativeToURL:self.baseURL] absoluteString]; if (files.count > 0) { + __weak __typeof(self)weakSelf = self; request = [self.requestSerializer multipartFormRequestWithMethod:@"POST" URLString:urlString parameters:nil constructingBodyWithBlock:^(id formData) { [formParams enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { - NSString *objString = [self parameterToString:obj]; + NSString *objString = [weakSelf.sanitizer parameterToString:obj]; NSData *data = [objString dataUsingEncoding:NSUTF8StringEncoding]; [formData appendPartWithFormData:data name:key]; }]; @@ -653,7 +467,7 @@ static void (^reachabilityChangeBlock)(int); [request setHTTPShouldHandleCookies:NO]; NSNumber* requestId = [SWGApiClient queueRequest]; - if ([responseType isEqualToString:@"NSURL*"]) { + if ([responseType isEqualToString:@"NSURL*"] || [responseType isEqualToString:@"NSURL"]) { [self downloadOperationWithCompletionBlock:request requestId:requestId completionBlock:^(id data, NSError *error) { completionBlock(data, error); }]; @@ -661,7 +475,7 @@ static void (^reachabilityChangeBlock)(int); else { [self operationWithCompletionBlock:request requestId:requestId completionBlock:^(id data, NSError *error) { NSError * serializationError; - id response = [self deserialize:data class:responseType error:&serializationError]; + id response = [self.responseDeserializer deserialize:data class:responseType error:&serializationError]; if(!response && !error){ error = serializationError; } @@ -760,48 +574,6 @@ static void (^reachabilityChangeBlock)(int); *querys = [NSDictionary dictionaryWithDictionary:querysWithAuth]; } -- (id) sanitizeForSerialization:(id) object { - if (object == nil) { - return nil; - } - else if ([object isKindOfClass:[NSString class]] || [object isKindOfClass:[NSNumber class]] || [object isKindOfClass:[SWGQueryParamCollection class]]) { - return object; - } - else if ([object isKindOfClass:[NSDate class]]) { - return [object ISO8601String]; - } - else if ([object isKindOfClass:[NSArray class]]) { - NSArray *objectArray = object; - NSMutableArray *sanitizedObjs = [NSMutableArray arrayWithCapacity:[objectArray count]]; - [object enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { - if (obj) { - [sanitizedObjs addObject:[self sanitizeForSerialization:obj]]; - } - }]; - return sanitizedObjs; - } - else if ([object isKindOfClass:[NSDictionary class]]) { - NSDictionary *objectDict = object; - NSMutableDictionary *sanitizedObjs = [NSMutableDictionary dictionaryWithCapacity:[objectDict count]]; - [object enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { - if (obj) { - [sanitizedObjs setValue:[self sanitizeForSerialization:obj] forKey:key]; - } - }]; - return sanitizedObjs; - } - else if ([object isKindOfClass:[SWGObject class]]) { - return [object toDictionary]; - } - else { - NSException *e = [NSException - exceptionWithName:@"InvalidObjectArgumentException" - reason:[NSString stringWithFormat:@"*** The argument object: %@ is invalid", object] - userInfo:nil]; - @throw e; - } -} - - (AFSecurityPolicy *) customSecurityPolicy { AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone]; @@ -823,30 +595,4 @@ static void (^reachabilityChangeBlock)(int); return securityPolicy; } -- (NSString *) parameterToString:(id)param { - if ([param isKindOfClass:[NSString class]]) { - return param; - } - else if ([param isKindOfClass:[NSNumber class]]) { - return [param stringValue]; - } - else if ([param isKindOfClass:[NSDate class]]) { - return [param ISO8601String]; - } - else if ([param isKindOfClass:[NSArray class]]) { - NSMutableArray *mutableParam; - [param enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { - [mutableParam addObject:[self parameterToString:obj]]; - }]; - return [mutableParam componentsJoinedByString:@","]; - } - else { - NSException *e = [NSException - exceptionWithName:@"InvalidObjectArgumentException" - reason:[NSString stringWithFormat:@"*** The argument object: %@ is invalid", param] - userInfo:nil]; - @throw e; - } -} - @end diff --git a/samples/client/petstore/objc/SwaggerClient/SWGCategory.m b/samples/client/petstore/objc/SwaggerClient/SWGCategory.m index c323eda5a0a..29e3bc16226 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGCategory.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGCategory.m @@ -4,12 +4,10 @@ - (instancetype)init { self = [super init]; - if (self) { // initalise property's default value, if any } - return self; } @@ -18,8 +16,7 @@ * Maps json key to property name. * This method is used by `JSONModel`. */ -+ (JSONKeyMapper *)keyMapper -{ ++ (JSONKeyMapper *)keyMapper { return [[JSONKeyMapper alloc] initWithDictionary:@{ @"id": @"_id", @"name": @"name" }]; } @@ -28,24 +25,11 @@ * If `propertyName` is optional, then return `YES`, otherwise return `NO`. * This method is used by `JSONModel`. */ -+ (BOOL)propertyIsOptional:(NSString *)propertyName -{ ++ (BOOL)propertyIsOptional:(NSString *)propertyName { + NSArray *optionalProperties = @[@"_id", @"name"]; + return [optionalProperties containsObject:propertyName]; - if ([optionalProperties containsObject:propertyName]) { - return YES; - } - else { - return NO; - } -} - -/** - * Gets the string presentation of the object. - * This method will be called when logging model object using `NSLog`. - */ -- (NSString *)description { - return [[self toDictionary] description]; } @end diff --git a/samples/client/petstore/objc/SwaggerClient/SWGConfiguration.m b/samples/client/petstore/objc/SwaggerClient/SWGConfiguration.m index c9d80f5c488..dd1596bf8ce 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGConfiguration.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGConfiguration.m @@ -72,7 +72,7 @@ return @""; } else { - return [NSString stringWithFormat:@"BEARER %@", self.accessToken]; + return [NSString stringWithFormat:@"Bearer %@", self.accessToken]; } } diff --git a/samples/client/petstore/objc/SwaggerClient/SWGInlineResponse200.h b/samples/client/petstore/objc/SwaggerClient/SWGInlineResponse200.h deleted file mode 100644 index 577434faae6..00000000000 --- a/samples/client/petstore/objc/SwaggerClient/SWGInlineResponse200.h +++ /dev/null @@ -1,32 +0,0 @@ -#import -#import "SWGObject.h" - -/** - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen - * Do not edit the class manually. - */ - -#import "SWGTag.h" - - -@protocol SWGInlineResponse200 -@end - -@interface SWGInlineResponse200 : SWGObject - - -@property(nonatomic) NSArray* /* NSString */ photoUrls; - -@property(nonatomic) NSString* name; - -@property(nonatomic) NSNumber* _id; - -@property(nonatomic) NSObject* category; - -@property(nonatomic) NSArray* tags; -/* pet status in the store [optional] - */ -@property(nonatomic) NSString* status; - -@end diff --git a/samples/client/petstore/objc/SwaggerClient/SWGInlineResponse200.m b/samples/client/petstore/objc/SwaggerClient/SWGInlineResponse200.m deleted file mode 100644 index 5fbe9ec6ec2..00000000000 --- a/samples/client/petstore/objc/SwaggerClient/SWGInlineResponse200.m +++ /dev/null @@ -1,51 +0,0 @@ -#import "SWGInlineResponse200.h" - -@implementation SWGInlineResponse200 - -- (instancetype)init { - self = [super init]; - - if (self) { - // initalise property's default value, if any - - } - - return self; -} - - -/** - * Maps json key to property name. - * This method is used by `JSONModel`. - */ -+ (JSONKeyMapper *)keyMapper -{ - return [[JSONKeyMapper alloc] initWithDictionary:@{ @"photoUrls": @"photoUrls", @"name": @"name", @"id": @"_id", @"category": @"category", @"tags": @"tags", @"status": @"status" }]; -} - -/** - * Indicates whether the property with the given name is optional. - * If `propertyName` is optional, then return `YES`, otherwise return `NO`. - * This method is used by `JSONModel`. - */ -+ (BOOL)propertyIsOptional:(NSString *)propertyName -{ - NSArray *optionalProperties = @[@"photoUrls", @"name", @"category", @"tags", @"status"]; - - if ([optionalProperties containsObject:propertyName]) { - return YES; - } - else { - return NO; - } -} - -/** - * Gets the string presentation of the object. - * This method will be called when logging model object using `NSLog`. - */ -- (NSString *)description { - return [[self toDictionary] description]; -} - -@end diff --git a/samples/client/petstore/objc/SwaggerClient/SWGName.h b/samples/client/petstore/objc/SwaggerClient/SWGName.h deleted file mode 100644 index fd34af7b66a..00000000000 --- a/samples/client/petstore/objc/SwaggerClient/SWGName.h +++ /dev/null @@ -1,22 +0,0 @@ -#import -#import "SWGObject.h" - -/** - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen - * Do not edit the class manually. - */ - - - -@protocol SWGName -@end - -@interface SWGName : SWGObject - - -@property(nonatomic) NSNumber* name; - -@property(nonatomic) NSNumber* snakeCase; - -@end diff --git a/samples/client/petstore/objc/SwaggerClient/SWGName.m b/samples/client/petstore/objc/SwaggerClient/SWGName.m deleted file mode 100644 index 16aec784549..00000000000 --- a/samples/client/petstore/objc/SwaggerClient/SWGName.m +++ /dev/null @@ -1,51 +0,0 @@ -#import "SWGName.h" - -@implementation SWGName - -- (instancetype)init { - self = [super init]; - - if (self) { - // initalise property's default value, if any - - } - - return self; -} - - -/** - * Maps json key to property name. - * This method is used by `JSONModel`. - */ -+ (JSONKeyMapper *)keyMapper -{ - return [[JSONKeyMapper alloc] initWithDictionary:@{ @"name": @"name", @"snake_case": @"snakeCase" }]; -} - -/** - * Indicates whether the property with the given name is optional. - * If `propertyName` is optional, then return `YES`, otherwise return `NO`. - * This method is used by `JSONModel`. - */ -+ (BOOL)propertyIsOptional:(NSString *)propertyName -{ - NSArray *optionalProperties = @[@"snakeCase"]; - - if ([optionalProperties containsObject:propertyName]) { - return YES; - } - else { - return NO; - } -} - -/** - * Gets the string presentation of the object. - * This method will be called when logging model object using `NSLog`. - */ -- (NSString *)description { - return [[self toDictionary] description]; -} - -@end diff --git a/samples/client/petstore/objc/SwaggerClient/SWGObject.m b/samples/client/petstore/objc/SwaggerClient/SWGObject.m index 1f897ab1d56..8085c404f7e 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGObject.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGObject.m @@ -1,4 +1,13 @@ #import "SWGObject.h" @implementation SWGObject + +/** + * Gets the string presentation of the object. + * This method will be called when logging model object using `NSLog`. + */ +- (NSString *)description { + return [[self toDictionary] description]; +} + @end diff --git a/samples/client/petstore/objc/SwaggerClient/SWGOrder.m b/samples/client/petstore/objc/SwaggerClient/SWGOrder.m index e41bc7a188d..d10ed802b8d 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGOrder.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGOrder.m @@ -4,12 +4,10 @@ - (instancetype)init { self = [super init]; - if (self) { // initalise property's default value, if any } - return self; } @@ -18,8 +16,7 @@ * Maps json key to property name. * This method is used by `JSONModel`. */ -+ (JSONKeyMapper *)keyMapper -{ ++ (JSONKeyMapper *)keyMapper { return [[JSONKeyMapper alloc] initWithDictionary:@{ @"id": @"_id", @"petId": @"petId", @"quantity": @"quantity", @"shipDate": @"shipDate", @"status": @"status", @"complete": @"complete" }]; } @@ -28,24 +25,11 @@ * If `propertyName` is optional, then return `YES`, otherwise return `NO`. * This method is used by `JSONModel`. */ -+ (BOOL)propertyIsOptional:(NSString *)propertyName -{ ++ (BOOL)propertyIsOptional:(NSString *)propertyName { + NSArray *optionalProperties = @[@"_id", @"petId", @"quantity", @"shipDate", @"status", @"complete"]; + return [optionalProperties containsObject:propertyName]; - if ([optionalProperties containsObject:propertyName]) { - return YES; - } - else { - return NO; - } -} - -/** - * Gets the string presentation of the object. - * This method will be called when logging model object using `NSLog`. - */ -- (NSString *)description { - return [[self toDictionary] description]; } @end diff --git a/samples/client/petstore/objc/SwaggerClient/SWGPet.h b/samples/client/petstore/objc/SwaggerClient/SWGPet.h index 84f10969e5b..2f83af6c4e1 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGPet.h +++ b/samples/client/petstore/objc/SwaggerClient/SWGPet.h @@ -23,7 +23,7 @@ @property(nonatomic) NSString* name; -@property(nonatomic) NSArray* /* NSString */ photoUrls; +@property(nonatomic) NSArray* photoUrls; @property(nonatomic) NSArray* tags; /* pet status in the store [optional] diff --git a/samples/client/petstore/objc/SwaggerClient/SWGPet.m b/samples/client/petstore/objc/SwaggerClient/SWGPet.m index 86389c2590b..98e75189ed3 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGPet.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGPet.m @@ -4,12 +4,10 @@ - (instancetype)init { self = [super init]; - if (self) { // initalise property's default value, if any } - return self; } @@ -18,8 +16,7 @@ * Maps json key to property name. * This method is used by `JSONModel`. */ -+ (JSONKeyMapper *)keyMapper -{ ++ (JSONKeyMapper *)keyMapper { return [[JSONKeyMapper alloc] initWithDictionary:@{ @"id": @"_id", @"category": @"category", @"name": @"name", @"photoUrls": @"photoUrls", @"tags": @"tags", @"status": @"status" }]; } @@ -28,24 +25,11 @@ * If `propertyName` is optional, then return `YES`, otherwise return `NO`. * This method is used by `JSONModel`. */ -+ (BOOL)propertyIsOptional:(NSString *)propertyName -{ ++ (BOOL)propertyIsOptional:(NSString *)propertyName { + NSArray *optionalProperties = @[@"_id", @"category", @"tags", @"status"]; + return [optionalProperties containsObject:propertyName]; - if ([optionalProperties containsObject:propertyName]) { - return YES; - } - else { - return NO; - } -} - -/** - * Gets the string presentation of the object. - * This method will be called when logging model object using `NSLog`. - */ -- (NSString *)description { - return [[self toDictionary] description]; } @end diff --git a/samples/client/petstore/objc/SwaggerClient/SWGPetApi.h b/samples/client/petstore/objc/SwaggerClient/SWGPetApi.h index ef66979613f..908771588e0 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGPetApi.h +++ b/samples/client/petstore/objc/SwaggerClient/SWGPetApi.h @@ -56,7 +56,7 @@ /// /// /// @return NSArray* --(NSNumber*) findPetsByStatusWithStatus: (NSArray* /* NSString */) status +-(NSNumber*) findPetsByStatusWithStatus: (NSArray*) status completionHandler: (void (^)(NSArray* output, NSError* error)) handler; @@ -69,7 +69,7 @@ /// /// /// @return NSArray* --(NSNumber*) findPetsByTagsWithTags: (NSArray* /* NSString */) tags +-(NSNumber*) findPetsByTagsWithTags: (NSArray*) tags completionHandler: (void (^)(NSArray* output, NSError* error)) handler; diff --git a/samples/client/petstore/objc/SwaggerClient/SWGPetApi.m b/samples/client/petstore/objc/SwaggerClient/SWGPetApi.m index 87201064542..b3ebc31bf68 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGPetApi.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGPetApi.m @@ -217,7 +217,7 @@ static SWGPetApi* singletonAPI = nil; /// /// @returns NSArray* /// --(NSNumber*) findPetsByStatusWithStatus: (NSArray* /* NSString */) status +-(NSNumber*) findPetsByStatusWithStatus: (NSArray*) status completionHandler: (void (^)(NSArray* output, NSError* error)) handler { NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/pet/findByStatus"]; @@ -284,7 +284,7 @@ static SWGPetApi* singletonAPI = nil; /// /// @returns NSArray* /// --(NSNumber*) findPetsByTagsWithTags: (NSArray* /* NSString */) tags +-(NSNumber*) findPetsByTagsWithTags: (NSArray*) tags completionHandler: (void (^)(NSArray* output, NSError* error)) handler { NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/pet/findByTags"]; diff --git a/samples/client/petstore/objc/SwaggerClient/SWGResponseDeserializer.h b/samples/client/petstore/objc/SwaggerClient/SWGResponseDeserializer.h new file mode 100644 index 00000000000..b20ead44f83 --- /dev/null +++ b/samples/client/petstore/objc/SwaggerClient/SWGResponseDeserializer.h @@ -0,0 +1,50 @@ +#import + +/** + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen + * Do not edit the class manually. + */ + +/** + * A key for deserialization ErrorDomain + */ +extern NSString *const SWGDeserializationErrorDomainKey; + +/** + * Code for deserialization type mismatch error + */ +extern NSInteger const SWGTypeMismatchErrorCode; + +/** + * Code for deserialization empty value error + */ +extern NSInteger const SWGEmptyValueOccurredErrorCode; + +/** + * Error code for unknown response + */ +extern NSInteger const SWGUnknownResponseObjectErrorCode; + +@protocol SWGResponseDeserializer + +/** + * Deserializes the given data to Objective-C object. + * + * @param data The data will be deserialized. + * @param class The type of objective-c object. + * @param error The error + */ +- (id) deserialize:(id) data class:(NSString *) className error:(NSError**)error; + +@end + +@interface SWGResponseDeserializer : NSObject + +/** + * If an null value occurs in dictionary or array if set to YES whole response will be invalid else will be ignored + * @default NO + */ +@property (nonatomic, assign) BOOL treatNullAsError; + +@end diff --git a/samples/client/petstore/objc/SwaggerClient/SWGResponseDeserializer.m b/samples/client/petstore/objc/SwaggerClient/SWGResponseDeserializer.m new file mode 100644 index 00000000000..a0efd1d5927 --- /dev/null +++ b/samples/client/petstore/objc/SwaggerClient/SWGResponseDeserializer.m @@ -0,0 +1,231 @@ +#import "SWGResponseDeserializer.h" +#import +#import + +NSString *const SWGDeserializationErrorDomainKey = @"SWGDeserializationErrorDomainKey"; + +NSInteger const SWGTypeMismatchErrorCode = 143553; + +NSInteger const SWGEmptyValueOccurredErrorCode = 143509; + +NSInteger const SWGUnknownResponseObjectErrorCode = 143528; + + +@interface SWGResponseDeserializer () + +@property (nonatomic, strong) NSNumberFormatter* numberFormatter; +@property (nonatomic, strong) NSArray *primitiveTypes; +@property (nonatomic, strong) NSArray *basicReturnTypes; + +@property (nonatomic, strong) NSRegularExpression* arrayOfModelsPatExpression; +@property (nonatomic, strong) NSRegularExpression* arrayOfPrimitivesPatExpression; +@property (nonatomic, strong) NSRegularExpression* dictPatExpression; +@property (nonatomic, strong) NSRegularExpression* dictModelsPatExpression; + +@end + +@implementation SWGResponseDeserializer + +- (instancetype)init { + self = [super init]; + if (self) { + NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init]; + formatter.numberStyle = NSNumberFormatterDecimalStyle; + _numberFormatter = formatter; + _primitiveTypes = @[@"NSString", @"NSDate", @"NSNumber"]; + _basicReturnTypes = @[@"NSObject", @"id", @"NSData"]; + _arrayOfModelsPatExpression = [NSRegularExpression regularExpressionWithPattern:@"NSArray<(.+)>" + options:NSRegularExpressionCaseInsensitive + error:nil]; + _arrayOfPrimitivesPatExpression = [NSRegularExpression regularExpressionWithPattern:@"NSArray\\* /\\* (.+) \\*/" + options:NSRegularExpressionCaseInsensitive + error:nil]; + _dictPatExpression = [NSRegularExpression regularExpressionWithPattern:@"NSDictionary\\* /\\* (.+?), (.+) \\*/" + options:NSRegularExpressionCaseInsensitive + error:nil]; + _dictModelsPatExpression = [NSRegularExpression regularExpressionWithPattern:@"NSDictionary\\<(.+?), (.+)*\\>" + options:NSRegularExpressionCaseInsensitive + error:nil]; + } + return self; +} + +#pragma mark - Deserialize methods + +- (id) deserialize:(id) data class:(NSString *) className error:(NSError **) error { + // return nil if data is nil or className is nil + if (!data || !className || [data isKindOfClass:[NSNull class]]) { + return nil; + } + + // remove "*" from className, if ends with "*" + if ([className hasSuffix:@"*"]) { + className = [className substringToIndex:[className length] - 1]; + } + // pure object + if ([self.basicReturnTypes containsObject:className]) { + return data; + } + + // primitives + if ([self.primitiveTypes containsObject:className]) { + return [self deserializePrimitiveValue:data class:className error:error]; + } + + NSTextCheckingResult *match = nil; + NSRange range = NSMakeRange(0, [className length]); + // list of models + match = [self.arrayOfModelsPatExpression firstMatchInString:className options:0 range:range]; + if (match) { + NSString *innerType = [className substringWithRange:[match rangeAtIndex:1]]; + return [self deserializeArrayValue:data innerType:innerType error:error]; + } + + // list of primitives + match = [self.arrayOfPrimitivesPatExpression firstMatchInString:className options:0 range:range]; + if (match) { + NSString *innerType = [className substringWithRange:[match rangeAtIndex:1]]; + return [self deserializeArrayValue:data innerType:innerType error:error]; + } + + // map + match = [self.dictPatExpression firstMatchInString:className options:0 range:range]; + if (match) { + NSString *valueType = [className substringWithRange:[match rangeAtIndex:2]]; + return [self deserializeDictionaryValue:data valueType:valueType error:error]; + } + + match = [self.dictModelsPatExpression firstMatchInString:className options:0 range:range]; + if (match) { + NSString *valueType = [className substringWithRange:[match rangeAtIndex:2]]; + return [self deserializeDictionaryValue:data valueType:valueType error:error]; + } + + // model + Class ModelClass = NSClassFromString(className); + if ([ModelClass instancesRespondToSelector:@selector(initWithDictionary:error:)]) { + return [(JSONModel *) [ModelClass alloc] initWithDictionary:data error:error]; + } + + if(error) { + *error = [self unknownResponseErrorWithExpectedType:className data:data]; + } + return nil; +} + +- (id) deserializeDictionaryValue:(id) data valueType:(NSString *) valueType error:(NSError**)error { + if(![data isKindOfClass: [NSDictionary class]]) { + if(error) { + *error = [self typeMismatchErrorWithExpectedType:NSStringFromClass([NSDictionary class]) data:data]; + } + return nil; + } + __block NSMutableDictionary *resultDict = [NSMutableDictionary dictionaryWithCapacity:[data count]]; + for (id key in [data allKeys]) { + id obj = [data valueForKey:key]; + id dicObj = [self deserialize:obj class:valueType error:error]; + if(dicObj) { + [resultDict setValue:dicObj forKey:key]; + } else if([obj isKindOfClass:[NSNull class]]) { + if(self.treatNullAsError) { + if (error) { + *error = [self emptyValueOccurredError]; + } + resultDict = nil; + break; + } + } else { + resultDict = nil; + break; + } + } + return resultDict; +} + +- (id) deserializeArrayValue:(id) data innerType:(NSString *) innerType error:(NSError**)error { + if(![data isKindOfClass: [NSArray class]]) { + if(error) { + *error = [self typeMismatchErrorWithExpectedType:NSStringFromClass([NSArray class]) data:data]; + } + return nil; + } + NSMutableArray* resultArray = [NSMutableArray arrayWithCapacity:[data count]]; + for (id obj in data) { + id arrObj = [self deserialize:obj class:innerType error:error]; + if(arrObj) { + [resultArray addObject:arrObj]; + } else if([obj isKindOfClass:[NSNull class]]) { + if(self.treatNullAsError) { + if (error) { + *error = [self emptyValueOccurredError]; + } + resultArray = nil; + break; + } + } else { + resultArray = nil; + break; + } + } + return resultArray; +}; + +- (id) deserializePrimitiveValue:(id) data class:(NSString *) className error:(NSError**)error { + if ([className isEqualToString:@"NSString"]) { + return [NSString stringWithString:data]; + } + else if ([className isEqualToString:@"NSDate"]) { + return [self deserializeDateValue:data error:error]; + } + else if ([className isEqualToString:@"NSNumber"]) { + // NSNumber from NSNumber + if ([data isKindOfClass:[NSNumber class]]) { + return data; + } + else if ([data isKindOfClass:[NSString class]]) { + // NSNumber (NSCFBoolean) from NSString + if ([[data lowercaseString] isEqualToString:@"true"] || [[data lowercaseString] isEqualToString:@"false"]) { + return @([data boolValue]); + // NSNumber from NSString + } else { + NSNumber* formattedValue = [self.numberFormatter numberFromString:data]; + if(!formattedValue && [data length] > 0 && error) { + *error = [self typeMismatchErrorWithExpectedType:className data:data]; + } + return formattedValue; + } + } + } + if(error) { + *error = [self typeMismatchErrorWithExpectedType:className data:data]; + } + return nil; +} + +- (id) deserializeDateValue:(id) data error:(NSError**)error { + NSDate *date =[NSDate dateWithISO8601String:data]; + if(!date && [data length] > 0 && error) { + *error = [self typeMismatchErrorWithExpectedType:NSStringFromClass([NSDate class]) data:data]; + } + return date; +}; + +-(NSError *)typeMismatchErrorWithExpectedType:(NSString *)expected data:(id)data { + NSString * message = [NSString stringWithFormat:NSLocalizedString(@"Received response [%@] is not an object of type %@",nil),data, expected]; + NSDictionary * userInfo = @{NSLocalizedDescriptionKey : message}; + return [NSError errorWithDomain:SWGDeserializationErrorDomainKey code:SWGTypeMismatchErrorCode userInfo:userInfo]; +} + +-(NSError *)emptyValueOccurredError { + NSString * message = NSLocalizedString(@"Received response contains null value in dictionary or array response",nil); + NSDictionary * userInfo = @{NSLocalizedDescriptionKey : message}; + return [NSError errorWithDomain:SWGDeserializationErrorDomainKey code:SWGEmptyValueOccurredErrorCode userInfo:userInfo]; +} + +-(NSError *)unknownResponseErrorWithExpectedType:(NSString *)expected data:(id)data { + NSString * message = [NSString stringWithFormat:NSLocalizedString(@"Unknown response expected type %@ [reponse: %@]",nil),expected,data]; + NSDictionary * userInfo = @{NSLocalizedDescriptionKey : message}; + return [NSError errorWithDomain:SWGDeserializationErrorDomainKey code:SWGUnknownResponseObjectErrorCode userInfo:userInfo]; +} + +@end diff --git a/samples/client/petstore/objc/SwaggerClient/SWGReturn.h b/samples/client/petstore/objc/SwaggerClient/SWGReturn.h deleted file mode 100644 index fcce78f3681..00000000000 --- a/samples/client/petstore/objc/SwaggerClient/SWGReturn.h +++ /dev/null @@ -1,20 +0,0 @@ -#import -#import "SWGObject.h" - -/** - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen - * Do not edit the class manually. - */ - - - -@protocol SWGReturn -@end - -@interface SWGReturn : SWGObject - - -@property(nonatomic) NSNumber* _return; - -@end diff --git a/samples/client/petstore/objc/SwaggerClient/SWGReturn.m b/samples/client/petstore/objc/SwaggerClient/SWGReturn.m deleted file mode 100644 index ad97f1b15e9..00000000000 --- a/samples/client/petstore/objc/SwaggerClient/SWGReturn.m +++ /dev/null @@ -1,51 +0,0 @@ -#import "SWGReturn.h" - -@implementation SWGReturn - -- (instancetype)init { - self = [super init]; - - if (self) { - // initalise property's default value, if any - - } - - return self; -} - - -/** - * Maps json key to property name. - * This method is used by `JSONModel`. - */ -+ (JSONKeyMapper *)keyMapper -{ - return [[JSONKeyMapper alloc] initWithDictionary:@{ @"return": @"_return" }]; -} - -/** - * Indicates whether the property with the given name is optional. - * If `propertyName` is optional, then return `YES`, otherwise return `NO`. - * This method is used by `JSONModel`. - */ -+ (BOOL)propertyIsOptional:(NSString *)propertyName -{ - NSArray *optionalProperties = @[@"_return"]; - - if ([optionalProperties containsObject:propertyName]) { - return YES; - } - else { - return NO; - } -} - -/** - * Gets the string presentation of the object. - * This method will be called when logging model object using `NSLog`. - */ -- (NSString *)description { - return [[self toDictionary] description]; -} - -@end diff --git a/samples/client/petstore/objc/SwaggerClient/SWGSanitizer.h b/samples/client/petstore/objc/SwaggerClient/SWGSanitizer.h new file mode 100644 index 00000000000..5803999f362 --- /dev/null +++ b/samples/client/petstore/objc/SwaggerClient/SWGSanitizer.h @@ -0,0 +1,29 @@ +#import + +/** + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen + * Do not edit the class manually. + */ + +@protocol SWGSanitizer + +/** + * Sanitize object for request + * + * @param object The query/path/header/form/body param to be sanitized. + */ +- (id) sanitizeForSerialization:(id) object; + +/** + * Convert parameter to NSString + */ +- (NSString *) parameterToString: (id) param; + +@end + +@interface SWGSanitizer : NSObject + + + +@end diff --git a/samples/client/petstore/objc/SwaggerClient/SWGSanitizer.m b/samples/client/petstore/objc/SwaggerClient/SWGSanitizer.m new file mode 100644 index 00000000000..3f1dea7726e --- /dev/null +++ b/samples/client/petstore/objc/SwaggerClient/SWGSanitizer.m @@ -0,0 +1,82 @@ +#import "SWGSanitizer.h" +#import "SWGObject.h" +#import "SWGQueryParamCollection.h" +#import + +@interface SWGSanitizer () + +@end + +@implementation SWGSanitizer + +- (id) sanitizeForSerialization:(id) object { + if (object == nil) { + return nil; + } + else if ([object isKindOfClass:[NSString class]] || [object isKindOfClass:[NSNumber class]] || [object isKindOfClass:[SWGQueryParamCollection class]]) { + return object; + } + else if ([object isKindOfClass:[NSDate class]]) { + return [object ISO8601String]; + } + else if ([object isKindOfClass:[NSArray class]]) { + NSArray *objectArray = object; + NSMutableArray *sanitizedObjs = [NSMutableArray arrayWithCapacity:[objectArray count]]; + [object enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { + id sanitizedObj = [self sanitizeForSerialization:obj]; + if (sanitizedObj) { + [sanitizedObjs addObject:sanitizedObj]; + } + }]; + return sanitizedObjs; + } + else if ([object isKindOfClass:[NSDictionary class]]) { + NSDictionary *objectDict = object; + NSMutableDictionary *sanitizedObjs = [NSMutableDictionary dictionaryWithCapacity:[objectDict count]]; + [object enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { + id sanitizedObj = [self sanitizeForSerialization:obj]; + if (sanitizedObj) { + sanitizedObjs[key] = sanitizedObj; + } + }]; + return sanitizedObjs; + } + else if ([object isKindOfClass:[SWGObject class]]) { + return [object toDictionary]; + } + else { + NSException *e = [NSException + exceptionWithName:@"InvalidObjectArgumentException" + reason:[NSString stringWithFormat:@"*** The argument object: %@ is invalid", object] + userInfo:nil]; + @throw e; + } +} + +- (NSString *) parameterToString:(id)param { + if ([param isKindOfClass:[NSString class]]) { + return param; + } + else if ([param isKindOfClass:[NSNumber class]]) { + return [param stringValue]; + } + else if ([param isKindOfClass:[NSDate class]]) { + return [param ISO8601String]; + } + else if ([param isKindOfClass:[NSArray class]]) { + NSMutableArray *mutableParam = [NSMutableArray array]; + [param enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { + [mutableParam addObject:[self parameterToString:obj]]; + }]; + return [mutableParam componentsJoinedByString:@","]; + } + else { + NSException *e = [NSException + exceptionWithName:@"InvalidObjectArgumentException" + reason:[NSString stringWithFormat:@"*** The argument object: %@ is invalid", param] + userInfo:nil]; + @throw e; + } +} + +@end diff --git a/samples/client/petstore/objc/SwaggerClient/SWGSpecialModelName_.h b/samples/client/petstore/objc/SwaggerClient/SWGSpecialModelName_.h deleted file mode 100644 index 88187b28877..00000000000 --- a/samples/client/petstore/objc/SwaggerClient/SWGSpecialModelName_.h +++ /dev/null @@ -1,20 +0,0 @@ -#import -#import "SWGObject.h" - -/** - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen - * Do not edit the class manually. - */ - - - -@protocol SWGSpecialModelName_ -@end - -@interface SWGSpecialModelName_ : SWGObject - - -@property(nonatomic) NSNumber* specialPropertyName; - -@end diff --git a/samples/client/petstore/objc/SwaggerClient/SWGSpecialModelName_.m b/samples/client/petstore/objc/SwaggerClient/SWGSpecialModelName_.m deleted file mode 100644 index 9e1e680787d..00000000000 --- a/samples/client/petstore/objc/SwaggerClient/SWGSpecialModelName_.m +++ /dev/null @@ -1,51 +0,0 @@ -#import "SWGSpecialModelName_.h" - -@implementation SWGSpecialModelName_ - -- (instancetype)init { - self = [super init]; - - if (self) { - // initalise property's default value, if any - - } - - return self; -} - - -/** - * Maps json key to property name. - * This method is used by `JSONModel`. - */ -+ (JSONKeyMapper *)keyMapper -{ - return [[JSONKeyMapper alloc] initWithDictionary:@{ @"$special[property.name]": @"specialPropertyName" }]; -} - -/** - * Indicates whether the property with the given name is optional. - * If `propertyName` is optional, then return `YES`, otherwise return `NO`. - * This method is used by `JSONModel`. - */ -+ (BOOL)propertyIsOptional:(NSString *)propertyName -{ - NSArray *optionalProperties = @[@"specialPropertyName"]; - - if ([optionalProperties containsObject:propertyName]) { - return YES; - } - else { - return NO; - } -} - -/** - * Gets the string presentation of the object. - * This method will be called when logging model object using `NSLog`. - */ -- (NSString *)description { - return [[self toDictionary] description]; -} - -@end diff --git a/samples/client/petstore/objc/SwaggerClient/SWGStoreApi.h b/samples/client/petstore/objc/SwaggerClient/SWGStoreApi.h index 0a7bc70864a..d86eb23a046 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGStoreApi.h +++ b/samples/client/petstore/objc/SwaggerClient/SWGStoreApi.h @@ -39,9 +39,9 @@ /// /// /// -/// @return NSDictionary* /* NSString, NSNumber */ +/// @return NSDictionary* -(NSNumber*) getInventoryWithCompletionHandler: - (void (^)(NSDictionary* /* NSString, NSNumber */ output, NSError* error)) handler; + (void (^)(NSDictionary* output, NSError* error)) handler; /// diff --git a/samples/client/petstore/objc/SwaggerClient/SWGStoreApi.m b/samples/client/petstore/objc/SwaggerClient/SWGStoreApi.m index 84cd3a699d0..336258c3c5b 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGStoreApi.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGStoreApi.m @@ -141,10 +141,10 @@ static SWGStoreApi* singletonAPI = nil; /// /// Returns pet inventories by status /// Returns a map of status codes to quantities -/// @returns NSDictionary* /* NSString, NSNumber */ +/// @returns NSDictionary* /// -(NSNumber*) getInventoryWithCompletionHandler: - (void (^)(NSDictionary* /* NSString, NSNumber */ output, NSError* error)) handler { + (void (^)(NSDictionary* output, NSError* error)) handler { NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/store/inventory"]; // remove format in URL if needed @@ -192,9 +192,9 @@ static SWGStoreApi* singletonAPI = nil; authSettings: authSettings requestContentType: requestContentType responseContentType: responseContentType - responseType: @"NSDictionary* /* NSString, NSNumber */" + responseType: @"NSDictionary*" completionBlock: ^(id data, NSError *error) { - handler((NSDictionary* /* NSString, NSNumber */)data, error); + handler((NSDictionary*)data, error); } ]; } diff --git a/samples/client/petstore/objc/SwaggerClient/SWGTag.m b/samples/client/petstore/objc/SwaggerClient/SWGTag.m index 9eb00a157e3..8ad1742750d 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGTag.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGTag.m @@ -4,12 +4,10 @@ - (instancetype)init { self = [super init]; - if (self) { // initalise property's default value, if any } - return self; } @@ -18,8 +16,7 @@ * Maps json key to property name. * This method is used by `JSONModel`. */ -+ (JSONKeyMapper *)keyMapper -{ ++ (JSONKeyMapper *)keyMapper { return [[JSONKeyMapper alloc] initWithDictionary:@{ @"id": @"_id", @"name": @"name" }]; } @@ -28,24 +25,11 @@ * If `propertyName` is optional, then return `YES`, otherwise return `NO`. * This method is used by `JSONModel`. */ -+ (BOOL)propertyIsOptional:(NSString *)propertyName -{ ++ (BOOL)propertyIsOptional:(NSString *)propertyName { + NSArray *optionalProperties = @[@"_id", @"name"]; + return [optionalProperties containsObject:propertyName]; - if ([optionalProperties containsObject:propertyName]) { - return YES; - } - else { - return NO; - } -} - -/** - * Gets the string presentation of the object. - * This method will be called when logging model object using `NSLog`. - */ -- (NSString *)description { - return [[self toDictionary] description]; } @end diff --git a/samples/client/petstore/objc/SwaggerClient/SWGUser.m b/samples/client/petstore/objc/SwaggerClient/SWGUser.m index 2445dd37854..2551108cb5f 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGUser.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGUser.m @@ -4,12 +4,10 @@ - (instancetype)init { self = [super init]; - if (self) { // initalise property's default value, if any } - return self; } @@ -18,8 +16,7 @@ * Maps json key to property name. * This method is used by `JSONModel`. */ -+ (JSONKeyMapper *)keyMapper -{ ++ (JSONKeyMapper *)keyMapper { return [[JSONKeyMapper alloc] initWithDictionary:@{ @"id": @"_id", @"username": @"username", @"firstName": @"firstName", @"lastName": @"lastName", @"email": @"email", @"password": @"password", @"phone": @"phone", @"userStatus": @"userStatus" }]; } @@ -28,24 +25,11 @@ * If `propertyName` is optional, then return `YES`, otherwise return `NO`. * This method is used by `JSONModel`. */ -+ (BOOL)propertyIsOptional:(NSString *)propertyName -{ ++ (BOOL)propertyIsOptional:(NSString *)propertyName { + NSArray *optionalProperties = @[@"_id", @"username", @"firstName", @"lastName", @"email", @"password", @"phone", @"userStatus"]; + return [optionalProperties containsObject:propertyName]; - if ([optionalProperties containsObject:propertyName]) { - return YES; - } - else { - return NO; - } -} - -/** - * Gets the string presentation of the object. - * This method will be called when logging model object using `NSLog`. - */ -- (NSString *)description { - return [[self toDictionary] description]; } @end diff --git a/samples/client/petstore/objc/SwaggerClientTests/SwaggerClient/SWGViewController.m b/samples/client/petstore/objc/SwaggerClientTests/SwaggerClient/SWGViewController.m index 57fd9828e03..4405438e7ee 100644 --- a/samples/client/petstore/objc/SwaggerClientTests/SwaggerClient/SWGViewController.m +++ b/samples/client/petstore/objc/SwaggerClientTests/SwaggerClient/SWGViewController.m @@ -27,16 +27,11 @@ SWGPetApi *api = [[SWGPetApi alloc] init]; NSURL *file = [NSURL fileURLWithPath:@"/Users/geekerzp/tmp/test.jpg"]; - [api uploadFileWithPetId:@2 additionalMetadata:@2 file:file completionHandler:^(NSError *error) { + [api uploadFileWithPetId:@2 additionalMetadata:@"2" file:file completionHandler:^(NSError *error) { NSLog(@"*** error: %@", error); }]; } -- (void)didReceiveMemoryWarning -{ - [super didReceiveMemoryWarning]; -} - - (SWGPet*) createPet { SWGPet * pet = [[SWGPet alloc] init]; pet._id = [[NSNumber alloc] initWithLong:[[NSDate date] timeIntervalSince1970]]; diff --git a/samples/client/petstore/objc/SwaggerClientTests/Tests/DeserializationTest.m b/samples/client/petstore/objc/SwaggerClientTests/Tests/DeserializationTest.m index 5f5d274b4b0..6077ab42981 100644 --- a/samples/client/petstore/objc/SwaggerClientTests/Tests/DeserializationTest.m +++ b/samples/client/petstore/objc/SwaggerClientTests/Tests/DeserializationTest.m @@ -27,11 +27,28 @@ [formatter setDateFormat:@"yyyy-MM-dd"]; NSDate *date = [formatter dateFromString:dateStr]; NSError* error; - NSDate *deserializedDate = [apiClient deserialize:dateStr class:@"NSDate*" error:&error]; + NSDate *deserializedDate = [apiClient.responseDeserializer deserialize:dateStr class:@"NSDate*" error:&error]; XCTAssertNil(error); XCTAssertEqualWithAccuracy([date timeIntervalSinceReferenceDate], [deserializedDate timeIntervalSinceReferenceDate], 0.001); } +- (void)testDeserializeInvalidDate { + NSString *dateStr = @"random string"; + + NSError* error; + NSDate *deserializedDate = [apiClient.responseDeserializer deserialize:dateStr class:@"NSDate*" error:&error]; + XCTAssertNotNil(error); + XCTAssertNil(deserializedDate); +} + +- (void)testDeserializeEmptyDate { + NSString *dateStr = @""; + NSError* error; + NSDate *deserializedDate = [apiClient.responseDeserializer deserialize:dateStr class:@"NSDate*" error:&error]; + XCTAssertNil(error); + XCTAssertNil(deserializedDate); +} + - (void)testDeserializeDateTime { NSString *dateTimeStr = @"1997-07-16T19:20:30+00:00"; @@ -39,15 +56,23 @@ [formatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZ"]; NSDate *dateTime = [formatter dateFromString:dateTimeStr]; NSError* error; - NSDate *deserializedDateTime = [apiClient deserialize:dateTimeStr class:@"NSDate*" error:&error]; + NSDate *deserializedDateTime = [apiClient.responseDeserializer deserialize:dateTimeStr class:@"NSDate*" error:&error]; XCTAssertNil(error); XCTAssertEqualWithAccuracy([dateTime timeIntervalSinceReferenceDate], [deserializedDateTime timeIntervalSinceReferenceDate], 0.001); } +- (void)testDeserializeUnknownObject { + NSString *data = @"random string"; + NSError* error; + NSNumber *result = [apiClient.responseDeserializer deserialize:data class:@"DeserializationTest*" error:&error]; + XCTAssertNotNil(error); + XCTAssertNil(result); +} + - (void)testDeserializeObject { NSNumber *data = @1; NSError* error; - NSNumber *result = [apiClient deserialize:data class:@"NSObject*" error:&error]; + NSNumber *result = [apiClient.responseDeserializer deserialize:data class:@"NSObject*" error:&error]; XCTAssertNil(error); XCTAssertEqualObjects(data, result); } @@ -55,7 +80,7 @@ - (void)testDeserializeString { NSString *data = @"test string"; NSError* error; - NSString *result = [apiClient deserialize:data class:@"NSString*" error:&error]; + NSString *result = [apiClient.responseDeserializer deserialize:data class:@"NSString*" error:&error]; XCTAssertNil(error); XCTAssertTrue([result isEqualToString:data]); } @@ -63,12 +88,29 @@ - (void)testDeserializeListOfString { NSArray *data = @[@"test string"]; NSError* error; - NSArray *result = [apiClient deserialize:data class:@"NSArray* /* NSString */" error:&error]; + NSArray *result = [apiClient.responseDeserializer deserialize:data class:@"NSArray*" error:&error]; XCTAssertNil(error); XCTAssertTrue([result isKindOfClass:[NSArray class]]); XCTAssertTrue([result[0] isKindOfClass:[NSString class]]); } +- (void)testDeserializeInvalidListOfNumbers { + NSArray *data = @[@"test string"]; + NSError* error; + NSArray *result = [apiClient.responseDeserializer deserialize:data class:@"NSArray*" error:&error]; + XCTAssertNotNil(error); + XCTAssertNil(result); +} + +- (void)testDeserializeListOfNumbers { + NSArray *data = @[@"1.0"]; + NSError* error; + NSArray *result = [apiClient.responseDeserializer deserialize:data class:@"NSArray*" error:&error]; + XCTAssertNil(error); + XCTAssertTrue([result isKindOfClass:[NSArray class]]); + XCTAssertTrue([result[0] isKindOfClass:[NSNumber class]]); +} + - (void)testDeserializeListOfModels { NSArray *data = @[ @@ -92,11 +134,17 @@ }]; NSError* error; - NSArray *result = [apiClient deserialize:data class:@"NSArray*" error:&error]; + NSArray *result = [apiClient.responseDeserializer deserialize:data class:@"NSArray*" error:&error]; XCTAssertTrue([result isKindOfClass:[NSArray class]]); XCTAssertTrue([[result firstObject] isKindOfClass:[SWGPet class]]); - XCTAssertEqualObjects([[result firstObject] _id], @119); + SWGPet*pet = [result firstObject]; + XCTAssertEqualObjects([pet.photoUrls firstObject],@"string"); + XCTAssertTrue([[pet.tags firstObject] isKindOfClass:[SWGTag class]]); + SWGTag* tag = [pet.tags firstObject]; + XCTAssertEqualObjects(tag._id, @0); + XCTAssertEqualObjects(tag.name, @"string"); + XCTAssertEqualObjects(pet._id, @119); } - (void)testDeserializeMapOfModels { @@ -123,7 +171,7 @@ } }; NSError* error; - NSDictionary *result = [apiClient deserialize:data class:@"NSDictionary* /* NSString, SWGPet */" error:&error]; + NSDictionary *result = [apiClient.responseDeserializer deserialize:data class:@"NSDictionary* /* NSString, SWGPet */" error:&error]; XCTAssertTrue([result isKindOfClass:[NSDictionary class]]); XCTAssertTrue([result[@"pet"] isKindOfClass:[SWGPet class]]); @@ -134,11 +182,44 @@ NSDictionary *data = @{ @"foo": @{ - @"bar": @1 + @"bar": @1, + @"bar2": [NSNull null] } }; + SWGResponseDeserializer* responseDeserializer = [[SWGResponseDeserializer alloc] init]; NSError* error; - NSDictionary *result = [apiClient deserialize:data class:@"NSDictionary* /* NSString, NSDictionary* /* NSString, NSNumber */ */" error:&error]; + NSDictionary *result = [responseDeserializer deserialize:data class:@"NSDictionary* /* NSString, NSDictionary* /* NSString, NSNumber */ */" error:&error]; + + XCTAssertTrue([result isKindOfClass:[NSDictionary class]]); + XCTAssertTrue([result[@"foo"] isKindOfClass:[NSDictionary class]]); + XCTAssertTrue([result[@"foo"][@"bar"] isKindOfClass:[NSNumber class]]); +} + + +- (void)testDeserializeNestedMapWithNullValue { + NSDictionary *data = + @{ + @"foo": @{ + @"bar": @1, + @"bar2": [NSNull null] + } + }; + SWGResponseDeserializer* responseDeserializer = [[SWGResponseDeserializer alloc] init]; + responseDeserializer.treatNullAsError = YES; + NSError* error; + NSDictionary *result = [responseDeserializer deserialize:data class:@"NSDictionary* /* NSString, NSDictionary* /* NSString, NSNumber */ */" error:&error]; + XCTAssertNil(result); + XCTAssertNotNil(error); +} + +- (void)testDeserializeNestedMap2 { + NSDictionary *data = @{ + @"foo": @{ + @"bar": @1 + } + }; + NSError* error; + NSDictionary *result = [apiClient.responseDeserializer deserialize:data class:@"NSDictionary*>*" error:&error]; XCTAssertTrue([result isKindOfClass:[NSDictionary class]]); XCTAssertTrue([result[@"foo"] isKindOfClass:[NSDictionary class]]); @@ -148,7 +229,7 @@ - (void)testDeserializeNestedList { NSArray *data = @[@[@"foo"]]; NSError* error; - NSArray *result = [apiClient deserialize:data class:@"NSArray* /* NSArray* /* NSString */ */" error:&error]; + NSArray *result = [apiClient.responseDeserializer deserialize:data class:@"NSArray* /* NSArray* /* NSString */ */" error:&error]; XCTAssertTrue([result isKindOfClass:[NSArray class]]); XCTAssertTrue([result[0] isKindOfClass:[NSArray class]]); @@ -161,11 +242,11 @@ data = @"true"; NSError* error; - result = [apiClient deserialize:data class:@"NSNumber*" error:&error]; + result = [apiClient.responseDeserializer deserialize:data class:@"NSNumber*" error:&error]; XCTAssertTrue([result isEqual:@YES]); data = @"false"; - result = [apiClient deserialize:data class:@"NSNumber*" error:&error]; + result = [apiClient.responseDeserializer deserialize:data class:@"NSNumber*" error:&error]; XCTAssertTrue([result isEqual:@NO]); } diff --git a/samples/client/petstore/objc/SwaggerClientTests/Tests/PetApiTest.m b/samples/client/petstore/objc/SwaggerClientTests/Tests/PetApiTest.m index 7fd3d4f97c8..7ddc817e9ef 100644 --- a/samples/client/petstore/objc/SwaggerClientTests/Tests/PetApiTest.m +++ b/samples/client/petstore/objc/SwaggerClientTests/Tests/PetApiTest.m @@ -165,7 +165,7 @@ which causes an exception when deserializing the data SWGTag* tag = [[SWGTag alloc] init]; tag.name = @"tony"; NSLog(@"%@", pet._id); - pet.tags = [[NSArray alloc] initWithObjects:tag, nil]; + pet.tags = (id)[[NSArray alloc] initWithObjects:tag, nil]; [api addPetWithBody:pet completionHandler:^(NSError *error) { if(error) { diff --git a/samples/client/petstore/objc/SwaggerClientTests/Tests/SWGApiClientTest.m b/samples/client/petstore/objc/SwaggerClientTests/Tests/SWGApiClientTest.m index e9f1a46af3b..ed87d8f9e2d 100644 --- a/samples/client/petstore/objc/SwaggerClientTests/Tests/SWGApiClientTest.m +++ b/samples/client/petstore/objc/SwaggerClientTests/Tests/SWGApiClientTest.m @@ -2,11 +2,6 @@ #import #import #import -#import -#import -#import -#import -#import @interface SWGApiClientTest : XCTestCase @@ -109,31 +104,31 @@ // nil data = nil; - result = [self.apiClient sanitizeForSerialization:data]; + result = [self.apiClient.sanitizer sanitizeForSerialization:data]; XCTAssertEqualObjects(result, data); // NSString data = @"test string"; - result = [self.apiClient sanitizeForSerialization:data]; + result = [self.apiClient.sanitizer sanitizeForSerialization:data]; XCTAssertEqualObjects(result, data); // NSNumber data = @1; - result = [self.apiClient sanitizeForSerialization:data]; + result = [self.apiClient.sanitizer sanitizeForSerialization:data]; XCTAssertEqualObjects(result, data); // SWGQueryParamCollection data = [[SWGQueryParamCollection alloc] init]; - result = [self.apiClient sanitizeForSerialization:data]; + result = [self.apiClient.sanitizer sanitizeForSerialization:data]; XCTAssertEqualObjects(result, data); // NSDate data = [NSDate dateWithISO8601String:@"1997-07-16T19:20:30.45+01:00"]; - result = [self.apiClient sanitizeForSerialization:data]; + result = [self.apiClient.sanitizer sanitizeForSerialization:data]; XCTAssertEqualObjects(result, [data ISO8601String]); data = [NSDate dateWithISO8601String:@"1997-07-16"]; - result = [self.apiClient sanitizeForSerialization:data]; + result = [self.apiClient.sanitizer sanitizeForSerialization:data]; XCTAssertEqualObjects(result, [data ISO8601String]); // model @@ -144,23 +139,23 @@ @"status": @"available", @"photoUrls": @[@"http://foo.bar.com/3", @"http://foo.bar.com/4"]}; data = [[SWGPet alloc] initWithDictionary:petDict error:nil]; - result = [self.apiClient sanitizeForSerialization:data]; + result = [self.apiClient.sanitizer sanitizeForSerialization:data]; XCTAssertEqualObjects(result, petDict); // NSArray data = @[@1]; - result = [self.apiClient sanitizeForSerialization:data]; + result = [self.apiClient.sanitizer sanitizeForSerialization:data]; XCTAssertEqualObjects(result, data); // NSArray of models NSArray *arrayOfPetDict = @[petDict]; - data = [NSArray arrayWithObject:[[SWGPet alloc] initWithDictionary:petDict error:nil]]; - result = [self.apiClient sanitizeForSerialization:data]; + data = @[[[SWGPet alloc] initWithDictionary:petDict error:nil]]; + result = [self.apiClient.sanitizer sanitizeForSerialization:data]; XCTAssertEqualObjects(result, arrayOfPetDict); // NSDictionary data = @{@"test key": @"test value"}; - result = [self.apiClient sanitizeForSerialization:data]; + result = [self.apiClient.sanitizer sanitizeForSerialization:data]; XCTAssertEqualObjects(result, data); } diff --git a/samples/client/petstore/objc/docs/SWGPet.md b/samples/client/petstore/objc/docs/SWGPet.md index 6c7286531f9..c8298c66bf1 100644 --- a/samples/client/petstore/objc/docs/SWGPet.md +++ b/samples/client/petstore/objc/docs/SWGPet.md @@ -6,7 +6,7 @@ Name | Type | Description | Notes **_id** | **NSNumber*** | | [optional] **category** | [**SWGCategory***](SWGCategory.md) | | [optional] **name** | **NSString*** | | -**photoUrls** | **NSArray* /* NSString */** | | +**photoUrls** | **NSArray<NSString*>*** | | **tags** | [**NSArray<SWGTag>***](SWGTag.md) | | [optional] **status** | **NSString*** | pet status in the store | [optional] diff --git a/samples/client/petstore/objc/docs/SWGPetApi.md b/samples/client/petstore/objc/docs/SWGPetApi.md index 78a54942c2f..a07f0cf067c 100644 --- a/samples/client/petstore/objc/docs/SWGPetApi.md +++ b/samples/client/petstore/objc/docs/SWGPetApi.md @@ -140,7 +140,7 @@ void (empty response body) # **findPetsByStatus** ```objc --(NSNumber*) findPetsByStatusWithStatus: (NSArray* /* NSString */) status +-(NSNumber*) findPetsByStatusWithStatus: (NSArray*) status completionHandler: (void (^)(NSArray* output, NSError* error)) handler; ``` @@ -156,7 +156,7 @@ SWGConfiguration *apiConfig = [SWGConfiguration sharedConfig]; [apiConfig setAccessToken:@"YOUR_ACCESS_TOKEN"]; -NSArray* /* NSString */ status = @[@"available"]; // Status values that need to be considered for filter (optional) (default to available) +NSArray* status = @[@"available"]; // Status values that need to be considered for filter (optional) (default to available) @try { @@ -184,7 +184,7 @@ NSArray* /* NSString */ status = @[@"available"]; // Status values that need to Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **status** | [**NSArray* /* NSString */**](NSString*.md)| Status values that need to be considered for filter | [optional] [default to available] + **status** | [**NSArray<NSString*>***](NSString*.md)| Status values that need to be considered for filter | [optional] [default to available] ### Return type @@ -203,7 +203,7 @@ Name | Type | Description | Notes # **findPetsByTags** ```objc --(NSNumber*) findPetsByTagsWithTags: (NSArray* /* NSString */) tags +-(NSNumber*) findPetsByTagsWithTags: (NSArray*) tags completionHandler: (void (^)(NSArray* output, NSError* error)) handler; ``` @@ -219,7 +219,7 @@ SWGConfiguration *apiConfig = [SWGConfiguration sharedConfig]; [apiConfig setAccessToken:@"YOUR_ACCESS_TOKEN"]; -NSArray* /* NSString */ tags = @[@"tags_example"]; // Tags to filter by (optional) +NSArray* tags = @[@"tags_example"]; // Tags to filter by (optional) @try { @@ -247,7 +247,7 @@ NSArray* /* NSString */ tags = @[@"tags_example"]; // Tags to filter by (optiona Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **tags** | [**NSArray* /* NSString */**](NSString*.md)| Tags to filter by | [optional] + **tags** | [**NSArray<NSString*>***](NSString*.md)| Tags to filter by | [optional] ### Return type @@ -283,8 +283,8 @@ SWGConfiguration *apiConfig = [SWGConfiguration sharedConfig]; // Configure API key authorization: (authentication scheme: api_key) [apiConfig setApiKey:@"YOUR_API_KEY" forApiKeyIdentifier:@"api_key"]; -// Uncomment below to setup prefix (e.g. BEARER) for API key, if needed -//[apiConfig setApiKeyPrefix:@"BEARER" forApiKeyIdentifier:@"api_key"]; +// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed +//[apiConfig setApiKeyPrefix:@"Bearer" forApiKeyIdentifier:@"api_key"]; NSNumber* petId = @789; // ID of pet that needs to be fetched diff --git a/samples/client/petstore/objc/docs/SWGStoreApi.md b/samples/client/petstore/objc/docs/SWGStoreApi.md index 1eacf83431a..29dfde60aa7 100644 --- a/samples/client/petstore/objc/docs/SWGStoreApi.md +++ b/samples/client/petstore/objc/docs/SWGStoreApi.md @@ -68,7 +68,7 @@ No authorization required # **getInventory** ```objc -(NSNumber*) getInventoryWithCompletionHandler: - (void (^)(NSDictionary* /* NSString, NSNumber */ output, NSError* error)) handler; + (void (^)(NSDictionary* output, NSError* error)) handler; ``` Returns pet inventories by status @@ -81,8 +81,8 @@ SWGConfiguration *apiConfig = [SWGConfiguration sharedConfig]; // Configure API key authorization: (authentication scheme: api_key) [apiConfig setApiKey:@"YOUR_API_KEY" forApiKeyIdentifier:@"api_key"]; -// Uncomment below to setup prefix (e.g. BEARER) for API key, if needed -//[apiConfig setApiKeyPrefix:@"BEARER" forApiKeyIdentifier:@"api_key"]; +// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed +//[apiConfig setApiKeyPrefix:@"Bearer" forApiKeyIdentifier:@"api_key"]; @@ -92,7 +92,7 @@ SWGConfiguration *apiConfig = [SWGConfiguration sharedConfig]; // Returns pet inventories by status [apiInstance getInventoryWithCompletionHandler: - ^(NSDictionary* /* NSString, NSNumber */ output, NSError* error) { + ^(NSDictionary* output, NSError* error) { if (output) { NSLog(@"%@", output); } @@ -113,7 +113,7 @@ This endpoint does not need any parameter. ### Return type -[**NSDictionary* /* NSString, NSNumber */**](NSDictionary.md) +[**NSDictionary***](NSDictionary.md) ### Authorization diff --git a/samples/client/petstore/objc/git_push.sh b/samples/client/petstore/objc/git_push.sh index 1a36388db02..ed374619b13 100644 --- a/samples/client/petstore/objc/git_push.sh +++ b/samples/client/petstore/objc/git_push.sh @@ -8,12 +8,12 @@ git_repo_id=$2 release_note=$3 if [ "$git_user_id" = "" ]; then - git_user_id="YOUR_GIT_USR_ID" + git_user_id="GIT_USER_ID" echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" fi if [ "$git_repo_id" = "" ]; then - git_repo_id="YOUR_GIT_REPO_ID" + git_repo_id="GIT_REPO_ID" echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" fi diff --git a/samples/client/petstore/perl/docs/PetApi.md b/samples/client/petstore/perl/docs/PetApi.md index c696eac92cd..829dc3a08ef 100644 --- a/samples/client/petstore/perl/docs/PetApi.md +++ b/samples/client/petstore/perl/docs/PetApi.md @@ -269,8 +269,8 @@ use Data::Dumper; # Configure API key authorization: api_key $WWW::SwaggerClient::Configuration::api_key->{'api_key'} = 'YOUR_API_KEY'; -# uncomment below to setup prefix (e.g. BEARER) for API key, if needed -#$WWW::SwaggerClient::Configuration::api_key_prefix->{'api_key'} = "BEARER"; +# uncomment below to setup prefix (e.g. Bearer) for API key, if needed +#$WWW::SwaggerClient::Configuration::api_key_prefix->{'api_key'} = "Bearer"; # Configure OAuth2 access token for authorization: petstore_auth $WWW::SwaggerClient::Configuration::access_token = 'YOUR_ACCESS_TOKEN'; @@ -320,8 +320,8 @@ use Data::Dumper; # Configure API key authorization: api_key $WWW::SwaggerClient::Configuration::api_key->{'api_key'} = 'YOUR_API_KEY'; -# uncomment below to setup prefix (e.g. BEARER) for API key, if needed -#$WWW::SwaggerClient::Configuration::api_key_prefix->{'api_key'} = "BEARER"; +# uncomment below to setup prefix (e.g. Bearer) for API key, if needed +#$WWW::SwaggerClient::Configuration::api_key_prefix->{'api_key'} = "Bearer"; # Configure OAuth2 access token for authorization: petstore_auth $WWW::SwaggerClient::Configuration::access_token = 'YOUR_ACCESS_TOKEN'; @@ -371,8 +371,8 @@ use Data::Dumper; # Configure API key authorization: api_key $WWW::SwaggerClient::Configuration::api_key->{'api_key'} = 'YOUR_API_KEY'; -# uncomment below to setup prefix (e.g. BEARER) for API key, if needed -#$WWW::SwaggerClient::Configuration::api_key_prefix->{'api_key'} = "BEARER"; +# uncomment below to setup prefix (e.g. Bearer) for API key, if needed +#$WWW::SwaggerClient::Configuration::api_key_prefix->{'api_key'} = "Bearer"; # Configure OAuth2 access token for authorization: petstore_auth $WWW::SwaggerClient::Configuration::access_token = 'YOUR_ACCESS_TOKEN'; diff --git a/samples/client/petstore/perl/docs/StoreApi.md b/samples/client/petstore/perl/docs/StoreApi.md index 15b02bca3fd..c5eb55a3f12 100644 --- a/samples/client/petstore/perl/docs/StoreApi.md +++ b/samples/client/petstore/perl/docs/StoreApi.md @@ -73,12 +73,12 @@ use Data::Dumper; # Configure API key authorization: test_api_client_id $WWW::SwaggerClient::Configuration::api_key->{'x-test_api_client_id'} = 'YOUR_API_KEY'; -# uncomment below to setup prefix (e.g. BEARER) for API key, if needed -#$WWW::SwaggerClient::Configuration::api_key_prefix->{'x-test_api_client_id'} = "BEARER"; +# uncomment below to setup prefix (e.g. Bearer) for API key, if needed +#$WWW::SwaggerClient::Configuration::api_key_prefix->{'x-test_api_client_id'} = "Bearer"; # Configure API key authorization: test_api_client_secret $WWW::SwaggerClient::Configuration::api_key->{'x-test_api_client_secret'} = 'YOUR_API_KEY'; -# uncomment below to setup prefix (e.g. BEARER) for API key, if needed -#$WWW::SwaggerClient::Configuration::api_key_prefix->{'x-test_api_client_secret'} = "BEARER"; +# uncomment below to setup prefix (e.g. Bearer) for API key, if needed +#$WWW::SwaggerClient::Configuration::api_key_prefix->{'x-test_api_client_secret'} = "Bearer"; my $api_instance = WWW::SwaggerClient::StoreApi->new(); my $status = 'status_example'; # string | Status value that needs to be considered for query @@ -126,8 +126,8 @@ use Data::Dumper; # Configure API key authorization: api_key $WWW::SwaggerClient::Configuration::api_key->{'api_key'} = 'YOUR_API_KEY'; -# uncomment below to setup prefix (e.g. BEARER) for API key, if needed -#$WWW::SwaggerClient::Configuration::api_key_prefix->{'api_key'} = "BEARER"; +# uncomment below to setup prefix (e.g. Bearer) for API key, if needed +#$WWW::SwaggerClient::Configuration::api_key_prefix->{'api_key'} = "Bearer"; my $api_instance = WWW::SwaggerClient::StoreApi->new(); @@ -171,8 +171,8 @@ use Data::Dumper; # Configure API key authorization: api_key $WWW::SwaggerClient::Configuration::api_key->{'api_key'} = 'YOUR_API_KEY'; -# uncomment below to setup prefix (e.g. BEARER) for API key, if needed -#$WWW::SwaggerClient::Configuration::api_key_prefix->{'api_key'} = "BEARER"; +# uncomment below to setup prefix (e.g. Bearer) for API key, if needed +#$WWW::SwaggerClient::Configuration::api_key_prefix->{'api_key'} = "Bearer"; my $api_instance = WWW::SwaggerClient::StoreApi->new(); @@ -216,12 +216,12 @@ use Data::Dumper; # Configure API key authorization: test_api_key_header $WWW::SwaggerClient::Configuration::api_key->{'test_api_key_header'} = 'YOUR_API_KEY'; -# uncomment below to setup prefix (e.g. BEARER) for API key, if needed -#$WWW::SwaggerClient::Configuration::api_key_prefix->{'test_api_key_header'} = "BEARER"; +# uncomment below to setup prefix (e.g. Bearer) for API key, if needed +#$WWW::SwaggerClient::Configuration::api_key_prefix->{'test_api_key_header'} = "Bearer"; # Configure API key authorization: test_api_key_query $WWW::SwaggerClient::Configuration::api_key->{'test_api_key_query'} = 'YOUR_API_KEY'; -# uncomment below to setup prefix (e.g. BEARER) for API key, if needed -#$WWW::SwaggerClient::Configuration::api_key_prefix->{'test_api_key_query'} = "BEARER"; +# uncomment below to setup prefix (e.g. Bearer) for API key, if needed +#$WWW::SwaggerClient::Configuration::api_key_prefix->{'test_api_key_query'} = "Bearer"; my $api_instance = WWW::SwaggerClient::StoreApi->new(); my $order_id = 'order_id_example'; # string | ID of pet that needs to be fetched @@ -269,12 +269,12 @@ use Data::Dumper; # Configure API key authorization: test_api_client_id $WWW::SwaggerClient::Configuration::api_key->{'x-test_api_client_id'} = 'YOUR_API_KEY'; -# uncomment below to setup prefix (e.g. BEARER) for API key, if needed -#$WWW::SwaggerClient::Configuration::api_key_prefix->{'x-test_api_client_id'} = "BEARER"; +# uncomment below to setup prefix (e.g. Bearer) for API key, if needed +#$WWW::SwaggerClient::Configuration::api_key_prefix->{'x-test_api_client_id'} = "Bearer"; # Configure API key authorization: test_api_client_secret $WWW::SwaggerClient::Configuration::api_key->{'x-test_api_client_secret'} = 'YOUR_API_KEY'; -# uncomment below to setup prefix (e.g. BEARER) for API key, if needed -#$WWW::SwaggerClient::Configuration::api_key_prefix->{'x-test_api_client_secret'} = "BEARER"; +# uncomment below to setup prefix (e.g. Bearer) for API key, if needed +#$WWW::SwaggerClient::Configuration::api_key_prefix->{'x-test_api_client_secret'} = "Bearer"; my $api_instance = WWW::SwaggerClient::StoreApi->new(); my $body = WWW::SwaggerClient::Object::Order->new(); # Order | order placed for purchasing the pet diff --git a/samples/client/petstore/perl/test.pl b/samples/client/petstore/perl/test.pl index 626d25357fc..a5b608aa403 100755 --- a/samples/client/petstore/perl/test.pl +++ b/samples/client/petstore/perl/test.pl @@ -17,7 +17,7 @@ use DateTime; $WWW::SwaggerClient::Configuration::http_user_agent = 'Perl-Swagger-Test'; $WWW::SwaggerClient::Configuration::api_key->{'api_key'} = 'ZZZZZZZZZZZZZZ'; -$WWW::SwaggerClient::Configuration::api_key_prefix->{'api_key'} = 'BEARER'; +$WWW::SwaggerClient::Configuration::api_key_prefix->{'api_key'} = 'Bearer'; $WWW::SwaggerClient::Configuration::username = 'username'; $WWW::SwaggerClient::Configuration::password = 'password'; diff --git a/samples/client/petstore/php/SwaggerClient-php/README.md b/samples/client/petstore/php/SwaggerClient-php/README.md index a0db472b07f..fe09a19fa93 100644 --- a/samples/client/petstore/php/SwaggerClient-php/README.md +++ b/samples/client/petstore/php/SwaggerClient-php/README.md @@ -5,7 +5,7 @@ This PHP package is automatically generated by the [Swagger Codegen](https://git - API version: 1.0.0 - Package version: 1.0.0 -- Build date: 2016-04-27T17:54:12.143+08:00 +- Build date: 2016-05-10T22:37:00.768+08:00 - Build package: class io.swagger.codegen.languages.PhpClientCodegen ## Requirements @@ -22,11 +22,11 @@ To install the bindings via [Composer](http://getcomposer.org/), add the followi "repositories": [ { "type": "git", - "url": "https://github.com/YOUR_GIT_USR_ID/YOUR_GIT_REPO_ID.git" + "url": "https://github.com/GIT_USER_ID/GIT_REPO_ID.git" } ], "require": { - "YOUR_GIT_USR_ID/YOUR_GIT_REPO_ID": "*@dev" + "GIT_USER_ID/GIT_REPO_ID": "*@dev" } } ``` @@ -59,7 +59,7 @@ Please follow the [installation procedure](#installation--usage) and then run th require_once(__DIR__ . '/vendor/autoload.php'); $api_instance = new Swagger\Client\Api\FakeApi(); -$number = "number_example"; // string | None +$number = 3.4; // float | None $double = 1.2; // double | None $string = "string_example"; // string | None $byte = "B"; // string | None @@ -87,47 +87,48 @@ All URIs are relative to *http://petstore.swagger.io/v2* Class | Method | HTTP request | Description ------------ | ------------- | ------------- | ------------- -*FakeApi* | [**testEndpointParameters**](docs/FakeApi.md#testendpointparameters) | **POST** /fake | Fake endpoint for testing various parameters -*PetApi* | [**addPet**](docs/PetApi.md#addpet) | **POST** /pet | Add a new pet to the store -*PetApi* | [**deletePet**](docs/PetApi.md#deletepet) | **DELETE** /pet/{petId} | Deletes a pet -*PetApi* | [**findPetsByStatus**](docs/PetApi.md#findpetsbystatus) | **GET** /pet/findByStatus | Finds Pets by status -*PetApi* | [**findPetsByTags**](docs/PetApi.md#findpetsbytags) | **GET** /pet/findByTags | Finds Pets by tags -*PetApi* | [**getPetById**](docs/PetApi.md#getpetbyid) | **GET** /pet/{petId} | Find pet by ID -*PetApi* | [**updatePet**](docs/PetApi.md#updatepet) | **PUT** /pet | Update an existing pet -*PetApi* | [**updatePetWithForm**](docs/PetApi.md#updatepetwithform) | **POST** /pet/{petId} | Updates a pet in the store with form data -*PetApi* | [**uploadFile**](docs/PetApi.md#uploadfile) | **POST** /pet/{petId}/uploadImage | uploads an image -*StoreApi* | [**deleteOrder**](docs/StoreApi.md#deleteorder) | **DELETE** /store/order/{orderId} | Delete purchase order by ID -*StoreApi* | [**getInventory**](docs/StoreApi.md#getinventory) | **GET** /store/inventory | Returns pet inventories by status -*StoreApi* | [**getOrderById**](docs/StoreApi.md#getorderbyid) | **GET** /store/order/{orderId} | Find purchase order by ID -*StoreApi* | [**placeOrder**](docs/StoreApi.md#placeorder) | **POST** /store/order | Place an order for a pet -*UserApi* | [**createUser**](docs/UserApi.md#createuser) | **POST** /user | Create user -*UserApi* | [**createUsersWithArrayInput**](docs/UserApi.md#createuserswitharrayinput) | **POST** /user/createWithArray | Creates list of users with given input array -*UserApi* | [**createUsersWithListInput**](docs/UserApi.md#createuserswithlistinput) | **POST** /user/createWithList | Creates list of users with given input array -*UserApi* | [**deleteUser**](docs/UserApi.md#deleteuser) | **DELETE** /user/{username} | Delete user -*UserApi* | [**getUserByName**](docs/UserApi.md#getuserbyname) | **GET** /user/{username} | Get user by user name -*UserApi* | [**loginUser**](docs/UserApi.md#loginuser) | **GET** /user/login | Logs user into the system -*UserApi* | [**logoutUser**](docs/UserApi.md#logoutuser) | **GET** /user/logout | Logs out current logged in user session -*UserApi* | [**updateUser**](docs/UserApi.md#updateuser) | **PUT** /user/{username} | Updated user +*FakeApi* | [**testEndpointParameters**](docs/ApiFakeApi.md#testendpointparameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +*PetApi* | [**addPet**](docs/ApiPetApi.md#addpet) | **POST** /pet | Add a new pet to the store +*PetApi* | [**deletePet**](docs/ApiPetApi.md#deletepet) | **DELETE** /pet/{petId} | Deletes a pet +*PetApi* | [**findPetsByStatus**](docs/ApiPetApi.md#findpetsbystatus) | **GET** /pet/findByStatus | Finds Pets by status +*PetApi* | [**findPetsByTags**](docs/ApiPetApi.md#findpetsbytags) | **GET** /pet/findByTags | Finds Pets by tags +*PetApi* | [**getPetById**](docs/ApiPetApi.md#getpetbyid) | **GET** /pet/{petId} | Find pet by ID +*PetApi* | [**updatePet**](docs/ApiPetApi.md#updatepet) | **PUT** /pet | Update an existing pet +*PetApi* | [**updatePetWithForm**](docs/ApiPetApi.md#updatepetwithform) | **POST** /pet/{petId} | Updates a pet in the store with form data +*PetApi* | [**uploadFile**](docs/ApiPetApi.md#uploadfile) | **POST** /pet/{petId}/uploadImage | uploads an image +*StoreApi* | [**deleteOrder**](docs/ApiStoreApi.md#deleteorder) | **DELETE** /store/order/{orderId} | Delete purchase order by ID +*StoreApi* | [**getInventory**](docs/ApiStoreApi.md#getinventory) | **GET** /store/inventory | Returns pet inventories by status +*StoreApi* | [**getOrderById**](docs/ApiStoreApi.md#getorderbyid) | **GET** /store/order/{orderId} | Find purchase order by ID +*StoreApi* | [**placeOrder**](docs/ApiStoreApi.md#placeorder) | **POST** /store/order | Place an order for a pet +*UserApi* | [**createUser**](docs/ApiUserApi.md#createuser) | **POST** /user | Create user +*UserApi* | [**createUsersWithArrayInput**](docs/ApiUserApi.md#createuserswitharrayinput) | **POST** /user/createWithArray | Creates list of users with given input array +*UserApi* | [**createUsersWithListInput**](docs/ApiUserApi.md#createuserswithlistinput) | **POST** /user/createWithList | Creates list of users with given input array +*UserApi* | [**deleteUser**](docs/ApiUserApi.md#deleteuser) | **DELETE** /user/{username} | Delete user +*UserApi* | [**getUserByName**](docs/ApiUserApi.md#getuserbyname) | **GET** /user/{username} | Get user by user name +*UserApi* | [**loginUser**](docs/ApiUserApi.md#loginuser) | **GET** /user/login | Logs user into the system +*UserApi* | [**logoutUser**](docs/ApiUserApi.md#logoutuser) | **GET** /user/logout | Logs out current logged in user session +*UserApi* | [**updateUser**](docs/ApiUserApi.md#updateuser) | **PUT** /user/{username} | Updated user ## Documentation For Models - - [Animal](docs/Animal.md) - - [ApiResponse](docs/ApiResponse.md) - - [Cat](docs/Cat.md) - - [Category](docs/Category.md) - - [Dog](docs/Dog.md) - - [EnumClass](docs/EnumClass.md) - - [EnumTest](docs/EnumTest.md) - - [FormatTest](docs/FormatTest.md) - - [Model200Response](docs/Model200Response.md) - - [ModelReturn](docs/ModelReturn.md) - - [Name](docs/Name.md) - - [Order](docs/Order.md) - - [Pet](docs/Pet.md) - - [SpecialModelName](docs/SpecialModelName.md) - - [Tag](docs/Tag.md) - - [User](docs/User.md) + - [Animal](docs/ModelAnimal.md) + - [AnimalFarm](docs/ModelAnimalFarm.md) + - [ApiResponse](docs/ModelApiResponse.md) + - [Cat](docs/ModelCat.md) + - [Category](docs/ModelCategory.md) + - [Dog](docs/ModelDog.md) + - [EnumClass](docs/ModelEnumClass.md) + - [EnumTest](docs/ModelEnumTest.md) + - [FormatTest](docs/ModelFormatTest.md) + - [Model200Response](docs/ModelModel200Response.md) + - [ModelReturn](docs/ModelModelReturn.md) + - [Name](docs/ModelName.md) + - [Order](docs/ModelOrder.md) + - [Pet](docs/ModelPet.md) + - [SpecialModelName](docs/ModelSpecialModelName.md) + - [Tag](docs/ModelTag.md) + - [User](docs/ModelUser.md) ## Documentation For Authorization diff --git a/samples/client/petstore/php/SwaggerClient-php/composer.json b/samples/client/petstore/php/SwaggerClient-php/composer.json index 3822037d750..da3fdabfbb0 100644 --- a/samples/client/petstore/php/SwaggerClient-php/composer.json +++ b/samples/client/petstore/php/SwaggerClient-php/composer.json @@ -29,5 +29,8 @@ }, "autoload": { "psr-4": { "Swagger\\Client\\" : "lib/" } + }, + "autoload-dev": { + "psr-4": { "Swagger\\Client\\" : "test/" } } } diff --git a/samples/client/petstore/php/SwaggerClient-php/docs/FakeApi.md b/samples/client/petstore/php/SwaggerClient-php/docs/Api/FakeApi.md similarity index 86% rename from samples/client/petstore/php/SwaggerClient-php/docs/FakeApi.md rename to samples/client/petstore/php/SwaggerClient-php/docs/Api/FakeApi.md index 93c24ef7eeb..5988dc781b2 100644 --- a/samples/client/petstore/php/SwaggerClient-php/docs/FakeApi.md +++ b/samples/client/petstore/php/SwaggerClient-php/docs/Api/FakeApi.md @@ -4,15 +4,15 @@ All URIs are relative to *http://petstore.swagger.io/v2* Method | HTTP request | Description ------------- | ------------- | ------------- -[**testEndpointParameters**](FakeApi.md#testEndpointParameters) | **POST** /fake | Fake endpoint for testing various parameters +[**testEndpointParameters**](FakeApi.md#testEndpointParameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 # **testEndpointParameters** > testEndpointParameters($number, $double, $string, $byte, $integer, $int32, $int64, $float, $binary, $date, $date_time, $password) -Fake endpoint for testing various parameters +Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 -Fake endpoint for testing various parameters +Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 ### Example ```php diff --git a/samples/client/petstore/php/SwaggerClient-php/docs/PetApi.md b/samples/client/petstore/php/SwaggerClient-php/docs/Api/PetApi.md similarity index 99% rename from samples/client/petstore/php/SwaggerClient-php/docs/PetApi.md rename to samples/client/petstore/php/SwaggerClient-php/docs/Api/PetApi.md index a2a06445c73..bf119270a58 100644 --- a/samples/client/petstore/php/SwaggerClient-php/docs/PetApi.md +++ b/samples/client/petstore/php/SwaggerClient-php/docs/Api/PetApi.md @@ -220,8 +220,8 @@ require_once(__DIR__ . '/vendor/autoload.php'); // Configure API key authorization: api_key Swagger\Client\Configuration::getDefaultConfiguration()->setApiKey('api_key', 'YOUR_API_KEY'); -// Uncomment below to setup prefix (e.g. BEARER) for API key, if needed -// Swagger\Client\Configuration::getDefaultConfiguration()->setApiKeyPrefix('api_key', 'BEARER'); +// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed +// Swagger\Client\Configuration::getDefaultConfiguration()->setApiKeyPrefix('api_key', 'Bearer'); $api_instance = new Swagger\Client\Api\PetApi(); $pet_id = 789; // int | ID of pet to return diff --git a/samples/client/petstore/php/SwaggerClient-php/docs/StoreApi.md b/samples/client/petstore/php/SwaggerClient-php/docs/Api/StoreApi.md similarity index 98% rename from samples/client/petstore/php/SwaggerClient-php/docs/StoreApi.md rename to samples/client/petstore/php/SwaggerClient-php/docs/Api/StoreApi.md index 8198bf3dbf4..7040df371a4 100644 --- a/samples/client/petstore/php/SwaggerClient-php/docs/StoreApi.md +++ b/samples/client/petstore/php/SwaggerClient-php/docs/Api/StoreApi.md @@ -68,8 +68,8 @@ require_once(__DIR__ . '/vendor/autoload.php'); // Configure API key authorization: api_key Swagger\Client\Configuration::getDefaultConfiguration()->setApiKey('api_key', 'YOUR_API_KEY'); -// Uncomment below to setup prefix (e.g. BEARER) for API key, if needed -// Swagger\Client\Configuration::getDefaultConfiguration()->setApiKeyPrefix('api_key', 'BEARER'); +// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed +// Swagger\Client\Configuration::getDefaultConfiguration()->setApiKeyPrefix('api_key', 'Bearer'); $api_instance = new Swagger\Client\Api\StoreApi(); diff --git a/samples/client/petstore/php/SwaggerClient-php/docs/UserApi.md b/samples/client/petstore/php/SwaggerClient-php/docs/Api/UserApi.md similarity index 100% rename from samples/client/petstore/php/SwaggerClient-php/docs/UserApi.md rename to samples/client/petstore/php/SwaggerClient-php/docs/Api/UserApi.md diff --git a/samples/client/petstore/php/SwaggerClient-php/docs/InlineResponse200.md b/samples/client/petstore/php/SwaggerClient-php/docs/InlineResponse200.md deleted file mode 100644 index 1c0b9237453..00000000000 --- a/samples/client/petstore/php/SwaggerClient-php/docs/InlineResponse200.md +++ /dev/null @@ -1,15 +0,0 @@ -# InlineResponse200 - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**tags** | [**\Swagger\Client\Model\Tag[]**](Tag.md) | | [optional] -**id** | **int** | | -**category** | **object** | | [optional] -**status** | **string** | pet status in the store | [optional] -**name** | **string** | | [optional] -**photo_urls** | **string[]** | | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/samples/client/petstore/php/SwaggerClient-php/docs/Model/Animal.md b/samples/client/petstore/php/SwaggerClient-php/docs/Model/Animal.md new file mode 100644 index 00000000000..c57fbe8ea4a --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/docs/Model/Animal.md @@ -0,0 +1,11 @@ +# Animal + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**class_name** | **string** | | +**color** | **string** | | [optional] [default to 'red'] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/php/SwaggerClient-php/docs/Animal.md b/samples/client/petstore/php/SwaggerClient-php/docs/Model/AnimalFarm.md similarity index 86% rename from samples/client/petstore/php/SwaggerClient-php/docs/Animal.md rename to samples/client/petstore/php/SwaggerClient-php/docs/Model/AnimalFarm.md index 948a992f502..df6bab21dae 100644 --- a/samples/client/petstore/php/SwaggerClient-php/docs/Animal.md +++ b/samples/client/petstore/php/SwaggerClient-php/docs/Model/AnimalFarm.md @@ -1,9 +1,8 @@ -# Animal +# AnimalFarm ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**class_name** | **string** | | [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore/php/SwaggerClient-php/docs/ApiResponse.md b/samples/client/petstore/php/SwaggerClient-php/docs/Model/ApiResponse.md similarity index 100% rename from samples/client/petstore/php/SwaggerClient-php/docs/ApiResponse.md rename to samples/client/petstore/php/SwaggerClient-php/docs/Model/ApiResponse.md diff --git a/samples/client/petstore/php/SwaggerClient-php/docs/Cat.md b/samples/client/petstore/php/SwaggerClient-php/docs/Model/Cat.md similarity index 100% rename from samples/client/petstore/php/SwaggerClient-php/docs/Cat.md rename to samples/client/petstore/php/SwaggerClient-php/docs/Model/Cat.md diff --git a/samples/client/petstore/php/SwaggerClient-php/docs/Category.md b/samples/client/petstore/php/SwaggerClient-php/docs/Model/Category.md similarity index 100% rename from samples/client/petstore/php/SwaggerClient-php/docs/Category.md rename to samples/client/petstore/php/SwaggerClient-php/docs/Model/Category.md diff --git a/samples/client/petstore/php/SwaggerClient-php/docs/Dog.md b/samples/client/petstore/php/SwaggerClient-php/docs/Model/Dog.md similarity index 100% rename from samples/client/petstore/php/SwaggerClient-php/docs/Dog.md rename to samples/client/petstore/php/SwaggerClient-php/docs/Model/Dog.md diff --git a/samples/client/petstore/php/SwaggerClient-php/docs/200Response.md b/samples/client/petstore/php/SwaggerClient-php/docs/Model/EnumClass.md similarity index 84% rename from samples/client/petstore/php/SwaggerClient-php/docs/200Response.md rename to samples/client/petstore/php/SwaggerClient-php/docs/Model/EnumClass.md index 284a8795c61..67f017becd0 100644 --- a/samples/client/petstore/php/SwaggerClient-php/docs/200Response.md +++ b/samples/client/petstore/php/SwaggerClient-php/docs/Model/EnumClass.md @@ -1,9 +1,8 @@ -# 200Response +# EnumClass ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**name** | **int** | | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore/php/SwaggerClient-php/docs/Model/EnumTest.md b/samples/client/petstore/php/SwaggerClient-php/docs/Model/EnumTest.md new file mode 100644 index 00000000000..2ef9e6adaac --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/docs/Model/EnumTest.md @@ -0,0 +1,12 @@ +# EnumTest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**enum_string** | **string** | | [optional] +**enum_integer** | **int** | | [optional] +**enum_number** | **double** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/php/SwaggerClient-php/docs/FormatTest.md b/samples/client/petstore/php/SwaggerClient-php/docs/Model/FormatTest.md similarity index 100% rename from samples/client/petstore/php/SwaggerClient-php/docs/FormatTest.md rename to samples/client/petstore/php/SwaggerClient-php/docs/Model/FormatTest.md diff --git a/samples/client/petstore/php/SwaggerClient-php/docs/Model200Response.md b/samples/client/petstore/php/SwaggerClient-php/docs/Model/Model200Response.md similarity index 100% rename from samples/client/petstore/php/SwaggerClient-php/docs/Model200Response.md rename to samples/client/petstore/php/SwaggerClient-php/docs/Model/Model200Response.md diff --git a/samples/client/petstore/php/SwaggerClient-php/docs/ModelReturn.md b/samples/client/petstore/php/SwaggerClient-php/docs/Model/ModelReturn.md similarity index 100% rename from samples/client/petstore/php/SwaggerClient-php/docs/ModelReturn.md rename to samples/client/petstore/php/SwaggerClient-php/docs/Model/ModelReturn.md diff --git a/samples/client/petstore/php/SwaggerClient-php/docs/Name.md b/samples/client/petstore/php/SwaggerClient-php/docs/Model/Name.md similarity index 90% rename from samples/client/petstore/php/SwaggerClient-php/docs/Name.md rename to samples/client/petstore/php/SwaggerClient-php/docs/Model/Name.md index 5f31a2cc7fd..4565647e1ef 100644 --- a/samples/client/petstore/php/SwaggerClient-php/docs/Name.md +++ b/samples/client/petstore/php/SwaggerClient-php/docs/Model/Name.md @@ -6,6 +6,7 @@ Name | Type | Description | Notes **name** | **int** | | **snake_case** | **int** | | [optional] **property** | **string** | | [optional] +**_123_number** | **int** | | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore/php/SwaggerClient-php/docs/Order.md b/samples/client/petstore/php/SwaggerClient-php/docs/Model/Order.md similarity index 100% rename from samples/client/petstore/php/SwaggerClient-php/docs/Order.md rename to samples/client/petstore/php/SwaggerClient-php/docs/Model/Order.md diff --git a/samples/client/petstore/php/SwaggerClient-php/docs/Pet.md b/samples/client/petstore/php/SwaggerClient-php/docs/Model/Pet.md similarity index 100% rename from samples/client/petstore/php/SwaggerClient-php/docs/Pet.md rename to samples/client/petstore/php/SwaggerClient-php/docs/Model/Pet.md diff --git a/samples/client/petstore/php/SwaggerClient-php/docs/SpecialModelName.md b/samples/client/petstore/php/SwaggerClient-php/docs/Model/SpecialModelName.md similarity index 100% rename from samples/client/petstore/php/SwaggerClient-php/docs/SpecialModelName.md rename to samples/client/petstore/php/SwaggerClient-php/docs/Model/SpecialModelName.md diff --git a/samples/client/petstore/php/SwaggerClient-php/docs/Tag.md b/samples/client/petstore/php/SwaggerClient-php/docs/Model/Tag.md similarity index 100% rename from samples/client/petstore/php/SwaggerClient-php/docs/Tag.md rename to samples/client/petstore/php/SwaggerClient-php/docs/Model/Tag.md diff --git a/samples/client/petstore/php/SwaggerClient-php/docs/User.md b/samples/client/petstore/php/SwaggerClient-php/docs/Model/User.md similarity index 100% rename from samples/client/petstore/php/SwaggerClient-php/docs/User.md rename to samples/client/petstore/php/SwaggerClient-php/docs/Model/User.md diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php index 2938beaf9ce..5620c82fdcd 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php @@ -60,7 +60,7 @@ class FakeApi * Constructor * @param \Swagger\Client\ApiClient|null $apiClient The api client to use */ - function __construct($apiClient = null) + function __construct(\Swagger\Client\ApiClient $apiClient = null) { if ($apiClient == null) { $apiClient = new ApiClient(); @@ -84,7 +84,7 @@ class FakeApi * @param \Swagger\Client\ApiClient $apiClient set the API client * @return FakeApi */ - public function setApiClient(ApiClient $apiClient) + public function setApiClient(\Swagger\Client\ApiClient $apiClient) { $this->apiClient = $apiClient; return $this; @@ -93,7 +93,7 @@ class FakeApi /** * testEndpointParameters * - * Fake endpoint for testing various parameters + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 * * @param float $number None (required) * @param double $double None (required) @@ -120,7 +120,7 @@ class FakeApi /** * testEndpointParametersWithHttpInfo * - * Fake endpoint for testing various parameters + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 * * @param float $number None (required) * @param double $double None (required) @@ -198,7 +198,7 @@ class FakeApi if (strlen($password) > 64) { throw new \InvalidArgumentException('invalid length for "$password" when calling FakeApi.testEndpointParameters, must be smaller than or equal to 64.'); } - if (strlen($password) > 10) { + if (strlen($password) < 10) { throw new \InvalidArgumentException('invalid length for "$password" when calling FakeApi.testEndpointParameters, must be bigger than or equal to 10.'); } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Animal.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Animal.php index 12224679ac7..9120535bf5a 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Animal.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Animal.php @@ -34,6 +34,7 @@ namespace Swagger\Client\Model; use \ArrayAccess; + /** * Animal Class Doc Comment * @@ -57,9 +58,10 @@ class Animal implements ArrayAccess * @var string[] */ static $swaggerTypes = array( - 'class_name' => 'string' + 'class_name' => 'string', + 'color' => 'string' ); - + static function swaggerTypes() { return self::$swaggerTypes; } @@ -69,9 +71,10 @@ class Animal implements ArrayAccess * @var string[] */ static $attributeMap = array( - 'class_name' => 'className' + 'class_name' => 'className', + 'color' => 'color' ); - + static function attributeMap() { return self::$attributeMap; } @@ -81,9 +84,10 @@ class Animal implements ArrayAccess * @var string[] */ static $setters = array( - 'class_name' => 'setClassName' + 'class_name' => 'setClassName', + 'color' => 'setColor' ); - + static function setters() { return self::$setters; } @@ -93,7 +97,8 @@ class Animal implements ArrayAccess * @var string[] */ static $getters = array( - 'class_name' => 'getClassName' + 'class_name' => 'getClassName', + 'color' => 'getColor' ); static function getters() { @@ -105,10 +110,10 @@ class Animal implements ArrayAccess /** - * $class_name - * @var string + * Associative array for storing property values + * @var mixed[] */ - protected $class_name; + protected $container = array(); /** * Constructor @@ -116,22 +121,50 @@ class Animal implements ArrayAccess */ public function __construct(array $data = null) { - + $this->container['class_name'] = isset($data['class_name']) ? $data['class_name'] : null; + $this->container['color'] = isset($data['color']) ? $data['color'] : 'red'; + // Initialize discriminator property with the model name. $discrimintor = array_search('className', self::$attributeMap); - $this->{$discrimintor} = static::$swaggerModelName; - - if ($data != null) { - $this->class_name = $data["class_name"]; - } + $this->container[$discrimintor] = static::$swaggerModelName; } + + /** + * show all the invalid properties with reasons. + * + * @return array invalid properties with reasons + */ + public function list_invalid_properties() + { + $invalid_properties = array(); + if ($this->container['class_name'] === null) { + $invalid_properties[] = "'$class_name' can't be null"; + } + return $invalid_properties; + } + + /** + * validate all the properties in the model + * return true if all passed + * + * @return bool True if all properteis are valid + */ + public function valid() + { + if ($this->container['class_name'] === null) { + return false; + } + return true; + } + + /** * Gets class_name * @return string */ public function getClassName() { - return $this->class_name; + return $this->container['class_name']; } /** @@ -141,8 +174,29 @@ class Animal implements ArrayAccess */ public function setClassName($class_name) { - - $this->class_name = $class_name; + $this->container['class_name'] = $class_name; + + return $this; + } + + /** + * Gets color + * @return string + */ + public function getColor() + { + return $this->container['color']; + } + + /** + * Sets color + * @param string $color + * @return $this + */ + public function setColor($color) + { + $this->container['color'] = $color; + return $this; } /** @@ -152,7 +206,7 @@ class Animal implements ArrayAccess */ public function offsetExists($offset) { - return isset($this->$offset); + return isset($this->container[$offset]); } /** @@ -162,7 +216,7 @@ class Animal implements ArrayAccess */ public function offsetGet($offset) { - return $this->$offset; + return isset($this->container[$offset]) ? $this->container[$offset] : null; } /** @@ -173,7 +227,11 @@ class Animal implements ArrayAccess */ public function offsetSet($offset, $value) { - $this->$offset = $value; + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } } /** @@ -183,7 +241,7 @@ class Animal implements ArrayAccess */ public function offsetUnset($offset) { - unset($this->$offset); + unset($this->container[$offset]); } /** diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/AnimalFarm.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/AnimalFarm.php new file mode 100644 index 00000000000..2ff9da6a4ea --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/AnimalFarm.php @@ -0,0 +1,201 @@ +container[$offset]); + } + + /** + * Gets offset. + * @param integer $offset Offset + * @return mixed + */ + public function offsetGet($offset) + { + return isset($this->container[$offset]) ? $this->container[$offset] : null; + } + + /** + * Sets value based on offset. + * @param integer $offset Offset + * @param mixed $value Value to be set + * @return void + */ + public function offsetSet($offset, $value) + { + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } + } + + /** + * Unsets offset. + * @param integer $offset Offset + * @return void + */ + public function offsetUnset($offset) + { + unset($this->container[$offset]); + } + + /** + * Gets the string presentation of the object + * @return string + */ + public function __toString() + { + if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print + return json_encode(\Swagger\Client\ObjectSerializer::sanitizeForSerialization($this), JSON_PRETTY_PRINT); + } + + return json_encode(\Swagger\Client\ObjectSerializer::sanitizeForSerialization($this)); + } +} diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ApiResponse.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ApiResponse.php index 1e96648c7c1..8894f835aea 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ApiResponse.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ApiResponse.php @@ -34,6 +34,7 @@ namespace Swagger\Client\Model; use \ArrayAccess; + /** * ApiResponse Class Doc Comment * @@ -61,7 +62,7 @@ class ApiResponse implements ArrayAccess 'type' => 'string', 'message' => 'string' ); - + static function swaggerTypes() { return self::$swaggerTypes; } @@ -75,7 +76,7 @@ class ApiResponse implements ArrayAccess 'type' => 'type', 'message' => 'message' ); - + static function attributeMap() { return self::$attributeMap; } @@ -89,7 +90,7 @@ class ApiResponse implements ArrayAccess 'type' => 'setType', 'message' => 'setMessage' ); - + static function setters() { return self::$setters; } @@ -113,20 +114,10 @@ class ApiResponse implements ArrayAccess /** - * $code - * @var int + * Associative array for storing property values + * @var mixed[] */ - protected $code; - /** - * $type - * @var string - */ - protected $type; - /** - * $message - * @var string - */ - protected $message; + protected $container = array(); /** * Constructor @@ -134,21 +125,41 @@ class ApiResponse implements ArrayAccess */ public function __construct(array $data = null) { - - - if ($data != null) { - $this->code = $data["code"]; - $this->type = $data["type"]; - $this->message = $data["message"]; - } + $this->container['code'] = isset($data['code']) ? $data['code'] : null; + $this->container['type'] = isset($data['type']) ? $data['type'] : null; + $this->container['message'] = isset($data['message']) ? $data['message'] : null; } + + /** + * show all the invalid properties with reasons. + * + * @return array invalid properties with reasons + */ + public function list_invalid_properties() + { + $invalid_properties = array(); + return $invalid_properties; + } + + /** + * validate all the properties in the model + * return true if all passed + * + * @return bool True if all properteis are valid + */ + public function valid() + { + return true; + } + + /** * Gets code * @return int */ public function getCode() { - return $this->code; + return $this->container['code']; } /** @@ -158,17 +169,18 @@ class ApiResponse implements ArrayAccess */ public function setCode($code) { - - $this->code = $code; + $this->container['code'] = $code; + return $this; } + /** * Gets type * @return string */ public function getType() { - return $this->type; + return $this->container['type']; } /** @@ -178,17 +190,18 @@ class ApiResponse implements ArrayAccess */ public function setType($type) { - - $this->type = $type; + $this->container['type'] = $type; + return $this; } + /** * Gets message * @return string */ public function getMessage() { - return $this->message; + return $this->container['message']; } /** @@ -198,8 +211,8 @@ class ApiResponse implements ArrayAccess */ public function setMessage($message) { - - $this->message = $message; + $this->container['message'] = $message; + return $this; } /** @@ -209,7 +222,7 @@ class ApiResponse implements ArrayAccess */ public function offsetExists($offset) { - return isset($this->$offset); + return isset($this->container[$offset]); } /** @@ -219,7 +232,7 @@ class ApiResponse implements ArrayAccess */ public function offsetGet($offset) { - return $this->$offset; + return isset($this->container[$offset]) ? $this->container[$offset] : null; } /** @@ -230,7 +243,11 @@ class ApiResponse implements ArrayAccess */ public function offsetSet($offset, $value) { - $this->$offset = $value; + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } } /** @@ -240,7 +257,7 @@ class ApiResponse implements ArrayAccess */ public function offsetUnset($offset) { - unset($this->$offset); + unset($this->container[$offset]); } /** diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Cat.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Cat.php index cf85b9fb5bc..393f89e5b0f 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Cat.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Cat.php @@ -34,6 +34,7 @@ namespace Swagger\Client\Model; use \ArrayAccess; + /** * Cat Class Doc Comment * @@ -59,7 +60,7 @@ class Cat extends Animal implements ArrayAccess static $swaggerTypes = array( 'declawed' => 'bool' ); - + static function swaggerTypes() { return self::$swaggerTypes + parent::swaggerTypes(); } @@ -71,7 +72,7 @@ class Cat extends Animal implements ArrayAccess static $attributeMap = array( 'declawed' => 'declawed' ); - + static function attributeMap() { return parent::attributeMap() + self::$attributeMap; } @@ -83,7 +84,7 @@ class Cat extends Animal implements ArrayAccess static $setters = array( 'declawed' => 'setDeclawed' ); - + static function setters() { return parent::setters() + self::$setters; } @@ -105,10 +106,10 @@ class Cat extends Animal implements ArrayAccess /** - * $declawed - * @var bool + * Associative array for storing property values + * @var mixed[] */ - protected $declawed; + protected $container = array(); /** * Constructor @@ -117,18 +118,40 @@ class Cat extends Animal implements ArrayAccess public function __construct(array $data = null) { parent::__construct($data); - - if ($data != null) { - $this->declawed = $data["declawed"]; - } + + $this->container['declawed'] = isset($data['declawed']) ? $data['declawed'] : null; } + + /** + * show all the invalid properties with reasons. + * + * @return array invalid properties with reasons + */ + public function list_invalid_properties() + { + $invalid_properties = array(); + return $invalid_properties; + } + + /** + * validate all the properties in the model + * return true if all passed + * + * @return bool True if all properteis are valid + */ + public function valid() + { + return true; + } + + /** * Gets declawed * @return bool */ public function getDeclawed() { - return $this->declawed; + return $this->container['declawed']; } /** @@ -138,8 +161,8 @@ class Cat extends Animal implements ArrayAccess */ public function setDeclawed($declawed) { - - $this->declawed = $declawed; + $this->container['declawed'] = $declawed; + return $this; } /** @@ -149,7 +172,7 @@ class Cat extends Animal implements ArrayAccess */ public function offsetExists($offset) { - return isset($this->$offset); + return isset($this->container[$offset]); } /** @@ -159,7 +182,7 @@ class Cat extends Animal implements ArrayAccess */ public function offsetGet($offset) { - return $this->$offset; + return isset($this->container[$offset]) ? $this->container[$offset] : null; } /** @@ -170,7 +193,11 @@ class Cat extends Animal implements ArrayAccess */ public function offsetSet($offset, $value) { - $this->$offset = $value; + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } } /** @@ -180,7 +207,7 @@ class Cat extends Animal implements ArrayAccess */ public function offsetUnset($offset) { - unset($this->$offset); + unset($this->container[$offset]); } /** diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Category.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Category.php index ddc52637051..1c1a2340378 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Category.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Category.php @@ -34,6 +34,7 @@ namespace Swagger\Client\Model; use \ArrayAccess; + /** * Category Class Doc Comment * @@ -60,7 +61,7 @@ class Category implements ArrayAccess 'id' => 'int', 'name' => 'string' ); - + static function swaggerTypes() { return self::$swaggerTypes; } @@ -73,7 +74,7 @@ class Category implements ArrayAccess 'id' => 'id', 'name' => 'name' ); - + static function attributeMap() { return self::$attributeMap; } @@ -86,7 +87,7 @@ class Category implements ArrayAccess 'id' => 'setId', 'name' => 'setName' ); - + static function setters() { return self::$setters; } @@ -109,15 +110,10 @@ class Category implements ArrayAccess /** - * $id - * @var int + * Associative array for storing property values + * @var mixed[] */ - protected $id; - /** - * $name - * @var string - */ - protected $name; + protected $container = array(); /** * Constructor @@ -125,20 +121,40 @@ class Category implements ArrayAccess */ public function __construct(array $data = null) { - - - if ($data != null) { - $this->id = $data["id"]; - $this->name = $data["name"]; - } + $this->container['id'] = isset($data['id']) ? $data['id'] : null; + $this->container['name'] = isset($data['name']) ? $data['name'] : null; } + + /** + * show all the invalid properties with reasons. + * + * @return array invalid properties with reasons + */ + public function list_invalid_properties() + { + $invalid_properties = array(); + return $invalid_properties; + } + + /** + * validate all the properties in the model + * return true if all passed + * + * @return bool True if all properteis are valid + */ + public function valid() + { + return true; + } + + /** * Gets id * @return int */ public function getId() { - return $this->id; + return $this->container['id']; } /** @@ -148,17 +164,18 @@ class Category implements ArrayAccess */ public function setId($id) { - - $this->id = $id; + $this->container['id'] = $id; + return $this; } + /** * Gets name * @return string */ public function getName() { - return $this->name; + return $this->container['name']; } /** @@ -168,8 +185,8 @@ class Category implements ArrayAccess */ public function setName($name) { - - $this->name = $name; + $this->container['name'] = $name; + return $this; } /** @@ -179,7 +196,7 @@ class Category implements ArrayAccess */ public function offsetExists($offset) { - return isset($this->$offset); + return isset($this->container[$offset]); } /** @@ -189,7 +206,7 @@ class Category implements ArrayAccess */ public function offsetGet($offset) { - return $this->$offset; + return isset($this->container[$offset]) ? $this->container[$offset] : null; } /** @@ -200,7 +217,11 @@ class Category implements ArrayAccess */ public function offsetSet($offset, $value) { - $this->$offset = $value; + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } } /** @@ -210,7 +231,7 @@ class Category implements ArrayAccess */ public function offsetUnset($offset) { - unset($this->$offset); + unset($this->container[$offset]); } /** diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Dog.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Dog.php index 15b5c22e0ce..b79e76a4187 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Dog.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Dog.php @@ -34,6 +34,7 @@ namespace Swagger\Client\Model; use \ArrayAccess; + /** * Dog Class Doc Comment * @@ -59,7 +60,7 @@ class Dog extends Animal implements ArrayAccess static $swaggerTypes = array( 'breed' => 'string' ); - + static function swaggerTypes() { return self::$swaggerTypes + parent::swaggerTypes(); } @@ -71,7 +72,7 @@ class Dog extends Animal implements ArrayAccess static $attributeMap = array( 'breed' => 'breed' ); - + static function attributeMap() { return parent::attributeMap() + self::$attributeMap; } @@ -83,7 +84,7 @@ class Dog extends Animal implements ArrayAccess static $setters = array( 'breed' => 'setBreed' ); - + static function setters() { return parent::setters() + self::$setters; } @@ -105,10 +106,10 @@ class Dog extends Animal implements ArrayAccess /** - * $breed - * @var string + * Associative array for storing property values + * @var mixed[] */ - protected $breed; + protected $container = array(); /** * Constructor @@ -117,18 +118,40 @@ class Dog extends Animal implements ArrayAccess public function __construct(array $data = null) { parent::__construct($data); - - if ($data != null) { - $this->breed = $data["breed"]; - } + + $this->container['breed'] = isset($data['breed']) ? $data['breed'] : null; } + + /** + * show all the invalid properties with reasons. + * + * @return array invalid properties with reasons + */ + public function list_invalid_properties() + { + $invalid_properties = array(); + return $invalid_properties; + } + + /** + * validate all the properties in the model + * return true if all passed + * + * @return bool True if all properteis are valid + */ + public function valid() + { + return true; + } + + /** * Gets breed * @return string */ public function getBreed() { - return $this->breed; + return $this->container['breed']; } /** @@ -138,8 +161,8 @@ class Dog extends Animal implements ArrayAccess */ public function setBreed($breed) { - - $this->breed = $breed; + $this->container['breed'] = $breed; + return $this; } /** @@ -149,7 +172,7 @@ class Dog extends Animal implements ArrayAccess */ public function offsetExists($offset) { - return isset($this->$offset); + return isset($this->container[$offset]); } /** @@ -159,7 +182,7 @@ class Dog extends Animal implements ArrayAccess */ public function offsetGet($offset) { - return $this->$offset; + return isset($this->container[$offset]) ? $this->container[$offset] : null; } /** @@ -170,7 +193,11 @@ class Dog extends Animal implements ArrayAccess */ public function offsetSet($offset, $value) { - $this->$offset = $value; + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } } /** @@ -180,7 +207,7 @@ class Dog extends Animal implements ArrayAccess */ public function offsetUnset($offset) { - unset($this->$offset); + unset($this->container[$offset]); } /** diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumClass.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumClass.php new file mode 100644 index 00000000000..2b6d36c9b66 --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumClass.php @@ -0,0 +1,201 @@ +container[$offset]); + } + + /** + * Gets offset. + * @param integer $offset Offset + * @return mixed + */ + public function offsetGet($offset) + { + return isset($this->container[$offset]) ? $this->container[$offset] : null; + } + + /** + * Sets value based on offset. + * @param integer $offset Offset + * @param mixed $value Value to be set + * @return void + */ + public function offsetSet($offset, $value) + { + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } + } + + /** + * Unsets offset. + * @param integer $offset Offset + * @return void + */ + public function offsetUnset($offset) + { + unset($this->container[$offset]); + } + + /** + * Gets the string presentation of the object + * @return string + */ + public function __toString() + { + if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print + return json_encode(\Swagger\Client\ObjectSerializer::sanitizeForSerialization($this), JSON_PRETTY_PRINT); + } + + return json_encode(\Swagger\Client\ObjectSerializer::sanitizeForSerialization($this)); + } +} diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumTest.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumTest.php new file mode 100644 index 00000000000..6e10f45dd8f --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumTest.php @@ -0,0 +1,350 @@ + 'string', + 'enum_integer' => 'int', + 'enum_number' => 'double' + ); + + static function swaggerTypes() { + return self::$swaggerTypes; + } + + /** + * Array of attributes where the key is the local name, and the value is the original name + * @var string[] + */ + static $attributeMap = array( + 'enum_string' => 'enum_string', + 'enum_integer' => 'enum_integer', + 'enum_number' => 'enum_number' + ); + + static function attributeMap() { + return self::$attributeMap; + } + + /** + * Array of attributes to setter functions (for deserialization of responses) + * @var string[] + */ + static $setters = array( + 'enum_string' => 'setEnumString', + 'enum_integer' => 'setEnumInteger', + 'enum_number' => 'setEnumNumber' + ); + + static function setters() { + return self::$setters; + } + + /** + * Array of attributes to getter functions (for serialization of requests) + * @var string[] + */ + static $getters = array( + 'enum_string' => 'getEnumString', + 'enum_integer' => 'getEnumInteger', + 'enum_number' => 'getEnumNumber' + ); + + static function getters() { + return self::$getters; + } + + const ENUM_STRING_UPPER = 'UPPER'; + const ENUM_STRING_LOWER = 'lower'; + const ENUM_INTEGER_1 = 1; + const ENUM_INTEGER_MINUS_1 = -1; + const ENUM_NUMBER_1_DOT_1 = 1.1; + const ENUM_NUMBER_MINUS_1_DOT_2 = -1.2; + + + + /** + * Gets allowable values of the enum + * @return string[] + */ + public function getEnumStringAllowableValues() { + return [ + self::ENUM_STRING_UPPER, + self::ENUM_STRING_LOWER, + ]; + } + + /** + * Gets allowable values of the enum + * @return string[] + */ + public function getEnumIntegerAllowableValues() { + return [ + self::ENUM_INTEGER_1, + self::ENUM_INTEGER_MINUS_1, + ]; + } + + /** + * Gets allowable values of the enum + * @return string[] + */ + public function getEnumNumberAllowableValues() { + return [ + self::ENUM_NUMBER_1_DOT_1, + self::ENUM_NUMBER_MINUS_1_DOT_2, + ]; + } + + + /** + * Associative array for storing property values + * @var mixed[] + */ + protected $container = array(); + + /** + * Constructor + * @param mixed[] $data Associated array of property value initalizing the model + */ + public function __construct(array $data = null) + { + $this->container['enum_string'] = isset($data['enum_string']) ? $data['enum_string'] : null; + $this->container['enum_integer'] = isset($data['enum_integer']) ? $data['enum_integer'] : null; + $this->container['enum_number'] = isset($data['enum_number']) ? $data['enum_number'] : null; + } + + /** + * show all the invalid properties with reasons. + * + * @return array invalid properties with reasons + */ + public function list_invalid_properties() + { + $invalid_properties = array(); + $allowed_values = array("UPPER", "lower"); + if (!in_array($this->container['enum_string'], $allowed_values)) { + $invalid_properties[] = "invalid value for '$enum_string', must be one of #{allowed_values}."; + } + $allowed_values = array("1", "-1"); + if (!in_array($this->container['enum_integer'], $allowed_values)) { + $invalid_properties[] = "invalid value for '$enum_integer', must be one of #{allowed_values}."; + } + $allowed_values = array("1.1", "-1.2"); + if (!in_array($this->container['enum_number'], $allowed_values)) { + $invalid_properties[] = "invalid value for '$enum_number', must be one of #{allowed_values}."; + } + return $invalid_properties; + } + + /** + * validate all the properties in the model + * return true if all passed + * + * @return bool True if all properteis are valid + */ + public function valid() + { + $allowed_values = array("UPPER", "lower"); + if (!in_array($this->container['enum_string'], $allowed_values)) { + return false; + } + $allowed_values = array("1", "-1"); + if (!in_array($this->container['enum_integer'], $allowed_values)) { + return false; + } + $allowed_values = array("1.1", "-1.2"); + if (!in_array($this->container['enum_number'], $allowed_values)) { + return false; + } + return true; + } + + + /** + * Gets enum_string + * @return string + */ + public function getEnumString() + { + return $this->container['enum_string']; + } + + /** + * Sets enum_string + * @param string $enum_string + * @return $this + */ + public function setEnumString($enum_string) + { + $allowed_values = array('UPPER', 'lower'); + if (!in_array($enum_string, $allowed_values)) { + throw new \InvalidArgumentException("Invalid value for 'enum_string', must be one of 'UPPER', 'lower'"); + } + $this->container['enum_string'] = $enum_string; + + return $this; + } + + /** + * Gets enum_integer + * @return int + */ + public function getEnumInteger() + { + return $this->container['enum_integer']; + } + + /** + * Sets enum_integer + * @param int $enum_integer + * @return $this + */ + public function setEnumInteger($enum_integer) + { + $allowed_values = array('1', '-1'); + if (!in_array($enum_integer, $allowed_values)) { + throw new \InvalidArgumentException("Invalid value for 'enum_integer', must be one of '1', '-1'"); + } + $this->container['enum_integer'] = $enum_integer; + + return $this; + } + + /** + * Gets enum_number + * @return double + */ + public function getEnumNumber() + { + return $this->container['enum_number']; + } + + /** + * Sets enum_number + * @param double $enum_number + * @return $this + */ + public function setEnumNumber($enum_number) + { + $allowed_values = array('1.1', '-1.2'); + if (!in_array($enum_number, $allowed_values)) { + throw new \InvalidArgumentException("Invalid value for 'enum_number', must be one of '1.1', '-1.2'"); + } + $this->container['enum_number'] = $enum_number; + + return $this; + } + /** + * Returns true if offset exists. False otherwise. + * @param integer $offset Offset + * @return boolean + */ + public function offsetExists($offset) + { + return isset($this->container[$offset]); + } + + /** + * Gets offset. + * @param integer $offset Offset + * @return mixed + */ + public function offsetGet($offset) + { + return isset($this->container[$offset]) ? $this->container[$offset] : null; + } + + /** + * Sets value based on offset. + * @param integer $offset Offset + * @param mixed $value Value to be set + * @return void + */ + public function offsetSet($offset, $value) + { + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } + } + + /** + * Unsets offset. + * @param integer $offset Offset + * @return void + */ + public function offsetUnset($offset) + { + unset($this->container[$offset]); + } + + /** + * Gets the string presentation of the object + * @return string + */ + public function __toString() + { + if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print + return json_encode(\Swagger\Client\ObjectSerializer::sanitizeForSerialization($this), JSON_PRETTY_PRINT); + } + + return json_encode(\Swagger\Client\ObjectSerializer::sanitizeForSerialization($this)); + } +} diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/FormatTest.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/FormatTest.php index 6888cac7cd3..bf674b05102 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/FormatTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/FormatTest.php @@ -34,6 +34,7 @@ namespace Swagger\Client\Model; use \ArrayAccess; + /** * FormatTest Class Doc Comment * @@ -68,9 +69,10 @@ class FormatTest implements ArrayAccess 'binary' => 'string', 'date' => '\DateTime', 'date_time' => '\DateTime', + 'uuid' => 'string', 'password' => 'string' ); - + static function swaggerTypes() { return self::$swaggerTypes; } @@ -91,9 +93,10 @@ class FormatTest implements ArrayAccess 'binary' => 'binary', 'date' => 'date', 'date_time' => 'dateTime', + 'uuid' => 'uuid', 'password' => 'password' ); - + static function attributeMap() { return self::$attributeMap; } @@ -114,9 +117,10 @@ class FormatTest implements ArrayAccess 'binary' => 'setBinary', 'date' => 'setDate', 'date_time' => 'setDateTime', + 'uuid' => 'setUuid', 'password' => 'setPassword' ); - + static function setters() { return self::$setters; } @@ -137,6 +141,7 @@ class FormatTest implements ArrayAccess 'binary' => 'getBinary', 'date' => 'getDate', 'date_time' => 'getDateTime', + 'uuid' => 'getUuid', 'password' => 'getPassword' ); @@ -149,65 +154,10 @@ class FormatTest implements ArrayAccess /** - * $integer - * @var int + * Associative array for storing property values + * @var mixed[] */ - protected $integer; - /** - * $int32 - * @var int - */ - protected $int32; - /** - * $int64 - * @var int - */ - protected $int64; - /** - * $number - * @var float - */ - protected $number; - /** - * $float - * @var float - */ - protected $float; - /** - * $double - * @var double - */ - protected $double; - /** - * $string - * @var string - */ - protected $string; - /** - * $byte - * @var string - */ - protected $byte; - /** - * $binary - * @var string - */ - protected $binary; - /** - * $date - * @var \DateTime - */ - protected $date; - /** - * $date_time - * @var \DateTime - */ - protected $date_time; - /** - * $password - * @var string - */ - protected $password; + protected $container = array(); /** * Constructor @@ -215,30 +165,153 @@ class FormatTest implements ArrayAccess */ public function __construct(array $data = null) { - - - if ($data != null) { - $this->integer = $data["integer"]; - $this->int32 = $data["int32"]; - $this->int64 = $data["int64"]; - $this->number = $data["number"]; - $this->float = $data["float"]; - $this->double = $data["double"]; - $this->string = $data["string"]; - $this->byte = $data["byte"]; - $this->binary = $data["binary"]; - $this->date = $data["date"]; - $this->date_time = $data["date_time"]; - $this->password = $data["password"]; - } + $this->container['integer'] = isset($data['integer']) ? $data['integer'] : null; + $this->container['int32'] = isset($data['int32']) ? $data['int32'] : null; + $this->container['int64'] = isset($data['int64']) ? $data['int64'] : null; + $this->container['number'] = isset($data['number']) ? $data['number'] : null; + $this->container['float'] = isset($data['float']) ? $data['float'] : null; + $this->container['double'] = isset($data['double']) ? $data['double'] : null; + $this->container['string'] = isset($data['string']) ? $data['string'] : null; + $this->container['byte'] = isset($data['byte']) ? $data['byte'] : null; + $this->container['binary'] = isset($data['binary']) ? $data['binary'] : null; + $this->container['date'] = isset($data['date']) ? $data['date'] : null; + $this->container['date_time'] = isset($data['date_time']) ? $data['date_time'] : null; + $this->container['uuid'] = isset($data['uuid']) ? $data['uuid'] : null; + $this->container['password'] = isset($data['password']) ? $data['password'] : null; } + + /** + * show all the invalid properties with reasons. + * + * @return array invalid properties with reasons + */ + public function list_invalid_properties() + { + $invalid_properties = array(); + if ($this->container['integer'] > 100.0) { + $invalid_properties[] = "invalid value for '$integer', must be smaller than or equal to 100.0."; + } + if ($this->container['integer'] < 10.0) { + $invalid_properties[] = "invalid value for '$integer', must be bigger than or equal to 10.0."; + } + if ($this->container['int32'] > 200.0) { + $invalid_properties[] = "invalid value for '$int32', must be smaller than or equal to 200.0."; + } + if ($this->container['int32'] < 20.0) { + $invalid_properties[] = "invalid value for '$int32', must be bigger than or equal to 20.0."; + } + if ($this->container['number'] === null) { + $invalid_properties[] = "'$number' can't be null"; + } + if ($this->container['number'] > 543.2) { + $invalid_properties[] = "invalid value for '$number', must be smaller than or equal to 543.2."; + } + if ($this->container['number'] < 32.1) { + $invalid_properties[] = "invalid value for '$number', must be bigger than or equal to 32.1."; + } + if ($this->container['float'] > 987.6) { + $invalid_properties[] = "invalid value for '$float', must be smaller than or equal to 987.6."; + } + if ($this->container['float'] < 54.3) { + $invalid_properties[] = "invalid value for '$float', must be bigger than or equal to 54.3."; + } + if ($this->container['double'] > 123.4) { + $invalid_properties[] = "invalid value for '$double', must be smaller than or equal to 123.4."; + } + if ($this->container['double'] < 67.8) { + $invalid_properties[] = "invalid value for '$double', must be bigger than or equal to 67.8."; + } + if (!preg_match("/[a-z]/i", $this->container['string'])) { + $invalid_properties[] = "invalid value for '$string', must be conform to the pattern /[a-z]/i."; + } + if ($this->container['byte'] === null) { + $invalid_properties[] = "'$byte' can't be null"; + } + if ($this->container['date'] === null) { + $invalid_properties[] = "'$date' can't be null"; + } + if ($this->container['password'] === null) { + $invalid_properties[] = "'$password' can't be null"; + } + if (strlen($this->container['password']) > 64) { + $invalid_properties[] = "invalid value for '$password', the character length must be smaller than or equal to 64."; + } + if (strlen($this->container['password']) < 10) { + $invalid_properties[] = "invalid value for '$password', the character length must be bigger than or equal to 10."; + } + return $invalid_properties; + } + + /** + * validate all the properties in the model + * return true if all passed + * + * @return bool True if all properteis are valid + */ + public function valid() + { + if ($this->container['integer'] > 100.0) { + return false; + } + if ($this->container['integer'] < 10.0) { + return false; + } + if ($this->container['int32'] > 200.0) { + return false; + } + if ($this->container['int32'] < 20.0) { + return false; + } + if ($this->container['number'] === null) { + return false; + } + if ($this->container['number'] > 543.2) { + return false; + } + if ($this->container['number'] < 32.1) { + return false; + } + if ($this->container['float'] > 987.6) { + return false; + } + if ($this->container['float'] < 54.3) { + return false; + } + if ($this->container['double'] > 123.4) { + return false; + } + if ($this->container['double'] < 67.8) { + return false; + } + if (!preg_match("/[a-z]/i", $this->container['string'])) { + return false; + } + if ($this->container['byte'] === null) { + return false; + } + if ($this->container['date'] === null) { + return false; + } + if ($this->container['password'] === null) { + return false; + } + if (strlen($this->container['password']) > 64) { + return false; + } + if (strlen($this->container['password']) < 10) { + return false; + } + return true; + } + + /** * Gets integer * @return int */ public function getInteger() { - return $this->integer; + return $this->container['integer']; } /** @@ -248,17 +321,25 @@ class FormatTest implements ArrayAccess */ public function setInteger($integer) { - - $this->integer = $integer; + + if ($integer > 100.0) { + throw new \InvalidArgumentException('invalid value for $integer when calling FormatTest., must be smaller than or equal to 100.0.'); + } + if ($integer < 10.0) { + throw new \InvalidArgumentException('invalid value for $integer when calling FormatTest., must be bigger than or equal to 10.0.'); + } + $this->container['integer'] = $integer; + return $this; } + /** * Gets int32 * @return int */ public function getInt32() { - return $this->int32; + return $this->container['int32']; } /** @@ -268,17 +349,25 @@ class FormatTest implements ArrayAccess */ public function setInt32($int32) { - - $this->int32 = $int32; + + if ($int32 > 200.0) { + throw new \InvalidArgumentException('invalid value for $int32 when calling FormatTest., must be smaller than or equal to 200.0.'); + } + if ($int32 < 20.0) { + throw new \InvalidArgumentException('invalid value for $int32 when calling FormatTest., must be bigger than or equal to 20.0.'); + } + $this->container['int32'] = $int32; + return $this; } + /** * Gets int64 * @return int */ public function getInt64() { - return $this->int64; + return $this->container['int64']; } /** @@ -288,17 +377,18 @@ class FormatTest implements ArrayAccess */ public function setInt64($int64) { - - $this->int64 = $int64; + $this->container['int64'] = $int64; + return $this; } + /** * Gets number * @return float */ public function getNumber() { - return $this->number; + return $this->container['number']; } /** @@ -308,17 +398,25 @@ class FormatTest implements ArrayAccess */ public function setNumber($number) { - - $this->number = $number; + + if ($number > 543.2) { + throw new \InvalidArgumentException('invalid value for $number when calling FormatTest., must be smaller than or equal to 543.2.'); + } + if ($number < 32.1) { + throw new \InvalidArgumentException('invalid value for $number when calling FormatTest., must be bigger than or equal to 32.1.'); + } + $this->container['number'] = $number; + return $this; } + /** * Gets float * @return float */ public function getFloat() { - return $this->float; + return $this->container['float']; } /** @@ -328,17 +426,25 @@ class FormatTest implements ArrayAccess */ public function setFloat($float) { - - $this->float = $float; + + if ($float > 987.6) { + throw new \InvalidArgumentException('invalid value for $float when calling FormatTest., must be smaller than or equal to 987.6.'); + } + if ($float < 54.3) { + throw new \InvalidArgumentException('invalid value for $float when calling FormatTest., must be bigger than or equal to 54.3.'); + } + $this->container['float'] = $float; + return $this; } + /** * Gets double * @return double */ public function getDouble() { - return $this->double; + return $this->container['double']; } /** @@ -348,17 +454,25 @@ class FormatTest implements ArrayAccess */ public function setDouble($double) { - - $this->double = $double; + + if ($double > 123.4) { + throw new \InvalidArgumentException('invalid value for $double when calling FormatTest., must be smaller than or equal to 123.4.'); + } + if ($double < 67.8) { + throw new \InvalidArgumentException('invalid value for $double when calling FormatTest., must be bigger than or equal to 67.8.'); + } + $this->container['double'] = $double; + return $this; } + /** * Gets string * @return string */ public function getString() { - return $this->string; + return $this->container['string']; } /** @@ -368,17 +482,22 @@ class FormatTest implements ArrayAccess */ public function setString($string) { - - $this->string = $string; + + if (!preg_match("/[a-z]/i", $string)) { + throw new \InvalidArgumentException('invalid value for $string when calling FormatTest., must be conform to the pattern /[a-z]/i.'); + } + $this->container['string'] = $string; + return $this; } + /** * Gets byte * @return string */ public function getByte() { - return $this->byte; + return $this->container['byte']; } /** @@ -388,17 +507,18 @@ class FormatTest implements ArrayAccess */ public function setByte($byte) { - - $this->byte = $byte; + $this->container['byte'] = $byte; + return $this; } + /** * Gets binary * @return string */ public function getBinary() { - return $this->binary; + return $this->container['binary']; } /** @@ -408,17 +528,18 @@ class FormatTest implements ArrayAccess */ public function setBinary($binary) { - - $this->binary = $binary; + $this->container['binary'] = $binary; + return $this; } + /** * Gets date * @return \DateTime */ public function getDate() { - return $this->date; + return $this->container['date']; } /** @@ -428,17 +549,18 @@ class FormatTest implements ArrayAccess */ public function setDate($date) { - - $this->date = $date; + $this->container['date'] = $date; + return $this; } + /** * Gets date_time * @return \DateTime */ public function getDateTime() { - return $this->date_time; + return $this->container['date_time']; } /** @@ -448,17 +570,39 @@ class FormatTest implements ArrayAccess */ public function setDateTime($date_time) { - - $this->date_time = $date_time; + $this->container['date_time'] = $date_time; + return $this; } + + /** + * Gets uuid + * @return string + */ + public function getUuid() + { + return $this->container['uuid']; + } + + /** + * Sets uuid + * @param string $uuid + * @return $this + */ + public function setUuid($uuid) + { + $this->container['uuid'] = $uuid; + + return $this; + } + /** * Gets password * @return string */ public function getPassword() { - return $this->password; + return $this->container['password']; } /** @@ -468,8 +612,14 @@ class FormatTest implements ArrayAccess */ public function setPassword($password) { - - $this->password = $password; + if (strlen($password) > 64) { + throw new \InvalidArgumentException('invalid length for $password when calling FormatTest., must be smaller than or equal to 64.'); + } + if (strlen($password) < 10) { + throw new \InvalidArgumentException('invalid length for $password when calling FormatTest., must be bigger than or equal to 10.'); + } + $this->container['password'] = $password; + return $this; } /** @@ -479,7 +629,7 @@ class FormatTest implements ArrayAccess */ public function offsetExists($offset) { - return isset($this->$offset); + return isset($this->container[$offset]); } /** @@ -489,7 +639,7 @@ class FormatTest implements ArrayAccess */ public function offsetGet($offset) { - return $this->$offset; + return isset($this->container[$offset]) ? $this->container[$offset] : null; } /** @@ -500,7 +650,11 @@ class FormatTest implements ArrayAccess */ public function offsetSet($offset, $value) { - $this->$offset = $value; + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } } /** @@ -510,7 +664,7 @@ class FormatTest implements ArrayAccess */ public function offsetUnset($offset) { - unset($this->$offset); + unset($this->container[$offset]); } /** diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/InlineResponse200.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/InlineResponse200.php deleted file mode 100644 index d66a078a4e0..00000000000 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/InlineResponse200.php +++ /dev/null @@ -1,375 +0,0 @@ - '\Swagger\Client\Model\Tag[]', - 'id' => 'int', - 'category' => 'object', - 'status' => 'string', - 'name' => 'string', - 'photo_urls' => 'string[]' - ); - - static function swaggerTypes() { - return self::$swaggerTypes; - } - - /** - * Array of attributes where the key is the local name, and the value is the original name - * @var string[] - */ - static $attributeMap = array( - 'tags' => 'tags', - 'id' => 'id', - 'category' => 'category', - 'status' => 'status', - 'name' => 'name', - 'photo_urls' => 'photoUrls' - ); - - static function attributeMap() { - return self::$attributeMap; - } - - /** - * Array of attributes to setter functions (for deserialization of responses) - * @var string[] - */ - static $setters = array( - 'tags' => 'setTags', - 'id' => 'setId', - 'category' => 'setCategory', - 'status' => 'setStatus', - 'name' => 'setName', - 'photo_urls' => 'setPhotoUrls' - ); - - static function setters() { - return self::$setters; - } - - /** - * Array of attributes to getter functions (for serialization of requests) - * @var string[] - */ - static $getters = array( - 'tags' => 'getTags', - 'id' => 'getId', - 'category' => 'getCategory', - 'status' => 'getStatus', - 'name' => 'getName', - 'photo_urls' => 'getPhotoUrls' - ); - - static function getters() { - return self::$getters; - } - - const STATUS_AVAILABLE = 'available'; - const STATUS_PENDING = 'pending'; - const STATUS_SOLD = 'sold'; - - - - /** - * Gets allowable values of the enum - * @return string[] - */ - public function getStatusAllowableValues() { - return [ - self::STATUS_AVAILABLE, - self::STATUS_PENDING, - self::STATUS_SOLD, - ]; - } - - - - /** - * $tags - * @var \Swagger\Client\Model\Tag[] - */ - protected $tags; - - /** - * $id - * @var int - */ - protected $id; - - /** - * $category - * @var object - */ - protected $category; - - /** - * $status pet status in the store - * @var string - */ - protected $status; - - /** - * $name - * @var string - */ - protected $name; - - /** - * $photo_urls - * @var string[] - */ - protected $photo_urls; - - - /** - * Constructor - * @param mixed[] $data Associated array of property value initalizing the model - */ - public function __construct(array $data = null) - { - - if ($data != null) { - $this->tags = $data["tags"]; - $this->id = $data["id"]; - $this->category = $data["category"]; - $this->status = $data["status"]; - $this->name = $data["name"]; - $this->photo_urls = $data["photo_urls"]; - } - } - - /** - * Gets tags. - * @return \Swagger\Client\Model\Tag[] - */ - public function getTags() - { - return $this->tags; - } - - /** - * Sets tags. - * @param \Swagger\Client\Model\Tag[] $tags - * @return $this - */ - public function setTags($tags) - { - - $this->tags = $tags; - return $this; - } - - /** - * Gets id. - * @return int - */ - public function getId() - { - return $this->id; - } - - /** - * Sets id. - * @param int $id - * @return $this - */ - public function setId($id) - { - - $this->id = $id; - return $this; - } - - /** - * Gets category. - * @return object - */ - public function getCategory() - { - return $this->category; - } - - /** - * Sets category. - * @param object $category - * @return $this - */ - public function setCategory($category) - { - - $this->category = $category; - return $this; - } - - /** - * Gets status. - * @return string - */ - public function getStatus() - { - return $this->status; - } - - /** - * Sets status. - * @param string $status pet status in the store - * @return $this - */ - public function setStatus($status) - { - $allowed_values = array("available", "pending", "sold"); - if (!in_array($status, $allowed_values)) { - throw new \InvalidArgumentException("Invalid value for 'status', must be one of 'available', 'pending', 'sold'"); - } - $this->status = $status; - return $this; - } - - /** - * Gets name. - * @return string - */ - public function getName() - { - return $this->name; - } - - /** - * Sets name. - * @param string $name - * @return $this - */ - public function setName($name) - { - - $this->name = $name; - return $this; - } - - /** - * Gets photo_urls. - * @return string[] - */ - public function getPhotoUrls() - { - return $this->photo_urls; - } - - /** - * Sets photo_urls. - * @param string[] $photo_urls - * @return $this - */ - public function setPhotoUrls($photo_urls) - { - - $this->photo_urls = $photo_urls; - return $this; - } - - /** - * Returns true if offset exists. False otherwise. - * @param integer $offset Offset - * @return boolean - */ - public function offsetExists($offset) - { - return isset($this->$offset); - } - - /** - * Gets offset. - * @param integer $offset Offset - * @return mixed - */ - public function offsetGet($offset) - { - return $this->$offset; - } - - /** - * Sets value based on offset. - * @param integer $offset Offset - * @param mixed $value Value to be set - * @return void - */ - public function offsetSet($offset, $value) - { - $this->$offset = $value; - } - - /** - * Unsets offset. - * @param integer $offset Offset - * @return void - */ - public function offsetUnset($offset) - { - unset($this->$offset); - } - - /** - * Gets the string presentation of the object. - * @return string - */ - public function __toString() - { - if (defined('JSON_PRETTY_PRINT')) { - return json_encode(\Swagger\Client\ObjectSerializer::sanitizeForSerialization($this), JSON_PRETTY_PRINT); - } else { - return json_encode(\Swagger\Client\ObjectSerializer::sanitizeForSerialization($this)); - } - } -} - -?> diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Model200Response.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Model200Response.php index fd305916a2d..68eae680dc6 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Model200Response.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Model200Response.php @@ -34,6 +34,7 @@ namespace Swagger\Client\Model; use \ArrayAccess; + /** * Model200Response Class Doc Comment * @@ -59,7 +60,7 @@ class Model200Response implements ArrayAccess static $swaggerTypes = array( 'name' => 'int' ); - + static function swaggerTypes() { return self::$swaggerTypes; } @@ -71,7 +72,7 @@ class Model200Response implements ArrayAccess static $attributeMap = array( 'name' => 'name' ); - + static function attributeMap() { return self::$attributeMap; } @@ -83,7 +84,7 @@ class Model200Response implements ArrayAccess static $setters = array( 'name' => 'setName' ); - + static function setters() { return self::$setters; } @@ -105,10 +106,10 @@ class Model200Response implements ArrayAccess /** - * $name - * @var int + * Associative array for storing property values + * @var mixed[] */ - protected $name; + protected $container = array(); /** * Constructor @@ -116,19 +117,39 @@ class Model200Response implements ArrayAccess */ public function __construct(array $data = null) { - - - if ($data != null) { - $this->name = $data["name"]; - } + $this->container['name'] = isset($data['name']) ? $data['name'] : null; } + + /** + * show all the invalid properties with reasons. + * + * @return array invalid properties with reasons + */ + public function list_invalid_properties() + { + $invalid_properties = array(); + return $invalid_properties; + } + + /** + * validate all the properties in the model + * return true if all passed + * + * @return bool True if all properteis are valid + */ + public function valid() + { + return true; + } + + /** * Gets name * @return int */ public function getName() { - return $this->name; + return $this->container['name']; } /** @@ -138,8 +159,8 @@ class Model200Response implements ArrayAccess */ public function setName($name) { - - $this->name = $name; + $this->container['name'] = $name; + return $this; } /** @@ -149,7 +170,7 @@ class Model200Response implements ArrayAccess */ public function offsetExists($offset) { - return isset($this->$offset); + return isset($this->container[$offset]); } /** @@ -159,7 +180,7 @@ class Model200Response implements ArrayAccess */ public function offsetGet($offset) { - return $this->$offset; + return isset($this->container[$offset]) ? $this->container[$offset] : null; } /** @@ -170,7 +191,11 @@ class Model200Response implements ArrayAccess */ public function offsetSet($offset, $value) { - $this->$offset = $value; + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } } /** @@ -180,7 +205,7 @@ class Model200Response implements ArrayAccess */ public function offsetUnset($offset) { - unset($this->$offset); + unset($this->container[$offset]); } /** diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ModelReturn.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ModelReturn.php index a7e36a14365..7dce6f0029d 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ModelReturn.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ModelReturn.php @@ -34,6 +34,7 @@ namespace Swagger\Client\Model; use \ArrayAccess; + /** * ModelReturn Class Doc Comment * @@ -59,7 +60,7 @@ class ModelReturn implements ArrayAccess static $swaggerTypes = array( 'return' => 'int' ); - + static function swaggerTypes() { return self::$swaggerTypes; } @@ -71,7 +72,7 @@ class ModelReturn implements ArrayAccess static $attributeMap = array( 'return' => 'return' ); - + static function attributeMap() { return self::$attributeMap; } @@ -83,7 +84,7 @@ class ModelReturn implements ArrayAccess static $setters = array( 'return' => 'setReturn' ); - + static function setters() { return self::$setters; } @@ -105,10 +106,10 @@ class ModelReturn implements ArrayAccess /** - * $return - * @var int + * Associative array for storing property values + * @var mixed[] */ - protected $return; + protected $container = array(); /** * Constructor @@ -116,19 +117,39 @@ class ModelReturn implements ArrayAccess */ public function __construct(array $data = null) { - - - if ($data != null) { - $this->return = $data["return"]; - } + $this->container['return'] = isset($data['return']) ? $data['return'] : null; } + + /** + * show all the invalid properties with reasons. + * + * @return array invalid properties with reasons + */ + public function list_invalid_properties() + { + $invalid_properties = array(); + return $invalid_properties; + } + + /** + * validate all the properties in the model + * return true if all passed + * + * @return bool True if all properteis are valid + */ + public function valid() + { + return true; + } + + /** * Gets return * @return int */ public function getReturn() { - return $this->return; + return $this->container['return']; } /** @@ -138,8 +159,8 @@ class ModelReturn implements ArrayAccess */ public function setReturn($return) { - - $this->return = $return; + $this->container['return'] = $return; + return $this; } /** @@ -149,7 +170,7 @@ class ModelReturn implements ArrayAccess */ public function offsetExists($offset) { - return isset($this->$offset); + return isset($this->container[$offset]); } /** @@ -159,7 +180,7 @@ class ModelReturn implements ArrayAccess */ public function offsetGet($offset) { - return $this->$offset; + return isset($this->container[$offset]) ? $this->container[$offset] : null; } /** @@ -170,7 +191,11 @@ class ModelReturn implements ArrayAccess */ public function offsetSet($offset, $value) { - $this->$offset = $value; + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } } /** @@ -180,7 +205,7 @@ class ModelReturn implements ArrayAccess */ public function offsetUnset($offset) { - unset($this->$offset); + unset($this->container[$offset]); } /** diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Name.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Name.php index ff62e4f1c25..b77f3d78d0c 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Name.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Name.php @@ -34,6 +34,7 @@ namespace Swagger\Client\Model; use \ArrayAccess; + /** * Name Class Doc Comment * @@ -59,9 +60,10 @@ class Name implements ArrayAccess static $swaggerTypes = array( 'name' => 'int', 'snake_case' => 'int', - 'property' => 'string' + 'property' => 'string', + '_123_number' => 'int' ); - + static function swaggerTypes() { return self::$swaggerTypes; } @@ -73,9 +75,10 @@ class Name implements ArrayAccess static $attributeMap = array( 'name' => 'name', 'snake_case' => 'snake_case', - 'property' => 'property' + 'property' => 'property', + '_123_number' => '123Number' ); - + static function attributeMap() { return self::$attributeMap; } @@ -87,9 +90,10 @@ class Name implements ArrayAccess static $setters = array( 'name' => 'setName', 'snake_case' => 'setSnakeCase', - 'property' => 'setProperty' + 'property' => 'setProperty', + '_123_number' => 'set123Number' ); - + static function setters() { return self::$setters; } @@ -101,7 +105,8 @@ class Name implements ArrayAccess static $getters = array( 'name' => 'getName', 'snake_case' => 'getSnakeCase', - 'property' => 'getProperty' + 'property' => 'getProperty', + '_123_number' => 'get123Number' ); static function getters() { @@ -113,20 +118,10 @@ class Name implements ArrayAccess /** - * $name - * @var int + * Associative array for storing property values + * @var mixed[] */ - protected $name; - /** - * $snake_case - * @var int - */ - protected $snake_case; - /** - * $property - * @var string - */ - protected $property; + protected $container = array(); /** * Constructor @@ -134,21 +129,48 @@ class Name implements ArrayAccess */ public function __construct(array $data = null) { - - - if ($data != null) { - $this->name = $data["name"]; - $this->snake_case = $data["snake_case"]; - $this->property = $data["property"]; - } + $this->container['name'] = isset($data['name']) ? $data['name'] : null; + $this->container['snake_case'] = isset($data['snake_case']) ? $data['snake_case'] : null; + $this->container['property'] = isset($data['property']) ? $data['property'] : null; + $this->container['_123_number'] = isset($data['_123_number']) ? $data['_123_number'] : null; } + + /** + * show all the invalid properties with reasons. + * + * @return array invalid properties with reasons + */ + public function list_invalid_properties() + { + $invalid_properties = array(); + if ($this->container['name'] === null) { + $invalid_properties[] = "'$name' can't be null"; + } + return $invalid_properties; + } + + /** + * validate all the properties in the model + * return true if all passed + * + * @return bool True if all properteis are valid + */ + public function valid() + { + if ($this->container['name'] === null) { + return false; + } + return true; + } + + /** * Gets name * @return int */ public function getName() { - return $this->name; + return $this->container['name']; } /** @@ -158,17 +180,18 @@ class Name implements ArrayAccess */ public function setName($name) { - - $this->name = $name; + $this->container['name'] = $name; + return $this; } + /** * Gets snake_case * @return int */ public function getSnakeCase() { - return $this->snake_case; + return $this->container['snake_case']; } /** @@ -178,17 +201,18 @@ class Name implements ArrayAccess */ public function setSnakeCase($snake_case) { - - $this->snake_case = $snake_case; + $this->container['snake_case'] = $snake_case; + return $this; } + /** * Gets property * @return string */ public function getProperty() { - return $this->property; + return $this->container['property']; } /** @@ -198,8 +222,29 @@ class Name implements ArrayAccess */ public function setProperty($property) { - - $this->property = $property; + $this->container['property'] = $property; + + return $this; + } + + /** + * Gets _123_number + * @return int + */ + public function get123Number() + { + return $this->container['_123_number']; + } + + /** + * Sets _123_number + * @param int $_123_number + * @return $this + */ + public function set123Number($_123_number) + { + $this->container['_123_number'] = $_123_number; + return $this; } /** @@ -209,7 +254,7 @@ class Name implements ArrayAccess */ public function offsetExists($offset) { - return isset($this->$offset); + return isset($this->container[$offset]); } /** @@ -219,7 +264,7 @@ class Name implements ArrayAccess */ public function offsetGet($offset) { - return $this->$offset; + return isset($this->container[$offset]) ? $this->container[$offset] : null; } /** @@ -230,7 +275,11 @@ class Name implements ArrayAccess */ public function offsetSet($offset, $value) { - $this->$offset = $value; + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } } /** @@ -240,7 +289,7 @@ class Name implements ArrayAccess */ public function offsetUnset($offset) { - unset($this->$offset); + unset($this->container[$offset]); } /** diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Order.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Order.php index 270a53a41e7..88779ed8c73 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Order.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Order.php @@ -34,6 +34,7 @@ namespace Swagger\Client\Model; use \ArrayAccess; + /** * Order Class Doc Comment * @@ -64,7 +65,7 @@ class Order implements ArrayAccess 'status' => 'string', 'complete' => 'bool' ); - + static function swaggerTypes() { return self::$swaggerTypes; } @@ -81,7 +82,7 @@ class Order implements ArrayAccess 'status' => 'status', 'complete' => 'complete' ); - + static function attributeMap() { return self::$attributeMap; } @@ -98,7 +99,7 @@ class Order implements ArrayAccess 'status' => 'setStatus', 'complete' => 'setComplete' ); - + static function setters() { return self::$setters; } @@ -140,35 +141,10 @@ class Order implements ArrayAccess /** - * $id - * @var int + * Associative array for storing property values + * @var mixed[] */ - protected $id; - /** - * $pet_id - * @var int - */ - protected $pet_id; - /** - * $quantity - * @var int - */ - protected $quantity; - /** - * $ship_date - * @var \DateTime - */ - protected $ship_date; - /** - * $status Order Status - * @var string - */ - protected $status; - /** - * $complete - * @var bool - */ - protected $complete = false; + protected $container = array(); /** * Constructor @@ -176,24 +152,52 @@ class Order implements ArrayAccess */ public function __construct(array $data = null) { - - - if ($data != null) { - $this->id = $data["id"]; - $this->pet_id = $data["pet_id"]; - $this->quantity = $data["quantity"]; - $this->ship_date = $data["ship_date"]; - $this->status = $data["status"]; - $this->complete = $data["complete"]; - } + $this->container['id'] = isset($data['id']) ? $data['id'] : null; + $this->container['pet_id'] = isset($data['pet_id']) ? $data['pet_id'] : null; + $this->container['quantity'] = isset($data['quantity']) ? $data['quantity'] : null; + $this->container['ship_date'] = isset($data['ship_date']) ? $data['ship_date'] : null; + $this->container['status'] = isset($data['status']) ? $data['status'] : null; + $this->container['complete'] = isset($data['complete']) ? $data['complete'] : false; } + + /** + * show all the invalid properties with reasons. + * + * @return array invalid properties with reasons + */ + public function list_invalid_properties() + { + $invalid_properties = array(); + $allowed_values = array("placed", "approved", "delivered"); + if (!in_array($this->container['status'], $allowed_values)) { + $invalid_properties[] = "invalid value for '$status', must be one of #{allowed_values}."; + } + return $invalid_properties; + } + + /** + * validate all the properties in the model + * return true if all passed + * + * @return bool True if all properteis are valid + */ + public function valid() + { + $allowed_values = array("placed", "approved", "delivered"); + if (!in_array($this->container['status'], $allowed_values)) { + return false; + } + return true; + } + + /** * Gets id * @return int */ public function getId() { - return $this->id; + return $this->container['id']; } /** @@ -203,17 +207,18 @@ class Order implements ArrayAccess */ public function setId($id) { - - $this->id = $id; + $this->container['id'] = $id; + return $this; } + /** * Gets pet_id * @return int */ public function getPetId() { - return $this->pet_id; + return $this->container['pet_id']; } /** @@ -223,17 +228,18 @@ class Order implements ArrayAccess */ public function setPetId($pet_id) { - - $this->pet_id = $pet_id; + $this->container['pet_id'] = $pet_id; + return $this; } + /** * Gets quantity * @return int */ public function getQuantity() { - return $this->quantity; + return $this->container['quantity']; } /** @@ -243,17 +249,18 @@ class Order implements ArrayAccess */ public function setQuantity($quantity) { - - $this->quantity = $quantity; + $this->container['quantity'] = $quantity; + return $this; } + /** * Gets ship_date * @return \DateTime */ public function getShipDate() { - return $this->ship_date; + return $this->container['ship_date']; } /** @@ -263,17 +270,18 @@ class Order implements ArrayAccess */ public function setShipDate($ship_date) { - - $this->ship_date = $ship_date; + $this->container['ship_date'] = $ship_date; + return $this; } + /** * Gets status * @return string */ public function getStatus() { - return $this->status; + return $this->container['status']; } /** @@ -283,20 +291,22 @@ class Order implements ArrayAccess */ public function setStatus($status) { - $allowed_values = array("placed", "approved", "delivered"); + $allowed_values = array('placed', 'approved', 'delivered'); if (!in_array($status, $allowed_values)) { throw new \InvalidArgumentException("Invalid value for 'status', must be one of 'placed', 'approved', 'delivered'"); } - $this->status = $status; + $this->container['status'] = $status; + return $this; } + /** * Gets complete * @return bool */ public function getComplete() { - return $this->complete; + return $this->container['complete']; } /** @@ -306,8 +316,8 @@ class Order implements ArrayAccess */ public function setComplete($complete) { - - $this->complete = $complete; + $this->container['complete'] = $complete; + return $this; } /** @@ -317,7 +327,7 @@ class Order implements ArrayAccess */ public function offsetExists($offset) { - return isset($this->$offset); + return isset($this->container[$offset]); } /** @@ -327,7 +337,7 @@ class Order implements ArrayAccess */ public function offsetGet($offset) { - return $this->$offset; + return isset($this->container[$offset]) ? $this->container[$offset] : null; } /** @@ -338,7 +348,11 @@ class Order implements ArrayAccess */ public function offsetSet($offset, $value) { - $this->$offset = $value; + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } } /** @@ -348,7 +362,7 @@ class Order implements ArrayAccess */ public function offsetUnset($offset) { - unset($this->$offset); + unset($this->container[$offset]); } /** diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Pet.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Pet.php index ce1d7a63944..5a65e432538 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Pet.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Pet.php @@ -34,6 +34,7 @@ namespace Swagger\Client\Model; use \ArrayAccess; + /** * Pet Class Doc Comment * @@ -64,7 +65,7 @@ class Pet implements ArrayAccess 'tags' => '\Swagger\Client\Model\Tag[]', 'status' => 'string' ); - + static function swaggerTypes() { return self::$swaggerTypes; } @@ -81,7 +82,7 @@ class Pet implements ArrayAccess 'tags' => 'tags', 'status' => 'status' ); - + static function attributeMap() { return self::$attributeMap; } @@ -98,7 +99,7 @@ class Pet implements ArrayAccess 'tags' => 'setTags', 'status' => 'setStatus' ); - + static function setters() { return self::$setters; } @@ -140,35 +141,10 @@ class Pet implements ArrayAccess /** - * $id - * @var int + * Associative array for storing property values + * @var mixed[] */ - protected $id; - /** - * $category - * @var \Swagger\Client\Model\Category - */ - protected $category; - /** - * $name - * @var string - */ - protected $name; - /** - * $photo_urls - * @var string[] - */ - protected $photo_urls; - /** - * $tags - * @var \Swagger\Client\Model\Tag[] - */ - protected $tags; - /** - * $status pet status in the store - * @var string - */ - protected $status; + protected $container = array(); /** * Constructor @@ -176,24 +152,64 @@ class Pet implements ArrayAccess */ public function __construct(array $data = null) { - - - if ($data != null) { - $this->id = $data["id"]; - $this->category = $data["category"]; - $this->name = $data["name"]; - $this->photo_urls = $data["photo_urls"]; - $this->tags = $data["tags"]; - $this->status = $data["status"]; - } + $this->container['id'] = isset($data['id']) ? $data['id'] : null; + $this->container['category'] = isset($data['category']) ? $data['category'] : null; + $this->container['name'] = isset($data['name']) ? $data['name'] : null; + $this->container['photo_urls'] = isset($data['photo_urls']) ? $data['photo_urls'] : null; + $this->container['tags'] = isset($data['tags']) ? $data['tags'] : null; + $this->container['status'] = isset($data['status']) ? $data['status'] : null; } + + /** + * show all the invalid properties with reasons. + * + * @return array invalid properties with reasons + */ + public function list_invalid_properties() + { + $invalid_properties = array(); + if ($this->container['name'] === null) { + $invalid_properties[] = "'$name' can't be null"; + } + if ($this->container['photo_urls'] === null) { + $invalid_properties[] = "'$photo_urls' can't be null"; + } + $allowed_values = array("available", "pending", "sold"); + if (!in_array($this->container['status'], $allowed_values)) { + $invalid_properties[] = "invalid value for '$status', must be one of #{allowed_values}."; + } + return $invalid_properties; + } + + /** + * validate all the properties in the model + * return true if all passed + * + * @return bool True if all properteis are valid + */ + public function valid() + { + if ($this->container['name'] === null) { + return false; + } + if ($this->container['photo_urls'] === null) { + return false; + } + $allowed_values = array("available", "pending", "sold"); + if (!in_array($this->container['status'], $allowed_values)) { + return false; + } + return true; + } + + /** * Gets id * @return int */ public function getId() { - return $this->id; + return $this->container['id']; } /** @@ -203,17 +219,18 @@ class Pet implements ArrayAccess */ public function setId($id) { - - $this->id = $id; + $this->container['id'] = $id; + return $this; } + /** * Gets category * @return \Swagger\Client\Model\Category */ public function getCategory() { - return $this->category; + return $this->container['category']; } /** @@ -223,17 +240,18 @@ class Pet implements ArrayAccess */ public function setCategory($category) { - - $this->category = $category; + $this->container['category'] = $category; + return $this; } + /** * Gets name * @return string */ public function getName() { - return $this->name; + return $this->container['name']; } /** @@ -243,17 +261,18 @@ class Pet implements ArrayAccess */ public function setName($name) { - - $this->name = $name; + $this->container['name'] = $name; + return $this; } + /** * Gets photo_urls * @return string[] */ public function getPhotoUrls() { - return $this->photo_urls; + return $this->container['photo_urls']; } /** @@ -263,17 +282,18 @@ class Pet implements ArrayAccess */ public function setPhotoUrls($photo_urls) { - - $this->photo_urls = $photo_urls; + $this->container['photo_urls'] = $photo_urls; + return $this; } + /** * Gets tags * @return \Swagger\Client\Model\Tag[] */ public function getTags() { - return $this->tags; + return $this->container['tags']; } /** @@ -283,17 +303,18 @@ class Pet implements ArrayAccess */ public function setTags($tags) { - - $this->tags = $tags; + $this->container['tags'] = $tags; + return $this; } + /** * Gets status * @return string */ public function getStatus() { - return $this->status; + return $this->container['status']; } /** @@ -303,11 +324,12 @@ class Pet implements ArrayAccess */ public function setStatus($status) { - $allowed_values = array("available", "pending", "sold"); + $allowed_values = array('available', 'pending', 'sold'); if (!in_array($status, $allowed_values)) { throw new \InvalidArgumentException("Invalid value for 'status', must be one of 'available', 'pending', 'sold'"); } - $this->status = $status; + $this->container['status'] = $status; + return $this; } /** @@ -317,7 +339,7 @@ class Pet implements ArrayAccess */ public function offsetExists($offset) { - return isset($this->$offset); + return isset($this->container[$offset]); } /** @@ -327,7 +349,7 @@ class Pet implements ArrayAccess */ public function offsetGet($offset) { - return $this->$offset; + return isset($this->container[$offset]) ? $this->container[$offset] : null; } /** @@ -338,7 +360,11 @@ class Pet implements ArrayAccess */ public function offsetSet($offset, $value) { - $this->$offset = $value; + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } } /** @@ -348,7 +374,7 @@ class Pet implements ArrayAccess */ public function offsetUnset($offset) { - unset($this->$offset); + unset($this->container[$offset]); } /** diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/SpecialModelName.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/SpecialModelName.php index e2cb5b6e90f..25ebecd55a0 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/SpecialModelName.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/SpecialModelName.php @@ -34,6 +34,7 @@ namespace Swagger\Client\Model; use \ArrayAccess; + /** * SpecialModelName Class Doc Comment * @@ -59,7 +60,7 @@ class SpecialModelName implements ArrayAccess static $swaggerTypes = array( 'special_property_name' => 'int' ); - + static function swaggerTypes() { return self::$swaggerTypes; } @@ -71,7 +72,7 @@ class SpecialModelName implements ArrayAccess static $attributeMap = array( 'special_property_name' => '$special[property.name]' ); - + static function attributeMap() { return self::$attributeMap; } @@ -83,7 +84,7 @@ class SpecialModelName implements ArrayAccess static $setters = array( 'special_property_name' => 'setSpecialPropertyName' ); - + static function setters() { return self::$setters; } @@ -105,10 +106,10 @@ class SpecialModelName implements ArrayAccess /** - * $special_property_name - * @var int + * Associative array for storing property values + * @var mixed[] */ - protected $special_property_name; + protected $container = array(); /** * Constructor @@ -116,19 +117,39 @@ class SpecialModelName implements ArrayAccess */ public function __construct(array $data = null) { - - - if ($data != null) { - $this->special_property_name = $data["special_property_name"]; - } + $this->container['special_property_name'] = isset($data['special_property_name']) ? $data['special_property_name'] : null; } + + /** + * show all the invalid properties with reasons. + * + * @return array invalid properties with reasons + */ + public function list_invalid_properties() + { + $invalid_properties = array(); + return $invalid_properties; + } + + /** + * validate all the properties in the model + * return true if all passed + * + * @return bool True if all properteis are valid + */ + public function valid() + { + return true; + } + + /** * Gets special_property_name * @return int */ public function getSpecialPropertyName() { - return $this->special_property_name; + return $this->container['special_property_name']; } /** @@ -138,8 +159,8 @@ class SpecialModelName implements ArrayAccess */ public function setSpecialPropertyName($special_property_name) { - - $this->special_property_name = $special_property_name; + $this->container['special_property_name'] = $special_property_name; + return $this; } /** @@ -149,7 +170,7 @@ class SpecialModelName implements ArrayAccess */ public function offsetExists($offset) { - return isset($this->$offset); + return isset($this->container[$offset]); } /** @@ -159,7 +180,7 @@ class SpecialModelName implements ArrayAccess */ public function offsetGet($offset) { - return $this->$offset; + return isset($this->container[$offset]) ? $this->container[$offset] : null; } /** @@ -170,7 +191,11 @@ class SpecialModelName implements ArrayAccess */ public function offsetSet($offset, $value) { - $this->$offset = $value; + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } } /** @@ -180,7 +205,7 @@ class SpecialModelName implements ArrayAccess */ public function offsetUnset($offset) { - unset($this->$offset); + unset($this->container[$offset]); } /** diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Tag.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Tag.php index 159c531b8b2..a2132ca7e5c 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Tag.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Tag.php @@ -34,6 +34,7 @@ namespace Swagger\Client\Model; use \ArrayAccess; + /** * Tag Class Doc Comment * @@ -60,7 +61,7 @@ class Tag implements ArrayAccess 'id' => 'int', 'name' => 'string' ); - + static function swaggerTypes() { return self::$swaggerTypes; } @@ -73,7 +74,7 @@ class Tag implements ArrayAccess 'id' => 'id', 'name' => 'name' ); - + static function attributeMap() { return self::$attributeMap; } @@ -86,7 +87,7 @@ class Tag implements ArrayAccess 'id' => 'setId', 'name' => 'setName' ); - + static function setters() { return self::$setters; } @@ -109,15 +110,10 @@ class Tag implements ArrayAccess /** - * $id - * @var int + * Associative array for storing property values + * @var mixed[] */ - protected $id; - /** - * $name - * @var string - */ - protected $name; + protected $container = array(); /** * Constructor @@ -125,20 +121,40 @@ class Tag implements ArrayAccess */ public function __construct(array $data = null) { - - - if ($data != null) { - $this->id = $data["id"]; - $this->name = $data["name"]; - } + $this->container['id'] = isset($data['id']) ? $data['id'] : null; + $this->container['name'] = isset($data['name']) ? $data['name'] : null; } + + /** + * show all the invalid properties with reasons. + * + * @return array invalid properties with reasons + */ + public function list_invalid_properties() + { + $invalid_properties = array(); + return $invalid_properties; + } + + /** + * validate all the properties in the model + * return true if all passed + * + * @return bool True if all properteis are valid + */ + public function valid() + { + return true; + } + + /** * Gets id * @return int */ public function getId() { - return $this->id; + return $this->container['id']; } /** @@ -148,17 +164,18 @@ class Tag implements ArrayAccess */ public function setId($id) { - - $this->id = $id; + $this->container['id'] = $id; + return $this; } + /** * Gets name * @return string */ public function getName() { - return $this->name; + return $this->container['name']; } /** @@ -168,8 +185,8 @@ class Tag implements ArrayAccess */ public function setName($name) { - - $this->name = $name; + $this->container['name'] = $name; + return $this; } /** @@ -179,7 +196,7 @@ class Tag implements ArrayAccess */ public function offsetExists($offset) { - return isset($this->$offset); + return isset($this->container[$offset]); } /** @@ -189,7 +206,7 @@ class Tag implements ArrayAccess */ public function offsetGet($offset) { - return $this->$offset; + return isset($this->container[$offset]) ? $this->container[$offset] : null; } /** @@ -200,7 +217,11 @@ class Tag implements ArrayAccess */ public function offsetSet($offset, $value) { - $this->$offset = $value; + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } } /** @@ -210,7 +231,7 @@ class Tag implements ArrayAccess */ public function offsetUnset($offset) { - unset($this->$offset); + unset($this->container[$offset]); } /** diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/User.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/User.php index 2d624103218..a97727f0a8f 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/User.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/User.php @@ -34,6 +34,7 @@ namespace Swagger\Client\Model; use \ArrayAccess; + /** * User Class Doc Comment * @@ -66,7 +67,7 @@ class User implements ArrayAccess 'phone' => 'string', 'user_status' => 'int' ); - + static function swaggerTypes() { return self::$swaggerTypes; } @@ -85,7 +86,7 @@ class User implements ArrayAccess 'phone' => 'phone', 'user_status' => 'userStatus' ); - + static function attributeMap() { return self::$attributeMap; } @@ -104,7 +105,7 @@ class User implements ArrayAccess 'phone' => 'setPhone', 'user_status' => 'setUserStatus' ); - + static function setters() { return self::$setters; } @@ -133,45 +134,10 @@ class User implements ArrayAccess /** - * $id - * @var int + * Associative array for storing property values + * @var mixed[] */ - protected $id; - /** - * $username - * @var string - */ - protected $username; - /** - * $first_name - * @var string - */ - protected $first_name; - /** - * $last_name - * @var string - */ - protected $last_name; - /** - * $email - * @var string - */ - protected $email; - /** - * $password - * @var string - */ - protected $password; - /** - * $phone - * @var string - */ - protected $phone; - /** - * $user_status User Status - * @var int - */ - protected $user_status; + protected $container = array(); /** * Constructor @@ -179,26 +145,46 @@ class User implements ArrayAccess */ public function __construct(array $data = null) { - - - if ($data != null) { - $this->id = $data["id"]; - $this->username = $data["username"]; - $this->first_name = $data["first_name"]; - $this->last_name = $data["last_name"]; - $this->email = $data["email"]; - $this->password = $data["password"]; - $this->phone = $data["phone"]; - $this->user_status = $data["user_status"]; - } + $this->container['id'] = isset($data['id']) ? $data['id'] : null; + $this->container['username'] = isset($data['username']) ? $data['username'] : null; + $this->container['first_name'] = isset($data['first_name']) ? $data['first_name'] : null; + $this->container['last_name'] = isset($data['last_name']) ? $data['last_name'] : null; + $this->container['email'] = isset($data['email']) ? $data['email'] : null; + $this->container['password'] = isset($data['password']) ? $data['password'] : null; + $this->container['phone'] = isset($data['phone']) ? $data['phone'] : null; + $this->container['user_status'] = isset($data['user_status']) ? $data['user_status'] : null; } + + /** + * show all the invalid properties with reasons. + * + * @return array invalid properties with reasons + */ + public function list_invalid_properties() + { + $invalid_properties = array(); + return $invalid_properties; + } + + /** + * validate all the properties in the model + * return true if all passed + * + * @return bool True if all properteis are valid + */ + public function valid() + { + return true; + } + + /** * Gets id * @return int */ public function getId() { - return $this->id; + return $this->container['id']; } /** @@ -208,17 +194,18 @@ class User implements ArrayAccess */ public function setId($id) { - - $this->id = $id; + $this->container['id'] = $id; + return $this; } + /** * Gets username * @return string */ public function getUsername() { - return $this->username; + return $this->container['username']; } /** @@ -228,17 +215,18 @@ class User implements ArrayAccess */ public function setUsername($username) { - - $this->username = $username; + $this->container['username'] = $username; + return $this; } + /** * Gets first_name * @return string */ public function getFirstName() { - return $this->first_name; + return $this->container['first_name']; } /** @@ -248,17 +236,18 @@ class User implements ArrayAccess */ public function setFirstName($first_name) { - - $this->first_name = $first_name; + $this->container['first_name'] = $first_name; + return $this; } + /** * Gets last_name * @return string */ public function getLastName() { - return $this->last_name; + return $this->container['last_name']; } /** @@ -268,17 +257,18 @@ class User implements ArrayAccess */ public function setLastName($last_name) { - - $this->last_name = $last_name; + $this->container['last_name'] = $last_name; + return $this; } + /** * Gets email * @return string */ public function getEmail() { - return $this->email; + return $this->container['email']; } /** @@ -288,17 +278,18 @@ class User implements ArrayAccess */ public function setEmail($email) { - - $this->email = $email; + $this->container['email'] = $email; + return $this; } + /** * Gets password * @return string */ public function getPassword() { - return $this->password; + return $this->container['password']; } /** @@ -308,17 +299,18 @@ class User implements ArrayAccess */ public function setPassword($password) { - - $this->password = $password; + $this->container['password'] = $password; + return $this; } + /** * Gets phone * @return string */ public function getPhone() { - return $this->phone; + return $this->container['phone']; } /** @@ -328,17 +320,18 @@ class User implements ArrayAccess */ public function setPhone($phone) { - - $this->phone = $phone; + $this->container['phone'] = $phone; + return $this; } + /** * Gets user_status * @return int */ public function getUserStatus() { - return $this->user_status; + return $this->container['user_status']; } /** @@ -348,8 +341,8 @@ class User implements ArrayAccess */ public function setUserStatus($user_status) { - - $this->user_status = $user_status; + $this->container['user_status'] = $user_status; + return $this; } /** @@ -359,7 +352,7 @@ class User implements ArrayAccess */ public function offsetExists($offset) { - return isset($this->$offset); + return isset($this->container[$offset]); } /** @@ -369,7 +362,7 @@ class User implements ArrayAccess */ public function offsetGet($offset) { - return $this->$offset; + return isset($this->container[$offset]) ? $this->container[$offset] : null; } /** @@ -380,7 +373,11 @@ class User implements ArrayAccess */ public function offsetSet($offset, $value) { - $this->$offset = $value; + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } } /** @@ -390,7 +387,7 @@ class User implements ArrayAccess */ public function offsetUnset($offset) { - unset($this->$offset); + unset($this->container[$offset]); } /** diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Tests/FakeApiTest.php b/samples/client/petstore/php/SwaggerClient-php/test/Api/FakeApiTest.php similarity index 94% rename from samples/client/petstore/php/SwaggerClient-php/lib/Tests/FakeApiTest.php rename to samples/client/petstore/php/SwaggerClient-php/test/Api/FakeApiTest.php index 47b8fa21b68..dc599fbe5d7 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Tests/FakeApiTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/test/Api/FakeApiTest.php @@ -67,7 +67,7 @@ class FakeApiTest extends \PHPUnit_Framework_TestCase /** * Test case for testEndpointParameters * - * Fake endpoint for testing various parameters + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 * */ public function test_testEndpointParameters() { diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Tests/PetApiTest.php b/samples/client/petstore/php/SwaggerClient-php/test/Api/PetApiTest.php similarity index 100% rename from samples/client/petstore/php/SwaggerClient-php/lib/Tests/PetApiTest.php rename to samples/client/petstore/php/SwaggerClient-php/test/Api/PetApiTest.php diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Tests/StoreApiTest.php b/samples/client/petstore/php/SwaggerClient-php/test/Api/StoreApiTest.php similarity index 100% rename from samples/client/petstore/php/SwaggerClient-php/lib/Tests/StoreApiTest.php rename to samples/client/petstore/php/SwaggerClient-php/test/Api/StoreApiTest.php diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Tests/UserApiTest.php b/samples/client/petstore/php/SwaggerClient-php/test/Api/UserApiTest.php similarity index 100% rename from samples/client/petstore/php/SwaggerClient-php/lib/Tests/UserApiTest.php rename to samples/client/petstore/php/SwaggerClient-php/test/Api/UserApiTest.php diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Tests/InlineResponse200Test.php b/samples/client/petstore/php/SwaggerClient-php/test/Model/AnimalFarmTest.php similarity index 88% rename from samples/client/petstore/php/SwaggerClient-php/lib/Tests/InlineResponse200Test.php rename to samples/client/petstore/php/SwaggerClient-php/test/Model/AnimalFarmTest.php index 1bd1c822700..f154716c064 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Tests/InlineResponse200Test.php +++ b/samples/client/petstore/php/SwaggerClient-php/test/Model/AnimalFarmTest.php @@ -1,6 +1,6 @@ assertSame('Dog', $new_dog->getClassName()); } + // test if ArrayAccess interface works + public function testArrayStuff() + { + // create an AnimalFarm which is an object implementing the + // ArrayAccess interface + $farm = new Swagger\Client\Model\AnimalFarm(); + + // add some animals to the farm to make sure the ArrayAccess + // interface works + $farm[] = new Swagger\Client\Model\Dog(); + $farm[] = new Swagger\Client\Model\Cat(); + $farm[] = new Swagger\Client\Model\Animal(); + + // assert we can look up the animals in the farm by array + // indices (let's try a random order) + $this->assertInstanceOf('Swagger\Client\Model\Cat', $farm[1]); + $this->assertInstanceOf('Swagger\Client\Model\Dog', $farm[0]); + $this->assertInstanceOf('Swagger\Client\Model\Animal', $farm[2]); + + // let's try to `foreach` the animals in the farm and let's + // try to use the objects we loop through + foreach ($farm as $animal) { + $this->assertContains($animal->getClassName(), array('Dog', 'Cat', 'Animal')); + $this->assertInstanceOf('Swagger\Client\Model\Animal', $animal); + } + } + + // test if default values works + public function testDefaultValues() + { + // add some animals to the farm to make sure the ArrayAccess + // interface works + $dog = new Swagger\Client\Model\Dog(); + $animal = new Swagger\Client\Model\Animal(); + + // assert we can look up the animals in the farm by array + // indices (let's try a random order) + $this->assertSame('red', $dog->getColor()); + $this->assertSame('red', $animal->getColor()); + } + } ?> diff --git a/samples/client/petstore/python/README.md b/samples/client/petstore/python/README.md index 6640785fae9..3cdf5029787 100644 --- a/samples/client/petstore/python/README.md +++ b/samples/client/petstore/python/README.md @@ -5,7 +5,7 @@ This Python package is automatically generated by the [Swagger Codegen](https:// - API version: 1.0.0 - Package version: 1.0.0 -- Build date: 2016-04-27T22:50:21.115+01:00 +- Build date: 2016-05-09T01:08:25.311+01:00 - Build package: class io.swagger.codegen.languages.PythonClientCodegen ## Requirements. @@ -18,9 +18,9 @@ Python 2.7 and 3.4+ If the python package is hosted on Github, you can install directly from Github ```sh -pip install git+https://github.com/YOUR_GIT_USR_ID/YOUR_GIT_REPO_ID.git +pip install git+https://github.com/GIT_USER_ID/GIT_REPO_ID.git ``` -(you may need to run `pip` with root permission: `sudo pip install git+https://github.com/YOUR_GIT_USR_ID/YOUR_GIT_REPO_ID.git`) +(you may need to run `pip` with root permission: `sudo pip install git+https://github.com/GIT_USER_ID/GIT_REPO_ID.git`) Then import the package: ```python diff --git a/samples/client/petstore/python/docs/PetApi.md b/samples/client/petstore/python/docs/PetApi.md index 3b14d2b8062..fb69778f611 100644 --- a/samples/client/petstore/python/docs/PetApi.md +++ b/samples/client/petstore/python/docs/PetApi.md @@ -230,8 +230,8 @@ from pprint import pprint # Configure API key authorization: api_key swagger_client.configuration.api_key['api_key'] = 'YOUR_API_KEY' -# Uncomment below to setup prefix (e.g. BEARER) for API key, if needed -# swagger_client.configuration.api_key_prefix['api_key'] = 'BEARER' +# Uncomment below to setup prefix (e.g. Bearer) for API key, if needed +# swagger_client.configuration.api_key_prefix['api_key'] = 'Bearer' # create an instance of the API class api_instance = swagger_client.PetApi() diff --git a/samples/client/petstore/python/docs/StoreApi.md b/samples/client/petstore/python/docs/StoreApi.md index 04b4300d58d..537009bde52 100644 --- a/samples/client/petstore/python/docs/StoreApi.md +++ b/samples/client/petstore/python/docs/StoreApi.md @@ -72,8 +72,8 @@ from pprint import pprint # Configure API key authorization: api_key swagger_client.configuration.api_key['api_key'] = 'YOUR_API_KEY' -# Uncomment below to setup prefix (e.g. BEARER) for API key, if needed -# swagger_client.configuration.api_key_prefix['api_key'] = 'BEARER' +# Uncomment below to setup prefix (e.g. Bearer) for API key, if needed +# swagger_client.configuration.api_key_prefix['api_key'] = 'Bearer' # create an instance of the API class api_instance = swagger_client.StoreApi() diff --git a/samples/client/petstore/python/git_push.sh b/samples/client/petstore/python/git_push.sh index 1a36388db02..ed374619b13 100644 --- a/samples/client/petstore/python/git_push.sh +++ b/samples/client/petstore/python/git_push.sh @@ -8,12 +8,12 @@ git_repo_id=$2 release_note=$3 if [ "$git_user_id" = "" ]; then - git_user_id="YOUR_GIT_USR_ID" + git_user_id="GIT_USER_ID" echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" fi if [ "$git_repo_id" = "" ]; then - git_repo_id="YOUR_GIT_REPO_ID" + git_repo_id="GIT_REPO_ID" echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" fi diff --git a/samples/client/petstore/python/swagger_client/apis/fake_api.py b/samples/client/petstore/python/swagger_client/apis/fake_api.py index 2b183794ef1..5d3903b2d21 100644 --- a/samples/client/petstore/python/swagger_client/apis/fake_api.py +++ b/samples/client/petstore/python/swagger_client/apis/fake_api.py @@ -21,6 +21,7 @@ from __future__ import absolute_import import sys import os +import re # python 2 and python 3 compatibility library from six import iteritems @@ -103,6 +104,31 @@ class FakeApi(object): if ('byte' not in params) or (params['byte'] is None): raise ValueError("Missing the required parameter `byte` when calling `test_endpoint_parameters`") + if 'number' in params and params['number'] > 543.2: + raise ValueError("Invalid value for parameter `number` when calling `test_endpoint_parameters`, must be a value less than or equal to `543.2`") + if 'number' in params and params['number'] < 32.1: + raise ValueError("Invalid value for parameter `number` when calling `test_endpoint_parameters`, must be a value greater than or equal to `32.1`") + if 'double' in params and params['double'] > 123.4: + raise ValueError("Invalid value for parameter `double` when calling `test_endpoint_parameters`, must be a value less than or equal to `123.4`") + if 'double' in params and params['double'] < 67.8: + raise ValueError("Invalid value for parameter `double` when calling `test_endpoint_parameters`, must be a value greater than or equal to `67.8`") + if 'string' in params and not re.search('[a-z]', params['string'], flags=re.IGNORECASE): + raise ValueError("Invalid value for parameter `string` when calling `test_endpoint_parameters`, must conform to the pattern `/[a-z]/i`") + if 'integer' in params and params['integer'] > 100.0: + raise ValueError("Invalid value for parameter `integer` when calling `test_endpoint_parameters`, must be a value less than or equal to `100.0`") + if 'integer' in params and params['integer'] < 10.0: + raise ValueError("Invalid value for parameter `integer` when calling `test_endpoint_parameters`, must be a value greater than or equal to `10.0`") + if 'int32' in params and params['int32'] > 200.0: + raise ValueError("Invalid value for parameter `int32` when calling `test_endpoint_parameters`, must be a value less than or equal to `200.0`") + if 'int32' in params and params['int32'] < 20.0: + raise ValueError("Invalid value for parameter `int32` when calling `test_endpoint_parameters`, must be a value greater than or equal to `20.0`") + if 'float' in params and params['float'] > 987.6: + raise ValueError("Invalid value for parameter `float` when calling `test_endpoint_parameters`, must be a value less than or equal to `987.6`") + if 'password' in params and len(params['password']) > 64: + raise ValueError("Invalid value for parameter `password` when calling `test_endpoint_parameters`, length must be less than or equal to `64`") + if 'password' in params and len(params['password']) < 10: + raise ValueError("Invalid value for parameter `password` when calling `test_endpoint_parameters`, length must be greater than or equal to `10`") + resource_path = '/fake'.replace('{format}', 'json') path_params = {} diff --git a/samples/client/petstore/python/swagger_client/apis/pet_api.py b/samples/client/petstore/python/swagger_client/apis/pet_api.py index cab854e3019..3b6d9ba82fe 100644 --- a/samples/client/petstore/python/swagger_client/apis/pet_api.py +++ b/samples/client/petstore/python/swagger_client/apis/pet_api.py @@ -21,6 +21,7 @@ from __future__ import absolute_import import sys import os +import re # python 2 and python 3 compatibility library from six import iteritems @@ -83,6 +84,7 @@ class PetApi(object): if ('body' not in params) or (params['body'] is None): raise ValueError("Missing the required parameter `body` when calling `add_pet`") + resource_path = '/pet'.replace('{format}', 'json') path_params = {} @@ -161,6 +163,7 @@ class PetApi(object): if ('pet_id' not in params) or (params['pet_id'] is None): raise ValueError("Missing the required parameter `pet_id` when calling `delete_pet`") + resource_path = '/pet/{petId}'.replace('{format}', 'json') path_params = {} if 'pet_id' in params: @@ -240,6 +243,7 @@ class PetApi(object): if ('status' not in params) or (params['status'] is None): raise ValueError("Missing the required parameter `status` when calling `find_pets_by_status`") + resource_path = '/pet/findByStatus'.replace('{format}', 'json') path_params = {} @@ -317,6 +321,7 @@ class PetApi(object): if ('tags' not in params) or (params['tags'] is None): raise ValueError("Missing the required parameter `tags` when calling `find_pets_by_tags`") + resource_path = '/pet/findByTags'.replace('{format}', 'json') path_params = {} @@ -394,6 +399,7 @@ class PetApi(object): if ('pet_id' not in params) or (params['pet_id'] is None): raise ValueError("Missing the required parameter `pet_id` when calling `get_pet_by_id`") + resource_path = '/pet/{petId}'.replace('{format}', 'json') path_params = {} if 'pet_id' in params: @@ -471,6 +477,7 @@ class PetApi(object): if ('body' not in params) or (params['body'] is None): raise ValueError("Missing the required parameter `body` when calling `update_pet`") + resource_path = '/pet'.replace('{format}', 'json') path_params = {} @@ -550,6 +557,7 @@ class PetApi(object): if ('pet_id' not in params) or (params['pet_id'] is None): raise ValueError("Missing the required parameter `pet_id` when calling `update_pet_with_form`") + resource_path = '/pet/{petId}'.replace('{format}', 'json') path_params = {} if 'pet_id' in params: @@ -633,6 +641,7 @@ class PetApi(object): if ('pet_id' not in params) or (params['pet_id'] is None): raise ValueError("Missing the required parameter `pet_id` when calling `upload_file`") + resource_path = '/pet/{petId}/uploadImage'.replace('{format}', 'json') path_params = {} if 'pet_id' in params: diff --git a/samples/client/petstore/python/swagger_client/apis/store_api.py b/samples/client/petstore/python/swagger_client/apis/store_api.py index 9391a6a6096..352ab7eae63 100644 --- a/samples/client/petstore/python/swagger_client/apis/store_api.py +++ b/samples/client/petstore/python/swagger_client/apis/store_api.py @@ -21,6 +21,7 @@ from __future__ import absolute_import import sys import os +import re # python 2 and python 3 compatibility library from six import iteritems @@ -83,6 +84,9 @@ class StoreApi(object): if ('order_id' not in params) or (params['order_id'] is None): raise ValueError("Missing the required parameter `order_id` when calling `delete_order`") + if 'order_id' in params and params['order_id'] < 1.0: + raise ValueError("Invalid value for parameter `order_id` when calling `delete_order`, must be a value greater than or equal to `1.0`") + resource_path = '/store/order/{orderId}'.replace('{format}', 'json') path_params = {} if 'order_id' in params: @@ -156,6 +160,7 @@ class StoreApi(object): del params['kwargs'] + resource_path = '/store/inventory'.replace('{format}', 'json') path_params = {} @@ -231,6 +236,11 @@ class StoreApi(object): if ('order_id' not in params) or (params['order_id'] is None): raise ValueError("Missing the required parameter `order_id` when calling `get_order_by_id`") + if 'order_id' in params and params['order_id'] > 5.0: + raise ValueError("Invalid value for parameter `order_id` when calling `get_order_by_id`, must be a value less than or equal to `5.0`") + if 'order_id' in params and params['order_id'] < 1.0: + raise ValueError("Invalid value for parameter `order_id` when calling `get_order_by_id`, must be a value greater than or equal to `1.0`") + resource_path = '/store/order/{orderId}'.replace('{format}', 'json') path_params = {} if 'order_id' in params: @@ -308,6 +318,7 @@ class StoreApi(object): if ('body' not in params) or (params['body'] is None): raise ValueError("Missing the required parameter `body` when calling `place_order`") + resource_path = '/store/order'.replace('{format}', 'json') path_params = {} diff --git a/samples/client/petstore/python/swagger_client/apis/user_api.py b/samples/client/petstore/python/swagger_client/apis/user_api.py index 733a950f393..d5df6f0f541 100644 --- a/samples/client/petstore/python/swagger_client/apis/user_api.py +++ b/samples/client/petstore/python/swagger_client/apis/user_api.py @@ -21,6 +21,7 @@ from __future__ import absolute_import import sys import os +import re # python 2 and python 3 compatibility library from six import iteritems @@ -83,6 +84,7 @@ class UserApi(object): if ('body' not in params) or (params['body'] is None): raise ValueError("Missing the required parameter `body` when calling `create_user`") + resource_path = '/user'.replace('{format}', 'json') path_params = {} @@ -160,6 +162,7 @@ class UserApi(object): if ('body' not in params) or (params['body'] is None): raise ValueError("Missing the required parameter `body` when calling `create_users_with_array_input`") + resource_path = '/user/createWithArray'.replace('{format}', 'json') path_params = {} @@ -237,6 +240,7 @@ class UserApi(object): if ('body' not in params) or (params['body'] is None): raise ValueError("Missing the required parameter `body` when calling `create_users_with_list_input`") + resource_path = '/user/createWithList'.replace('{format}', 'json') path_params = {} @@ -314,6 +318,7 @@ class UserApi(object): if ('username' not in params) or (params['username'] is None): raise ValueError("Missing the required parameter `username` when calling `delete_user`") + resource_path = '/user/{username}'.replace('{format}', 'json') path_params = {} if 'username' in params: @@ -391,6 +396,7 @@ class UserApi(object): if ('username' not in params) or (params['username'] is None): raise ValueError("Missing the required parameter `username` when calling `get_user_by_name`") + resource_path = '/user/{username}'.replace('{format}', 'json') path_params = {} if 'username' in params: @@ -472,6 +478,7 @@ class UserApi(object): if ('password' not in params) or (params['password'] is None): raise ValueError("Missing the required parameter `password` when calling `login_user`") + resource_path = '/user/login'.replace('{format}', 'json') path_params = {} @@ -547,6 +554,7 @@ class UserApi(object): del params['kwargs'] + resource_path = '/user/logout'.replace('{format}', 'json') path_params = {} @@ -626,6 +634,7 @@ class UserApi(object): if ('body' not in params) or (params['body'] is None): raise ValueError("Missing the required parameter `body` when calling `update_user`") + resource_path = '/user/{username}'.replace('{format}', 'json') path_params = {} if 'username' in params: diff --git a/samples/client/petstore/python/swagger_client/models/animal.py b/samples/client/petstore/python/swagger_client/models/animal.py index 762e3df5b37..0ae8f2b4bde 100644 --- a/samples/client/petstore/python/swagger_client/models/animal.py +++ b/samples/client/petstore/python/swagger_client/models/animal.py @@ -20,6 +20,7 @@ Copyright 2016 SmartBear Software from pprint import pformat from six import iteritems +import re class Animal(object): @@ -66,6 +67,7 @@ class Animal(object): :param class_name: The class_name of this Animal. :type: str """ + self._class_name = class_name def to_dict(self): diff --git a/samples/client/petstore/python/swagger_client/models/api_response.py b/samples/client/petstore/python/swagger_client/models/api_response.py index c49bde7fbc6..918b4a98223 100644 --- a/samples/client/petstore/python/swagger_client/models/api_response.py +++ b/samples/client/petstore/python/swagger_client/models/api_response.py @@ -20,6 +20,7 @@ Copyright 2016 SmartBear Software from pprint import pformat from six import iteritems +import re class ApiResponse(object): @@ -72,6 +73,7 @@ class ApiResponse(object): :param code: The code of this ApiResponse. :type: int """ + self._code = code @property @@ -94,6 +96,7 @@ class ApiResponse(object): :param type: The type of this ApiResponse. :type: str """ + self._type = type @property @@ -116,6 +119,7 @@ class ApiResponse(object): :param message: The message of this ApiResponse. :type: str """ + self._message = message def to_dict(self): diff --git a/samples/client/petstore/python/swagger_client/models/cat.py b/samples/client/petstore/python/swagger_client/models/cat.py index 4744fc4821c..fd2e5e4fce4 100644 --- a/samples/client/petstore/python/swagger_client/models/cat.py +++ b/samples/client/petstore/python/swagger_client/models/cat.py @@ -20,6 +20,7 @@ Copyright 2016 SmartBear Software from pprint import pformat from six import iteritems +import re class Cat(object): @@ -69,6 +70,7 @@ class Cat(object): :param class_name: The class_name of this Cat. :type: str """ + self._class_name = class_name @property @@ -91,6 +93,7 @@ class Cat(object): :param declawed: The declawed of this Cat. :type: bool """ + self._declawed = declawed def to_dict(self): diff --git a/samples/client/petstore/python/swagger_client/models/category.py b/samples/client/petstore/python/swagger_client/models/category.py index b8d540c51bd..e4f4a993cab 100644 --- a/samples/client/petstore/python/swagger_client/models/category.py +++ b/samples/client/petstore/python/swagger_client/models/category.py @@ -20,6 +20,7 @@ Copyright 2016 SmartBear Software from pprint import pformat from six import iteritems +import re class Category(object): @@ -69,6 +70,7 @@ class Category(object): :param id: The id of this Category. :type: int """ + self._id = id @property @@ -91,6 +93,7 @@ class Category(object): :param name: The name of this Category. :type: str """ + self._name = name def to_dict(self): diff --git a/samples/client/petstore/python/swagger_client/models/dog.py b/samples/client/petstore/python/swagger_client/models/dog.py index 3885dd314ef..ac25ef01807 100644 --- a/samples/client/petstore/python/swagger_client/models/dog.py +++ b/samples/client/petstore/python/swagger_client/models/dog.py @@ -20,6 +20,7 @@ Copyright 2016 SmartBear Software from pprint import pformat from six import iteritems +import re class Dog(object): @@ -69,6 +70,7 @@ class Dog(object): :param class_name: The class_name of this Dog. :type: str """ + self._class_name = class_name @property @@ -91,6 +93,7 @@ class Dog(object): :param breed: The breed of this Dog. :type: str """ + self._breed = breed def to_dict(self): diff --git a/samples/client/petstore/python/swagger_client/models/format_test.py b/samples/client/petstore/python/swagger_client/models/format_test.py index 28f348edf04..7fce3351dd4 100644 --- a/samples/client/petstore/python/swagger_client/models/format_test.py +++ b/samples/client/petstore/python/swagger_client/models/format_test.py @@ -20,6 +20,7 @@ Copyright 2016 SmartBear Software from pprint import pformat from six import iteritems +import re class FormatTest(object): @@ -102,6 +103,14 @@ class FormatTest(object): :param integer: The integer of this FormatTest. :type: int """ + + if not integer: + raise ValueError("Invalid value for `integer`, must not be `None`") + if integer > 100.0: + raise ValueError("Invalid value for `integer`, must be a value less than or equal to `100.0`") + if integer < 10.0: + raise ValueError("Invalid value for `integer`, must be a value greater than or equal to `10.0`") + self._integer = integer @property @@ -124,6 +133,14 @@ class FormatTest(object): :param int32: The int32 of this FormatTest. :type: int """ + + if not int32: + raise ValueError("Invalid value for `int32`, must not be `None`") + if int32 > 200.0: + raise ValueError("Invalid value for `int32`, must be a value less than or equal to `200.0`") + if int32 < 20.0: + raise ValueError("Invalid value for `int32`, must be a value greater than or equal to `20.0`") + self._int32 = int32 @property @@ -146,6 +163,7 @@ class FormatTest(object): :param int64: The int64 of this FormatTest. :type: int """ + self._int64 = int64 @property @@ -168,6 +186,14 @@ class FormatTest(object): :param number: The number of this FormatTest. :type: float """ + + if not number: + raise ValueError("Invalid value for `number`, must not be `None`") + if number > 543.2: + raise ValueError("Invalid value for `number`, must be a value less than or equal to `543.2`") + if number < 32.1: + raise ValueError("Invalid value for `number`, must be a value greater than or equal to `32.1`") + self._number = number @property @@ -190,6 +216,14 @@ class FormatTest(object): :param float: The float of this FormatTest. :type: float """ + + if not float: + raise ValueError("Invalid value for `float`, must not be `None`") + if float > 987.6: + raise ValueError("Invalid value for `float`, must be a value less than or equal to `987.6`") + if float < 54.3: + raise ValueError("Invalid value for `float`, must be a value greater than or equal to `54.3`") + self._float = float @property @@ -212,6 +246,14 @@ class FormatTest(object): :param double: The double of this FormatTest. :type: float """ + + if not double: + raise ValueError("Invalid value for `double`, must not be `None`") + if double > 123.4: + raise ValueError("Invalid value for `double`, must be a value less than or equal to `123.4`") + if double < 67.8: + raise ValueError("Invalid value for `double`, must be a value greater than or equal to `67.8`") + self._double = double @property @@ -234,6 +276,12 @@ class FormatTest(object): :param string: The string of this FormatTest. :type: str """ + + if not string: + raise ValueError("Invalid value for `string`, must not be `None`") + if not re.search('[a-z]', string, flags=re.IGNORECASE): + raise ValueError("Invalid value for `string`, must be a follow pattern or equal to `/[a-z]/i`") + self._string = string @property @@ -256,6 +304,7 @@ class FormatTest(object): :param byte: The byte of this FormatTest. :type: str """ + self._byte = byte @property @@ -278,6 +327,7 @@ class FormatTest(object): :param binary: The binary of this FormatTest. :type: str """ + self._binary = binary @property @@ -300,6 +350,7 @@ class FormatTest(object): :param date: The date of this FormatTest. :type: date """ + self._date = date @property @@ -322,6 +373,7 @@ class FormatTest(object): :param date_time: The date_time of this FormatTest. :type: datetime """ + self._date_time = date_time @property @@ -344,6 +396,7 @@ class FormatTest(object): :param uuid: The uuid of this FormatTest. :type: str """ + self._uuid = uuid @property @@ -366,6 +419,14 @@ class FormatTest(object): :param password: The password of this FormatTest. :type: str """ + + if not password: + raise ValueError("Invalid value for `password`, must not be `None`") + if len(password) > 64: + raise ValueError("Invalid value for `password`, length must be less than `64`") + if len(password) < 10: + raise ValueError("Invalid value for `password`, length must be greater than or equal to `10`") + self._password = password def to_dict(self): diff --git a/samples/client/petstore/python/swagger_client/models/model_200_response.py b/samples/client/petstore/python/swagger_client/models/model_200_response.py index 681de963e6e..f99847cbdd5 100644 --- a/samples/client/petstore/python/swagger_client/models/model_200_response.py +++ b/samples/client/petstore/python/swagger_client/models/model_200_response.py @@ -20,6 +20,7 @@ Copyright 2016 SmartBear Software from pprint import pformat from six import iteritems +import re class Model200Response(object): @@ -66,6 +67,7 @@ class Model200Response(object): :param name: The name of this Model200Response. :type: int """ + self._name = name def to_dict(self): diff --git a/samples/client/petstore/python/swagger_client/models/model_return.py b/samples/client/petstore/python/swagger_client/models/model_return.py index 75b46259d6f..8228f41943c 100644 --- a/samples/client/petstore/python/swagger_client/models/model_return.py +++ b/samples/client/petstore/python/swagger_client/models/model_return.py @@ -20,6 +20,7 @@ Copyright 2016 SmartBear Software from pprint import pformat from six import iteritems +import re class ModelReturn(object): @@ -66,6 +67,7 @@ class ModelReturn(object): :param _return: The _return of this ModelReturn. :type: int """ + self.__return = _return def to_dict(self): diff --git a/samples/client/petstore/python/swagger_client/models/name.py b/samples/client/petstore/python/swagger_client/models/name.py index 4fbf1a03211..51345d131ff 100644 --- a/samples/client/petstore/python/swagger_client/models/name.py +++ b/samples/client/petstore/python/swagger_client/models/name.py @@ -20,6 +20,7 @@ Copyright 2016 SmartBear Software from pprint import pformat from six import iteritems +import re class Name(object): @@ -72,6 +73,7 @@ class Name(object): :param name: The name of this Name. :type: int """ + self._name = name @property @@ -94,6 +96,7 @@ class Name(object): :param snake_case: The snake_case of this Name. :type: int """ + self._snake_case = snake_case @property @@ -116,6 +119,7 @@ class Name(object): :param _property: The _property of this Name. :type: str """ + self.__property = _property def to_dict(self): diff --git a/samples/client/petstore/python/swagger_client/models/order.py b/samples/client/petstore/python/swagger_client/models/order.py index 8fe90765e03..07f2c627d91 100644 --- a/samples/client/petstore/python/swagger_client/models/order.py +++ b/samples/client/petstore/python/swagger_client/models/order.py @@ -20,6 +20,7 @@ Copyright 2016 SmartBear Software from pprint import pformat from six import iteritems +import re class Order(object): @@ -81,6 +82,7 @@ class Order(object): :param id: The id of this Order. :type: int """ + self._id = id @property @@ -103,6 +105,7 @@ class Order(object): :param pet_id: The pet_id of this Order. :type: int """ + self._pet_id = pet_id @property @@ -125,6 +128,7 @@ class Order(object): :param quantity: The quantity of this Order. :type: int """ + self._quantity = quantity @property @@ -147,6 +151,7 @@ class Order(object): :param ship_date: The ship_date of this Order. :type: datetime """ + self._ship_date = ship_date @property @@ -175,6 +180,7 @@ class Order(object): "Invalid value for `status`, must be one of {0}" .format(allowed_values) ) + self._status = status @property @@ -197,6 +203,7 @@ class Order(object): :param complete: The complete of this Order. :type: bool """ + self._complete = complete def to_dict(self): diff --git a/samples/client/petstore/python/swagger_client/models/pet.py b/samples/client/petstore/python/swagger_client/models/pet.py index dfa614b1e9b..60f762238f3 100644 --- a/samples/client/petstore/python/swagger_client/models/pet.py +++ b/samples/client/petstore/python/swagger_client/models/pet.py @@ -20,6 +20,7 @@ Copyright 2016 SmartBear Software from pprint import pformat from six import iteritems +import re class Pet(object): @@ -81,6 +82,7 @@ class Pet(object): :param id: The id of this Pet. :type: int """ + self._id = id @property @@ -103,6 +105,7 @@ class Pet(object): :param category: The category of this Pet. :type: Category """ + self._category = category @property @@ -125,6 +128,7 @@ class Pet(object): :param name: The name of this Pet. :type: str """ + self._name = name @property @@ -147,6 +151,7 @@ class Pet(object): :param photo_urls: The photo_urls of this Pet. :type: list[str] """ + self._photo_urls = photo_urls @property @@ -169,6 +174,7 @@ class Pet(object): :param tags: The tags of this Pet. :type: list[Tag] """ + self._tags = tags @property @@ -197,6 +203,7 @@ class Pet(object): "Invalid value for `status`, must be one of {0}" .format(allowed_values) ) + self._status = status def to_dict(self): diff --git a/samples/client/petstore/python/swagger_client/models/special_model_name.py b/samples/client/petstore/python/swagger_client/models/special_model_name.py index 191798d7d9a..3e45c0e4496 100644 --- a/samples/client/petstore/python/swagger_client/models/special_model_name.py +++ b/samples/client/petstore/python/swagger_client/models/special_model_name.py @@ -20,6 +20,7 @@ Copyright 2016 SmartBear Software from pprint import pformat from six import iteritems +import re class SpecialModelName(object): @@ -66,6 +67,7 @@ class SpecialModelName(object): :param special_property_name: The special_property_name of this SpecialModelName. :type: int """ + self._special_property_name = special_property_name def to_dict(self): diff --git a/samples/client/petstore/python/swagger_client/models/tag.py b/samples/client/petstore/python/swagger_client/models/tag.py index 50f829d65e3..f09a4c36df3 100644 --- a/samples/client/petstore/python/swagger_client/models/tag.py +++ b/samples/client/petstore/python/swagger_client/models/tag.py @@ -20,6 +20,7 @@ Copyright 2016 SmartBear Software from pprint import pformat from six import iteritems +import re class Tag(object): @@ -69,6 +70,7 @@ class Tag(object): :param id: The id of this Tag. :type: int """ + self._id = id @property @@ -91,6 +93,7 @@ class Tag(object): :param name: The name of this Tag. :type: str """ + self._name = name def to_dict(self): diff --git a/samples/client/petstore/python/swagger_client/models/user.py b/samples/client/petstore/python/swagger_client/models/user.py index fd6d16824b3..87d132a5037 100644 --- a/samples/client/petstore/python/swagger_client/models/user.py +++ b/samples/client/petstore/python/swagger_client/models/user.py @@ -20,6 +20,7 @@ Copyright 2016 SmartBear Software from pprint import pformat from six import iteritems +import re class User(object): @@ -87,6 +88,7 @@ class User(object): :param id: The id of this User. :type: int """ + self._id = id @property @@ -109,6 +111,7 @@ class User(object): :param username: The username of this User. :type: str """ + self._username = username @property @@ -131,6 +134,7 @@ class User(object): :param first_name: The first_name of this User. :type: str """ + self._first_name = first_name @property @@ -153,6 +157,7 @@ class User(object): :param last_name: The last_name of this User. :type: str """ + self._last_name = last_name @property @@ -175,6 +180,7 @@ class User(object): :param email: The email of this User. :type: str """ + self._email = email @property @@ -197,6 +203,7 @@ class User(object): :param password: The password of this User. :type: str """ + self._password = password @property @@ -219,6 +226,7 @@ class User(object): :param phone: The phone of this User. :type: str """ + self._phone = phone @property @@ -241,6 +249,7 @@ class User(object): :param user_status: The user_status of this User. :type: int """ + self._user_status = user_status def to_dict(self): diff --git a/samples/client/petstore/ruby/.rspec b/samples/client/petstore/ruby/.rspec new file mode 100644 index 00000000000..83e16f80447 --- /dev/null +++ b/samples/client/petstore/ruby/.rspec @@ -0,0 +1,2 @@ +--color +--require spec_helper diff --git a/samples/client/petstore/ruby/README.md b/samples/client/petstore/ruby/README.md index 62b0d52dc7b..7aa7d19b003 100644 --- a/samples/client/petstore/ruby/README.md +++ b/samples/client/petstore/ruby/README.md @@ -2,13 +2,13 @@ Petstore - the Ruby gem for the Swagger Petstore -This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ This SDK is automatically generated by the [Swagger Codegen](https://github.com/swagger-api/swagger-codegen) project: - API version: 1.0.0 - Package version: 1.0.0 -- Build date: 2016-05-02T21:47:16.723+08:00 +- Build date: 2016-05-11T16:13:11.464+08:00 - Build package: class io.swagger.codegen.languages.RubyClientCodegen ## Installation @@ -77,7 +77,7 @@ opts = { } begin - #Fake endpoint for testing various parameters + #Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 api_instance.test_endpoint_parameters(number, double, string, byte, opts) rescue Petstore::ApiError => e puts "Exception when calling FakeApi->test_endpoint_parameters: #{e}" @@ -91,7 +91,7 @@ All URIs are relative to *http://petstore.swagger.io/v2* Class | Method | HTTP request | Description ------------ | ------------- | ------------- | ------------- -*Petstore::FakeApi* | [**test_endpoint_parameters**](docs/FakeApi.md#test_endpoint_parameters) | **POST** /fake | Fake endpoint for testing various parameters +*Petstore::FakeApi* | [**test_endpoint_parameters**](docs/FakeApi.md#test_endpoint_parameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 *Petstore::PetApi* | [**add_pet**](docs/PetApi.md#add_pet) | **POST** /pet | Add a new pet to the store *Petstore::PetApi* | [**delete_pet**](docs/PetApi.md#delete_pet) | **DELETE** /pet/{petId} | Deletes a pet *Petstore::PetApi* | [**find_pets_by_status**](docs/PetApi.md#find_pets_by_status) | **GET** /pet/findByStatus | Finds Pets by status @@ -117,10 +117,13 @@ Class | Method | HTTP request | Description ## Documentation for Models - [Petstore::Animal](docs/Animal.md) + - [Petstore::AnimalFarm](docs/AnimalFarm.md) - [Petstore::ApiResponse](docs/ApiResponse.md) - [Petstore::Cat](docs/Cat.md) - [Petstore::Category](docs/Category.md) - [Petstore::Dog](docs/Dog.md) + - [Petstore::EnumClass](docs/EnumClass.md) + - [Petstore::EnumTest](docs/EnumTest.md) - [Petstore::FormatTest](docs/FormatTest.md) - [Petstore::Model200Response](docs/Model200Response.md) - [Petstore::ModelReturn](docs/ModelReturn.md) diff --git a/samples/client/petstore/ruby/docs/Animal.md b/samples/client/petstore/ruby/docs/Animal.md index 0e262c78726..5ff8837de15 100644 --- a/samples/client/petstore/ruby/docs/Animal.md +++ b/samples/client/petstore/ruby/docs/Animal.md @@ -4,5 +4,6 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **class_name** | **String** | | +**color** | **String** | | [optional] [default to "red"] diff --git a/samples/client/petstore/ruby/docs/AnimalFarm.md b/samples/client/petstore/ruby/docs/AnimalFarm.md new file mode 100644 index 00000000000..30d704dc7d1 --- /dev/null +++ b/samples/client/petstore/ruby/docs/AnimalFarm.md @@ -0,0 +1,7 @@ +# Petstore::AnimalFarm + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + + diff --git a/samples/client/petstore/ruby/docs/Cat.md b/samples/client/petstore/ruby/docs/Cat.md index 6b7dfb710df..5c13d986ece 100644 --- a/samples/client/petstore/ruby/docs/Cat.md +++ b/samples/client/petstore/ruby/docs/Cat.md @@ -4,6 +4,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **class_name** | **String** | | +**color** | **String** | | [optional] [default to "red"] **declawed** | **BOOLEAN** | | [optional] diff --git a/samples/client/petstore/ruby/docs/Dog.md b/samples/client/petstore/ruby/docs/Dog.md index 7af6f549d5d..9224ad05310 100644 --- a/samples/client/petstore/ruby/docs/Dog.md +++ b/samples/client/petstore/ruby/docs/Dog.md @@ -4,6 +4,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **class_name** | **String** | | +**color** | **String** | | [optional] [default to "red"] **breed** | **String** | | [optional] diff --git a/samples/client/petstore/ruby/docs/EnumClass.md b/samples/client/petstore/ruby/docs/EnumClass.md new file mode 100644 index 00000000000..8d56e1f8873 --- /dev/null +++ b/samples/client/petstore/ruby/docs/EnumClass.md @@ -0,0 +1,7 @@ +# Petstore::EnumClass + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + + diff --git a/samples/client/petstore/ruby/docs/EnumTest.md b/samples/client/petstore/ruby/docs/EnumTest.md new file mode 100644 index 00000000000..ad3ee5c31bb --- /dev/null +++ b/samples/client/petstore/ruby/docs/EnumTest.md @@ -0,0 +1,10 @@ +# Petstore::EnumTest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**enum_string** | **String** | | [optional] +**enum_integer** | **Integer** | | [optional] +**enum_number** | **Float** | | [optional] + + diff --git a/samples/client/petstore/ruby/docs/FakeApi.md b/samples/client/petstore/ruby/docs/FakeApi.md index 32f2902d930..c0312e00f51 100644 --- a/samples/client/petstore/ruby/docs/FakeApi.md +++ b/samples/client/petstore/ruby/docs/FakeApi.md @@ -4,15 +4,15 @@ All URIs are relative to *http://petstore.swagger.io/v2* Method | HTTP request | Description ------------- | ------------- | ------------- -[**test_endpoint_parameters**](FakeApi.md#test_endpoint_parameters) | **POST** /fake | Fake endpoint for testing various parameters +[**test_endpoint_parameters**](FakeApi.md#test_endpoint_parameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 # **test_endpoint_parameters** > test_endpoint_parameters(number, double, string, byte, opts) -Fake endpoint for testing various parameters +Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 -Fake endpoint for testing various parameters +Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 ### Example ```ruby @@ -41,7 +41,7 @@ opts = { } begin - #Fake endpoint for testing various parameters + #Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 api_instance.test_endpoint_parameters(number, double, string, byte, opts) rescue Petstore::ApiError => e puts "Exception when calling FakeApi->test_endpoint_parameters: #{e}" diff --git a/samples/client/petstore/ruby/docs/Name.md b/samples/client/petstore/ruby/docs/Name.md index 4858862c725..1ae49f8ee1b 100644 --- a/samples/client/petstore/ruby/docs/Name.md +++ b/samples/client/petstore/ruby/docs/Name.md @@ -6,5 +6,6 @@ Name | Type | Description | Notes **name** | **Integer** | | **snake_case** | **Integer** | | [optional] **property** | **String** | | [optional] +**_123_number** | **Integer** | | [optional] diff --git a/samples/client/petstore/ruby/docs/PetApi.md b/samples/client/petstore/ruby/docs/PetApi.md index d485993c6ed..d5a498c6ff0 100644 --- a/samples/client/petstore/ruby/docs/PetApi.md +++ b/samples/client/petstore/ruby/docs/PetApi.md @@ -239,8 +239,8 @@ require 'petstore' Petstore.configure do |config| # Configure API key authorization: api_key config.api_key['api_key'] = 'YOUR API KEY' - # Uncomment the following line to set a prefix for the API key, e.g. 'BEARER' (defaults to nil) - #config.api_key_prefix['api_key'] = 'BEARER' + # Uncomment the following line to set a prefix for the API key, e.g. 'Bearer' (defaults to nil) + #config.api_key_prefix['api_key'] = 'Bearer' end api_instance = Petstore::PetApi.new diff --git a/samples/client/petstore/ruby/docs/StoreApi.md b/samples/client/petstore/ruby/docs/StoreApi.md index 8c607b9d7c9..c38a41eeef4 100644 --- a/samples/client/petstore/ruby/docs/StoreApi.md +++ b/samples/client/petstore/ruby/docs/StoreApi.md @@ -71,8 +71,8 @@ require 'petstore' Petstore.configure do |config| # Configure API key authorization: api_key config.api_key['api_key'] = 'YOUR API KEY' - # Uncomment the following line to set a prefix for the API key, e.g. 'BEARER' (defaults to nil) - #config.api_key_prefix['api_key'] = 'BEARER' + # Uncomment the following line to set a prefix for the API key, e.g. 'Bearer' (defaults to nil) + #config.api_key_prefix['api_key'] = 'Bearer' end api_instance = Petstore::StoreApi.new diff --git a/samples/client/petstore/ruby/lib/petstore.rb b/samples/client/petstore/ruby/lib/petstore.rb index f203db3f5ba..ce77b3d21b6 100644 --- a/samples/client/petstore/ruby/lib/petstore.rb +++ b/samples/client/petstore/ruby/lib/petstore.rb @@ -1,7 +1,7 @@ =begin Swagger Petstore -This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -22,10 +22,13 @@ require 'petstore/configuration' # Models require 'petstore/models/animal' +require 'petstore/models/animal_farm' require 'petstore/models/api_response' require 'petstore/models/cat' require 'petstore/models/category' require 'petstore/models/dog' +require 'petstore/models/enum_class' +require 'petstore/models/enum_test' require 'petstore/models/format_test' require 'petstore/models/model_200_response' require 'petstore/models/model_return' diff --git a/samples/client/petstore/ruby/lib/petstore/api/fake_api.rb b/samples/client/petstore/ruby/lib/petstore/api/fake_api.rb index a0cf2913f43..e7e6e45c262 100644 --- a/samples/client/petstore/ruby/lib/petstore/api/fake_api.rb +++ b/samples/client/petstore/ruby/lib/petstore/api/fake_api.rb @@ -1,7 +1,7 @@ =begin Swagger Petstore -This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -24,8 +24,8 @@ module Petstore @api_client = api_client end - # Fake endpoint for testing various parameters - # Fake endpoint for testing various parameters + # Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + # Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 # @param number None # @param double None # @param string None @@ -45,8 +45,8 @@ module Petstore return nil end - # Fake endpoint for testing various parameters - # Fake endpoint for testing various parameters + # Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + # Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 # @param number None # @param double None # @param string None 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 7e4121d5120..2d7a12dfd2a 100644 --- a/samples/client/petstore/ruby/lib/petstore/api/pet_api.rb +++ b/samples/client/petstore/ruby/lib/petstore/api/pet_api.rb @@ -1,7 +1,7 @@ =begin Swagger Petstore -This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io diff --git a/samples/client/petstore/ruby/lib/petstore/api/store_api.rb b/samples/client/petstore/ruby/lib/petstore/api/store_api.rb index 04c7f2701d8..2ef8b526c69 100644 --- a/samples/client/petstore/ruby/lib/petstore/api/store_api.rb +++ b/samples/client/petstore/ruby/lib/petstore/api/store_api.rb @@ -1,7 +1,7 @@ =begin Swagger Petstore -This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io diff --git a/samples/client/petstore/ruby/lib/petstore/api/user_api.rb b/samples/client/petstore/ruby/lib/petstore/api/user_api.rb index 469c950934a..bdecfa87ec2 100644 --- a/samples/client/petstore/ruby/lib/petstore/api/user_api.rb +++ b/samples/client/petstore/ruby/lib/petstore/api/user_api.rb @@ -1,7 +1,7 @@ =begin Swagger Petstore -This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io diff --git a/samples/client/petstore/ruby/lib/petstore/api_client.rb b/samples/client/petstore/ruby/lib/petstore/api_client.rb index ed1c501d71a..1723abbac42 100644 --- a/samples/client/petstore/ruby/lib/petstore/api_client.rb +++ b/samples/client/petstore/ruby/lib/petstore/api_client.rb @@ -1,7 +1,7 @@ =begin Swagger Petstore -This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io diff --git a/samples/client/petstore/ruby/lib/petstore/api_error.rb b/samples/client/petstore/ruby/lib/petstore/api_error.rb index e4c233b2e98..95b1fc6cdb7 100644 --- a/samples/client/petstore/ruby/lib/petstore/api_error.rb +++ b/samples/client/petstore/ruby/lib/petstore/api_error.rb @@ -1,7 +1,7 @@ =begin Swagger Petstore -This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io diff --git a/samples/client/petstore/ruby/lib/petstore/models/animal.rb b/samples/client/petstore/ruby/lib/petstore/models/animal.rb index 5612f227d09..d23fe94a733 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/animal.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/animal.rb @@ -1,7 +1,7 @@ =begin Swagger Petstore -This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -20,17 +20,21 @@ module Petstore class Animal attr_accessor :class_name + attr_accessor :color + # Attribute mapping from ruby-style variable name to JSON key. def self.attribute_map { - :'class_name' => :'className' + :'class_name' => :'className', + :'color' => :'color' } end # Attribute type mapping. def self.swagger_types { - :'class_name' => :'String' + :'class_name' => :'String', + :'color' => :'String' } end @@ -46,6 +50,12 @@ module Petstore self.class_name = attributes[:'className'] end + if attributes.has_key?(:'color') + self.color = attributes[:'color'] + else + self.color = "red" + end + end # Show invalid properties with the reasons. Usually used together with valid? @@ -69,7 +79,8 @@ module Petstore def ==(o) return true if self.equal?(o) self.class == o.class && - class_name == o.class_name + class_name == o.class_name && + color == o.color end # @see the `==` method @@ -81,7 +92,7 @@ module Petstore # Calculates hash code according to all attributes. # @return [Fixnum] Hash code def hash - [class_name].hash + [class_name, color].hash end # Builds the object from hash diff --git a/samples/client/petstore/ruby/lib/petstore/models/animal_farm.rb b/samples/client/petstore/ruby/lib/petstore/models/animal_farm.rb new file mode 100644 index 00000000000..f4f2f6ba6a0 --- /dev/null +++ b/samples/client/petstore/ruby/lib/petstore/models/animal_farm.rb @@ -0,0 +1,179 @@ +=begin +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +License: Apache 2.0 +http://www.apache.org/licenses/LICENSE-2.0.html + +Terms of Service: http://swagger.io/terms/ + +=end + +require 'date' + +module Petstore + class AnimalFarm + # Attribute mapping from ruby-style variable name to JSON key. + def self.attribute_map + { + } + end + + # Attribute type mapping. + def self.swagger_types + { + } + end + + # Initializes the object + # @param [Hash] attributes Model attributes in the form of hash + def initialize(attributes = {}) + return unless attributes.is_a?(Hash) + + # convert string to symbol for hash key + attributes = attributes.each_with_object({}){|(k,v), h| h[k.to_sym] = v} + + end + + # Show invalid properties with the reasons. Usually used together with valid? + # @return Array for valid properies with the reasons + def list_invalid_properties + invalid_properties = Array.new + return invalid_properties + end + + # Check to see if the all the properties in the model are valid + # @return true if the model is valid + def valid? + end + + # Checks equality by comparing each attribute. + # @param [Object] Object to be compared + def ==(o) + return true if self.equal?(o) + self.class == o.class + end + + # @see the `==` method + # @param [Object] Object to be compared + def eql?(o) + self == o + end + + # Calculates hash code according to all attributes. + # @return [Fixnum] Hash code + def hash + [].hash + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def build_from_hash(attributes) + return nil unless attributes.is_a?(Hash) + self.class.swagger_types.each_pair do |key, type| + if type =~ /^Array<(.*)>/i + # check to ensure the input is an array given that the the attribute + # is documented as an array but the input is not + if attributes[self.class.attribute_map[key]].is_a?(Array) + self.send("#{key}=", attributes[self.class.attribute_map[key]].map{ |v| _deserialize($1, v) } ) + end + elsif !attributes[self.class.attribute_map[key]].nil? + self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) + end # or else data not found in attributes(hash), not an issue as the data can be optional + end + + self + end + + # Deserializes the data based on type + # @param string type Data type + # @param string value Value to be deserialized + # @return [Object] Deserialized data + def _deserialize(type, value) + case type.to_sym + when :DateTime + DateTime.parse(value) + when :Date + Date.parse(value) + when :String + value.to_s + when :Integer + value.to_i + when :Float + value.to_f + when :BOOLEAN + if value.to_s =~ /^(true|t|yes|y|1)$/i + true + else + false + end + when :Object + # generic object (usually a Hash), return directly + value + when /\AArray<(?.+)>\z/ + inner_type = Regexp.last_match[:inner_type] + value.map { |v| _deserialize(inner_type, v) } + when /\AHash<(?.+), (?.+)>\z/ + k_type = Regexp.last_match[:k_type] + v_type = Regexp.last_match[:v_type] + {}.tap do |hash| + value.each do |k, v| + hash[_deserialize(k_type, k)] = _deserialize(v_type, v) + end + end + else # model + temp_model = Petstore.const_get(type).new + temp_model.build_from_hash(value) + end + end + + # Returns the string representation of the object + # @return [String] String presentation of the object + def to_s + to_hash.to_s + end + + # to_body is an alias to to_hash (backward compatibility) + # @return [Hash] Returns the object in the form of hash + def to_body + to_hash + end + + # Returns the object in the form of hash + # @return [Hash] Returns the object in the form of hash + def to_hash + hash = {} + self.class.attribute_map.each_pair do |attr, param| + value = self.send(attr) + next if value.nil? + hash[param] = _to_hash(value) + end + hash + end + + # Outputs non-array value in the form of hash + # For object, use to_hash. Otherwise, just return the value + # @param [Object] value Any valid value + # @return [Hash] Returns the value in the form of hash + def _to_hash(value) + if value.is_a?(Array) + value.compact.map{ |v| _to_hash(v) } + elsif value.is_a?(Hash) + {}.tap do |hash| + value.each { |k, v| hash[k] = _to_hash(v) } + end + elsif value.respond_to? :to_hash + value.to_hash + else + value + end + end + + end +end diff --git a/samples/client/petstore/ruby/lib/petstore/models/api_response.rb b/samples/client/petstore/ruby/lib/petstore/models/api_response.rb index 79da573e941..3893b842879 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/api_response.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/api_response.rb @@ -1,7 +1,7 @@ =begin Swagger Petstore -This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io diff --git a/samples/client/petstore/ruby/lib/petstore/models/cat.rb b/samples/client/petstore/ruby/lib/petstore/models/cat.rb index 12f17b85553..653b9b506f7 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/cat.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/cat.rb @@ -1,7 +1,7 @@ =begin Swagger Petstore -This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -20,12 +20,15 @@ module Petstore class Cat attr_accessor :class_name + attr_accessor :color + attr_accessor :declawed # Attribute mapping from ruby-style variable name to JSON key. def self.attribute_map { :'class_name' => :'className', + :'color' => :'color', :'declawed' => :'declawed' } end @@ -34,6 +37,7 @@ module Petstore def self.swagger_types { :'class_name' => :'String', + :'color' => :'String', :'declawed' => :'BOOLEAN' } end @@ -50,6 +54,12 @@ module Petstore self.class_name = attributes[:'className'] end + if attributes.has_key?(:'color') + self.color = attributes[:'color'] + else + self.color = "red" + end + if attributes.has_key?(:'declawed') self.declawed = attributes[:'declawed'] end @@ -78,6 +88,7 @@ module Petstore return true if self.equal?(o) self.class == o.class && class_name == o.class_name && + color == o.color && declawed == o.declawed end @@ -90,7 +101,7 @@ module Petstore # Calculates hash code according to all attributes. # @return [Fixnum] Hash code def hash - [class_name, declawed].hash + [class_name, color, declawed].hash end # Builds the object from hash diff --git a/samples/client/petstore/ruby/lib/petstore/models/category.rb b/samples/client/petstore/ruby/lib/petstore/models/category.rb index c4879d65bb4..5aced3c55c7 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/category.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/category.rb @@ -1,7 +1,7 @@ =begin Swagger Petstore -This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io diff --git a/samples/client/petstore/ruby/lib/petstore/models/dog.rb b/samples/client/petstore/ruby/lib/petstore/models/dog.rb index 90d213dbf45..b08d82d49f8 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/dog.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/dog.rb @@ -1,7 +1,7 @@ =begin Swagger Petstore -This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -20,12 +20,15 @@ module Petstore class Dog attr_accessor :class_name + attr_accessor :color + attr_accessor :breed # Attribute mapping from ruby-style variable name to JSON key. def self.attribute_map { :'class_name' => :'className', + :'color' => :'color', :'breed' => :'breed' } end @@ -34,6 +37,7 @@ module Petstore def self.swagger_types { :'class_name' => :'String', + :'color' => :'String', :'breed' => :'String' } end @@ -50,6 +54,12 @@ module Petstore self.class_name = attributes[:'className'] end + if attributes.has_key?(:'color') + self.color = attributes[:'color'] + else + self.color = "red" + end + if attributes.has_key?(:'breed') self.breed = attributes[:'breed'] end @@ -78,6 +88,7 @@ module Petstore return true if self.equal?(o) self.class == o.class && class_name == o.class_name && + color == o.color && breed == o.breed end @@ -90,7 +101,7 @@ module Petstore # Calculates hash code according to all attributes. # @return [Fixnum] Hash code def hash - [class_name, breed].hash + [class_name, color, breed].hash end # Builds the object from hash diff --git a/samples/client/petstore/ruby/lib/petstore/models/enum_class.rb b/samples/client/petstore/ruby/lib/petstore/models/enum_class.rb new file mode 100644 index 00000000000..30c570708c3 --- /dev/null +++ b/samples/client/petstore/ruby/lib/petstore/models/enum_class.rb @@ -0,0 +1,184 @@ +=begin +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +License: Apache 2.0 +http://www.apache.org/licenses/LICENSE-2.0.html + +Terms of Service: http://swagger.io/terms/ + +=end + +require 'date' + +module Petstore + class EnumClass + # Attribute mapping from ruby-style variable name to JSON key. + def self.attribute_map + { + } + end + + # Attribute type mapping. + def self.swagger_types + { + } + end + + # Initializes the object + # @param [Hash] attributes Model attributes in the form of hash + def initialize(attributes = {}) + return unless attributes.is_a?(Hash) + + # convert string to symbol for hash key + attributes = attributes.each_with_object({}){|(k,v), h| h[k.to_sym] = v} + + end + + # Show invalid properties with the reasons. Usually used together with valid? + # @return Array for valid properies with the reasons + def list_invalid_properties + invalid_properties = Array.new + allowed_values = ["_abc", "-efg", "(xyz)"] + if @EnumClass && !allowed_values.include?(EnumClass) + invalid_properties.push("invalid value for 'EnumClass', must be one of #{allowed_values}.") + end + + return invalid_properties + end + + # Check to see if the all the properties in the model are valid + # @return true if the model is valid + def valid? + end + + # Checks equality by comparing each attribute. + # @param [Object] Object to be compared + def ==(o) + return true if self.equal?(o) + self.class == o.class + end + + # @see the `==` method + # @param [Object] Object to be compared + def eql?(o) + self == o + end + + # Calculates hash code according to all attributes. + # @return [Fixnum] Hash code + def hash + [].hash + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def build_from_hash(attributes) + return nil unless attributes.is_a?(Hash) + self.class.swagger_types.each_pair do |key, type| + if type =~ /^Array<(.*)>/i + # check to ensure the input is an array given that the the attribute + # is documented as an array but the input is not + if attributes[self.class.attribute_map[key]].is_a?(Array) + self.send("#{key}=", attributes[self.class.attribute_map[key]].map{ |v| _deserialize($1, v) } ) + end + elsif !attributes[self.class.attribute_map[key]].nil? + self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) + end # or else data not found in attributes(hash), not an issue as the data can be optional + end + + self + end + + # Deserializes the data based on type + # @param string type Data type + # @param string value Value to be deserialized + # @return [Object] Deserialized data + def _deserialize(type, value) + case type.to_sym + when :DateTime + DateTime.parse(value) + when :Date + Date.parse(value) + when :String + value.to_s + when :Integer + value.to_i + when :Float + value.to_f + when :BOOLEAN + if value.to_s =~ /^(true|t|yes|y|1)$/i + true + else + false + end + when :Object + # generic object (usually a Hash), return directly + value + when /\AArray<(?.+)>\z/ + inner_type = Regexp.last_match[:inner_type] + value.map { |v| _deserialize(inner_type, v) } + when /\AHash<(?.+), (?.+)>\z/ + k_type = Regexp.last_match[:k_type] + v_type = Regexp.last_match[:v_type] + {}.tap do |hash| + value.each do |k, v| + hash[_deserialize(k_type, k)] = _deserialize(v_type, v) + end + end + else # model + temp_model = Petstore.const_get(type).new + temp_model.build_from_hash(value) + end + end + + # Returns the string representation of the object + # @return [String] String presentation of the object + def to_s + to_hash.to_s + end + + # to_body is an alias to to_hash (backward compatibility) + # @return [Hash] Returns the object in the form of hash + def to_body + to_hash + end + + # Returns the object in the form of hash + # @return [Hash] Returns the object in the form of hash + def to_hash + hash = {} + self.class.attribute_map.each_pair do |attr, param| + value = self.send(attr) + next if value.nil? + hash[param] = _to_hash(value) + end + hash + end + + # Outputs non-array value in the form of hash + # For object, use to_hash. Otherwise, just return the value + # @param [Object] value Any valid value + # @return [Hash] Returns the value in the form of hash + def _to_hash(value) + if value.is_a?(Array) + value.compact.map{ |v| _to_hash(v) } + elsif value.is_a?(Hash) + {}.tap do |hash| + value.each { |k, v| hash[k] = _to_hash(v) } + end + elsif value.respond_to? :to_hash + value.to_hash + else + value + end + end + + end +end diff --git a/samples/client/petstore/ruby/lib/petstore/models/enum_test.rb b/samples/client/petstore/ruby/lib/petstore/models/enum_test.rb new file mode 100644 index 00000000000..618c6336d58 --- /dev/null +++ b/samples/client/petstore/ruby/lib/petstore/models/enum_test.rb @@ -0,0 +1,248 @@ +=begin +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +License: Apache 2.0 +http://www.apache.org/licenses/LICENSE-2.0.html + +Terms of Service: http://swagger.io/terms/ + +=end + +require 'date' + +module Petstore + class EnumTest + attr_accessor :enum_string + + attr_accessor :enum_integer + + attr_accessor :enum_number + + # Attribute mapping from ruby-style variable name to JSON key. + def self.attribute_map + { + :'enum_string' => :'enum_string', + :'enum_integer' => :'enum_integer', + :'enum_number' => :'enum_number' + } + end + + # Attribute type mapping. + def self.swagger_types + { + :'enum_string' => :'String', + :'enum_integer' => :'Integer', + :'enum_number' => :'Float' + } + end + + # Initializes the object + # @param [Hash] attributes Model attributes in the form of hash + def initialize(attributes = {}) + return unless attributes.is_a?(Hash) + + # convert string to symbol for hash key + attributes = attributes.each_with_object({}){|(k,v), h| h[k.to_sym] = v} + + if attributes.has_key?(:'enum_string') + self.enum_string = attributes[:'enum_string'] + end + + if attributes.has_key?(:'enum_integer') + self.enum_integer = attributes[:'enum_integer'] + end + + if attributes.has_key?(:'enum_number') + self.enum_number = attributes[:'enum_number'] + end + + end + + # Show invalid properties with the reasons. Usually used together with valid? + # @return Array for valid properies with the reasons + def list_invalid_properties + invalid_properties = Array.new + return invalid_properties + end + + # Check to see if the all the properties in the model are valid + # @return true if the model is valid + def valid? + allowed_values = ["UPPER", "lower"] + if @enum_string && !allowed_values.include?(@enum_string) + return false + end + allowed_values = ["1", "-1"] + if @enum_integer && !allowed_values.include?(@enum_integer) + return false + end + allowed_values = ["1.1", "-1.2"] + if @enum_number && !allowed_values.include?(@enum_number) + return false + end + end + + # Custom attribute writer method checking allowed values (enum). + # @param [Object] enum_string Object to be assigned + def enum_string=(enum_string) + allowed_values = ["UPPER", "lower"] + if enum_string && !allowed_values.include?(enum_string) + fail ArgumentError, "invalid value for 'enum_string', must be one of #{allowed_values}." + end + @enum_string = enum_string + end + + # Custom attribute writer method checking allowed values (enum). + # @param [Object] enum_integer Object to be assigned + def enum_integer=(enum_integer) + allowed_values = ["1", "-1"] + if enum_integer && !allowed_values.include?(enum_integer) + fail ArgumentError, "invalid value for 'enum_integer', must be one of #{allowed_values}." + end + @enum_integer = enum_integer + end + + # Custom attribute writer method checking allowed values (enum). + # @param [Object] enum_number Object to be assigned + def enum_number=(enum_number) + allowed_values = ["1.1", "-1.2"] + if enum_number && !allowed_values.include?(enum_number) + fail ArgumentError, "invalid value for 'enum_number', must be one of #{allowed_values}." + end + @enum_number = enum_number + end + + # Checks equality by comparing each attribute. + # @param [Object] Object to be compared + def ==(o) + return true if self.equal?(o) + self.class == o.class && + enum_string == o.enum_string && + enum_integer == o.enum_integer && + enum_number == o.enum_number + end + + # @see the `==` method + # @param [Object] Object to be compared + def eql?(o) + self == o + end + + # Calculates hash code according to all attributes. + # @return [Fixnum] Hash code + def hash + [enum_string, enum_integer, enum_number].hash + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def build_from_hash(attributes) + return nil unless attributes.is_a?(Hash) + self.class.swagger_types.each_pair do |key, type| + if type =~ /^Array<(.*)>/i + # check to ensure the input is an array given that the the attribute + # is documented as an array but the input is not + if attributes[self.class.attribute_map[key]].is_a?(Array) + self.send("#{key}=", attributes[self.class.attribute_map[key]].map{ |v| _deserialize($1, v) } ) + end + elsif !attributes[self.class.attribute_map[key]].nil? + self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) + end # or else data not found in attributes(hash), not an issue as the data can be optional + end + + self + end + + # Deserializes the data based on type + # @param string type Data type + # @param string value Value to be deserialized + # @return [Object] Deserialized data + def _deserialize(type, value) + case type.to_sym + when :DateTime + DateTime.parse(value) + when :Date + Date.parse(value) + when :String + value.to_s + when :Integer + value.to_i + when :Float + value.to_f + when :BOOLEAN + if value.to_s =~ /^(true|t|yes|y|1)$/i + true + else + false + end + when :Object + # generic object (usually a Hash), return directly + value + when /\AArray<(?.+)>\z/ + inner_type = Regexp.last_match[:inner_type] + value.map { |v| _deserialize(inner_type, v) } + when /\AHash<(?.+), (?.+)>\z/ + k_type = Regexp.last_match[:k_type] + v_type = Regexp.last_match[:v_type] + {}.tap do |hash| + value.each do |k, v| + hash[_deserialize(k_type, k)] = _deserialize(v_type, v) + end + end + else # model + temp_model = Petstore.const_get(type).new + temp_model.build_from_hash(value) + end + end + + # Returns the string representation of the object + # @return [String] String presentation of the object + def to_s + to_hash.to_s + end + + # to_body is an alias to to_hash (backward compatibility) + # @return [Hash] Returns the object in the form of hash + def to_body + to_hash + end + + # Returns the object in the form of hash + # @return [Hash] Returns the object in the form of hash + def to_hash + hash = {} + self.class.attribute_map.each_pair do |attr, param| + value = self.send(attr) + next if value.nil? + hash[param] = _to_hash(value) + end + hash + end + + # Outputs non-array value in the form of hash + # For object, use to_hash. Otherwise, just return the value + # @param [Object] value Any valid value + # @return [Hash] Returns the value in the form of hash + def _to_hash(value) + if value.is_a?(Array) + value.compact.map{ |v| _to_hash(v) } + elsif value.is_a?(Hash) + {}.tap do |hash| + value.each { |k, v| hash[k] = _to_hash(v) } + end + elsif value.respond_to? :to_hash + value.to_hash + else + value + end + end + + end +end diff --git a/samples/client/petstore/ruby/lib/petstore/models/format_test.rb b/samples/client/petstore/ruby/lib/petstore/models/format_test.rb index 946e0001555..9952352f9fd 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/format_test.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/format_test.rb @@ -1,7 +1,7 @@ =begin Swagger Petstore -This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io diff --git a/samples/client/petstore/ruby/lib/petstore/models/model_200_response.rb b/samples/client/petstore/ruby/lib/petstore/models/model_200_response.rb index 7a2473fb8b9..c7bcf594aca 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/model_200_response.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/model_200_response.rb @@ -1,7 +1,7 @@ =begin Swagger Petstore -This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io diff --git a/samples/client/petstore/ruby/lib/petstore/models/model_return.rb b/samples/client/petstore/ruby/lib/petstore/models/model_return.rb index 0361451b290..1a18970eebe 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/model_return.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/model_return.rb @@ -1,7 +1,7 @@ =begin Swagger Petstore -This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io diff --git a/samples/client/petstore/ruby/lib/petstore/models/name.rb b/samples/client/petstore/ruby/lib/petstore/models/name.rb index d5e3ef4adb8..0b4d3835d0e 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/name.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/name.rb @@ -1,7 +1,7 @@ =begin Swagger Petstore -This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io @@ -25,12 +25,15 @@ module Petstore attr_accessor :property + attr_accessor :_123_number + # Attribute mapping from ruby-style variable name to JSON key. def self.attribute_map { :'name' => :'name', :'snake_case' => :'snake_case', - :'property' => :'property' + :'property' => :'property', + :'_123_number' => :'123Number' } end @@ -39,7 +42,8 @@ module Petstore { :'name' => :'Integer', :'snake_case' => :'Integer', - :'property' => :'String' + :'property' => :'String', + :'_123_number' => :'Integer' } end @@ -63,6 +67,10 @@ module Petstore self.property = attributes[:'property'] end + if attributes.has_key?(:'123Number') + self._123_number = attributes[:'123Number'] + end + end # Show invalid properties with the reasons. Usually used together with valid? @@ -88,7 +96,8 @@ module Petstore self.class == o.class && name == o.name && snake_case == o.snake_case && - property == o.property + property == o.property && + _123_number == o._123_number end # @see the `==` method @@ -100,7 +109,7 @@ module Petstore # Calculates hash code according to all attributes. # @return [Fixnum] Hash code def hash - [name, snake_case, property].hash + [name, snake_case, property, _123_number].hash end # Builds the object from hash diff --git a/samples/client/petstore/ruby/lib/petstore/models/order.rb b/samples/client/petstore/ruby/lib/petstore/models/order.rb index 6c021e50ec7..e0397710618 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/order.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/order.rb @@ -1,7 +1,7 @@ =begin Swagger Petstore -This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io diff --git a/samples/client/petstore/ruby/lib/petstore/models/pet.rb b/samples/client/petstore/ruby/lib/petstore/models/pet.rb index ba4d466df21..0f484cd0c43 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/pet.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/pet.rb @@ -1,7 +1,7 @@ =begin Swagger Petstore -This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io diff --git a/samples/client/petstore/ruby/lib/petstore/models/special_model_name.rb b/samples/client/petstore/ruby/lib/petstore/models/special_model_name.rb index 853d1e49600..781cf39ad0c 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/special_model_name.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/special_model_name.rb @@ -1,7 +1,7 @@ =begin Swagger Petstore -This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io diff --git a/samples/client/petstore/ruby/lib/petstore/models/tag.rb b/samples/client/petstore/ruby/lib/petstore/models/tag.rb index d6d49068e37..b40ad1046f1 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/tag.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/tag.rb @@ -1,7 +1,7 @@ =begin Swagger Petstore -This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io diff --git a/samples/client/petstore/ruby/lib/petstore/models/user.rb b/samples/client/petstore/ruby/lib/petstore/models/user.rb index f0c39b741d5..8bdc816bd0e 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/user.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/user.rb @@ -1,7 +1,7 @@ =begin Swagger Petstore -This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io diff --git a/samples/client/petstore/ruby/lib/petstore/version.rb b/samples/client/petstore/ruby/lib/petstore/version.rb index e28b737d97c..e5c868d3d09 100644 --- a/samples/client/petstore/ruby/lib/petstore/version.rb +++ b/samples/client/petstore/ruby/lib/petstore/version.rb @@ -1,7 +1,7 @@ =begin Swagger Petstore -This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io diff --git a/samples/client/petstore/ruby/petstore.gemspec b/samples/client/petstore/ruby/petstore.gemspec index 08b733a0921..66258d1ff5c 100644 --- a/samples/client/petstore/ruby/petstore.gemspec +++ b/samples/client/petstore/ruby/petstore.gemspec @@ -10,7 +10,7 @@ Gem::Specification.new do |s| s.email = ["apiteam@swagger.io"] s.homepage = "https://github.com/swagger-api/swagger-codegen" s.summary = "Swagger Petstore Ruby Gem" - s.description = "This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose." + s.description = "This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ " s.license = "Apache 2.0" s.add_runtime_dependency 'typhoeus', '~> 1.0', '>= 1.0.1' diff --git a/samples/client/petstore/ruby/spec/api/fake_api_spec.rb b/samples/client/petstore/ruby/spec/api/fake_api_spec.rb index 84929b8115c..a30c9d9c7a7 100644 --- a/samples/client/petstore/ruby/spec/api/fake_api_spec.rb +++ b/samples/client/petstore/ruby/spec/api/fake_api_spec.rb @@ -32,13 +32,13 @@ describe 'FakeApi' do describe 'test an instance of FakeApi' do it 'should create an instact of FakeApi' do - @instance.should be_a(Petstore::FakeApi) + expect(@instance).to be_instance_of(Petstore::FakeApi) end end # unit tests for test_endpoint_parameters - # Fake endpoint for testing various parameters - # Fake endpoint for testing various parameters + # Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + # Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 # @param number None # @param double None # @param string None @@ -55,11 +55,7 @@ describe 'FakeApi' do # @return [nil] describe 'test_endpoint_parameters test' do it "should work" do - # assertion here - # should be_a() - # should be_nil - # should == - # should_not == + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end diff --git a/samples/client/petstore/ruby/spec/api/pet_api_spec.rb b/samples/client/petstore/ruby/spec/api/pet_api_spec.rb index e903362291b..72a6e8209c5 100644 --- a/samples/client/petstore/ruby/spec/api/pet_api_spec.rb +++ b/samples/client/petstore/ruby/spec/api/pet_api_spec.rb @@ -32,7 +32,7 @@ describe 'PetApi' do describe 'test an instance of PetApi' do it 'should create an instact of PetApi' do - @instance.should be_a(Petstore::PetApi) + expect(@instance).to be_instance_of(Petstore::PetApi) end end @@ -44,11 +44,7 @@ describe 'PetApi' do # @return [nil] describe 'add_pet test' do it "should work" do - # assertion here - # should be_a() - # should be_nil - # should == - # should_not == + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end @@ -61,11 +57,7 @@ describe 'PetApi' do # @return [nil] describe 'delete_pet test' do it "should work" do - # assertion here - # should be_a() - # should be_nil - # should == - # should_not == + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end @@ -77,11 +69,7 @@ describe 'PetApi' do # @return [Array] describe 'find_pets_by_status test' do it "should work" do - # assertion here - # should be_a() - # should be_nil - # should == - # should_not == + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end @@ -93,11 +81,7 @@ describe 'PetApi' do # @return [Array] describe 'find_pets_by_tags test' do it "should work" do - # assertion here - # should be_a() - # should be_nil - # should == - # should_not == + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end @@ -109,11 +93,7 @@ describe 'PetApi' do # @return [Pet] describe 'get_pet_by_id test' do it "should work" do - # assertion here - # should be_a() - # should be_nil - # should == - # should_not == + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end @@ -125,11 +105,7 @@ describe 'PetApi' do # @return [nil] describe 'update_pet test' do it "should work" do - # assertion here - # should be_a() - # should be_nil - # should == - # should_not == + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end @@ -143,11 +119,7 @@ describe 'PetApi' do # @return [nil] describe 'update_pet_with_form test' do it "should work" do - # assertion here - # should be_a() - # should be_nil - # should == - # should_not == + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end @@ -161,11 +133,7 @@ describe 'PetApi' do # @return [ApiResponse] describe 'upload_file test' do it "should work" do - # assertion here - # should be_a() - # should be_nil - # should == - # should_not == + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end diff --git a/samples/client/petstore/ruby/spec/api/store_api_spec.rb b/samples/client/petstore/ruby/spec/api/store_api_spec.rb index 015d1d8e39d..428c9c5f282 100644 --- a/samples/client/petstore/ruby/spec/api/store_api_spec.rb +++ b/samples/client/petstore/ruby/spec/api/store_api_spec.rb @@ -32,7 +32,7 @@ describe 'StoreApi' do describe 'test an instance of StoreApi' do it 'should create an instact of StoreApi' do - @instance.should be_a(Petstore::StoreApi) + expect(@instance).to be_instance_of(Petstore::StoreApi) end end @@ -44,11 +44,7 @@ describe 'StoreApi' do # @return [nil] describe 'delete_order test' do it "should work" do - # assertion here - # should be_a() - # should be_nil - # should == - # should_not == + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end @@ -59,27 +55,19 @@ describe 'StoreApi' do # @return [Hash] describe 'get_inventory test' do it "should work" do - # assertion here - # should be_a() - # should be_nil - # should == - # should_not == + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end # unit tests for get_order_by_id # Find purchase order by ID - # For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + # For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions # @param order_id ID of pet that needs to be fetched # @param [Hash] opts the optional parameters # @return [Order] describe 'get_order_by_id test' do it "should work" do - # assertion here - # should be_a() - # should be_nil - # should == - # should_not == + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end @@ -91,11 +79,7 @@ describe 'StoreApi' do # @return [Order] describe 'place_order test' do it "should work" do - # assertion here - # should be_a() - # should be_nil - # should == - # should_not == + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end diff --git a/samples/client/petstore/ruby/spec/api/user_api_spec.rb b/samples/client/petstore/ruby/spec/api/user_api_spec.rb index 272980a6db0..37194b3c158 100644 --- a/samples/client/petstore/ruby/spec/api/user_api_spec.rb +++ b/samples/client/petstore/ruby/spec/api/user_api_spec.rb @@ -32,7 +32,7 @@ describe 'UserApi' do describe 'test an instance of UserApi' do it 'should create an instact of UserApi' do - @instance.should be_a(Petstore::UserApi) + expect(@instance).to be_instance_of(Petstore::UserApi) end end @@ -44,11 +44,7 @@ describe 'UserApi' do # @return [nil] describe 'create_user test' do it "should work" do - # assertion here - # should be_a() - # should be_nil - # should == - # should_not == + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end @@ -60,11 +56,7 @@ describe 'UserApi' do # @return [nil] describe 'create_users_with_array_input test' do it "should work" do - # assertion here - # should be_a() - # should be_nil - # should == - # should_not == + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end @@ -76,11 +68,7 @@ describe 'UserApi' do # @return [nil] describe 'create_users_with_list_input test' do it "should work" do - # assertion here - # should be_a() - # should be_nil - # should == - # should_not == + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end @@ -92,27 +80,19 @@ describe 'UserApi' do # @return [nil] describe 'delete_user test' do it "should work" do - # assertion here - # should be_a() - # should be_nil - # should == - # should_not == + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end # unit tests for get_user_by_name # Get user by user name # - # @param username The name that needs to be fetched. Use user1 for testing. + # @param username The name that needs to be fetched. Use user1 for testing. # @param [Hash] opts the optional parameters # @return [User] describe 'get_user_by_name test' do it "should work" do - # assertion here - # should be_a() - # should be_nil - # should == - # should_not == + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end @@ -125,11 +105,7 @@ describe 'UserApi' do # @return [String] describe 'login_user test' do it "should work" do - # assertion here - # should be_a() - # should be_nil - # should == - # should_not == + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end @@ -140,11 +116,7 @@ describe 'UserApi' do # @return [nil] describe 'logout_user test' do it "should work" do - # assertion here - # should be_a() - # should be_nil - # should == - # should_not == + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end @@ -157,11 +129,7 @@ describe 'UserApi' do # @return [nil] describe 'update_user test' do it "should work" do - # assertion here - # should be_a() - # should be_nil - # should == - # should_not == + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end diff --git a/samples/client/petstore/ruby/spec/base_object_spec.rb b/samples/client/petstore/ruby/spec/base_object_spec.rb index a315d52276b..5b84351f7b8 100644 --- a/samples/client/petstore/ruby/spec/base_object_spec.rb +++ b/samples/client/petstore/ruby/spec/base_object_spec.rb @@ -35,8 +35,8 @@ describe 'BaseObject' do let(:obj) { Petstore::Cat.new({declawed: false}) } it 'should have values set' do - obj.declawed.should_not eq nil - obj.declawed.should eq false + expect(obj.declawed).not_to be_nil + expect(obj.declawed).to eq(false) end end @@ -58,42 +58,43 @@ describe 'BaseObject' do it 'works for #build_from_hash' do obj.build_from_hash(data) - obj.int_arr.should == [123, 456] + expect(obj.int_arr).to match_array([123, 456]) + + expect(obj.pet_arr).to be_instance_of(Array) + expect(obj.pet_arr.size).to eq(1) - obj.pet_arr.should be_a(Array) - obj.pet_arr.size.should == 1 pet = obj.pet_arr.first - pet.should be_a(Petstore::Pet) - pet.name.should == 'Kitty' + expect(pet).to be_instance_of(Petstore::Pet) + expect(pet.name).to eq('Kitty') - obj.int_map.should be_a(Hash) - obj.int_map.should == {'int' => 123} + expect(obj.int_map).to be_instance_of(Hash) + expect(obj.int_map).to eq({'int' => 123}) - obj.pet_map.should be_a(Hash) + expect(obj.pet_map).to be_instance_of(Hash) pet = obj.pet_map['pet'] - pet.should be_a(Petstore::Pet) - pet.name.should == 'Kitty' + expect(pet).to be_instance_of(Petstore::Pet) + expect(pet.name).to eq('Kitty') - obj.int_arr_map.should be_a(Hash) + expect(obj.int_arr_map).to be_instance_of(Hash) arr = obj.int_arr_map['int_arr'] - arr.should == [123, 456] + expect(arr).to match_array([123, 456]) - obj.pet_arr_map.should be_a(Hash) + expect(obj.pet_arr_map).to be_instance_of(Hash) arr = obj.pet_arr_map['pet_arr'] - arr.should be_a(Array) - arr.size.should == 1 + expect(arr).to be_instance_of(Array) + expect(arr.size).to eq(1) pet = arr.first - pet.should be_a(Petstore::Pet) - pet.name.should == 'Kitty' + expect(pet).to be_instance_of(Petstore::Pet) + expect(pet.name).to eq('Kitty') - obj.boolean_true_arr.should be_a(Array) + expect(obj.boolean_true_arr).to be_instance_of(Array) obj.boolean_true_arr.each do |b| - b.should eq true + expect(b).to eq(true) end - obj.boolean_false_arr.should be_a(Array) + expect(obj.boolean_false_arr).to be_instance_of(Array) obj.boolean_false_arr.each do |b| - b.should eq false + expect(b).to eq(false) end end @@ -102,7 +103,7 @@ describe 'BaseObject' do expect_data = data.dup expect_data[:boolean_true_arr].map! {true} expect_data[:boolean_false_arr].map! {false} - obj.to_hash.should == expect_data + expect(obj.to_hash).to eq(expect_data) end end end diff --git a/samples/client/petstore/ruby/spec/models/animal_farm_spec.rb b/samples/client/petstore/ruby/spec/models/animal_farm_spec.rb new file mode 100644 index 00000000000..016b86fd8af --- /dev/null +++ b/samples/client/petstore/ruby/spec/models/animal_farm_spec.rb @@ -0,0 +1,40 @@ +=begin +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +License: Apache 2.0 +http://www.apache.org/licenses/LICENSE-2.0.html + +Terms of Service: http://swagger.io/terms/ + +=end + +require 'spec_helper' +require 'json' +require 'date' + +# Unit tests for Petstore::AnimalFarm +# Automatically generated by swagger-codegen (github.com/swagger-api/swagger-codegen) +# Please update as you see appropriate +describe 'AnimalFarm' do + before do + # run before each test + @instance = Petstore::AnimalFarm.new + end + + after do + # run after each test + end + + describe 'test an instance of AnimalFarm' do + it 'should create an instact of AnimalFarm' do + expect(@instance).to be_instance_of(Petstore::AnimalFarm) + end + end +end + diff --git a/samples/client/petstore/ruby/spec/models/animal_spec.rb b/samples/client/petstore/ruby/spec/models/animal_spec.rb index e35b12411be..3f98b0f7b84 100644 --- a/samples/client/petstore/ruby/spec/models/animal_spec.rb +++ b/samples/client/petstore/ruby/spec/models/animal_spec.rb @@ -33,16 +33,12 @@ describe 'Animal' do describe 'test an instance of Animal' do it 'should create an instact of Animal' do - @instance.should be_a(Petstore::Animal) + expect(@instance).to be_instance_of(Petstore::Animal) end end describe 'test attribute "class_name"' do it 'should work' do - # assertion here - # should be_a() - # should be_nil - # should == - # should_not == + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end diff --git a/samples/client/petstore/ruby/spec/models/api_response_spec.rb b/samples/client/petstore/ruby/spec/models/api_response_spec.rb index 279d8cb0aa5..67b0cbe1a03 100644 --- a/samples/client/petstore/ruby/spec/models/api_response_spec.rb +++ b/samples/client/petstore/ruby/spec/models/api_response_spec.rb @@ -33,36 +33,24 @@ describe 'ApiResponse' do describe 'test an instance of ApiResponse' do it 'should create an instact of ApiResponse' do - @instance.should be_a(Petstore::ApiResponse) + expect(@instance).to be_instance_of(Petstore::ApiResponse) end end describe 'test attribute "code"' do it 'should work' do - # assertion here - # should be_a() - # should be_nil - # should == - # should_not == + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "type"' do it 'should work' do - # assertion here - # should be_a() - # should be_nil - # should == - # should_not == + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "message"' do it 'should work' do - # assertion here - # should be_a() - # should be_nil - # should == - # should_not == + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end diff --git a/samples/client/petstore/ruby/spec/models/cat_spec.rb b/samples/client/petstore/ruby/spec/models/cat_spec.rb index e9b20d57eb0..97ae668ea3b 100644 --- a/samples/client/petstore/ruby/spec/models/cat_spec.rb +++ b/samples/client/petstore/ruby/spec/models/cat_spec.rb @@ -33,26 +33,18 @@ describe 'Cat' do describe 'test an instance of Cat' do it 'should create an instact of Cat' do - @instance.should be_a(Petstore::Cat) + expect(@instance).to be_instance_of(Petstore::Cat) end end describe 'test attribute "class_name"' do it 'should work' do - # assertion here - # should be_a() - # should be_nil - # should == - # should_not == + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "declawed"' do it 'should work' do - # assertion here - # should be_a() - # should be_nil - # should == - # should_not == + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end diff --git a/samples/client/petstore/ruby/spec/models/category_spec.rb b/samples/client/petstore/ruby/spec/models/category_spec.rb index 0e7001053f7..1481358afdc 100644 --- a/samples/client/petstore/ruby/spec/models/category_spec.rb +++ b/samples/client/petstore/ruby/spec/models/category_spec.rb @@ -33,26 +33,18 @@ describe 'Category' do describe 'test an instance of Category' do it 'should create an instact of Category' do - @instance.should be_a(Petstore::Category) + expect(@instance).to be_instance_of(Petstore::Category) end end describe 'test attribute "id"' do it 'should work' do - # assertion here - # should be_a() - # should be_nil - # should == - # should_not == + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "name"' do it 'should work' do - # assertion here - # should be_a() - # should be_nil - # should == - # should_not == + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end diff --git a/samples/client/petstore/ruby/spec/models/dog_spec.rb b/samples/client/petstore/ruby/spec/models/dog_spec.rb index b319d72b80a..e3eb4be12fc 100644 --- a/samples/client/petstore/ruby/spec/models/dog_spec.rb +++ b/samples/client/petstore/ruby/spec/models/dog_spec.rb @@ -33,26 +33,18 @@ describe 'Dog' do describe 'test an instance of Dog' do it 'should create an instact of Dog' do - @instance.should be_a(Petstore::Dog) + expect(@instance).to be_instance_of(Petstore::Dog) end end - describe 'test attribute "breed"' do + describe 'test attribute "class_name"' do it 'should work' do - # assertion here - # should be_a() - # should be_nil - # should == - # should_not == + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end - describe 'test attribute "class_name"' do + describe 'test attribute "breed"' do it 'should work' do - # assertion here - # should be_a() - # should be_nil - # should == - # should_not == + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end diff --git a/samples/client/petstore/ruby/spec/models/enum_class_spec.rb b/samples/client/petstore/ruby/spec/models/enum_class_spec.rb new file mode 100644 index 00000000000..b8610d74a1b --- /dev/null +++ b/samples/client/petstore/ruby/spec/models/enum_class_spec.rb @@ -0,0 +1,40 @@ +=begin +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +License: Apache 2.0 +http://www.apache.org/licenses/LICENSE-2.0.html + +Terms of Service: http://swagger.io/terms/ + +=end + +require 'spec_helper' +require 'json' +require 'date' + +# Unit tests for Petstore::EnumClass +# Automatically generated by swagger-codegen (github.com/swagger-api/swagger-codegen) +# Please update as you see appropriate +describe 'EnumClass' do + before do + # run before each test + @instance = Petstore::EnumClass.new + end + + after do + # run after each test + end + + describe 'test an instance of EnumClass' do + it 'should create an instact of EnumClass' do + expect(@instance).to be_instance_of(Petstore::EnumClass) + end + end +end + diff --git a/samples/client/petstore/ruby/spec/models/enum_test_spec.rb b/samples/client/petstore/ruby/spec/models/enum_test_spec.rb new file mode 100644 index 00000000000..91941d8a50d --- /dev/null +++ b/samples/client/petstore/ruby/spec/models/enum_test_spec.rb @@ -0,0 +1,58 @@ +=begin +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +License: Apache 2.0 +http://www.apache.org/licenses/LICENSE-2.0.html + +Terms of Service: http://swagger.io/terms/ + +=end + +require 'spec_helper' +require 'json' +require 'date' + +# Unit tests for Petstore::EnumTest +# Automatically generated by swagger-codegen (github.com/swagger-api/swagger-codegen) +# Please update as you see appropriate +describe 'EnumTest' do + before do + # run before each test + @instance = Petstore::EnumTest.new + end + + after do + # run after each test + end + + describe 'test an instance of EnumTest' do + it 'should create an instact of EnumTest' do + expect(@instance).to be_instance_of(Petstore::EnumTest) + end + end + describe 'test attribute "enum_string"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + describe 'test attribute "enum_integer"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + describe 'test attribute "enum_number"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + +end + diff --git a/samples/client/petstore/ruby/spec/models/format_test_spec.rb b/samples/client/petstore/ruby/spec/models/format_test_spec.rb index 50b2980d17b..e7a81fe537c 100644 --- a/samples/client/petstore/ruby/spec/models/format_test_spec.rb +++ b/samples/client/petstore/ruby/spec/models/format_test_spec.rb @@ -33,136 +33,84 @@ describe 'FormatTest' do describe 'test an instance of FormatTest' do it 'should create an instact of FormatTest' do - @instance.should be_a(Petstore::FormatTest) + expect(@instance).to be_instance_of(Petstore::FormatTest) end end describe 'test attribute "integer"' do it 'should work' do - # assertion here - # should be_a() - # should be_nil - # should == - # should_not == + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "int32"' do it 'should work' do - # assertion here - # should be_a() - # should be_nil - # should == - # should_not == + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "int64"' do it 'should work' do - # assertion here - # should be_a() - # should be_nil - # should == - # should_not == + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "number"' do it 'should work' do - # assertion here - # should be_a() - # should be_nil - # should == - # should_not == + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "float"' do it 'should work' do - # assertion here - # should be_a() - # should be_nil - # should == - # should_not == + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "double"' do it 'should work' do - # assertion here - # should be_a() - # should be_nil - # should == - # should_not == + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "string"' do it 'should work' do - # assertion here - # should be_a() - # should be_nil - # should == - # should_not == + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "byte"' do it 'should work' do - # assertion here - # should be_a() - # should be_nil - # should == - # should_not == + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "binary"' do it 'should work' do - # assertion here - # should be_a() - # should be_nil - # should == - # should_not == + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "date"' do it 'should work' do - # assertion here - # should be_a() - # should be_nil - # should == - # should_not == + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "date_time"' do it 'should work' do - # assertion here - # should be_a() - # should be_nil - # should == - # should_not == + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "uuid"' do it 'should work' do - # assertion here - # should be_a() - # should be_nil - # should == - # should_not == + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "password"' do it 'should work' do - # assertion here - # should be_a() - # should be_nil - # should == - # should_not == + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end diff --git a/samples/client/petstore/ruby/spec/models/inline_response_200_spec.rb b/samples/client/petstore/ruby/spec/models/inline_response_200_spec.rb deleted file mode 100644 index 36a4da3baaa..00000000000 --- a/samples/client/petstore/ruby/spec/models/inline_response_200_spec.rb +++ /dev/null @@ -1,100 +0,0 @@ -=begin -Swagger Petstore - -This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters - -OpenAPI spec version: 1.0.0 -Contact: apiteam@swagger.io -Generated by: https://github.com/swagger-api/swagger-codegen.git - -License: Apache 2.0 -http://www.apache.org/licenses/LICENSE-2.0.html - -Terms of Service: http://swagger.io/terms/ - -=end - -require 'spec_helper' -require 'json' -require 'date' - -# Unit tests for Petstore::InlineResponse200 -# Automatically generated by swagger-codegen (github.com/swagger-api/swagger-codegen) -# Please update as you see appropriate -describe 'InlineResponse200', pending: "Original spec does not have InlineResponse200 and we'll renable this after updating Petstore server" do - before do - # run before each test - @instance = Petstore::InlineResponse200.new - end - - after do - # run after each test - end - - describe 'test an instance of InlineResponse200' do - it 'should create an instact of InlineResponse200' do - @instance.should be_a(Petstore::InlineResponse200) - end - end - describe 'test attribute "tags"' do - it 'should work' do - # assertion here - # should be_a() - # should be_nil - # should == - # should_not == - end - end - - describe 'test attribute "id"' do - it 'should work' do - # assertion here - # should be_a() - # should be_nil - # should == - # should_not == - end - end - - describe 'test attribute "category"' do - it 'should work' do - # assertion here - # should be_a() - # should be_nil - # should == - # should_not == - end - end - - describe 'test attribute "status"' do - it 'should work' do - # assertion here - # should be_a() - # should be_nil - # should == - # should_not == - end - end - - describe 'test attribute "name"' do - it 'should work' do - # assertion here - # should be_a() - # should be_nil - # should == - # should_not == - end - end - - describe 'test attribute "photo_urls"' do - it 'should work' do - # assertion here - # should be_a() - # should be_nil - # should == - # should_not == - end - end - -end - diff --git a/samples/client/petstore/ruby/spec/models/model_200_response_spec.rb b/samples/client/petstore/ruby/spec/models/model_200_response_spec.rb index 88045611d9c..8b8879105d0 100644 --- a/samples/client/petstore/ruby/spec/models/model_200_response_spec.rb +++ b/samples/client/petstore/ruby/spec/models/model_200_response_spec.rb @@ -33,16 +33,12 @@ describe 'Model200Response' do describe 'test an instance of Model200Response' do it 'should create an instact of Model200Response' do - @instance.should be_a(Petstore::Model200Response) + expect(@instance).to be_instance_of(Petstore::Model200Response) end end describe 'test attribute "name"' do it 'should work' do - # assertion here - # should be_a() - # should be_nil - # should == - # should_not == + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end diff --git a/samples/client/petstore/ruby/spec/models/model_return_spec.rb b/samples/client/petstore/ruby/spec/models/model_return_spec.rb index 7b6f3a571c4..5a80c97542b 100644 --- a/samples/client/petstore/ruby/spec/models/model_return_spec.rb +++ b/samples/client/petstore/ruby/spec/models/model_return_spec.rb @@ -33,16 +33,12 @@ describe 'ModelReturn' do describe 'test an instance of ModelReturn' do it 'should create an instact of ModelReturn' do - @instance.should be_a(Petstore::ModelReturn) + expect(@instance).to be_instance_of(Petstore::ModelReturn) end end describe 'test attribute "_return"' do it 'should work' do - # assertion here - # should be_a() - # should be_nil - # should == - # should_not == + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end diff --git a/samples/client/petstore/ruby/spec/models/name_spec.rb b/samples/client/petstore/ruby/spec/models/name_spec.rb index e4942b173b9..03a9c69ece1 100644 --- a/samples/client/petstore/ruby/spec/models/name_spec.rb +++ b/samples/client/petstore/ruby/spec/models/name_spec.rb @@ -33,36 +33,24 @@ describe 'Name' do describe 'test an instance of Name' do it 'should create an instact of Name' do - @instance.should be_a(Petstore::Name) + expect(@instance).to be_instance_of(Petstore::Name) end end describe 'test attribute "name"' do it 'should work' do - # assertion here - # should be_a() - # should be_nil - # should == - # should_not == + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "snake_case"' do it 'should work' do - # assertion here - # should be_a() - # should be_nil - # should == - # should_not == + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "property"' do it 'should work' do - # assertion here - # should be_a() - # should be_nil - # should == - # should_not == + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end diff --git a/samples/client/petstore/ruby/spec/models/order_spec.rb b/samples/client/petstore/ruby/spec/models/order_spec.rb index 420cfea059c..73bd5c082fd 100644 --- a/samples/client/petstore/ruby/spec/models/order_spec.rb +++ b/samples/client/petstore/ruby/spec/models/order_spec.rb @@ -33,66 +33,42 @@ describe 'Order' do describe 'test an instance of Order' do it 'should create an instact of Order' do - @instance.should be_a(Petstore::Order) + expect(@instance).to be_instance_of(Petstore::Order) end end describe 'test attribute "id"' do it 'should work' do - # assertion here - # should be_a() - # should be_nil - # should == - # should_not == + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "pet_id"' do it 'should work' do - # assertion here - # should be_a() - # should be_nil - # should == - # should_not == + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "quantity"' do it 'should work' do - # assertion here - # should be_a() - # should be_nil - # should == - # should_not == + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "ship_date"' do it 'should work' do - # assertion here - # should be_a() - # should be_nil - # should == - # should_not == + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "status"' do it 'should work' do - # assertion here - # should be_a() - # should be_nil - # should == - # should_not == + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "complete"' do it 'should work' do - # assertion here - # should be_a() - # should be_nil - # should == - # should_not == + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end diff --git a/samples/client/petstore/ruby/spec/models/pet_spec.rb b/samples/client/petstore/ruby/spec/models/pet_spec.rb index 96ced2cd366..9911ced1366 100644 --- a/samples/client/petstore/ruby/spec/models/pet_spec.rb +++ b/samples/client/petstore/ruby/spec/models/pet_spec.rb @@ -33,66 +33,42 @@ describe 'Pet' do describe 'test an instance of Pet' do it 'should create an instact of Pet' do - @instance.should be_a(Petstore::Pet) + expect(@instance).to be_instance_of(Petstore::Pet) end end describe 'test attribute "id"' do it 'should work' do - # assertion here - # should be_a() - # should be_nil - # should == - # should_not == + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "category"' do it 'should work' do - # assertion here - # should be_a() - # should be_nil - # should == - # should_not == + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "name"' do it 'should work' do - # assertion here - # should be_a() - # should be_nil - # should == - # should_not == + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "photo_urls"' do it 'should work' do - # assertion here - # should be_a() - # should be_nil - # should == - # should_not == + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "tags"' do it 'should work' do - # assertion here - # should be_a() - # should be_nil - # should == - # should_not == + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "status"' do it 'should work' do - # assertion here - # should be_a() - # should be_nil - # should == - # should_not == + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end diff --git a/samples/client/petstore/ruby/spec/models/special_model_name_spec.rb b/samples/client/petstore/ruby/spec/models/special_model_name_spec.rb index aa32e3fc7b2..cd93568e8f9 100644 --- a/samples/client/petstore/ruby/spec/models/special_model_name_spec.rb +++ b/samples/client/petstore/ruby/spec/models/special_model_name_spec.rb @@ -33,16 +33,12 @@ describe 'SpecialModelName' do describe 'test an instance of SpecialModelName' do it 'should create an instact of SpecialModelName' do - @instance.should be_a(Petstore::SpecialModelName) + expect(@instance).to be_instance_of(Petstore::SpecialModelName) end end describe 'test attribute "special_property_name"' do it 'should work' do - # assertion here - # should be_a() - # should be_nil - # should == - # should_not == + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end diff --git a/samples/client/petstore/ruby/spec/models/tag_spec.rb b/samples/client/petstore/ruby/spec/models/tag_spec.rb index 55778d8fd67..68b77e026b1 100644 --- a/samples/client/petstore/ruby/spec/models/tag_spec.rb +++ b/samples/client/petstore/ruby/spec/models/tag_spec.rb @@ -33,26 +33,18 @@ describe 'Tag' do describe 'test an instance of Tag' do it 'should create an instact of Tag' do - @instance.should be_a(Petstore::Tag) + expect(@instance).to be_instance_of(Petstore::Tag) end end describe 'test attribute "id"' do it 'should work' do - # assertion here - # should be_a() - # should be_nil - # should == - # should_not == + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "name"' do it 'should work' do - # assertion here - # should be_a() - # should be_nil - # should == - # should_not == + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end diff --git a/samples/client/petstore/ruby/spec/models/user_spec.rb b/samples/client/petstore/ruby/spec/models/user_spec.rb index a6b872e834c..fc510605b5c 100644 --- a/samples/client/petstore/ruby/spec/models/user_spec.rb +++ b/samples/client/petstore/ruby/spec/models/user_spec.rb @@ -33,86 +33,54 @@ describe 'User' do describe 'test an instance of User' do it 'should create an instact of User' do - @instance.should be_a(Petstore::User) + expect(@instance).to be_instance_of(Petstore::User) end end describe 'test attribute "id"' do it 'should work' do - # assertion here - # should be_a() - # should be_nil - # should == - # should_not == + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "username"' do it 'should work' do - # assertion here - # should be_a() - # should be_nil - # should == - # should_not == + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "first_name"' do it 'should work' do - # assertion here - # should be_a() - # should be_nil - # should == - # should_not == + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "last_name"' do it 'should work' do - # assertion here - # should be_a() - # should be_nil - # should == - # should_not == + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "email"' do it 'should work' do - # assertion here - # should be_a() - # should be_nil - # should == - # should_not == + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "password"' do it 'should work' do - # assertion here - # should be_a() - # should be_nil - # should == - # should_not == + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "phone"' do it 'should work' do - # assertion here - # should be_a() - # should be_nil - # should == - # should_not == + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "user_status"' do it 'should work' do - # assertion here - # should be_a() - # should be_nil - # should == - # should_not == + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end diff --git a/samples/client/petstore/ruby/spec/pet_spec.rb b/samples/client/petstore/ruby/spec/pet_spec.rb index b05b2163353..737eee56d07 100644 --- a/samples/client/petstore/ruby/spec/pet_spec.rb +++ b/samples/client/petstore/ruby/spec/pet_spec.rb @@ -1,16 +1,6 @@ require 'spec_helper' require 'json' -def serialize_json(o) - API_CLIENT.object_to_http_body(o) -end - -def deserialize_json(s, type) - headers = {'Content-Type' => 'application/json'} - response = double('response', headers: headers, body: s) - API_CLIENT.deserialize(response, type) -end - describe "Pet" do before do @pet_api = Petstore::PetApi.new(API_CLIENT) diff --git a/samples/client/petstore/ruby/spec/spec.opts b/samples/client/petstore/ruby/spec/spec.opts deleted file mode 100644 index 391705bf8b0..00000000000 --- a/samples/client/petstore/ruby/spec/spec.opts +++ /dev/null @@ -1,4 +0,0 @@ ---colour ---format progress ---loadby mtime ---reverse diff --git a/samples/client/petstore/ruby/spec/spec_helper.rb b/samples/client/petstore/ruby/spec/spec_helper.rb index 50702c439b7..11794c9ebcf 100644 --- a/samples/client/petstore/ruby/spec/spec_helper.rb +++ b/samples/client/petstore/ruby/spec/spec_helper.rb @@ -1,43 +1,107 @@ -require 'rubygems' -require 'bundler/setup' +# load the gem require 'petstore' -require 'vcr' -require 'typhoeus' -require 'json' -require 'yaml' -require 'rspec' +# The following was generated by the `rspec --init` command. Conventionally, all +# specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`. +# The generated `.rspec` file contains `--require spec_helper` which will cause +# this file to always be loaded, without a need to explicitly require it in any +# files. +# +# Given that it is always loaded, you are encouraged to keep this file as +# light-weight as possible. Requiring heavyweight dependencies from this file +# will add to the boot time of your test suite on EVERY test run, even for an +# individual file that may not need all of that loaded. Instead, consider making +# a separate helper file that requires the additional dependencies and performs +# the additional setup, and require it from the spec files that actually need +# it. +# +# The `.rspec` file also contains a few flags that are not defaults but that +# users commonly want. +# +# See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration RSpec.configure do |config| - # some (optional) config here - config.expect_with :rspec do |c| - c.syntax = :should + # rspec-expectations config goes here. You can use an alternate + # assertion/expectation library such as wrong or the stdlib/minitest + # assertions if you prefer. + config.expect_with :rspec do |expectations| + # This option will default to `true` in RSpec 4. It makes the `description` + # and `failure_message` of custom matchers include text for helper methods + # defined using `chain`, e.g.: + # be_bigger_than(2).and_smaller_than(4).description + # # => "be bigger than 2 and smaller than 4" + # ...rather than: + # # => "be bigger than 2" + expectations.include_chain_clauses_in_custom_matcher_descriptions = true end - config.mock_with :rspec do |c| - c.syntax = :should + + # rspec-mocks config goes here. You can use an alternate test double + # library (such as bogus or mocha) by changing the `mock_with` option here. + config.mock_with :rspec do |mocks| + # Prevents you from mocking or stubbing a method that does not exist on + # a real object. This is generally recommended, and will default to + # `true` in RSpec 4. + mocks.verify_partial_doubles = true end + +# The settings below are suggested to provide a good initial experience +# with RSpec, but feel free to customize to your heart's content. +=begin + # These two settings work together to allow you to limit a spec run + # to individual examples or groups you care about by tagging them with + # `:focus` metadata. When nothing is tagged with `:focus`, all examples + # get run. + config.filter_run :focus + config.run_all_when_everything_filtered = true + + # Allows RSpec to persist some state between runs in order to support + # the `--only-failures` and `--next-failure` CLI options. We recommend + # you configure your source control system to ignore this file. + config.example_status_persistence_file_path = "spec/examples.txt" + + # Limits the available syntax to the non-monkey patched syntax that is + # recommended. For more details, see: + # - http://rspec.info/blog/2012/06/rspecs-new-expectation-syntax/ + # - http://www.teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/ + # - http://rspec.info/blog/2014/05/notable-changes-in-rspec-3/#zero-monkey-patching-mode + config.disable_monkey_patching! + + # This setting enables warnings. It's recommended, but in some cases may + # be too noisy due to issues in dependencies. + config.warnings = true + + # Many RSpec users commonly either run the entire suite or an individual + # file, and it's useful to allow more verbose output when running an + # individual spec file. + if config.files_to_run.one? + # Use the documentation formatter for detailed output, + # unless a formatter has already been configured + # (e.g. via a command-line flag). + config.default_formatter = 'doc' + end + + # Print the 10 slowest examples and example groups at the + # end of the spec run, to help surface which specs are running + # particularly slow. + config.profile_examples = 10 + + # Run specs in random order to surface order dependencies. If you find an + # order dependency and want to debug it, you can fix the order by providing + # the seed, which is printed after each run. + # --seed 1234 + config.order = :random + + # Seed global randomization in this process using the `--seed` CLI option. + # Setting this allows you to use `--seed` to deterministically reproduce + # test failures related to randomization by passing the same `--seed` value + # as the one that triggered the failure. + Kernel.srand config.seed +=end end - -WebMock.allow_net_connect! if defined? WebMock - -def help - puts "\nOh noes! You gotta stuff your swagger credentials in ~/.swagger.yml like so:\n\n" - puts "api_key: '12345abcdefg'" - puts "username: 'fumanchu'" - puts "password: 'kalamazoo'\n\n" - exit -end - -# no longer reading credentials (not used) from file (20150413) -# Parse ~/.swagger.yml for user credentials -#begin -# CREDENTIALS = YAML::load_file(File.join(ENV['HOME'], ".swagger.yml")).symbolize_keys -#rescue -# help -#end - +# API client (shared between all the test cases) API_CLIENT = Petstore::ApiClient.new(Petstore::Configuration.new) +# randomly generate an ID def random_id rand(1000000) + 20000 end @@ -57,11 +121,11 @@ end def prepare_store(store_api) order_id = 5 order = Petstore::Order.new("id" => order_id, - "petId" => 123, - "quantity" => 789, - "shipDate" => "2015-04-06T23:42:01.678Z", - "status" => "placed", - "complete" => false) + "petId" => 123, + "quantity" => 789, + "shipDate" => "2015-04-06T23:42:01.678Z", + "status" => "placed", + "complete" => false) store_api.place_order(order) return order_id end @@ -69,3 +133,15 @@ end # A random string to tack onto stuff to ensure we're not seeing # data from a previous test run RAND = ("a".."z").to_a.sample(8).join + +# helper method to serialize object to json string +def serialize_json(o) + API_CLIENT.object_to_http_body(o) +end + +# helper method to deserialize json string back to object +def deserialize_json(s, type) + headers = {'Content-Type' => 'application/json'} + response = double('response', headers: headers, body: s) + API_CLIENT.deserialize(response, type) +end diff --git a/samples/client/petstore/typescript-angular/package.json b/samples/client/petstore/typescript-angular/package.json index f50b782c09f..0819b27f295 100644 --- a/samples/client/petstore/typescript-angular/package.json +++ b/samples/client/petstore/typescript-angular/package.json @@ -5,12 +5,13 @@ "main": "api.js", "scripts": { "postinstall": "tsd reinstall --overwrite", - "test": "tsc", + "test": "tsc --target ES6 && node client.js", "clean": "rm -Rf node_modules/ typings/ *.js" }, "author": "Mads M. Tandrup", "license": "Apache 2.0", "dependencies": { + "request": "^2.60.0", "angular": "^1.4.3" }, "devDependencies": { diff --git a/samples/client/petstore/typescript-angular/tsd.json b/samples/client/petstore/typescript-angular/tsd.json index 182b9f68fa2..c4cfa3f1bac 100644 --- a/samples/client/petstore/typescript-angular/tsd.json +++ b/samples/client/petstore/typescript-angular/tsd.json @@ -5,11 +5,20 @@ "path": "typings", "bundle": "typings/tsd.d.ts", "installed": { - "angularjs/angular.d.ts": { + "angularjs/angular.d.ts": { "commit": "f6c8ca47193fb67947944a3170912672ac3e908e" }, "jquery/jquery.d.ts": { "commit": "f6c8ca47193fb67947944a3170912672ac3e908e" + }, + "request/request.d.ts": { + "commit": "f6c8ca47193fb67947944a3170912672ac3e908e" + }, + "form-data/form-data.d.ts": { + "commit": "f6c8ca47193fb67947944a3170912672ac3e908e" + }, + "node/node.d.ts": { + "commit": "f6c8ca47193fb67947944a3170912672ac3e908e" } } } diff --git a/samples/client/petstore/typescript-fetch/api.ts b/samples/client/petstore/typescript-fetch/api.ts new file mode 100644 index 00000000000..0c8f4201e4c --- /dev/null +++ b/samples/client/petstore/typescript-fetch/api.ts @@ -0,0 +1,859 @@ +import * as querystring from 'querystring'; +import * as fetch from 'isomorphic-fetch'; +import {assign} from './assign'; + + +export interface Category { + "id"?: number; + "name"?: string; +} + +export interface Order { + "id"?: number; + "petId"?: number; + "quantity"?: number; + "shipDate"?: Date; + + /** + * Order Status + */ + "status"?: Order.StatusEnum; + "complete"?: boolean; +} + + +export enum StatusEnum { + placed = 'placed', + approved = 'approved', + delivered = 'delivered' +} +export interface Pet { + "id"?: number; + "category"?: Category; + "name": string; + "photoUrls": Array; + "tags"?: Array; + + /** + * pet status in the store + */ + "status"?: Pet.StatusEnum; +} + + +export enum StatusEnum { + available = 'available', + pending = 'pending', + sold = 'sold' +} +export interface Tag { + "id"?: number; + "name"?: string; +} + +export interface User { + "id"?: number; + "username"?: string; + "firstName"?: string; + "lastName"?: string; + "email"?: string; + "password"?: string; + "phone"?: string; + + /** + * User Status + */ + "userStatus"?: number; +} + + +//export namespace { + 'use strict'; + + export class PetApi { + protected basePath = 'http://petstore.swagger.io/v2'; + public defaultHeaders : any = {}; + + constructor(basePath?: string) { + if (basePath) { + this.basePath = basePath; + } + } + + /** + * Add a new pet to the store + * + * @param body Pet object that needs to be added to the store + */ + public addPet (params: { body?: Pet; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { + const localVarPath = this.basePath + '/pet'; + + let queryParameters: any = assign({}, extraQueryParams); + let headerParams: any = assign({}, this.defaultHeaders); + headerParams['Content-Type'] = 'application/json'; + + let fetchParams = { + method: 'POST', + headers: headerParams, + body: JSON.stringify(params.body), + + }; + + if (extraFetchParams) { + fetchParams = assign(fetchParams, extraFetchParams); + } + + let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); + + return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + var error = new Error(response.statusText); + error['response'] = response; + throw error; + } + }); + } + /** + * Deletes a pet + * + * @param petId Pet id to delete + * @param apiKey + */ + public deletePet (params: { petId: number; apiKey?: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { + const localVarPath = this.basePath + '/pet/{petId}' + .replace('{' + 'petId' + '}', String(params.petId)); + + let queryParameters: any = assign({}, extraQueryParams); + let headerParams: any = assign({}, this.defaultHeaders); + // verify required parameter 'petId' is set + if (params.petId == null) { + throw new Error('Missing required parameter petId when calling deletePet'); + } + headerParams['api_key'] = params.apiKey; + + let fetchParams = { + method: 'DELETE', + headers: headerParams, + + }; + + if (extraFetchParams) { + fetchParams = assign(fetchParams, extraFetchParams); + } + + let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); + + return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + var error = new Error(response.statusText); + error['response'] = response; + throw error; + } + }); + } + /** + * Finds Pets by status + * Multiple status values can be provided with comma seperated strings + * @param status Status values that need to be considered for filter + */ + public findPetsByStatus (params: { status?: Array; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise> { + const localVarPath = this.basePath + '/pet/findByStatus'; + + let queryParameters: any = assign({}, extraQueryParams); + let headerParams: any = assign({}, this.defaultHeaders); + if (params.status !== undefined) { + queryParameters['status'] = params.status; + } + + let fetchParams = { + method: 'GET', + headers: headerParams, + + }; + + if (extraFetchParams) { + fetchParams = assign(fetchParams, extraFetchParams); + } + + let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); + + return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + var error = new Error(response.statusText); + error['response'] = response; + throw error; + } + }); + } + /** + * Finds Pets by tags + * Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + * @param tags Tags to filter by + */ + public findPetsByTags (params: { tags?: Array; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise> { + const localVarPath = this.basePath + '/pet/findByTags'; + + let queryParameters: any = assign({}, extraQueryParams); + let headerParams: any = assign({}, this.defaultHeaders); + if (params.tags !== undefined) { + queryParameters['tags'] = params.tags; + } + + let fetchParams = { + method: 'GET', + headers: headerParams, + + }; + + if (extraFetchParams) { + fetchParams = assign(fetchParams, extraFetchParams); + } + + let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); + + return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + var error = new Error(response.statusText); + error['response'] = response; + throw error; + } + }); + } + /** + * Find pet by ID + * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + * @param petId ID of pet that needs to be fetched + */ + public getPetById (params: { petId: number; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise { + const localVarPath = this.basePath + '/pet/{petId}' + .replace('{' + 'petId' + '}', String(params.petId)); + + let queryParameters: any = assign({}, extraQueryParams); + let headerParams: any = assign({}, this.defaultHeaders); + // verify required parameter 'petId' is set + if (params.petId == null) { + throw new Error('Missing required parameter petId when calling getPetById'); + } + let fetchParams = { + method: 'GET', + headers: headerParams, + + }; + + if (extraFetchParams) { + fetchParams = assign(fetchParams, extraFetchParams); + } + + let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); + + return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + var error = new Error(response.statusText); + error['response'] = response; + throw error; + } + }); + } + /** + * Update an existing pet + * + * @param body Pet object that needs to be added to the store + */ + public updatePet (params: { body?: Pet; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { + const localVarPath = this.basePath + '/pet'; + + let queryParameters: any = assign({}, extraQueryParams); + let headerParams: any = assign({}, this.defaultHeaders); + headerParams['Content-Type'] = 'application/json'; + + let fetchParams = { + method: 'PUT', + headers: headerParams, + body: JSON.stringify(params.body), + + }; + + if (extraFetchParams) { + fetchParams = assign(fetchParams, extraFetchParams); + } + + let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); + + return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + var error = new Error(response.statusText); + error['response'] = response; + throw error; + } + }); + } + /** + * Updates a pet in the store with form data + * + * @param petId ID of pet that needs to be updated + * @param name Updated name of the pet + * @param status Updated status of the pet + */ + public updatePetWithForm (params: { petId: string; name?: string; status?: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { + const localVarPath = this.basePath + '/pet/{petId}' + .replace('{' + 'petId' + '}', String(params.petId)); + + let queryParameters: any = assign({}, extraQueryParams); + let headerParams: any = assign({}, this.defaultHeaders); + let formParams: any = {}; + headerParams['Content-Type'] = 'application/x-www-form-urlencoded'; + + // verify required parameter 'petId' is set + if (params.petId == null) { + throw new Error('Missing required parameter petId when calling updatePetWithForm'); + } + formParams['name'] = params.name; + + formParams['status'] = params.status; + + let fetchParams = { + method: 'POST', + headers: headerParams, + body: querystring.stringify(formParams), + + }; + + if (extraFetchParams) { + fetchParams = assign(fetchParams, extraFetchParams); + } + + let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); + + return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + var error = new Error(response.statusText); + error['response'] = response; + throw error; + } + }); + } + /** + * uploads an image + * + * @param petId ID of pet to update + * @param additionalMetadata Additional data to pass to server + * @param file file to upload + */ + public uploadFile (params: { petId: number; additionalMetadata?: string; file?: any; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { + const localVarPath = this.basePath + '/pet/{petId}/uploadImage' + .replace('{' + 'petId' + '}', String(params.petId)); + + let queryParameters: any = assign({}, extraQueryParams); + let headerParams: any = assign({}, this.defaultHeaders); + let formParams: any = {}; + headerParams['Content-Type'] = 'application/x-www-form-urlencoded'; + + // verify required parameter 'petId' is set + if (params.petId == null) { + throw new Error('Missing required parameter petId when calling uploadFile'); + } + formParams['additionalMetadata'] = params.additionalMetadata; + + formParams['file'] = params.file; + + let fetchParams = { + method: 'POST', + headers: headerParams, + body: querystring.stringify(formParams), + + }; + + if (extraFetchParams) { + fetchParams = assign(fetchParams, extraFetchParams); + } + + let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); + + return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + var error = new Error(response.statusText); + error['response'] = response; + throw error; + } + }); + } + } +//} +//export namespace { + 'use strict'; + + export class StoreApi { + protected basePath = 'http://petstore.swagger.io/v2'; + public defaultHeaders : any = {}; + + constructor(basePath?: string) { + if (basePath) { + this.basePath = basePath; + } + } + + /** + * Delete purchase order by ID + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * @param orderId ID of the order that needs to be deleted + */ + public deleteOrder (params: { orderId: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { + const localVarPath = this.basePath + '/store/order/{orderId}' + .replace('{' + 'orderId' + '}', String(params.orderId)); + + let queryParameters: any = assign({}, extraQueryParams); + let headerParams: any = assign({}, this.defaultHeaders); + // verify required parameter 'orderId' is set + if (params.orderId == null) { + throw new Error('Missing required parameter orderId when calling deleteOrder'); + } + let fetchParams = { + method: 'DELETE', + headers: headerParams, + + }; + + if (extraFetchParams) { + fetchParams = assign(fetchParams, extraFetchParams); + } + + let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); + + return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + var error = new Error(response.statusText); + error['response'] = response; + throw error; + } + }); + } + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + */ + public getInventory (params: { }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{ [key: string]: number; }> { + const localVarPath = this.basePath + '/store/inventory'; + + let queryParameters: any = assign({}, extraQueryParams); + let headerParams: any = assign({}, this.defaultHeaders); + let fetchParams = { + method: 'GET', + headers: headerParams, + + }; + + if (extraFetchParams) { + fetchParams = assign(fetchParams, extraFetchParams); + } + + let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); + + return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + var error = new Error(response.statusText); + error['response'] = response; + throw error; + } + }); + } + /** + * Find purchase order by ID + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * @param orderId ID of pet that needs to be fetched + */ + public getOrderById (params: { orderId: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise { + const localVarPath = this.basePath + '/store/order/{orderId}' + .replace('{' + 'orderId' + '}', String(params.orderId)); + + let queryParameters: any = assign({}, extraQueryParams); + let headerParams: any = assign({}, this.defaultHeaders); + // verify required parameter 'orderId' is set + if (params.orderId == null) { + throw new Error('Missing required parameter orderId when calling getOrderById'); + } + let fetchParams = { + method: 'GET', + headers: headerParams, + + }; + + if (extraFetchParams) { + fetchParams = assign(fetchParams, extraFetchParams); + } + + let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); + + return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + var error = new Error(response.statusText); + error['response'] = response; + throw error; + } + }); + } + /** + * Place an order for a pet + * + * @param body order placed for purchasing the pet + */ + public placeOrder (params: { body?: Order; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise { + const localVarPath = this.basePath + '/store/order'; + + let queryParameters: any = assign({}, extraQueryParams); + let headerParams: any = assign({}, this.defaultHeaders); + headerParams['Content-Type'] = 'application/json'; + + let fetchParams = { + method: 'POST', + headers: headerParams, + body: JSON.stringify(params.body), + + }; + + if (extraFetchParams) { + fetchParams = assign(fetchParams, extraFetchParams); + } + + let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); + + return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + var error = new Error(response.statusText); + error['response'] = response; + throw error; + } + }); + } + } +//} +//export namespace { + 'use strict'; + + export class UserApi { + protected basePath = 'http://petstore.swagger.io/v2'; + public defaultHeaders : any = {}; + + constructor(basePath?: string) { + if (basePath) { + this.basePath = basePath; + } + } + + /** + * Create user + * This can only be done by the logged in user. + * @param body Created user object + */ + public createUser (params: { body?: User; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { + const localVarPath = this.basePath + '/user'; + + let queryParameters: any = assign({}, extraQueryParams); + let headerParams: any = assign({}, this.defaultHeaders); + headerParams['Content-Type'] = 'application/json'; + + let fetchParams = { + method: 'POST', + headers: headerParams, + body: JSON.stringify(params.body), + + }; + + if (extraFetchParams) { + fetchParams = assign(fetchParams, extraFetchParams); + } + + let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); + + return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + var error = new Error(response.statusText); + error['response'] = response; + throw error; + } + }); + } + /** + * Creates list of users with given input array + * + * @param body List of user object + */ + public createUsersWithArrayInput (params: { body?: Array; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { + const localVarPath = this.basePath + '/user/createWithArray'; + + let queryParameters: any = assign({}, extraQueryParams); + let headerParams: any = assign({}, this.defaultHeaders); + headerParams['Content-Type'] = 'application/json'; + + let fetchParams = { + method: 'POST', + headers: headerParams, + body: JSON.stringify(params.body), + + }; + + if (extraFetchParams) { + fetchParams = assign(fetchParams, extraFetchParams); + } + + let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); + + return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + var error = new Error(response.statusText); + error['response'] = response; + throw error; + } + }); + } + /** + * Creates list of users with given input array + * + * @param body List of user object + */ + public createUsersWithListInput (params: { body?: Array; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { + const localVarPath = this.basePath + '/user/createWithList'; + + let queryParameters: any = assign({}, extraQueryParams); + let headerParams: any = assign({}, this.defaultHeaders); + headerParams['Content-Type'] = 'application/json'; + + let fetchParams = { + method: 'POST', + headers: headerParams, + body: JSON.stringify(params.body), + + }; + + if (extraFetchParams) { + fetchParams = assign(fetchParams, extraFetchParams); + } + + let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); + + return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + var error = new Error(response.statusText); + error['response'] = response; + throw error; + } + }); + } + /** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted + */ + public deleteUser (params: { username: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { + const localVarPath = this.basePath + '/user/{username}' + .replace('{' + 'username' + '}', String(params.username)); + + let queryParameters: any = assign({}, extraQueryParams); + let headerParams: any = assign({}, this.defaultHeaders); + // verify required parameter 'username' is set + if (params.username == null) { + throw new Error('Missing required parameter username when calling deleteUser'); + } + let fetchParams = { + method: 'DELETE', + headers: headerParams, + + }; + + if (extraFetchParams) { + fetchParams = assign(fetchParams, extraFetchParams); + } + + let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); + + return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + var error = new Error(response.statusText); + error['response'] = response; + throw error; + } + }); + } + /** + * Get user by user name + * + * @param username The name that needs to be fetched. Use user1 for testing. + */ + public getUserByName (params: { username: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise { + const localVarPath = this.basePath + '/user/{username}' + .replace('{' + 'username' + '}', String(params.username)); + + let queryParameters: any = assign({}, extraQueryParams); + let headerParams: any = assign({}, this.defaultHeaders); + // verify required parameter 'username' is set + if (params.username == null) { + throw new Error('Missing required parameter username when calling getUserByName'); + } + let fetchParams = { + method: 'GET', + headers: headerParams, + + }; + + if (extraFetchParams) { + fetchParams = assign(fetchParams, extraFetchParams); + } + + let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); + + return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + var error = new Error(response.statusText); + error['response'] = response; + throw error; + } + }); + } + /** + * Logs user into the system + * + * @param username The user name for login + * @param password The password for login in clear text + */ + public loginUser (params: { username?: string; password?: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise { + const localVarPath = this.basePath + '/user/login'; + + let queryParameters: any = assign({}, extraQueryParams); + let headerParams: any = assign({}, this.defaultHeaders); + if (params.username !== undefined) { + queryParameters['username'] = params.username; + } + + if (params.password !== undefined) { + queryParameters['password'] = params.password; + } + + let fetchParams = { + method: 'GET', + headers: headerParams, + + }; + + if (extraFetchParams) { + fetchParams = assign(fetchParams, extraFetchParams); + } + + let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); + + return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + var error = new Error(response.statusText); + error['response'] = response; + throw error; + } + }); + } + /** + * Logs out current logged in user session + * + */ + public logoutUser (params: { }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { + const localVarPath = this.basePath + '/user/logout'; + + let queryParameters: any = assign({}, extraQueryParams); + let headerParams: any = assign({}, this.defaultHeaders); + let fetchParams = { + method: 'GET', + headers: headerParams, + + }; + + if (extraFetchParams) { + fetchParams = assign(fetchParams, extraFetchParams); + } + + let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); + + return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + var error = new Error(response.statusText); + error['response'] = response; + throw error; + } + }); + } + /** + * Updated user + * This can only be done by the logged in user. + * @param username name that need to be deleted + * @param body Updated user object + */ + public updateUser (params: { username: string; body?: User; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { + const localVarPath = this.basePath + '/user/{username}' + .replace('{' + 'username' + '}', String(params.username)); + + let queryParameters: any = assign({}, extraQueryParams); + let headerParams: any = assign({}, this.defaultHeaders); + headerParams['Content-Type'] = 'application/json'; + + // verify required parameter 'username' is set + if (params.username == null) { + throw new Error('Missing required parameter username when calling updateUser'); + } + let fetchParams = { + method: 'PUT', + headers: headerParams, + body: JSON.stringify(params.body), + + }; + + if (extraFetchParams) { + fetchParams = assign(fetchParams, extraFetchParams); + } + + let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); + + return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + var error = new Error(response.statusText); + error['response'] = response; + throw error; + } + }); + } + } +//} diff --git a/samples/client/petstore/typescript-fetch/assign.ts b/samples/client/petstore/typescript-fetch/assign.ts new file mode 100644 index 00000000000..040f87d7d98 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/assign.ts @@ -0,0 +1,18 @@ +export function assign (target, ...args) { + 'use strict'; + if (target === undefined || target === null) { + throw new TypeError('Cannot convert undefined or null to object'); + } + + var output = Object(target); + for (let source of args) { + if (source !== undefined && source !== null) { + for (var nextKey in source) { + if (source.hasOwnProperty(nextKey)) { + output[nextKey] = source[nextKey]; + } + } + } + } + return output; +}; \ No newline at end of file diff --git a/samples/client/petstore/typescript-fetch/default-es6/README.md b/samples/client/petstore/typescript-fetch/default-es6/README.md new file mode 100644 index 00000000000..8ec43e76497 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/default-es6/README.md @@ -0,0 +1,44 @@ +# TypeScript-Fetch + +This generator creates TypeScript/JavaScript client that utilizes [Fetch API](https://fetch.spec.whatwg.org/). The codegen Node module can be used in the following environments: + +* Node.JS +* Webpack +* Browserify + +It is usable in both TypeScript and JavaScript. In TypeScript, the definition should be automatically resolved via `typings` in `package.json`. ([Reference](http://www.typescriptlang.org/docs/handbook/typings-for-npm-packages.html)) + +### Installation ### + +`swagger-codegen` does not generate JavaScript directly. The codegen Node module comes with `package.json` that bundles `typescript` and `typings` so it can self-compile. The self-compile is normally run automatically via the `npm` `postinstall` script of `npm install`. + +CAVEAT: Due to [privilege implications](https://docs.npmjs.com/misc/scripts#user), `npm` may skip `postinstall` script if the user is `root`. You would need to manually invoke `npm install` or `npm run postinstall` for the codegen module if that's the case. + +#### NPM repository ### +If you remove `"private": true` from `package.json`, you may publish the module to NPM. In which case, you would be able to install the module as any other NPM module. + +It maybe useful to use [scoped packages](https://docs.npmjs.com/misc/scope). + +#### NPM install local file ### +You should be able to directly install the module using `npm install file:///codegen_path`. + +NOTES: If you do `npm install file:///codegen_path --save` NPM might convert your path to relative path, maybe have adverse affect. `npm install` and `npm shrinkwrap` may misbehave if the installation path is not absolute. + +#### direct copy/symlink ### +You may also simply copy or symlink the codegen into a directly under your project. The syntax of the usage would differ if you take this route. (See below) + +### Usage ### +With ES6 module syntax, the following syntaxes are supported: +``` +import * as localName from 'npmName'; +import {operationId} from 'npmName'; + +import * as localName from './symlinkDir'; +import {operationId} from './symlinkDir'; +``` +With CommonJS, the following syntaxes are supported: +``` +import localName = require('npmName'); + +import localName = require('./symlinkDir')'; +``` \ No newline at end of file diff --git a/samples/client/petstore/typescript-fetch/default-es6/api.ts b/samples/client/petstore/typescript-fetch/default-es6/api.ts new file mode 100644 index 00000000000..3d075fc2809 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/default-es6/api.ts @@ -0,0 +1,855 @@ +import * as querystring from 'querystring'; +import * as fetch from 'isomorphic-fetch'; +import {assign} from './assign'; + + +export interface Category { + "id"?: number; + "name"?: string; +} + +export interface Order { + "id"?: number; + "petId"?: number; + "quantity"?: number; + "shipDate"?: Date; + + /** + * Order Status + */ + "status"?: Order.StatusEnum; + "complete"?: boolean; +} + +export namespace Order { + +export type StatusEnum = 'placed' | 'approved' | 'delivered'; +} +export interface Pet { + "id"?: number; + "category"?: Category; + "name": string; + "photoUrls": Array; + "tags"?: Array; + + /** + * pet status in the store + */ + "status"?: Pet.StatusEnum; +} + +export namespace Pet { + +export type StatusEnum = 'available' | 'pending' | 'sold'; +} +export interface Tag { + "id"?: number; + "name"?: string; +} + +export interface User { + "id"?: number; + "username"?: string; + "firstName"?: string; + "lastName"?: string; + "email"?: string; + "password"?: string; + "phone"?: string; + + /** + * User Status + */ + "userStatus"?: number; +} + + +//export namespace { + 'use strict'; + + export class PetApi { + protected basePath = 'http://petstore.swagger.io/v2'; + public defaultHeaders : any = {}; + + constructor(basePath?: string) { + if (basePath) { + this.basePath = basePath; + } + } + + /** + * Add a new pet to the store + * + * @param body Pet object that needs to be added to the store + */ + public addPet (params: { body?: Pet; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { + const localVarPath = this.basePath + '/pet'; + + let queryParameters: any = assign({}, extraQueryParams); + let headerParams: any = assign({}, this.defaultHeaders); + headerParams['Content-Type'] = 'application/json'; + + let fetchParams = { + method: 'POST', + headers: headerParams, + body: JSON.stringify(params.body), + + }; + + if (extraFetchParams) { + fetchParams = assign(fetchParams, extraFetchParams); + } + + let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); + + return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + let error = new Error(response.statusText); + (error as any).response = response; + throw error; + } + }); + } + /** + * Deletes a pet + * + * @param petId Pet id to delete + * @param apiKey + */ + public deletePet (params: { petId: number; apiKey?: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { + const localVarPath = this.basePath + '/pet/{petId}' + .replace('{' + 'petId' + '}', String(params.petId)); + + let queryParameters: any = assign({}, extraQueryParams); + let headerParams: any = assign({}, this.defaultHeaders); + // verify required parameter 'petId' is set + if (params.petId == null) { + throw new Error('Missing required parameter petId when calling deletePet'); + } + headerParams['api_key'] = params.apiKey; + + let fetchParams = { + method: 'DELETE', + headers: headerParams, + + }; + + if (extraFetchParams) { + fetchParams = assign(fetchParams, extraFetchParams); + } + + let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); + + return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + let error = new Error(response.statusText); + (error as any).response = response; + throw error; + } + }); + } + /** + * Finds Pets by status + * Multiple status values can be provided with comma seperated strings + * @param status Status values that need to be considered for filter + */ + public findPetsByStatus (params: { status?: Array; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise> { + const localVarPath = this.basePath + '/pet/findByStatus'; + + let queryParameters: any = assign({}, extraQueryParams); + let headerParams: any = assign({}, this.defaultHeaders); + if (params.status !== undefined) { + queryParameters['status'] = params.status; + } + + let fetchParams = { + method: 'GET', + headers: headerParams, + + }; + + if (extraFetchParams) { + fetchParams = assign(fetchParams, extraFetchParams); + } + + let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); + + return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + let error = new Error(response.statusText); + (error as any).response = response; + throw error; + } + }); + } + /** + * Finds Pets by tags + * Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + * @param tags Tags to filter by + */ + public findPetsByTags (params: { tags?: Array; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise> { + const localVarPath = this.basePath + '/pet/findByTags'; + + let queryParameters: any = assign({}, extraQueryParams); + let headerParams: any = assign({}, this.defaultHeaders); + if (params.tags !== undefined) { + queryParameters['tags'] = params.tags; + } + + let fetchParams = { + method: 'GET', + headers: headerParams, + + }; + + if (extraFetchParams) { + fetchParams = assign(fetchParams, extraFetchParams); + } + + let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); + + return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + let error = new Error(response.statusText); + (error as any).response = response; + throw error; + } + }); + } + /** + * Find pet by ID + * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + * @param petId ID of pet that needs to be fetched + */ + public getPetById (params: { petId: number; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise { + const localVarPath = this.basePath + '/pet/{petId}' + .replace('{' + 'petId' + '}', String(params.petId)); + + let queryParameters: any = assign({}, extraQueryParams); + let headerParams: any = assign({}, this.defaultHeaders); + // verify required parameter 'petId' is set + if (params.petId == null) { + throw new Error('Missing required parameter petId when calling getPetById'); + } + let fetchParams = { + method: 'GET', + headers: headerParams, + + }; + + if (extraFetchParams) { + fetchParams = assign(fetchParams, extraFetchParams); + } + + let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); + + return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + let error = new Error(response.statusText); + (error as any).response = response; + throw error; + } + }); + } + /** + * Update an existing pet + * + * @param body Pet object that needs to be added to the store + */ + public updatePet (params: { body?: Pet; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { + const localVarPath = this.basePath + '/pet'; + + let queryParameters: any = assign({}, extraQueryParams); + let headerParams: any = assign({}, this.defaultHeaders); + headerParams['Content-Type'] = 'application/json'; + + let fetchParams = { + method: 'PUT', + headers: headerParams, + body: JSON.stringify(params.body), + + }; + + if (extraFetchParams) { + fetchParams = assign(fetchParams, extraFetchParams); + } + + let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); + + return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + let error = new Error(response.statusText); + (error as any).response = response; + throw error; + } + }); + } + /** + * Updates a pet in the store with form data + * + * @param petId ID of pet that needs to be updated + * @param name Updated name of the pet + * @param status Updated status of the pet + */ + public updatePetWithForm (params: { petId: string; name?: string; status?: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { + const localVarPath = this.basePath + '/pet/{petId}' + .replace('{' + 'petId' + '}', String(params.petId)); + + let queryParameters: any = assign({}, extraQueryParams); + let headerParams: any = assign({}, this.defaultHeaders); + let formParams: any = {}; + headerParams['Content-Type'] = 'application/x-www-form-urlencoded'; + + // verify required parameter 'petId' is set + if (params.petId == null) { + throw new Error('Missing required parameter petId when calling updatePetWithForm'); + } + formParams['name'] = params.name; + + formParams['status'] = params.status; + + let fetchParams = { + method: 'POST', + headers: headerParams, + body: querystring.stringify(formParams), + + }; + + if (extraFetchParams) { + fetchParams = assign(fetchParams, extraFetchParams); + } + + let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); + + return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + let error = new Error(response.statusText); + (error as any).response = response; + throw error; + } + }); + } + /** + * uploads an image + * + * @param petId ID of pet to update + * @param additionalMetadata Additional data to pass to server + * @param file file to upload + */ + public uploadFile (params: { petId: number; additionalMetadata?: string; file?: any; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { + const localVarPath = this.basePath + '/pet/{petId}/uploadImage' + .replace('{' + 'petId' + '}', String(params.petId)); + + let queryParameters: any = assign({}, extraQueryParams); + let headerParams: any = assign({}, this.defaultHeaders); + let formParams: any = {}; + headerParams['Content-Type'] = 'application/x-www-form-urlencoded'; + + // verify required parameter 'petId' is set + if (params.petId == null) { + throw new Error('Missing required parameter petId when calling uploadFile'); + } + formParams['additionalMetadata'] = params.additionalMetadata; + + formParams['file'] = params.file; + + let fetchParams = { + method: 'POST', + headers: headerParams, + body: querystring.stringify(formParams), + + }; + + if (extraFetchParams) { + fetchParams = assign(fetchParams, extraFetchParams); + } + + let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); + + return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + let error = new Error(response.statusText); + (error as any).response = response; + throw error; + } + }); + } + } +//} +//export namespace { + 'use strict'; + + export class StoreApi { + protected basePath = 'http://petstore.swagger.io/v2'; + public defaultHeaders : any = {}; + + constructor(basePath?: string) { + if (basePath) { + this.basePath = basePath; + } + } + + /** + * Delete purchase order by ID + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * @param orderId ID of the order that needs to be deleted + */ + public deleteOrder (params: { orderId: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { + const localVarPath = this.basePath + '/store/order/{orderId}' + .replace('{' + 'orderId' + '}', String(params.orderId)); + + let queryParameters: any = assign({}, extraQueryParams); + let headerParams: any = assign({}, this.defaultHeaders); + // verify required parameter 'orderId' is set + if (params.orderId == null) { + throw new Error('Missing required parameter orderId when calling deleteOrder'); + } + let fetchParams = { + method: 'DELETE', + headers: headerParams, + + }; + + if (extraFetchParams) { + fetchParams = assign(fetchParams, extraFetchParams); + } + + let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); + + return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + let error = new Error(response.statusText); + (error as any).response = response; + throw error; + } + }); + } + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + */ + public getInventory (params: { }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{ [key: string]: number; }> { + const localVarPath = this.basePath + '/store/inventory'; + + let queryParameters: any = assign({}, extraQueryParams); + let headerParams: any = assign({}, this.defaultHeaders); + let fetchParams = { + method: 'GET', + headers: headerParams, + + }; + + if (extraFetchParams) { + fetchParams = assign(fetchParams, extraFetchParams); + } + + let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); + + return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + let error = new Error(response.statusText); + (error as any).response = response; + throw error; + } + }); + } + /** + * Find purchase order by ID + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * @param orderId ID of pet that needs to be fetched + */ + public getOrderById (params: { orderId: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise { + const localVarPath = this.basePath + '/store/order/{orderId}' + .replace('{' + 'orderId' + '}', String(params.orderId)); + + let queryParameters: any = assign({}, extraQueryParams); + let headerParams: any = assign({}, this.defaultHeaders); + // verify required parameter 'orderId' is set + if (params.orderId == null) { + throw new Error('Missing required parameter orderId when calling getOrderById'); + } + let fetchParams = { + method: 'GET', + headers: headerParams, + + }; + + if (extraFetchParams) { + fetchParams = assign(fetchParams, extraFetchParams); + } + + let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); + + return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + let error = new Error(response.statusText); + (error as any).response = response; + throw error; + } + }); + } + /** + * Place an order for a pet + * + * @param body order placed for purchasing the pet + */ + public placeOrder (params: { body?: Order; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise { + const localVarPath = this.basePath + '/store/order'; + + let queryParameters: any = assign({}, extraQueryParams); + let headerParams: any = assign({}, this.defaultHeaders); + headerParams['Content-Type'] = 'application/json'; + + let fetchParams = { + method: 'POST', + headers: headerParams, + body: JSON.stringify(params.body), + + }; + + if (extraFetchParams) { + fetchParams = assign(fetchParams, extraFetchParams); + } + + let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); + + return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + let error = new Error(response.statusText); + (error as any).response = response; + throw error; + } + }); + } + } +//} +//export namespace { + 'use strict'; + + export class UserApi { + protected basePath = 'http://petstore.swagger.io/v2'; + public defaultHeaders : any = {}; + + constructor(basePath?: string) { + if (basePath) { + this.basePath = basePath; + } + } + + /** + * Create user + * This can only be done by the logged in user. + * @param body Created user object + */ + public createUser (params: { body?: User; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { + const localVarPath = this.basePath + '/user'; + + let queryParameters: any = assign({}, extraQueryParams); + let headerParams: any = assign({}, this.defaultHeaders); + headerParams['Content-Type'] = 'application/json'; + + let fetchParams = { + method: 'POST', + headers: headerParams, + body: JSON.stringify(params.body), + + }; + + if (extraFetchParams) { + fetchParams = assign(fetchParams, extraFetchParams); + } + + let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); + + return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + let error = new Error(response.statusText); + (error as any).response = response; + throw error; + } + }); + } + /** + * Creates list of users with given input array + * + * @param body List of user object + */ + public createUsersWithArrayInput (params: { body?: Array; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { + const localVarPath = this.basePath + '/user/createWithArray'; + + let queryParameters: any = assign({}, extraQueryParams); + let headerParams: any = assign({}, this.defaultHeaders); + headerParams['Content-Type'] = 'application/json'; + + let fetchParams = { + method: 'POST', + headers: headerParams, + body: JSON.stringify(params.body), + + }; + + if (extraFetchParams) { + fetchParams = assign(fetchParams, extraFetchParams); + } + + let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); + + return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + let error = new Error(response.statusText); + (error as any).response = response; + throw error; + } + }); + } + /** + * Creates list of users with given input array + * + * @param body List of user object + */ + public createUsersWithListInput (params: { body?: Array; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { + const localVarPath = this.basePath + '/user/createWithList'; + + let queryParameters: any = assign({}, extraQueryParams); + let headerParams: any = assign({}, this.defaultHeaders); + headerParams['Content-Type'] = 'application/json'; + + let fetchParams = { + method: 'POST', + headers: headerParams, + body: JSON.stringify(params.body), + + }; + + if (extraFetchParams) { + fetchParams = assign(fetchParams, extraFetchParams); + } + + let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); + + return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + let error = new Error(response.statusText); + (error as any).response = response; + throw error; + } + }); + } + /** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted + */ + public deleteUser (params: { username: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { + const localVarPath = this.basePath + '/user/{username}' + .replace('{' + 'username' + '}', String(params.username)); + + let queryParameters: any = assign({}, extraQueryParams); + let headerParams: any = assign({}, this.defaultHeaders); + // verify required parameter 'username' is set + if (params.username == null) { + throw new Error('Missing required parameter username when calling deleteUser'); + } + let fetchParams = { + method: 'DELETE', + headers: headerParams, + + }; + + if (extraFetchParams) { + fetchParams = assign(fetchParams, extraFetchParams); + } + + let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); + + return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + let error = new Error(response.statusText); + (error as any).response = response; + throw error; + } + }); + } + /** + * Get user by user name + * + * @param username The name that needs to be fetched. Use user1 for testing. + */ + public getUserByName (params: { username: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise { + const localVarPath = this.basePath + '/user/{username}' + .replace('{' + 'username' + '}', String(params.username)); + + let queryParameters: any = assign({}, extraQueryParams); + let headerParams: any = assign({}, this.defaultHeaders); + // verify required parameter 'username' is set + if (params.username == null) { + throw new Error('Missing required parameter username when calling getUserByName'); + } + let fetchParams = { + method: 'GET', + headers: headerParams, + + }; + + if (extraFetchParams) { + fetchParams = assign(fetchParams, extraFetchParams); + } + + let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); + + return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + let error = new Error(response.statusText); + (error as any).response = response; + throw error; + } + }); + } + /** + * Logs user into the system + * + * @param username The user name for login + * @param password The password for login in clear text + */ + public loginUser (params: { username?: string; password?: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise { + const localVarPath = this.basePath + '/user/login'; + + let queryParameters: any = assign({}, extraQueryParams); + let headerParams: any = assign({}, this.defaultHeaders); + if (params.username !== undefined) { + queryParameters['username'] = params.username; + } + + if (params.password !== undefined) { + queryParameters['password'] = params.password; + } + + let fetchParams = { + method: 'GET', + headers: headerParams, + + }; + + if (extraFetchParams) { + fetchParams = assign(fetchParams, extraFetchParams); + } + + let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); + + return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + let error = new Error(response.statusText); + (error as any).response = response; + throw error; + } + }); + } + /** + * Logs out current logged in user session + * + */ + public logoutUser (params: { }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { + const localVarPath = this.basePath + '/user/logout'; + + let queryParameters: any = assign({}, extraQueryParams); + let headerParams: any = assign({}, this.defaultHeaders); + let fetchParams = { + method: 'GET', + headers: headerParams, + + }; + + if (extraFetchParams) { + fetchParams = assign(fetchParams, extraFetchParams); + } + + let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); + + return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + let error = new Error(response.statusText); + (error as any).response = response; + throw error; + } + }); + } + /** + * Updated user + * This can only be done by the logged in user. + * @param username name that need to be deleted + * @param body Updated user object + */ + public updateUser (params: { username: string; body?: User; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { + const localVarPath = this.basePath + '/user/{username}' + .replace('{' + 'username' + '}', String(params.username)); + + let queryParameters: any = assign({}, extraQueryParams); + let headerParams: any = assign({}, this.defaultHeaders); + headerParams['Content-Type'] = 'application/json'; + + // verify required parameter 'username' is set + if (params.username == null) { + throw new Error('Missing required parameter username when calling updateUser'); + } + let fetchParams = { + method: 'PUT', + headers: headerParams, + body: JSON.stringify(params.body), + + }; + + if (extraFetchParams) { + fetchParams = assign(fetchParams, extraFetchParams); + } + + let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); + + return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + let error = new Error(response.statusText); + (error as any).response = response; + throw error; + } + }); + } + } +//} diff --git a/samples/client/petstore/typescript-fetch/default-es6/assign.ts b/samples/client/petstore/typescript-fetch/default-es6/assign.ts new file mode 100644 index 00000000000..23355144147 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/default-es6/assign.ts @@ -0,0 +1,18 @@ +export function assign (target: any, ...args: any[]) { + 'use strict'; + if (target === undefined || target === null) { + throw new TypeError('Cannot convert undefined or null to object'); + } + + var output = Object(target); + for (let source of args) { + if (source !== undefined && source !== null) { + for (var nextKey in source) { + if (source.hasOwnProperty(nextKey)) { + output[nextKey] = source[nextKey]; + } + } + } + } + return output; +}; \ No newline at end of file diff --git a/samples/client/petstore/typescript-fetch/default-es6/git_push.sh b/samples/client/petstore/typescript-fetch/default-es6/git_push.sh new file mode 100644 index 00000000000..ed374619b13 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/default-es6/git_push.sh @@ -0,0 +1,52 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 swagger-petstore-perl "minor update" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 + +if [ "$git_user_id" = "" ]; then + git_user_id="GIT_USER_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="GIT_REPO_ID" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="Minor update" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=`git remote` +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git crediential in your environment." + git remote add origin https://github.com/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:${GIT_TOKEN}@github.com/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://github.com/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' + diff --git a/samples/client/petstore/typescript-fetch/default-es6/package.json b/samples/client/petstore/typescript-fetch/default-es6/package.json new file mode 100644 index 00000000000..84cf629d931 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/default-es6/package.json @@ -0,0 +1,18 @@ +{ + "name": "typescript-fetch-api", + "version": "0.0.0", + "private": true, + "main": "./dist/api.js", + "browser": "./dist/api.js", + "typings": "./dist/api.d.ts", + "dependencies": { + "isomorphic-fetch": "^2.2.1" + }, + "scripts" : { + "install" : "typings install && tsc" + }, + "devDependencies": { + "typescript": "^1.8.10", + "typings": "^0.8.1" + } +} \ No newline at end of file diff --git a/samples/client/petstore/typescript-fetch/default-es6/tsconfig.json b/samples/client/petstore/typescript-fetch/default-es6/tsconfig.json new file mode 100644 index 00000000000..9d5f166e764 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/default-es6/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "declaration": true, + "target": "es6", + "module": "commonjs", + "noImplicitAny": true, + "outDir": "dist" + }, + "exclude": [ + "dist", + "node_modules", + "typings/browser", + "typings/main", + "typings/main.d.ts" + ] +} diff --git a/samples/client/petstore/typescript-fetch/default-es6/typings.json b/samples/client/petstore/typescript-fetch/default-es6/typings.json new file mode 100644 index 00000000000..3ce24427fc6 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/default-es6/typings.json @@ -0,0 +1,8 @@ +{ + "version": false, + "dependencies": {}, + "ambientDependencies": { + "node": "registry:dt/node#4.0.0+20160423143914", + "isomorphic-fetch": "registry:dt/isomorphic-fetch#0.0.0+20160505171433" + } +} diff --git a/samples/client/petstore/typescript-fetch/default/README.md b/samples/client/petstore/typescript-fetch/default/README.md new file mode 100644 index 00000000000..8ec43e76497 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/default/README.md @@ -0,0 +1,44 @@ +# TypeScript-Fetch + +This generator creates TypeScript/JavaScript client that utilizes [Fetch API](https://fetch.spec.whatwg.org/). The codegen Node module can be used in the following environments: + +* Node.JS +* Webpack +* Browserify + +It is usable in both TypeScript and JavaScript. In TypeScript, the definition should be automatically resolved via `typings` in `package.json`. ([Reference](http://www.typescriptlang.org/docs/handbook/typings-for-npm-packages.html)) + +### Installation ### + +`swagger-codegen` does not generate JavaScript directly. The codegen Node module comes with `package.json` that bundles `typescript` and `typings` so it can self-compile. The self-compile is normally run automatically via the `npm` `postinstall` script of `npm install`. + +CAVEAT: Due to [privilege implications](https://docs.npmjs.com/misc/scripts#user), `npm` may skip `postinstall` script if the user is `root`. You would need to manually invoke `npm install` or `npm run postinstall` for the codegen module if that's the case. + +#### NPM repository ### +If you remove `"private": true` from `package.json`, you may publish the module to NPM. In which case, you would be able to install the module as any other NPM module. + +It maybe useful to use [scoped packages](https://docs.npmjs.com/misc/scope). + +#### NPM install local file ### +You should be able to directly install the module using `npm install file:///codegen_path`. + +NOTES: If you do `npm install file:///codegen_path --save` NPM might convert your path to relative path, maybe have adverse affect. `npm install` and `npm shrinkwrap` may misbehave if the installation path is not absolute. + +#### direct copy/symlink ### +You may also simply copy or symlink the codegen into a directly under your project. The syntax of the usage would differ if you take this route. (See below) + +### Usage ### +With ES6 module syntax, the following syntaxes are supported: +``` +import * as localName from 'npmName'; +import {operationId} from 'npmName'; + +import * as localName from './symlinkDir'; +import {operationId} from './symlinkDir'; +``` +With CommonJS, the following syntaxes are supported: +``` +import localName = require('npmName'); + +import localName = require('./symlinkDir')'; +``` \ No newline at end of file diff --git a/samples/client/petstore/typescript-fetch/default/api.ts b/samples/client/petstore/typescript-fetch/default/api.ts new file mode 100644 index 00000000000..3d075fc2809 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/default/api.ts @@ -0,0 +1,855 @@ +import * as querystring from 'querystring'; +import * as fetch from 'isomorphic-fetch'; +import {assign} from './assign'; + + +export interface Category { + "id"?: number; + "name"?: string; +} + +export interface Order { + "id"?: number; + "petId"?: number; + "quantity"?: number; + "shipDate"?: Date; + + /** + * Order Status + */ + "status"?: Order.StatusEnum; + "complete"?: boolean; +} + +export namespace Order { + +export type StatusEnum = 'placed' | 'approved' | 'delivered'; +} +export interface Pet { + "id"?: number; + "category"?: Category; + "name": string; + "photoUrls": Array; + "tags"?: Array; + + /** + * pet status in the store + */ + "status"?: Pet.StatusEnum; +} + +export namespace Pet { + +export type StatusEnum = 'available' | 'pending' | 'sold'; +} +export interface Tag { + "id"?: number; + "name"?: string; +} + +export interface User { + "id"?: number; + "username"?: string; + "firstName"?: string; + "lastName"?: string; + "email"?: string; + "password"?: string; + "phone"?: string; + + /** + * User Status + */ + "userStatus"?: number; +} + + +//export namespace { + 'use strict'; + + export class PetApi { + protected basePath = 'http://petstore.swagger.io/v2'; + public defaultHeaders : any = {}; + + constructor(basePath?: string) { + if (basePath) { + this.basePath = basePath; + } + } + + /** + * Add a new pet to the store + * + * @param body Pet object that needs to be added to the store + */ + public addPet (params: { body?: Pet; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { + const localVarPath = this.basePath + '/pet'; + + let queryParameters: any = assign({}, extraQueryParams); + let headerParams: any = assign({}, this.defaultHeaders); + headerParams['Content-Type'] = 'application/json'; + + let fetchParams = { + method: 'POST', + headers: headerParams, + body: JSON.stringify(params.body), + + }; + + if (extraFetchParams) { + fetchParams = assign(fetchParams, extraFetchParams); + } + + let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); + + return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + let error = new Error(response.statusText); + (error as any).response = response; + throw error; + } + }); + } + /** + * Deletes a pet + * + * @param petId Pet id to delete + * @param apiKey + */ + public deletePet (params: { petId: number; apiKey?: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { + const localVarPath = this.basePath + '/pet/{petId}' + .replace('{' + 'petId' + '}', String(params.petId)); + + let queryParameters: any = assign({}, extraQueryParams); + let headerParams: any = assign({}, this.defaultHeaders); + // verify required parameter 'petId' is set + if (params.petId == null) { + throw new Error('Missing required parameter petId when calling deletePet'); + } + headerParams['api_key'] = params.apiKey; + + let fetchParams = { + method: 'DELETE', + headers: headerParams, + + }; + + if (extraFetchParams) { + fetchParams = assign(fetchParams, extraFetchParams); + } + + let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); + + return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + let error = new Error(response.statusText); + (error as any).response = response; + throw error; + } + }); + } + /** + * Finds Pets by status + * Multiple status values can be provided with comma seperated strings + * @param status Status values that need to be considered for filter + */ + public findPetsByStatus (params: { status?: Array; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise> { + const localVarPath = this.basePath + '/pet/findByStatus'; + + let queryParameters: any = assign({}, extraQueryParams); + let headerParams: any = assign({}, this.defaultHeaders); + if (params.status !== undefined) { + queryParameters['status'] = params.status; + } + + let fetchParams = { + method: 'GET', + headers: headerParams, + + }; + + if (extraFetchParams) { + fetchParams = assign(fetchParams, extraFetchParams); + } + + let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); + + return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + let error = new Error(response.statusText); + (error as any).response = response; + throw error; + } + }); + } + /** + * Finds Pets by tags + * Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + * @param tags Tags to filter by + */ + public findPetsByTags (params: { tags?: Array; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise> { + const localVarPath = this.basePath + '/pet/findByTags'; + + let queryParameters: any = assign({}, extraQueryParams); + let headerParams: any = assign({}, this.defaultHeaders); + if (params.tags !== undefined) { + queryParameters['tags'] = params.tags; + } + + let fetchParams = { + method: 'GET', + headers: headerParams, + + }; + + if (extraFetchParams) { + fetchParams = assign(fetchParams, extraFetchParams); + } + + let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); + + return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + let error = new Error(response.statusText); + (error as any).response = response; + throw error; + } + }); + } + /** + * Find pet by ID + * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + * @param petId ID of pet that needs to be fetched + */ + public getPetById (params: { petId: number; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise { + const localVarPath = this.basePath + '/pet/{petId}' + .replace('{' + 'petId' + '}', String(params.petId)); + + let queryParameters: any = assign({}, extraQueryParams); + let headerParams: any = assign({}, this.defaultHeaders); + // verify required parameter 'petId' is set + if (params.petId == null) { + throw new Error('Missing required parameter petId when calling getPetById'); + } + let fetchParams = { + method: 'GET', + headers: headerParams, + + }; + + if (extraFetchParams) { + fetchParams = assign(fetchParams, extraFetchParams); + } + + let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); + + return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + let error = new Error(response.statusText); + (error as any).response = response; + throw error; + } + }); + } + /** + * Update an existing pet + * + * @param body Pet object that needs to be added to the store + */ + public updatePet (params: { body?: Pet; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { + const localVarPath = this.basePath + '/pet'; + + let queryParameters: any = assign({}, extraQueryParams); + let headerParams: any = assign({}, this.defaultHeaders); + headerParams['Content-Type'] = 'application/json'; + + let fetchParams = { + method: 'PUT', + headers: headerParams, + body: JSON.stringify(params.body), + + }; + + if (extraFetchParams) { + fetchParams = assign(fetchParams, extraFetchParams); + } + + let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); + + return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + let error = new Error(response.statusText); + (error as any).response = response; + throw error; + } + }); + } + /** + * Updates a pet in the store with form data + * + * @param petId ID of pet that needs to be updated + * @param name Updated name of the pet + * @param status Updated status of the pet + */ + public updatePetWithForm (params: { petId: string; name?: string; status?: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { + const localVarPath = this.basePath + '/pet/{petId}' + .replace('{' + 'petId' + '}', String(params.petId)); + + let queryParameters: any = assign({}, extraQueryParams); + let headerParams: any = assign({}, this.defaultHeaders); + let formParams: any = {}; + headerParams['Content-Type'] = 'application/x-www-form-urlencoded'; + + // verify required parameter 'petId' is set + if (params.petId == null) { + throw new Error('Missing required parameter petId when calling updatePetWithForm'); + } + formParams['name'] = params.name; + + formParams['status'] = params.status; + + let fetchParams = { + method: 'POST', + headers: headerParams, + body: querystring.stringify(formParams), + + }; + + if (extraFetchParams) { + fetchParams = assign(fetchParams, extraFetchParams); + } + + let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); + + return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + let error = new Error(response.statusText); + (error as any).response = response; + throw error; + } + }); + } + /** + * uploads an image + * + * @param petId ID of pet to update + * @param additionalMetadata Additional data to pass to server + * @param file file to upload + */ + public uploadFile (params: { petId: number; additionalMetadata?: string; file?: any; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { + const localVarPath = this.basePath + '/pet/{petId}/uploadImage' + .replace('{' + 'petId' + '}', String(params.petId)); + + let queryParameters: any = assign({}, extraQueryParams); + let headerParams: any = assign({}, this.defaultHeaders); + let formParams: any = {}; + headerParams['Content-Type'] = 'application/x-www-form-urlencoded'; + + // verify required parameter 'petId' is set + if (params.petId == null) { + throw new Error('Missing required parameter petId when calling uploadFile'); + } + formParams['additionalMetadata'] = params.additionalMetadata; + + formParams['file'] = params.file; + + let fetchParams = { + method: 'POST', + headers: headerParams, + body: querystring.stringify(formParams), + + }; + + if (extraFetchParams) { + fetchParams = assign(fetchParams, extraFetchParams); + } + + let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); + + return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + let error = new Error(response.statusText); + (error as any).response = response; + throw error; + } + }); + } + } +//} +//export namespace { + 'use strict'; + + export class StoreApi { + protected basePath = 'http://petstore.swagger.io/v2'; + public defaultHeaders : any = {}; + + constructor(basePath?: string) { + if (basePath) { + this.basePath = basePath; + } + } + + /** + * Delete purchase order by ID + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * @param orderId ID of the order that needs to be deleted + */ + public deleteOrder (params: { orderId: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { + const localVarPath = this.basePath + '/store/order/{orderId}' + .replace('{' + 'orderId' + '}', String(params.orderId)); + + let queryParameters: any = assign({}, extraQueryParams); + let headerParams: any = assign({}, this.defaultHeaders); + // verify required parameter 'orderId' is set + if (params.orderId == null) { + throw new Error('Missing required parameter orderId when calling deleteOrder'); + } + let fetchParams = { + method: 'DELETE', + headers: headerParams, + + }; + + if (extraFetchParams) { + fetchParams = assign(fetchParams, extraFetchParams); + } + + let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); + + return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + let error = new Error(response.statusText); + (error as any).response = response; + throw error; + } + }); + } + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + */ + public getInventory (params: { }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{ [key: string]: number; }> { + const localVarPath = this.basePath + '/store/inventory'; + + let queryParameters: any = assign({}, extraQueryParams); + let headerParams: any = assign({}, this.defaultHeaders); + let fetchParams = { + method: 'GET', + headers: headerParams, + + }; + + if (extraFetchParams) { + fetchParams = assign(fetchParams, extraFetchParams); + } + + let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); + + return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + let error = new Error(response.statusText); + (error as any).response = response; + throw error; + } + }); + } + /** + * Find purchase order by ID + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * @param orderId ID of pet that needs to be fetched + */ + public getOrderById (params: { orderId: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise { + const localVarPath = this.basePath + '/store/order/{orderId}' + .replace('{' + 'orderId' + '}', String(params.orderId)); + + let queryParameters: any = assign({}, extraQueryParams); + let headerParams: any = assign({}, this.defaultHeaders); + // verify required parameter 'orderId' is set + if (params.orderId == null) { + throw new Error('Missing required parameter orderId when calling getOrderById'); + } + let fetchParams = { + method: 'GET', + headers: headerParams, + + }; + + if (extraFetchParams) { + fetchParams = assign(fetchParams, extraFetchParams); + } + + let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); + + return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + let error = new Error(response.statusText); + (error as any).response = response; + throw error; + } + }); + } + /** + * Place an order for a pet + * + * @param body order placed for purchasing the pet + */ + public placeOrder (params: { body?: Order; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise { + const localVarPath = this.basePath + '/store/order'; + + let queryParameters: any = assign({}, extraQueryParams); + let headerParams: any = assign({}, this.defaultHeaders); + headerParams['Content-Type'] = 'application/json'; + + let fetchParams = { + method: 'POST', + headers: headerParams, + body: JSON.stringify(params.body), + + }; + + if (extraFetchParams) { + fetchParams = assign(fetchParams, extraFetchParams); + } + + let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); + + return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + let error = new Error(response.statusText); + (error as any).response = response; + throw error; + } + }); + } + } +//} +//export namespace { + 'use strict'; + + export class UserApi { + protected basePath = 'http://petstore.swagger.io/v2'; + public defaultHeaders : any = {}; + + constructor(basePath?: string) { + if (basePath) { + this.basePath = basePath; + } + } + + /** + * Create user + * This can only be done by the logged in user. + * @param body Created user object + */ + public createUser (params: { body?: User; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { + const localVarPath = this.basePath + '/user'; + + let queryParameters: any = assign({}, extraQueryParams); + let headerParams: any = assign({}, this.defaultHeaders); + headerParams['Content-Type'] = 'application/json'; + + let fetchParams = { + method: 'POST', + headers: headerParams, + body: JSON.stringify(params.body), + + }; + + if (extraFetchParams) { + fetchParams = assign(fetchParams, extraFetchParams); + } + + let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); + + return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + let error = new Error(response.statusText); + (error as any).response = response; + throw error; + } + }); + } + /** + * Creates list of users with given input array + * + * @param body List of user object + */ + public createUsersWithArrayInput (params: { body?: Array; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { + const localVarPath = this.basePath + '/user/createWithArray'; + + let queryParameters: any = assign({}, extraQueryParams); + let headerParams: any = assign({}, this.defaultHeaders); + headerParams['Content-Type'] = 'application/json'; + + let fetchParams = { + method: 'POST', + headers: headerParams, + body: JSON.stringify(params.body), + + }; + + if (extraFetchParams) { + fetchParams = assign(fetchParams, extraFetchParams); + } + + let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); + + return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + let error = new Error(response.statusText); + (error as any).response = response; + throw error; + } + }); + } + /** + * Creates list of users with given input array + * + * @param body List of user object + */ + public createUsersWithListInput (params: { body?: Array; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { + const localVarPath = this.basePath + '/user/createWithList'; + + let queryParameters: any = assign({}, extraQueryParams); + let headerParams: any = assign({}, this.defaultHeaders); + headerParams['Content-Type'] = 'application/json'; + + let fetchParams = { + method: 'POST', + headers: headerParams, + body: JSON.stringify(params.body), + + }; + + if (extraFetchParams) { + fetchParams = assign(fetchParams, extraFetchParams); + } + + let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); + + return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + let error = new Error(response.statusText); + (error as any).response = response; + throw error; + } + }); + } + /** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted + */ + public deleteUser (params: { username: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { + const localVarPath = this.basePath + '/user/{username}' + .replace('{' + 'username' + '}', String(params.username)); + + let queryParameters: any = assign({}, extraQueryParams); + let headerParams: any = assign({}, this.defaultHeaders); + // verify required parameter 'username' is set + if (params.username == null) { + throw new Error('Missing required parameter username when calling deleteUser'); + } + let fetchParams = { + method: 'DELETE', + headers: headerParams, + + }; + + if (extraFetchParams) { + fetchParams = assign(fetchParams, extraFetchParams); + } + + let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); + + return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + let error = new Error(response.statusText); + (error as any).response = response; + throw error; + } + }); + } + /** + * Get user by user name + * + * @param username The name that needs to be fetched. Use user1 for testing. + */ + public getUserByName (params: { username: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise { + const localVarPath = this.basePath + '/user/{username}' + .replace('{' + 'username' + '}', String(params.username)); + + let queryParameters: any = assign({}, extraQueryParams); + let headerParams: any = assign({}, this.defaultHeaders); + // verify required parameter 'username' is set + if (params.username == null) { + throw new Error('Missing required parameter username when calling getUserByName'); + } + let fetchParams = { + method: 'GET', + headers: headerParams, + + }; + + if (extraFetchParams) { + fetchParams = assign(fetchParams, extraFetchParams); + } + + let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); + + return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + let error = new Error(response.statusText); + (error as any).response = response; + throw error; + } + }); + } + /** + * Logs user into the system + * + * @param username The user name for login + * @param password The password for login in clear text + */ + public loginUser (params: { username?: string; password?: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise { + const localVarPath = this.basePath + '/user/login'; + + let queryParameters: any = assign({}, extraQueryParams); + let headerParams: any = assign({}, this.defaultHeaders); + if (params.username !== undefined) { + queryParameters['username'] = params.username; + } + + if (params.password !== undefined) { + queryParameters['password'] = params.password; + } + + let fetchParams = { + method: 'GET', + headers: headerParams, + + }; + + if (extraFetchParams) { + fetchParams = assign(fetchParams, extraFetchParams); + } + + let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); + + return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + let error = new Error(response.statusText); + (error as any).response = response; + throw error; + } + }); + } + /** + * Logs out current logged in user session + * + */ + public logoutUser (params: { }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { + const localVarPath = this.basePath + '/user/logout'; + + let queryParameters: any = assign({}, extraQueryParams); + let headerParams: any = assign({}, this.defaultHeaders); + let fetchParams = { + method: 'GET', + headers: headerParams, + + }; + + if (extraFetchParams) { + fetchParams = assign(fetchParams, extraFetchParams); + } + + let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); + + return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + let error = new Error(response.statusText); + (error as any).response = response; + throw error; + } + }); + } + /** + * Updated user + * This can only be done by the logged in user. + * @param username name that need to be deleted + * @param body Updated user object + */ + public updateUser (params: { username: string; body?: User; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { + const localVarPath = this.basePath + '/user/{username}' + .replace('{' + 'username' + '}', String(params.username)); + + let queryParameters: any = assign({}, extraQueryParams); + let headerParams: any = assign({}, this.defaultHeaders); + headerParams['Content-Type'] = 'application/json'; + + // verify required parameter 'username' is set + if (params.username == null) { + throw new Error('Missing required parameter username when calling updateUser'); + } + let fetchParams = { + method: 'PUT', + headers: headerParams, + body: JSON.stringify(params.body), + + }; + + if (extraFetchParams) { + fetchParams = assign(fetchParams, extraFetchParams); + } + + let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); + + return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + let error = new Error(response.statusText); + (error as any).response = response; + throw error; + } + }); + } + } +//} diff --git a/samples/client/petstore/typescript-fetch/default/assign.ts b/samples/client/petstore/typescript-fetch/default/assign.ts new file mode 100644 index 00000000000..23355144147 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/default/assign.ts @@ -0,0 +1,18 @@ +export function assign (target: any, ...args: any[]) { + 'use strict'; + if (target === undefined || target === null) { + throw new TypeError('Cannot convert undefined or null to object'); + } + + var output = Object(target); + for (let source of args) { + if (source !== undefined && source !== null) { + for (var nextKey in source) { + if (source.hasOwnProperty(nextKey)) { + output[nextKey] = source[nextKey]; + } + } + } + } + return output; +}; \ No newline at end of file diff --git a/samples/client/petstore/typescript-fetch/default/git_push.sh b/samples/client/petstore/typescript-fetch/default/git_push.sh new file mode 100644 index 00000000000..ed374619b13 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/default/git_push.sh @@ -0,0 +1,52 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 swagger-petstore-perl "minor update" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 + +if [ "$git_user_id" = "" ]; then + git_user_id="GIT_USER_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="GIT_REPO_ID" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="Minor update" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=`git remote` +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git crediential in your environment." + git remote add origin https://github.com/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:${GIT_TOKEN}@github.com/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://github.com/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' + diff --git a/samples/client/petstore/typescript-fetch/default/package.json b/samples/client/petstore/typescript-fetch/default/package.json new file mode 100644 index 00000000000..84cf629d931 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/default/package.json @@ -0,0 +1,18 @@ +{ + "name": "typescript-fetch-api", + "version": "0.0.0", + "private": true, + "main": "./dist/api.js", + "browser": "./dist/api.js", + "typings": "./dist/api.d.ts", + "dependencies": { + "isomorphic-fetch": "^2.2.1" + }, + "scripts" : { + "install" : "typings install && tsc" + }, + "devDependencies": { + "typescript": "^1.8.10", + "typings": "^0.8.1" + } +} \ No newline at end of file diff --git a/samples/client/petstore/typescript-fetch/default/tsconfig.json b/samples/client/petstore/typescript-fetch/default/tsconfig.json new file mode 100644 index 00000000000..18db23e2f5f --- /dev/null +++ b/samples/client/petstore/typescript-fetch/default/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "declaration": true, + "target": "es5", + "module": "commonjs", + "noImplicitAny": true, + "outDir": "dist" + }, + "exclude": [ + "dist", + "node_modules", + "typings/browser", + "typings/main", + "typings/main.d.ts" + ] +} diff --git a/samples/client/petstore/typescript-fetch/default/typings.json b/samples/client/petstore/typescript-fetch/default/typings.json new file mode 100644 index 00000000000..eeca5afde97 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/default/typings.json @@ -0,0 +1,9 @@ +{ + "version": false, + "dependencies": {}, + "ambientDependencies": { + "es6-promise": "registry:dt/es6-promise#0.0.0+20160423074304", + "node": "registry:dt/node#4.0.0+20160423143914", + "isomorphic-fetch": "registry:dt/isomorphic-fetch#0.0.0+20160505171433" + } +} diff --git a/samples/client/petstore/typescript-fetch/git_push.sh b/samples/client/petstore/typescript-fetch/git_push.sh new file mode 100644 index 00000000000..ed374619b13 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/git_push.sh @@ -0,0 +1,52 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 swagger-petstore-perl "minor update" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 + +if [ "$git_user_id" = "" ]; then + git_user_id="GIT_USER_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="GIT_REPO_ID" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="Minor update" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=`git remote` +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git crediential in your environment." + git remote add origin https://github.com/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:${GIT_TOKEN}@github.com/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://github.com/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' + diff --git a/samples/client/petstore/typescript-fetch/package.json b/samples/client/petstore/typescript-fetch/package.json new file mode 100644 index 00000000000..722c87cc323 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/package.json @@ -0,0 +1,10 @@ +{ + "private": true, + "dependencies": { + "isomorphic-fetch": "^2.2.1" + }, + "devDependencies": { + "typescript": "^1.8.10", + "typings": "^0.8.1" + } +} \ No newline at end of file diff --git a/samples/client/petstore/typescript-fetch/tsconfig.json b/samples/client/petstore/typescript-fetch/tsconfig.json new file mode 100644 index 00000000000..fc93dc1610e --- /dev/null +++ b/samples/client/petstore/typescript-fetch/tsconfig.json @@ -0,0 +1,11 @@ +{ + "compilerOptions": { + "target": "es5" + }, + "exclude": [ + "node_modules", + "typings/browser", + "typings/main", + "typings/main.d.ts" + ] +} \ No newline at end of file diff --git a/samples/client/petstore/typescript-fetch/typings.json b/samples/client/petstore/typescript-fetch/typings.json new file mode 100644 index 00000000000..c22f086f7f0 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/typings.json @@ -0,0 +1,9 @@ +{ + "version": false, + "dependencies": {}, + "ambientDependencies": { + "es6-promise": "registry:dt/es6-promise#0.0.0+20160423074304", + "node": "registry:dt/node#4.0.0+20160423143914", + "isomorphic-fetch": "github:leonyu/DefinitelyTyped/isomorphic-fetch/isomorphic-fetch.d.ts#isomorphic-fetch-fix-module" + } +} diff --git a/samples/client/petstore/typescript-fetch/with-package-metadata/README.md b/samples/client/petstore/typescript-fetch/with-package-metadata/README.md new file mode 100644 index 00000000000..8ec43e76497 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/with-package-metadata/README.md @@ -0,0 +1,44 @@ +# TypeScript-Fetch + +This generator creates TypeScript/JavaScript client that utilizes [Fetch API](https://fetch.spec.whatwg.org/). The codegen Node module can be used in the following environments: + +* Node.JS +* Webpack +* Browserify + +It is usable in both TypeScript and JavaScript. In TypeScript, the definition should be automatically resolved via `typings` in `package.json`. ([Reference](http://www.typescriptlang.org/docs/handbook/typings-for-npm-packages.html)) + +### Installation ### + +`swagger-codegen` does not generate JavaScript directly. The codegen Node module comes with `package.json` that bundles `typescript` and `typings` so it can self-compile. The self-compile is normally run automatically via the `npm` `postinstall` script of `npm install`. + +CAVEAT: Due to [privilege implications](https://docs.npmjs.com/misc/scripts#user), `npm` may skip `postinstall` script if the user is `root`. You would need to manually invoke `npm install` or `npm run postinstall` for the codegen module if that's the case. + +#### NPM repository ### +If you remove `"private": true` from `package.json`, you may publish the module to NPM. In which case, you would be able to install the module as any other NPM module. + +It maybe useful to use [scoped packages](https://docs.npmjs.com/misc/scope). + +#### NPM install local file ### +You should be able to directly install the module using `npm install file:///codegen_path`. + +NOTES: If you do `npm install file:///codegen_path --save` NPM might convert your path to relative path, maybe have adverse affect. `npm install` and `npm shrinkwrap` may misbehave if the installation path is not absolute. + +#### direct copy/symlink ### +You may also simply copy or symlink the codegen into a directly under your project. The syntax of the usage would differ if you take this route. (See below) + +### Usage ### +With ES6 module syntax, the following syntaxes are supported: +``` +import * as localName from 'npmName'; +import {operationId} from 'npmName'; + +import * as localName from './symlinkDir'; +import {operationId} from './symlinkDir'; +``` +With CommonJS, the following syntaxes are supported: +``` +import localName = require('npmName'); + +import localName = require('./symlinkDir')'; +``` \ No newline at end of file diff --git a/samples/client/petstore/typescript-fetch/with-package-metadata/api.ts b/samples/client/petstore/typescript-fetch/with-package-metadata/api.ts new file mode 100644 index 00000000000..3d075fc2809 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/with-package-metadata/api.ts @@ -0,0 +1,855 @@ +import * as querystring from 'querystring'; +import * as fetch from 'isomorphic-fetch'; +import {assign} from './assign'; + + +export interface Category { + "id"?: number; + "name"?: string; +} + +export interface Order { + "id"?: number; + "petId"?: number; + "quantity"?: number; + "shipDate"?: Date; + + /** + * Order Status + */ + "status"?: Order.StatusEnum; + "complete"?: boolean; +} + +export namespace Order { + +export type StatusEnum = 'placed' | 'approved' | 'delivered'; +} +export interface Pet { + "id"?: number; + "category"?: Category; + "name": string; + "photoUrls": Array; + "tags"?: Array; + + /** + * pet status in the store + */ + "status"?: Pet.StatusEnum; +} + +export namespace Pet { + +export type StatusEnum = 'available' | 'pending' | 'sold'; +} +export interface Tag { + "id"?: number; + "name"?: string; +} + +export interface User { + "id"?: number; + "username"?: string; + "firstName"?: string; + "lastName"?: string; + "email"?: string; + "password"?: string; + "phone"?: string; + + /** + * User Status + */ + "userStatus"?: number; +} + + +//export namespace { + 'use strict'; + + export class PetApi { + protected basePath = 'http://petstore.swagger.io/v2'; + public defaultHeaders : any = {}; + + constructor(basePath?: string) { + if (basePath) { + this.basePath = basePath; + } + } + + /** + * Add a new pet to the store + * + * @param body Pet object that needs to be added to the store + */ + public addPet (params: { body?: Pet; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { + const localVarPath = this.basePath + '/pet'; + + let queryParameters: any = assign({}, extraQueryParams); + let headerParams: any = assign({}, this.defaultHeaders); + headerParams['Content-Type'] = 'application/json'; + + let fetchParams = { + method: 'POST', + headers: headerParams, + body: JSON.stringify(params.body), + + }; + + if (extraFetchParams) { + fetchParams = assign(fetchParams, extraFetchParams); + } + + let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); + + return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + let error = new Error(response.statusText); + (error as any).response = response; + throw error; + } + }); + } + /** + * Deletes a pet + * + * @param petId Pet id to delete + * @param apiKey + */ + public deletePet (params: { petId: number; apiKey?: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { + const localVarPath = this.basePath + '/pet/{petId}' + .replace('{' + 'petId' + '}', String(params.petId)); + + let queryParameters: any = assign({}, extraQueryParams); + let headerParams: any = assign({}, this.defaultHeaders); + // verify required parameter 'petId' is set + if (params.petId == null) { + throw new Error('Missing required parameter petId when calling deletePet'); + } + headerParams['api_key'] = params.apiKey; + + let fetchParams = { + method: 'DELETE', + headers: headerParams, + + }; + + if (extraFetchParams) { + fetchParams = assign(fetchParams, extraFetchParams); + } + + let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); + + return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + let error = new Error(response.statusText); + (error as any).response = response; + throw error; + } + }); + } + /** + * Finds Pets by status + * Multiple status values can be provided with comma seperated strings + * @param status Status values that need to be considered for filter + */ + public findPetsByStatus (params: { status?: Array; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise> { + const localVarPath = this.basePath + '/pet/findByStatus'; + + let queryParameters: any = assign({}, extraQueryParams); + let headerParams: any = assign({}, this.defaultHeaders); + if (params.status !== undefined) { + queryParameters['status'] = params.status; + } + + let fetchParams = { + method: 'GET', + headers: headerParams, + + }; + + if (extraFetchParams) { + fetchParams = assign(fetchParams, extraFetchParams); + } + + let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); + + return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + let error = new Error(response.statusText); + (error as any).response = response; + throw error; + } + }); + } + /** + * Finds Pets by tags + * Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + * @param tags Tags to filter by + */ + public findPetsByTags (params: { tags?: Array; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise> { + const localVarPath = this.basePath + '/pet/findByTags'; + + let queryParameters: any = assign({}, extraQueryParams); + let headerParams: any = assign({}, this.defaultHeaders); + if (params.tags !== undefined) { + queryParameters['tags'] = params.tags; + } + + let fetchParams = { + method: 'GET', + headers: headerParams, + + }; + + if (extraFetchParams) { + fetchParams = assign(fetchParams, extraFetchParams); + } + + let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); + + return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + let error = new Error(response.statusText); + (error as any).response = response; + throw error; + } + }); + } + /** + * Find pet by ID + * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + * @param petId ID of pet that needs to be fetched + */ + public getPetById (params: { petId: number; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise { + const localVarPath = this.basePath + '/pet/{petId}' + .replace('{' + 'petId' + '}', String(params.petId)); + + let queryParameters: any = assign({}, extraQueryParams); + let headerParams: any = assign({}, this.defaultHeaders); + // verify required parameter 'petId' is set + if (params.petId == null) { + throw new Error('Missing required parameter petId when calling getPetById'); + } + let fetchParams = { + method: 'GET', + headers: headerParams, + + }; + + if (extraFetchParams) { + fetchParams = assign(fetchParams, extraFetchParams); + } + + let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); + + return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + let error = new Error(response.statusText); + (error as any).response = response; + throw error; + } + }); + } + /** + * Update an existing pet + * + * @param body Pet object that needs to be added to the store + */ + public updatePet (params: { body?: Pet; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { + const localVarPath = this.basePath + '/pet'; + + let queryParameters: any = assign({}, extraQueryParams); + let headerParams: any = assign({}, this.defaultHeaders); + headerParams['Content-Type'] = 'application/json'; + + let fetchParams = { + method: 'PUT', + headers: headerParams, + body: JSON.stringify(params.body), + + }; + + if (extraFetchParams) { + fetchParams = assign(fetchParams, extraFetchParams); + } + + let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); + + return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + let error = new Error(response.statusText); + (error as any).response = response; + throw error; + } + }); + } + /** + * Updates a pet in the store with form data + * + * @param petId ID of pet that needs to be updated + * @param name Updated name of the pet + * @param status Updated status of the pet + */ + public updatePetWithForm (params: { petId: string; name?: string; status?: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { + const localVarPath = this.basePath + '/pet/{petId}' + .replace('{' + 'petId' + '}', String(params.petId)); + + let queryParameters: any = assign({}, extraQueryParams); + let headerParams: any = assign({}, this.defaultHeaders); + let formParams: any = {}; + headerParams['Content-Type'] = 'application/x-www-form-urlencoded'; + + // verify required parameter 'petId' is set + if (params.petId == null) { + throw new Error('Missing required parameter petId when calling updatePetWithForm'); + } + formParams['name'] = params.name; + + formParams['status'] = params.status; + + let fetchParams = { + method: 'POST', + headers: headerParams, + body: querystring.stringify(formParams), + + }; + + if (extraFetchParams) { + fetchParams = assign(fetchParams, extraFetchParams); + } + + let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); + + return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + let error = new Error(response.statusText); + (error as any).response = response; + throw error; + } + }); + } + /** + * uploads an image + * + * @param petId ID of pet to update + * @param additionalMetadata Additional data to pass to server + * @param file file to upload + */ + public uploadFile (params: { petId: number; additionalMetadata?: string; file?: any; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { + const localVarPath = this.basePath + '/pet/{petId}/uploadImage' + .replace('{' + 'petId' + '}', String(params.petId)); + + let queryParameters: any = assign({}, extraQueryParams); + let headerParams: any = assign({}, this.defaultHeaders); + let formParams: any = {}; + headerParams['Content-Type'] = 'application/x-www-form-urlencoded'; + + // verify required parameter 'petId' is set + if (params.petId == null) { + throw new Error('Missing required parameter petId when calling uploadFile'); + } + formParams['additionalMetadata'] = params.additionalMetadata; + + formParams['file'] = params.file; + + let fetchParams = { + method: 'POST', + headers: headerParams, + body: querystring.stringify(formParams), + + }; + + if (extraFetchParams) { + fetchParams = assign(fetchParams, extraFetchParams); + } + + let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); + + return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + let error = new Error(response.statusText); + (error as any).response = response; + throw error; + } + }); + } + } +//} +//export namespace { + 'use strict'; + + export class StoreApi { + protected basePath = 'http://petstore.swagger.io/v2'; + public defaultHeaders : any = {}; + + constructor(basePath?: string) { + if (basePath) { + this.basePath = basePath; + } + } + + /** + * Delete purchase order by ID + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * @param orderId ID of the order that needs to be deleted + */ + public deleteOrder (params: { orderId: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { + const localVarPath = this.basePath + '/store/order/{orderId}' + .replace('{' + 'orderId' + '}', String(params.orderId)); + + let queryParameters: any = assign({}, extraQueryParams); + let headerParams: any = assign({}, this.defaultHeaders); + // verify required parameter 'orderId' is set + if (params.orderId == null) { + throw new Error('Missing required parameter orderId when calling deleteOrder'); + } + let fetchParams = { + method: 'DELETE', + headers: headerParams, + + }; + + if (extraFetchParams) { + fetchParams = assign(fetchParams, extraFetchParams); + } + + let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); + + return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + let error = new Error(response.statusText); + (error as any).response = response; + throw error; + } + }); + } + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + */ + public getInventory (params: { }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{ [key: string]: number; }> { + const localVarPath = this.basePath + '/store/inventory'; + + let queryParameters: any = assign({}, extraQueryParams); + let headerParams: any = assign({}, this.defaultHeaders); + let fetchParams = { + method: 'GET', + headers: headerParams, + + }; + + if (extraFetchParams) { + fetchParams = assign(fetchParams, extraFetchParams); + } + + let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); + + return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + let error = new Error(response.statusText); + (error as any).response = response; + throw error; + } + }); + } + /** + * Find purchase order by ID + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * @param orderId ID of pet that needs to be fetched + */ + public getOrderById (params: { orderId: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise { + const localVarPath = this.basePath + '/store/order/{orderId}' + .replace('{' + 'orderId' + '}', String(params.orderId)); + + let queryParameters: any = assign({}, extraQueryParams); + let headerParams: any = assign({}, this.defaultHeaders); + // verify required parameter 'orderId' is set + if (params.orderId == null) { + throw new Error('Missing required parameter orderId when calling getOrderById'); + } + let fetchParams = { + method: 'GET', + headers: headerParams, + + }; + + if (extraFetchParams) { + fetchParams = assign(fetchParams, extraFetchParams); + } + + let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); + + return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + let error = new Error(response.statusText); + (error as any).response = response; + throw error; + } + }); + } + /** + * Place an order for a pet + * + * @param body order placed for purchasing the pet + */ + public placeOrder (params: { body?: Order; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise { + const localVarPath = this.basePath + '/store/order'; + + let queryParameters: any = assign({}, extraQueryParams); + let headerParams: any = assign({}, this.defaultHeaders); + headerParams['Content-Type'] = 'application/json'; + + let fetchParams = { + method: 'POST', + headers: headerParams, + body: JSON.stringify(params.body), + + }; + + if (extraFetchParams) { + fetchParams = assign(fetchParams, extraFetchParams); + } + + let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); + + return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + let error = new Error(response.statusText); + (error as any).response = response; + throw error; + } + }); + } + } +//} +//export namespace { + 'use strict'; + + export class UserApi { + protected basePath = 'http://petstore.swagger.io/v2'; + public defaultHeaders : any = {}; + + constructor(basePath?: string) { + if (basePath) { + this.basePath = basePath; + } + } + + /** + * Create user + * This can only be done by the logged in user. + * @param body Created user object + */ + public createUser (params: { body?: User; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { + const localVarPath = this.basePath + '/user'; + + let queryParameters: any = assign({}, extraQueryParams); + let headerParams: any = assign({}, this.defaultHeaders); + headerParams['Content-Type'] = 'application/json'; + + let fetchParams = { + method: 'POST', + headers: headerParams, + body: JSON.stringify(params.body), + + }; + + if (extraFetchParams) { + fetchParams = assign(fetchParams, extraFetchParams); + } + + let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); + + return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + let error = new Error(response.statusText); + (error as any).response = response; + throw error; + } + }); + } + /** + * Creates list of users with given input array + * + * @param body List of user object + */ + public createUsersWithArrayInput (params: { body?: Array; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { + const localVarPath = this.basePath + '/user/createWithArray'; + + let queryParameters: any = assign({}, extraQueryParams); + let headerParams: any = assign({}, this.defaultHeaders); + headerParams['Content-Type'] = 'application/json'; + + let fetchParams = { + method: 'POST', + headers: headerParams, + body: JSON.stringify(params.body), + + }; + + if (extraFetchParams) { + fetchParams = assign(fetchParams, extraFetchParams); + } + + let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); + + return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + let error = new Error(response.statusText); + (error as any).response = response; + throw error; + } + }); + } + /** + * Creates list of users with given input array + * + * @param body List of user object + */ + public createUsersWithListInput (params: { body?: Array; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { + const localVarPath = this.basePath + '/user/createWithList'; + + let queryParameters: any = assign({}, extraQueryParams); + let headerParams: any = assign({}, this.defaultHeaders); + headerParams['Content-Type'] = 'application/json'; + + let fetchParams = { + method: 'POST', + headers: headerParams, + body: JSON.stringify(params.body), + + }; + + if (extraFetchParams) { + fetchParams = assign(fetchParams, extraFetchParams); + } + + let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); + + return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + let error = new Error(response.statusText); + (error as any).response = response; + throw error; + } + }); + } + /** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted + */ + public deleteUser (params: { username: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { + const localVarPath = this.basePath + '/user/{username}' + .replace('{' + 'username' + '}', String(params.username)); + + let queryParameters: any = assign({}, extraQueryParams); + let headerParams: any = assign({}, this.defaultHeaders); + // verify required parameter 'username' is set + if (params.username == null) { + throw new Error('Missing required parameter username when calling deleteUser'); + } + let fetchParams = { + method: 'DELETE', + headers: headerParams, + + }; + + if (extraFetchParams) { + fetchParams = assign(fetchParams, extraFetchParams); + } + + let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); + + return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + let error = new Error(response.statusText); + (error as any).response = response; + throw error; + } + }); + } + /** + * Get user by user name + * + * @param username The name that needs to be fetched. Use user1 for testing. + */ + public getUserByName (params: { username: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise { + const localVarPath = this.basePath + '/user/{username}' + .replace('{' + 'username' + '}', String(params.username)); + + let queryParameters: any = assign({}, extraQueryParams); + let headerParams: any = assign({}, this.defaultHeaders); + // verify required parameter 'username' is set + if (params.username == null) { + throw new Error('Missing required parameter username when calling getUserByName'); + } + let fetchParams = { + method: 'GET', + headers: headerParams, + + }; + + if (extraFetchParams) { + fetchParams = assign(fetchParams, extraFetchParams); + } + + let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); + + return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + let error = new Error(response.statusText); + (error as any).response = response; + throw error; + } + }); + } + /** + * Logs user into the system + * + * @param username The user name for login + * @param password The password for login in clear text + */ + public loginUser (params: { username?: string; password?: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise { + const localVarPath = this.basePath + '/user/login'; + + let queryParameters: any = assign({}, extraQueryParams); + let headerParams: any = assign({}, this.defaultHeaders); + if (params.username !== undefined) { + queryParameters['username'] = params.username; + } + + if (params.password !== undefined) { + queryParameters['password'] = params.password; + } + + let fetchParams = { + method: 'GET', + headers: headerParams, + + }; + + if (extraFetchParams) { + fetchParams = assign(fetchParams, extraFetchParams); + } + + let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); + + return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + let error = new Error(response.statusText); + (error as any).response = response; + throw error; + } + }); + } + /** + * Logs out current logged in user session + * + */ + public logoutUser (params: { }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { + const localVarPath = this.basePath + '/user/logout'; + + let queryParameters: any = assign({}, extraQueryParams); + let headerParams: any = assign({}, this.defaultHeaders); + let fetchParams = { + method: 'GET', + headers: headerParams, + + }; + + if (extraFetchParams) { + fetchParams = assign(fetchParams, extraFetchParams); + } + + let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); + + return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + let error = new Error(response.statusText); + (error as any).response = response; + throw error; + } + }); + } + /** + * Updated user + * This can only be done by the logged in user. + * @param username name that need to be deleted + * @param body Updated user object + */ + public updateUser (params: { username: string; body?: User; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { + const localVarPath = this.basePath + '/user/{username}' + .replace('{' + 'username' + '}', String(params.username)); + + let queryParameters: any = assign({}, extraQueryParams); + let headerParams: any = assign({}, this.defaultHeaders); + headerParams['Content-Type'] = 'application/json'; + + // verify required parameter 'username' is set + if (params.username == null) { + throw new Error('Missing required parameter username when calling updateUser'); + } + let fetchParams = { + method: 'PUT', + headers: headerParams, + body: JSON.stringify(params.body), + + }; + + if (extraFetchParams) { + fetchParams = assign(fetchParams, extraFetchParams); + } + + let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); + + return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + let error = new Error(response.statusText); + (error as any).response = response; + throw error; + } + }); + } + } +//} diff --git a/samples/client/petstore/typescript-fetch/with-package-metadata/assign.ts b/samples/client/petstore/typescript-fetch/with-package-metadata/assign.ts new file mode 100644 index 00000000000..23355144147 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/with-package-metadata/assign.ts @@ -0,0 +1,18 @@ +export function assign (target: any, ...args: any[]) { + 'use strict'; + if (target === undefined || target === null) { + throw new TypeError('Cannot convert undefined or null to object'); + } + + var output = Object(target); + for (let source of args) { + if (source !== undefined && source !== null) { + for (var nextKey in source) { + if (source.hasOwnProperty(nextKey)) { + output[nextKey] = source[nextKey]; + } + } + } + } + return output; +}; \ No newline at end of file diff --git a/samples/client/petstore/typescript-fetch/with-package-metadata/git_push.sh b/samples/client/petstore/typescript-fetch/with-package-metadata/git_push.sh new file mode 100644 index 00000000000..ed374619b13 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/with-package-metadata/git_push.sh @@ -0,0 +1,52 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 swagger-petstore-perl "minor update" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 + +if [ "$git_user_id" = "" ]; then + git_user_id="GIT_USER_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="GIT_REPO_ID" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="Minor update" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=`git remote` +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git crediential in your environment." + git remote add origin https://github.com/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:${GIT_TOKEN}@github.com/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://github.com/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' + diff --git a/samples/client/petstore/typescript-fetch/with-package-metadata/package.json b/samples/client/petstore/typescript-fetch/with-package-metadata/package.json new file mode 100644 index 00000000000..ab2a67c51d0 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/with-package-metadata/package.json @@ -0,0 +1,18 @@ +{ + "name": "@swagger/typescript-fetch-petstore", + "version": "0.0.1", + "private": true, + "main": "./dist/api.js", + "browser": "./dist/api.js", + "typings": "./dist/api.d.ts", + "dependencies": { + "isomorphic-fetch": "^2.2.1" + }, + "scripts" : { + "install" : "typings install && tsc" + }, + "devDependencies": { + "typescript": "^1.8.10", + "typings": "^0.8.1" + } +} \ No newline at end of file diff --git a/samples/client/petstore/typescript-fetch/with-package-metadata/tsconfig.json b/samples/client/petstore/typescript-fetch/with-package-metadata/tsconfig.json new file mode 100644 index 00000000000..18db23e2f5f --- /dev/null +++ b/samples/client/petstore/typescript-fetch/with-package-metadata/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "declaration": true, + "target": "es5", + "module": "commonjs", + "noImplicitAny": true, + "outDir": "dist" + }, + "exclude": [ + "dist", + "node_modules", + "typings/browser", + "typings/main", + "typings/main.d.ts" + ] +} diff --git a/samples/client/petstore/typescript-fetch/with-package-metadata/typings.json b/samples/client/petstore/typescript-fetch/with-package-metadata/typings.json new file mode 100644 index 00000000000..eeca5afde97 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/with-package-metadata/typings.json @@ -0,0 +1,9 @@ +{ + "version": false, + "dependencies": {}, + "ambientDependencies": { + "es6-promise": "registry:dt/es6-promise#0.0.0+20160423074304", + "node": "registry:dt/node#4.0.0+20160423143914", + "isomorphic-fetch": "registry:dt/isomorphic-fetch#0.0.0+20160505171433" + } +} diff --git a/samples/client/petstore/typescript-node/default/api.js b/samples/client/petstore/typescript-node/default/api.js new file mode 100644 index 00000000000..9a6c0a28ec7 --- /dev/null +++ b/samples/client/petstore/typescript-node/default/api.js @@ -0,0 +1,1188 @@ +var request = require('request'); +var promise = require('bluebird'); +var defaultBasePath = 'http://petstore.swagger.io/v2'; +// =============================================== +// This file is autogenerated - Please do not edit +// =============================================== +/* tslint:disable:no-unused-variable */ +var Category = (function () { + function Category() { + } + return Category; +})(); +exports.Category = Category; +var Order = (function () { + function Order() { + } + return Order; +})(); +exports.Order = Order; +var Order; +(function (Order) { + (function (StatusEnum) { + StatusEnum[StatusEnum["StatusEnum_placed"] = 'placed'] = "StatusEnum_placed"; + StatusEnum[StatusEnum["StatusEnum_approved"] = 'approved'] = "StatusEnum_approved"; + StatusEnum[StatusEnum["StatusEnum_delivered"] = 'delivered'] = "StatusEnum_delivered"; + })(Order.StatusEnum || (Order.StatusEnum = {})); + var StatusEnum = Order.StatusEnum; +})(Order = exports.Order || (exports.Order = {})); +var Pet = (function () { + function Pet() { + } + return Pet; +})(); +exports.Pet = Pet; +var Pet; +(function (Pet) { + (function (StatusEnum) { + StatusEnum[StatusEnum["StatusEnum_available"] = 'available'] = "StatusEnum_available"; + StatusEnum[StatusEnum["StatusEnum_pending"] = 'pending'] = "StatusEnum_pending"; + StatusEnum[StatusEnum["StatusEnum_sold"] = 'sold'] = "StatusEnum_sold"; + })(Pet.StatusEnum || (Pet.StatusEnum = {})); + var StatusEnum = Pet.StatusEnum; +})(Pet = exports.Pet || (exports.Pet = {})); +var Tag = (function () { + function Tag() { + } + return Tag; +})(); +exports.Tag = Tag; +var User = (function () { + function User() { + } + return User; +})(); +exports.User = User; +var HttpBasicAuth = (function () { + function HttpBasicAuth() { + } + HttpBasicAuth.prototype.applyToRequest = function (requestOptions) { + requestOptions.auth = { + username: this.username, password: this.password + }; + }; + return HttpBasicAuth; +})(); +exports.HttpBasicAuth = HttpBasicAuth; +var ApiKeyAuth = (function () { + function ApiKeyAuth(location, paramName) { + this.location = location; + this.paramName = paramName; + } + ApiKeyAuth.prototype.applyToRequest = function (requestOptions) { + if (this.location == "query") { + requestOptions.qs[this.paramName] = this.apiKey; + } + else if (this.location == "header") { + requestOptions.headers[this.paramName] = this.apiKey; + } + }; + return ApiKeyAuth; +})(); +exports.ApiKeyAuth = ApiKeyAuth; +var OAuth = (function () { + function OAuth() { + } + OAuth.prototype.applyToRequest = function (requestOptions) { + requestOptions.headers["Authorization"] = "Bearer " + this.accessToken; + }; + return OAuth; +})(); +exports.OAuth = OAuth; +var VoidAuth = (function () { + function VoidAuth() { + } + VoidAuth.prototype.applyToRequest = function (requestOptions) { + // Do nothing + }; + return VoidAuth; +})(); +exports.VoidAuth = VoidAuth; +(function (PetApiApiKeys) { + PetApiApiKeys[PetApiApiKeys["api_key"] = 0] = "api_key"; +})(exports.PetApiApiKeys || (exports.PetApiApiKeys = {})); +var PetApiApiKeys = exports.PetApiApiKeys; +var PetApi = (function () { + function PetApi(basePathOrUsername, password, basePath) { + this.basePath = defaultBasePath; + this.defaultHeaders = {}; + this.authentications = { + 'default': new VoidAuth(), + 'api_key': new ApiKeyAuth('header', 'api_key'), + 'petstore_auth': new OAuth(), + }; + if (password) { + if (basePath) { + this.basePath = basePath; + } + } + else { + if (basePathOrUsername) { + this.basePath = basePathOrUsername; + } + } + } + PetApi.prototype.setApiKey = function (key, value) { + this.authentications[PetApiApiKeys[key]].apiKey = value; + }; + Object.defineProperty(PetApi.prototype, "accessToken", { + set: function (token) { + this.authentications.petstore_auth.accessToken = token; + }, + enumerable: true, + configurable: true + }); + PetApi.prototype.extendObj = function (objA, objB) { + for (var key in objB) { + if (objB.hasOwnProperty(key)) { + objA[key] = objB[key]; + } + } + return objA; + }; + /** + * Add a new pet to the store + * + * @param body Pet object that needs to be added to the store + */ + PetApi.prototype.addPet = function (body) { + var localVarPath = this.basePath + '/pet'; + var queryParameters = {}; + var headerParams = this.extendObj({}, this.defaultHeaders); + var formParams = {}; + var useFormData = false; + var localVarDeferred = promise.defer(); + var requestOptions = { + method: 'POST', + qs: queryParameters, + headers: headerParams, + uri: localVarPath, + json: true, + body: body, + }; + this.authentications.petstore_auth.applyToRequest(requestOptions); + this.authentications.default.applyToRequest(requestOptions); + if (Object.keys(formParams).length) { + if (useFormData) { + requestOptions.formData = formParams; + } + else { + requestOptions.form = formParams; + } + } + request(requestOptions, function (error, response, body) { + if (error) { + localVarDeferred.reject(error); + } + else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + localVarDeferred.resolve({ response: response, body: body }); + } + else { + localVarDeferred.reject({ response: response, body: body }); + } + } + }); + return localVarDeferred.promise; + }; + /** + * Deletes a pet + * + * @param petId Pet id to delete + * @param apiKey + */ + PetApi.prototype.deletePet = function (petId, apiKey) { + var localVarPath = this.basePath + '/pet/{petId}' + .replace('{' + 'petId' + '}', String(petId)); + var queryParameters = {}; + var headerParams = this.extendObj({}, this.defaultHeaders); + var formParams = {}; + // verify required parameter 'petId' is not null or undefined + if (petId === null || petId === undefined) { + throw new Error('Required parameter petId was null or undefined when calling deletePet.'); + } + headerParams['api_key'] = apiKey; + var useFormData = false; + var localVarDeferred = promise.defer(); + var requestOptions = { + method: 'DELETE', + qs: queryParameters, + headers: headerParams, + uri: localVarPath, + json: true, + }; + this.authentications.petstore_auth.applyToRequest(requestOptions); + this.authentications.default.applyToRequest(requestOptions); + if (Object.keys(formParams).length) { + if (useFormData) { + requestOptions.formData = formParams; + } + else { + requestOptions.form = formParams; + } + } + request(requestOptions, function (error, response, body) { + if (error) { + localVarDeferred.reject(error); + } + else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + localVarDeferred.resolve({ response: response, body: body }); + } + else { + localVarDeferred.reject({ response: response, body: body }); + } + } + }); + return localVarDeferred.promise; + }; + /** + * 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 + */ + PetApi.prototype.findPetsByStatus = function (status) { + var localVarPath = this.basePath + '/pet/findByStatus'; + var queryParameters = {}; + var headerParams = this.extendObj({}, this.defaultHeaders); + var formParams = {}; + if (status !== undefined) { + queryParameters['status'] = status; + } + var useFormData = false; + var localVarDeferred = promise.defer(); + var requestOptions = { + method: 'GET', + qs: queryParameters, + headers: headerParams, + uri: localVarPath, + json: true, + }; + this.authentications.petstore_auth.applyToRequest(requestOptions); + this.authentications.default.applyToRequest(requestOptions); + if (Object.keys(formParams).length) { + if (useFormData) { + requestOptions.formData = formParams; + } + else { + requestOptions.form = formParams; + } + } + request(requestOptions, function (error, response, body) { + if (error) { + localVarDeferred.reject(error); + } + else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + localVarDeferred.resolve({ response: response, body: body }); + } + else { + localVarDeferred.reject({ response: response, body: body }); + } + } + }); + return localVarDeferred.promise; + }; + /** + * 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 + */ + PetApi.prototype.findPetsByTags = function (tags) { + var localVarPath = this.basePath + '/pet/findByTags'; + var queryParameters = {}; + var headerParams = this.extendObj({}, this.defaultHeaders); + var formParams = {}; + if (tags !== undefined) { + queryParameters['tags'] = tags; + } + var useFormData = false; + var localVarDeferred = promise.defer(); + var requestOptions = { + method: 'GET', + qs: queryParameters, + headers: headerParams, + uri: localVarPath, + json: true, + }; + this.authentications.petstore_auth.applyToRequest(requestOptions); + this.authentications.default.applyToRequest(requestOptions); + if (Object.keys(formParams).length) { + if (useFormData) { + requestOptions.formData = formParams; + } + else { + requestOptions.form = formParams; + } + } + request(requestOptions, function (error, response, body) { + if (error) { + localVarDeferred.reject(error); + } + else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + localVarDeferred.resolve({ response: response, body: body }); + } + else { + localVarDeferred.reject({ response: response, body: body }); + } + } + }); + return localVarDeferred.promise; + }; + /** + * 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 + */ + PetApi.prototype.getPetById = function (petId) { + var localVarPath = this.basePath + '/pet/{petId}' + .replace('{' + 'petId' + '}', String(petId)); + var queryParameters = {}; + var headerParams = this.extendObj({}, this.defaultHeaders); + var formParams = {}; + // verify required parameter 'petId' is not null or undefined + if (petId === null || petId === undefined) { + throw new Error('Required parameter petId was null or undefined when calling getPetById.'); + } + var useFormData = false; + var localVarDeferred = promise.defer(); + var requestOptions = { + method: 'GET', + qs: queryParameters, + headers: headerParams, + uri: localVarPath, + json: true, + }; + this.authentications.api_key.applyToRequest(requestOptions); + this.authentications.petstore_auth.applyToRequest(requestOptions); + this.authentications.default.applyToRequest(requestOptions); + if (Object.keys(formParams).length) { + if (useFormData) { + requestOptions.formData = formParams; + } + else { + requestOptions.form = formParams; + } + } + request(requestOptions, function (error, response, body) { + if (error) { + localVarDeferred.reject(error); + } + else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + localVarDeferred.resolve({ response: response, body: body }); + } + else { + localVarDeferred.reject({ response: response, body: body }); + } + } + }); + return localVarDeferred.promise; + }; + /** + * Update an existing pet + * + * @param body Pet object that needs to be added to the store + */ + PetApi.prototype.updatePet = function (body) { + var localVarPath = this.basePath + '/pet'; + var queryParameters = {}; + var headerParams = this.extendObj({}, this.defaultHeaders); + var formParams = {}; + var useFormData = false; + var localVarDeferred = promise.defer(); + var requestOptions = { + method: 'PUT', + qs: queryParameters, + headers: headerParams, + uri: localVarPath, + json: true, + body: body, + }; + this.authentications.petstore_auth.applyToRequest(requestOptions); + this.authentications.default.applyToRequest(requestOptions); + if (Object.keys(formParams).length) { + if (useFormData) { + requestOptions.formData = formParams; + } + else { + requestOptions.form = formParams; + } + } + request(requestOptions, function (error, response, body) { + if (error) { + localVarDeferred.reject(error); + } + else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + localVarDeferred.resolve({ response: response, body: body }); + } + else { + localVarDeferred.reject({ response: response, body: body }); + } + } + }); + return localVarDeferred.promise; + }; + /** + * 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 + */ + PetApi.prototype.updatePetWithForm = function (petId, name, status) { + var localVarPath = this.basePath + '/pet/{petId}' + .replace('{' + 'petId' + '}', String(petId)); + var queryParameters = {}; + var headerParams = this.extendObj({}, this.defaultHeaders); + var formParams = {}; + // verify required parameter 'petId' is not null or undefined + if (petId === null || petId === undefined) { + throw new Error('Required parameter petId was null or undefined when calling updatePetWithForm.'); + } + var useFormData = false; + if (name !== undefined) { + formParams['name'] = name; + } + if (status !== undefined) { + formParams['status'] = status; + } + var localVarDeferred = promise.defer(); + var requestOptions = { + method: 'POST', + qs: queryParameters, + headers: headerParams, + uri: localVarPath, + json: true, + }; + this.authentications.petstore_auth.applyToRequest(requestOptions); + this.authentications.default.applyToRequest(requestOptions); + if (Object.keys(formParams).length) { + if (useFormData) { + requestOptions.formData = formParams; + } + else { + requestOptions.form = formParams; + } + } + request(requestOptions, function (error, response, body) { + if (error) { + localVarDeferred.reject(error); + } + else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + localVarDeferred.resolve({ response: response, body: body }); + } + else { + localVarDeferred.reject({ response: response, body: body }); + } + } + }); + return localVarDeferred.promise; + }; + /** + * uploads an image + * + * @param petId ID of pet to update + * @param additionalMetadata Additional data to pass to server + * @param file file to upload + */ + PetApi.prototype.uploadFile = function (petId, additionalMetadata, file) { + var localVarPath = this.basePath + '/pet/{petId}/uploadImage' + .replace('{' + 'petId' + '}', String(petId)); + var queryParameters = {}; + var headerParams = this.extendObj({}, this.defaultHeaders); + var formParams = {}; + // verify required parameter 'petId' is not null or undefined + if (petId === null || petId === undefined) { + throw new Error('Required parameter petId was null or undefined when calling uploadFile.'); + } + var useFormData = false; + if (additionalMetadata !== undefined) { + formParams['additionalMetadata'] = additionalMetadata; + } + if (file !== undefined) { + formParams['file'] = file; + } + useFormData = true; + var localVarDeferred = promise.defer(); + var requestOptions = { + method: 'POST', + qs: queryParameters, + headers: headerParams, + uri: localVarPath, + json: true, + }; + this.authentications.petstore_auth.applyToRequest(requestOptions); + this.authentications.default.applyToRequest(requestOptions); + if (Object.keys(formParams).length) { + if (useFormData) { + requestOptions.formData = formParams; + } + else { + requestOptions.form = formParams; + } + } + request(requestOptions, function (error, response, body) { + if (error) { + localVarDeferred.reject(error); + } + else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + localVarDeferred.resolve({ response: response, body: body }); + } + else { + localVarDeferred.reject({ response: response, body: body }); + } + } + }); + return localVarDeferred.promise; + }; + return PetApi; +})(); +exports.PetApi = PetApi; +(function (StoreApiApiKeys) { + StoreApiApiKeys[StoreApiApiKeys["api_key"] = 0] = "api_key"; +})(exports.StoreApiApiKeys || (exports.StoreApiApiKeys = {})); +var StoreApiApiKeys = exports.StoreApiApiKeys; +var StoreApi = (function () { + function StoreApi(basePathOrUsername, password, basePath) { + this.basePath = defaultBasePath; + this.defaultHeaders = {}; + this.authentications = { + 'default': new VoidAuth(), + 'api_key': new ApiKeyAuth('header', 'api_key'), + 'petstore_auth': new OAuth(), + }; + if (password) { + if (basePath) { + this.basePath = basePath; + } + } + else { + if (basePathOrUsername) { + this.basePath = basePathOrUsername; + } + } + } + StoreApi.prototype.setApiKey = function (key, value) { + this.authentications[StoreApiApiKeys[key]].apiKey = value; + }; + Object.defineProperty(StoreApi.prototype, "accessToken", { + set: function (token) { + this.authentications.petstore_auth.accessToken = token; + }, + enumerable: true, + configurable: true + }); + StoreApi.prototype.extendObj = function (objA, objB) { + for (var key in objB) { + if (objB.hasOwnProperty(key)) { + objA[key] = objB[key]; + } + } + return objA; + }; + /** + * 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 + */ + StoreApi.prototype.deleteOrder = function (orderId) { + var localVarPath = this.basePath + '/store/order/{orderId}' + .replace('{' + 'orderId' + '}', String(orderId)); + var queryParameters = {}; + var headerParams = this.extendObj({}, this.defaultHeaders); + var formParams = {}; + // verify required parameter 'orderId' is not null or undefined + if (orderId === null || orderId === undefined) { + throw new Error('Required parameter orderId was null or undefined when calling deleteOrder.'); + } + var useFormData = false; + var localVarDeferred = promise.defer(); + var requestOptions = { + method: 'DELETE', + qs: queryParameters, + headers: headerParams, + uri: localVarPath, + json: true, + }; + this.authentications.default.applyToRequest(requestOptions); + if (Object.keys(formParams).length) { + if (useFormData) { + requestOptions.formData = formParams; + } + else { + requestOptions.form = formParams; + } + } + request(requestOptions, function (error, response, body) { + if (error) { + localVarDeferred.reject(error); + } + else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + localVarDeferred.resolve({ response: response, body: body }); + } + else { + localVarDeferred.reject({ response: response, body: body }); + } + } + }); + return localVarDeferred.promise; + }; + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + */ + StoreApi.prototype.getInventory = function () { + var localVarPath = this.basePath + '/store/inventory'; + var queryParameters = {}; + var headerParams = this.extendObj({}, this.defaultHeaders); + var formParams = {}; + var useFormData = false; + var localVarDeferred = promise.defer(); + var requestOptions = { + method: 'GET', + qs: queryParameters, + headers: headerParams, + uri: localVarPath, + json: true, + }; + this.authentications.api_key.applyToRequest(requestOptions); + this.authentications.default.applyToRequest(requestOptions); + if (Object.keys(formParams).length) { + if (useFormData) { + requestOptions.formData = formParams; + } + else { + requestOptions.form = formParams; + } + } + request(requestOptions, function (error, response, body) { + if (error) { + localVarDeferred.reject(error); + } + else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + localVarDeferred.resolve({ response: response, body: body }); + } + else { + localVarDeferred.reject({ response: response, body: body }); + } + } + }); + return localVarDeferred.promise; + }; + /** + * 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 + */ + StoreApi.prototype.getOrderById = function (orderId) { + var localVarPath = this.basePath + '/store/order/{orderId}' + .replace('{' + 'orderId' + '}', String(orderId)); + var queryParameters = {}; + var headerParams = this.extendObj({}, this.defaultHeaders); + var formParams = {}; + // verify required parameter 'orderId' is not null or undefined + if (orderId === null || orderId === undefined) { + throw new Error('Required parameter orderId was null or undefined when calling getOrderById.'); + } + var useFormData = false; + var localVarDeferred = promise.defer(); + var requestOptions = { + method: 'GET', + qs: queryParameters, + headers: headerParams, + uri: localVarPath, + json: true, + }; + this.authentications.default.applyToRequest(requestOptions); + if (Object.keys(formParams).length) { + if (useFormData) { + requestOptions.formData = formParams; + } + else { + requestOptions.form = formParams; + } + } + request(requestOptions, function (error, response, body) { + if (error) { + localVarDeferred.reject(error); + } + else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + localVarDeferred.resolve({ response: response, body: body }); + } + else { + localVarDeferred.reject({ response: response, body: body }); + } + } + }); + return localVarDeferred.promise; + }; + /** + * Place an order for a pet + * + * @param body order placed for purchasing the pet + */ + StoreApi.prototype.placeOrder = function (body) { + var localVarPath = this.basePath + '/store/order'; + var queryParameters = {}; + var headerParams = this.extendObj({}, this.defaultHeaders); + var formParams = {}; + var useFormData = false; + var localVarDeferred = promise.defer(); + var requestOptions = { + method: 'POST', + qs: queryParameters, + headers: headerParams, + uri: localVarPath, + json: true, + body: body, + }; + this.authentications.default.applyToRequest(requestOptions); + if (Object.keys(formParams).length) { + if (useFormData) { + requestOptions.formData = formParams; + } + else { + requestOptions.form = formParams; + } + } + request(requestOptions, function (error, response, body) { + if (error) { + localVarDeferred.reject(error); + } + else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + localVarDeferred.resolve({ response: response, body: body }); + } + else { + localVarDeferred.reject({ response: response, body: body }); + } + } + }); + return localVarDeferred.promise; + }; + return StoreApi; +})(); +exports.StoreApi = StoreApi; +(function (UserApiApiKeys) { + UserApiApiKeys[UserApiApiKeys["api_key"] = 0] = "api_key"; +})(exports.UserApiApiKeys || (exports.UserApiApiKeys = {})); +var UserApiApiKeys = exports.UserApiApiKeys; +var UserApi = (function () { + function UserApi(basePathOrUsername, password, basePath) { + this.basePath = defaultBasePath; + this.defaultHeaders = {}; + this.authentications = { + 'default': new VoidAuth(), + 'api_key': new ApiKeyAuth('header', 'api_key'), + 'petstore_auth': new OAuth(), + }; + if (password) { + if (basePath) { + this.basePath = basePath; + } + } + else { + if (basePathOrUsername) { + this.basePath = basePathOrUsername; + } + } + } + UserApi.prototype.setApiKey = function (key, value) { + this.authentications[UserApiApiKeys[key]].apiKey = value; + }; + Object.defineProperty(UserApi.prototype, "accessToken", { + set: function (token) { + this.authentications.petstore_auth.accessToken = token; + }, + enumerable: true, + configurable: true + }); + UserApi.prototype.extendObj = function (objA, objB) { + for (var key in objB) { + if (objB.hasOwnProperty(key)) { + objA[key] = objB[key]; + } + } + return objA; + }; + /** + * Create user + * This can only be done by the logged in user. + * @param body Created user object + */ + UserApi.prototype.createUser = function (body) { + var localVarPath = this.basePath + '/user'; + var queryParameters = {}; + var headerParams = this.extendObj({}, this.defaultHeaders); + var formParams = {}; + var useFormData = false; + var localVarDeferred = promise.defer(); + var requestOptions = { + method: 'POST', + qs: queryParameters, + headers: headerParams, + uri: localVarPath, + json: true, + body: body, + }; + this.authentications.default.applyToRequest(requestOptions); + if (Object.keys(formParams).length) { + if (useFormData) { + requestOptions.formData = formParams; + } + else { + requestOptions.form = formParams; + } + } + request(requestOptions, function (error, response, body) { + if (error) { + localVarDeferred.reject(error); + } + else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + localVarDeferred.resolve({ response: response, body: body }); + } + else { + localVarDeferred.reject({ response: response, body: body }); + } + } + }); + return localVarDeferred.promise; + }; + /** + * Creates list of users with given input array + * + * @param body List of user object + */ + UserApi.prototype.createUsersWithArrayInput = function (body) { + var localVarPath = this.basePath + '/user/createWithArray'; + var queryParameters = {}; + var headerParams = this.extendObj({}, this.defaultHeaders); + var formParams = {}; + var useFormData = false; + var localVarDeferred = promise.defer(); + var requestOptions = { + method: 'POST', + qs: queryParameters, + headers: headerParams, + uri: localVarPath, + json: true, + body: body, + }; + this.authentications.default.applyToRequest(requestOptions); + if (Object.keys(formParams).length) { + if (useFormData) { + requestOptions.formData = formParams; + } + else { + requestOptions.form = formParams; + } + } + request(requestOptions, function (error, response, body) { + if (error) { + localVarDeferred.reject(error); + } + else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + localVarDeferred.resolve({ response: response, body: body }); + } + else { + localVarDeferred.reject({ response: response, body: body }); + } + } + }); + return localVarDeferred.promise; + }; + /** + * Creates list of users with given input array + * + * @param body List of user object + */ + UserApi.prototype.createUsersWithListInput = function (body) { + var localVarPath = this.basePath + '/user/createWithList'; + var queryParameters = {}; + var headerParams = this.extendObj({}, this.defaultHeaders); + var formParams = {}; + var useFormData = false; + var localVarDeferred = promise.defer(); + var requestOptions = { + method: 'POST', + qs: queryParameters, + headers: headerParams, + uri: localVarPath, + json: true, + body: body, + }; + this.authentications.default.applyToRequest(requestOptions); + if (Object.keys(formParams).length) { + if (useFormData) { + requestOptions.formData = formParams; + } + else { + requestOptions.form = formParams; + } + } + request(requestOptions, function (error, response, body) { + if (error) { + localVarDeferred.reject(error); + } + else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + localVarDeferred.resolve({ response: response, body: body }); + } + else { + localVarDeferred.reject({ response: response, body: body }); + } + } + }); + return localVarDeferred.promise; + }; + /** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted + */ + UserApi.prototype.deleteUser = function (username) { + var localVarPath = this.basePath + '/user/{username}' + .replace('{' + 'username' + '}', String(username)); + var queryParameters = {}; + var headerParams = this.extendObj({}, this.defaultHeaders); + var formParams = {}; + // verify required parameter 'username' is not null or undefined + if (username === null || username === undefined) { + throw new Error('Required parameter username was null or undefined when calling deleteUser.'); + } + var useFormData = false; + var localVarDeferred = promise.defer(); + var requestOptions = { + method: 'DELETE', + qs: queryParameters, + headers: headerParams, + uri: localVarPath, + json: true, + }; + this.authentications.default.applyToRequest(requestOptions); + if (Object.keys(formParams).length) { + if (useFormData) { + requestOptions.formData = formParams; + } + else { + requestOptions.form = formParams; + } + } + request(requestOptions, function (error, response, body) { + if (error) { + localVarDeferred.reject(error); + } + else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + localVarDeferred.resolve({ response: response, body: body }); + } + else { + localVarDeferred.reject({ response: response, body: body }); + } + } + }); + return localVarDeferred.promise; + }; + /** + * Get user by user name + * + * @param username The name that needs to be fetched. Use user1 for testing. + */ + UserApi.prototype.getUserByName = function (username) { + var localVarPath = this.basePath + '/user/{username}' + .replace('{' + 'username' + '}', String(username)); + var queryParameters = {}; + var headerParams = this.extendObj({}, this.defaultHeaders); + var formParams = {}; + // verify required parameter 'username' is not null or undefined + if (username === null || username === undefined) { + throw new Error('Required parameter username was null or undefined when calling getUserByName.'); + } + var useFormData = false; + var localVarDeferred = promise.defer(); + var requestOptions = { + method: 'GET', + qs: queryParameters, + headers: headerParams, + uri: localVarPath, + json: true, + }; + this.authentications.default.applyToRequest(requestOptions); + if (Object.keys(formParams).length) { + if (useFormData) { + requestOptions.formData = formParams; + } + else { + requestOptions.form = formParams; + } + } + request(requestOptions, function (error, response, body) { + if (error) { + localVarDeferred.reject(error); + } + else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + localVarDeferred.resolve({ response: response, body: body }); + } + else { + localVarDeferred.reject({ response: response, body: body }); + } + } + }); + return localVarDeferred.promise; + }; + /** + * Logs user into the system + * + * @param username The user name for login + * @param password The password for login in clear text + */ + UserApi.prototype.loginUser = function (username, password) { + var localVarPath = this.basePath + '/user/login'; + var queryParameters = {}; + var headerParams = this.extendObj({}, this.defaultHeaders); + var formParams = {}; + if (username !== undefined) { + queryParameters['username'] = username; + } + if (password !== undefined) { + queryParameters['password'] = password; + } + var useFormData = false; + var localVarDeferred = promise.defer(); + var requestOptions = { + method: 'GET', + qs: queryParameters, + headers: headerParams, + uri: localVarPath, + json: true, + }; + this.authentications.default.applyToRequest(requestOptions); + if (Object.keys(formParams).length) { + if (useFormData) { + requestOptions.formData = formParams; + } + else { + requestOptions.form = formParams; + } + } + request(requestOptions, function (error, response, body) { + if (error) { + localVarDeferred.reject(error); + } + else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + localVarDeferred.resolve({ response: response, body: body }); + } + else { + localVarDeferred.reject({ response: response, body: body }); + } + } + }); + return localVarDeferred.promise; + }; + /** + * Logs out current logged in user session + * + */ + UserApi.prototype.logoutUser = function () { + var localVarPath = this.basePath + '/user/logout'; + var queryParameters = {}; + var headerParams = this.extendObj({}, this.defaultHeaders); + var formParams = {}; + var useFormData = false; + var localVarDeferred = promise.defer(); + var requestOptions = { + method: 'GET', + qs: queryParameters, + headers: headerParams, + uri: localVarPath, + json: true, + }; + this.authentications.default.applyToRequest(requestOptions); + if (Object.keys(formParams).length) { + if (useFormData) { + requestOptions.formData = formParams; + } + else { + requestOptions.form = formParams; + } + } + request(requestOptions, function (error, response, body) { + if (error) { + localVarDeferred.reject(error); + } + else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + localVarDeferred.resolve({ response: response, body: body }); + } + else { + localVarDeferred.reject({ response: response, body: body }); + } + } + }); + return localVarDeferred.promise; + }; + /** + * 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 + */ + UserApi.prototype.updateUser = function (username, body) { + var localVarPath = this.basePath + '/user/{username}' + .replace('{' + 'username' + '}', String(username)); + var queryParameters = {}; + var headerParams = this.extendObj({}, this.defaultHeaders); + var formParams = {}; + // verify required parameter 'username' is not null or undefined + if (username === null || username === undefined) { + throw new Error('Required parameter username was null or undefined when calling updateUser.'); + } + var useFormData = false; + var localVarDeferred = promise.defer(); + var requestOptions = { + method: 'PUT', + qs: queryParameters, + headers: headerParams, + uri: localVarPath, + json: true, + body: body, + }; + this.authentications.default.applyToRequest(requestOptions); + if (Object.keys(formParams).length) { + if (useFormData) { + requestOptions.formData = formParams; + } + else { + requestOptions.form = formParams; + } + } + request(requestOptions, function (error, response, body) { + if (error) { + localVarDeferred.reject(error); + } + else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + localVarDeferred.resolve({ response: response, body: body }); + } + else { + localVarDeferred.reject({ response: response, body: body }); + } + } + }); + return localVarDeferred.promise; + }; + return UserApi; +})(); +exports.UserApi = UserApi; diff --git a/samples/client/petstore/typescript-node/default/api.ts b/samples/client/petstore/typescript-node/default/api.ts index c2bd53e8ca2..568335b5769 100644 --- a/samples/client/petstore/typescript-node/default/api.ts +++ b/samples/client/petstore/typescript-node/default/api.ts @@ -1,6 +1,8 @@ import request = require('request'); -import promise = require('bluebird'); import http = require('http'); +import promise = require('bluebird'); + +let defaultBasePath = 'http://petstore.swagger.io/v2'; // =============================================== // This file is autogenerated - Please do not edit @@ -9,65 +11,65 @@ import http = require('http'); /* tslint:disable:no-unused-variable */ export class Category { - "id": number; - "name": string; + 'id': number; + 'name': string; } export class Order { - "id": number; - "petId": number; - "quantity": number; - "shipDate": Date; + 'id': number; + 'petId': number; + 'quantity': number; + 'shipDate': Date; /** * Order Status */ - "status": Order.StatusEnum; - "complete": boolean; + 'status': Order.StatusEnum; + 'complete': boolean; } export namespace Order { export enum StatusEnum { - placed = 'placed', - approved = 'approved', - delivered = 'delivered' + StatusEnum_placed = 'placed', + StatusEnum_approved = 'approved', + StatusEnum_delivered = 'delivered' } } export class Pet { - "id": number; - "category": Category; - "name": string; - "photoUrls": Array; - "tags": Array; + 'id': number; + 'category': Category; + 'name': string; + 'photoUrls': Array; + 'tags': Array; /** * pet status in the store */ - "status": Pet.StatusEnum; + 'status': Pet.StatusEnum; } export namespace Pet { export enum StatusEnum { - available = 'available', - pending = 'pending', - sold = 'sold' + StatusEnum_available = 'available', + StatusEnum_pending = 'pending', + StatusEnum_sold = 'sold' } } export class Tag { - "id": number; - "name": string; + 'id': number; + 'name': string; } export class User { - "id": number; - "username": string; - "firstName": string; - "lastName": string; - "email": string; - "password": string; - "phone": string; + 'id': number; + 'username': string; + 'firstName': string; + 'lastName': string; + 'email': string; + 'password': string; + 'phone': string; /** * User Status */ - "userStatus": number; + 'userStatus': number; } @@ -124,7 +126,7 @@ export enum PetApiApiKeys { } export class PetApi { - protected basePath = 'http://petstore.swagger.io/v2'; + protected basePath = defaultBasePath; protected defaultHeaders : any = {}; protected authentications = { @@ -176,7 +178,6 @@ export class PetApi { let useFormData = false; let localVarDeferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); - let requestOptions: request.Options = { method: 'POST', qs: queryParameters, @@ -184,7 +185,7 @@ export class PetApi { uri: localVarPath, json: true, body: body, - } + }; this.authentications.petstore_auth.applyToRequest(requestOptions); @@ -197,7 +198,6 @@ export class PetApi { requestOptions.form = formParams; } } - request(requestOptions, (error, response, body) => { if (error) { localVarDeferred.reject(error); @@ -209,7 +209,6 @@ export class PetApi { } } }); - return localVarDeferred.promise; } /** @@ -236,14 +235,13 @@ export class PetApi { let useFormData = false; let localVarDeferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); - let requestOptions: request.Options = { method: 'DELETE', qs: queryParameters, headers: headerParams, uri: localVarPath, json: true, - } + }; this.authentications.petstore_auth.applyToRequest(requestOptions); @@ -256,7 +254,6 @@ export class PetApi { requestOptions.form = formParams; } } - request(requestOptions, (error, response, body) => { if (error) { localVarDeferred.reject(error); @@ -268,7 +265,6 @@ export class PetApi { } } }); - return localVarDeferred.promise; } /** @@ -290,14 +286,13 @@ export class PetApi { let useFormData = false; let localVarDeferred = promise.defer<{ response: http.ClientResponse; body: Array; }>(); - let requestOptions: request.Options = { method: 'GET', qs: queryParameters, headers: headerParams, uri: localVarPath, json: true, - } + }; this.authentications.petstore_auth.applyToRequest(requestOptions); @@ -310,7 +305,6 @@ export class PetApi { requestOptions.form = formParams; } } - request(requestOptions, (error, response, body) => { if (error) { localVarDeferred.reject(error); @@ -322,7 +316,6 @@ export class PetApi { } } }); - return localVarDeferred.promise; } /** @@ -344,14 +337,13 @@ export class PetApi { let useFormData = false; let localVarDeferred = promise.defer<{ response: http.ClientResponse; body: Array; }>(); - let requestOptions: request.Options = { method: 'GET', qs: queryParameters, headers: headerParams, uri: localVarPath, json: true, - } + }; this.authentications.petstore_auth.applyToRequest(requestOptions); @@ -364,7 +356,6 @@ export class PetApi { requestOptions.form = formParams; } } - request(requestOptions, (error, response, body) => { if (error) { localVarDeferred.reject(error); @@ -376,7 +367,6 @@ export class PetApi { } } }); - return localVarDeferred.promise; } /** @@ -400,14 +390,13 @@ export class PetApi { let useFormData = false; let localVarDeferred = promise.defer<{ response: http.ClientResponse; body: Pet; }>(); - let requestOptions: request.Options = { method: 'GET', qs: queryParameters, headers: headerParams, uri: localVarPath, json: true, - } + }; this.authentications.api_key.applyToRequest(requestOptions); @@ -422,7 +411,6 @@ export class PetApi { requestOptions.form = formParams; } } - request(requestOptions, (error, response, body) => { if (error) { localVarDeferred.reject(error); @@ -434,7 +422,6 @@ export class PetApi { } } }); - return localVarDeferred.promise; } /** @@ -452,7 +439,6 @@ export class PetApi { let useFormData = false; let localVarDeferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); - let requestOptions: request.Options = { method: 'PUT', qs: queryParameters, @@ -460,7 +446,7 @@ export class PetApi { uri: localVarPath, json: true, body: body, - } + }; this.authentications.petstore_auth.applyToRequest(requestOptions); @@ -473,7 +459,6 @@ export class PetApi { requestOptions.form = formParams; } } - request(requestOptions, (error, response, body) => { if (error) { localVarDeferred.reject(error); @@ -485,7 +470,6 @@ export class PetApi { } } }); - return localVarDeferred.promise; } /** @@ -519,14 +503,13 @@ export class PetApi { } let localVarDeferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); - let requestOptions: request.Options = { method: 'POST', qs: queryParameters, headers: headerParams, uri: localVarPath, json: true, - } + }; this.authentications.petstore_auth.applyToRequest(requestOptions); @@ -539,7 +522,6 @@ export class PetApi { requestOptions.form = formParams; } } - request(requestOptions, (error, response, body) => { if (error) { localVarDeferred.reject(error); @@ -551,7 +533,6 @@ export class PetApi { } } }); - return localVarDeferred.promise; } /** @@ -586,14 +567,13 @@ export class PetApi { useFormData = true; let localVarDeferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); - let requestOptions: request.Options = { method: 'POST', qs: queryParameters, headers: headerParams, uri: localVarPath, json: true, - } + }; this.authentications.petstore_auth.applyToRequest(requestOptions); @@ -606,7 +586,6 @@ export class PetApi { requestOptions.form = formParams; } } - request(requestOptions, (error, response, body) => { if (error) { localVarDeferred.reject(error); @@ -618,7 +597,6 @@ export class PetApi { } } }); - return localVarDeferred.promise; } } @@ -627,7 +605,7 @@ export enum StoreApiApiKeys { } export class StoreApi { - protected basePath = 'http://petstore.swagger.io/v2'; + protected basePath = defaultBasePath; protected defaultHeaders : any = {}; protected authentications = { @@ -685,14 +663,13 @@ export class StoreApi { let useFormData = false; let localVarDeferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); - let requestOptions: request.Options = { method: 'DELETE', qs: queryParameters, headers: headerParams, uri: localVarPath, json: true, - } + }; this.authentications.default.applyToRequest(requestOptions); @@ -703,7 +680,6 @@ export class StoreApi { requestOptions.form = formParams; } } - request(requestOptions, (error, response, body) => { if (error) { localVarDeferred.reject(error); @@ -715,7 +691,6 @@ export class StoreApi { } } }); - return localVarDeferred.promise; } /** @@ -732,14 +707,13 @@ export class StoreApi { let useFormData = false; let localVarDeferred = promise.defer<{ response: http.ClientResponse; body: { [key: string]: number; }; }>(); - let requestOptions: request.Options = { method: 'GET', qs: queryParameters, headers: headerParams, uri: localVarPath, json: true, - } + }; this.authentications.api_key.applyToRequest(requestOptions); @@ -752,7 +726,6 @@ export class StoreApi { requestOptions.form = formParams; } } - request(requestOptions, (error, response, body) => { if (error) { localVarDeferred.reject(error); @@ -764,7 +737,6 @@ export class StoreApi { } } }); - return localVarDeferred.promise; } /** @@ -788,14 +760,13 @@ export class StoreApi { let useFormData = false; let localVarDeferred = promise.defer<{ response: http.ClientResponse; body: Order; }>(); - let requestOptions: request.Options = { method: 'GET', qs: queryParameters, headers: headerParams, uri: localVarPath, json: true, - } + }; this.authentications.default.applyToRequest(requestOptions); @@ -806,7 +777,6 @@ export class StoreApi { requestOptions.form = formParams; } } - request(requestOptions, (error, response, body) => { if (error) { localVarDeferred.reject(error); @@ -818,7 +788,6 @@ export class StoreApi { } } }); - return localVarDeferred.promise; } /** @@ -836,7 +805,6 @@ export class StoreApi { let useFormData = false; let localVarDeferred = promise.defer<{ response: http.ClientResponse; body: Order; }>(); - let requestOptions: request.Options = { method: 'POST', qs: queryParameters, @@ -844,7 +812,7 @@ export class StoreApi { uri: localVarPath, json: true, body: body, - } + }; this.authentications.default.applyToRequest(requestOptions); @@ -855,7 +823,6 @@ export class StoreApi { requestOptions.form = formParams; } } - request(requestOptions, (error, response, body) => { if (error) { localVarDeferred.reject(error); @@ -867,7 +834,6 @@ export class StoreApi { } } }); - return localVarDeferred.promise; } } @@ -876,7 +842,7 @@ export enum UserApiApiKeys { } export class UserApi { - protected basePath = 'http://petstore.swagger.io/v2'; + protected basePath = defaultBasePath; protected defaultHeaders : any = {}; protected authentications = { @@ -928,7 +894,6 @@ export class UserApi { let useFormData = false; let localVarDeferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); - let requestOptions: request.Options = { method: 'POST', qs: queryParameters, @@ -936,7 +901,7 @@ export class UserApi { uri: localVarPath, json: true, body: body, - } + }; this.authentications.default.applyToRequest(requestOptions); @@ -947,7 +912,6 @@ export class UserApi { requestOptions.form = formParams; } } - request(requestOptions, (error, response, body) => { if (error) { localVarDeferred.reject(error); @@ -959,7 +923,6 @@ export class UserApi { } } }); - return localVarDeferred.promise; } /** @@ -977,7 +940,6 @@ export class UserApi { let useFormData = false; let localVarDeferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); - let requestOptions: request.Options = { method: 'POST', qs: queryParameters, @@ -985,7 +947,7 @@ export class UserApi { uri: localVarPath, json: true, body: body, - } + }; this.authentications.default.applyToRequest(requestOptions); @@ -996,7 +958,6 @@ export class UserApi { requestOptions.form = formParams; } } - request(requestOptions, (error, response, body) => { if (error) { localVarDeferred.reject(error); @@ -1008,7 +969,6 @@ export class UserApi { } } }); - return localVarDeferred.promise; } /** @@ -1026,7 +986,6 @@ export class UserApi { let useFormData = false; let localVarDeferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); - let requestOptions: request.Options = { method: 'POST', qs: queryParameters, @@ -1034,7 +993,7 @@ export class UserApi { uri: localVarPath, json: true, body: body, - } + }; this.authentications.default.applyToRequest(requestOptions); @@ -1045,7 +1004,6 @@ export class UserApi { requestOptions.form = formParams; } } - request(requestOptions, (error, response, body) => { if (error) { localVarDeferred.reject(error); @@ -1057,7 +1015,6 @@ export class UserApi { } } }); - return localVarDeferred.promise; } /** @@ -1081,14 +1038,13 @@ export class UserApi { let useFormData = false; let localVarDeferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); - let requestOptions: request.Options = { method: 'DELETE', qs: queryParameters, headers: headerParams, uri: localVarPath, json: true, - } + }; this.authentications.default.applyToRequest(requestOptions); @@ -1099,7 +1055,6 @@ export class UserApi { requestOptions.form = formParams; } } - request(requestOptions, (error, response, body) => { if (error) { localVarDeferred.reject(error); @@ -1111,7 +1066,6 @@ export class UserApi { } } }); - return localVarDeferred.promise; } /** @@ -1135,14 +1089,13 @@ export class UserApi { let useFormData = false; let localVarDeferred = promise.defer<{ response: http.ClientResponse; body: User; }>(); - let requestOptions: request.Options = { method: 'GET', qs: queryParameters, headers: headerParams, uri: localVarPath, json: true, - } + }; this.authentications.default.applyToRequest(requestOptions); @@ -1153,7 +1106,6 @@ export class UserApi { requestOptions.form = formParams; } } - request(requestOptions, (error, response, body) => { if (error) { localVarDeferred.reject(error); @@ -1165,7 +1117,6 @@ export class UserApi { } } }); - return localVarDeferred.promise; } /** @@ -1192,14 +1143,13 @@ export class UserApi { let useFormData = false; let localVarDeferred = promise.defer<{ response: http.ClientResponse; body: string; }>(); - let requestOptions: request.Options = { method: 'GET', qs: queryParameters, headers: headerParams, uri: localVarPath, json: true, - } + }; this.authentications.default.applyToRequest(requestOptions); @@ -1210,7 +1160,6 @@ export class UserApi { requestOptions.form = formParams; } } - request(requestOptions, (error, response, body) => { if (error) { localVarDeferred.reject(error); @@ -1222,7 +1171,6 @@ export class UserApi { } } }); - return localVarDeferred.promise; } /** @@ -1239,14 +1187,13 @@ export class UserApi { let useFormData = false; let localVarDeferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); - let requestOptions: request.Options = { method: 'GET', qs: queryParameters, headers: headerParams, uri: localVarPath, json: true, - } + }; this.authentications.default.applyToRequest(requestOptions); @@ -1257,7 +1204,6 @@ export class UserApi { requestOptions.form = formParams; } } - request(requestOptions, (error, response, body) => { if (error) { localVarDeferred.reject(error); @@ -1269,7 +1215,6 @@ export class UserApi { } } }); - return localVarDeferred.promise; } /** @@ -1294,7 +1239,6 @@ export class UserApi { let useFormData = false; let localVarDeferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); - let requestOptions: request.Options = { method: 'PUT', qs: queryParameters, @@ -1302,7 +1246,7 @@ export class UserApi { uri: localVarPath, json: true, body: body, - } + }; this.authentications.default.applyToRequest(requestOptions); @@ -1313,7 +1257,6 @@ export class UserApi { requestOptions.form = formParams; } } - request(requestOptions, (error, response, body) => { if (error) { localVarDeferred.reject(error); @@ -1325,7 +1268,6 @@ export class UserApi { } } }); - return localVarDeferred.promise; } } diff --git a/samples/client/petstore/typescript-node/npm/api.d.ts b/samples/client/petstore/typescript-node/npm/api.d.ts new file mode 100644 index 00000000000..7a1a1ff8199 --- /dev/null +++ b/samples/client/petstore/typescript-node/npm/api.d.ts @@ -0,0 +1,204 @@ +import request = require('request'); +import http = require('http'); +export declare class Category { + 'id': number; + 'name': string; +} +export declare class Order { + 'id': number; + 'petId': number; + 'quantity': number; + 'shipDate': Date; + 'status': Order.StatusEnum; + 'complete': boolean; +} +export declare namespace Order { + enum StatusEnum { + StatusEnum_placed, + StatusEnum_approved, + StatusEnum_delivered, + } +} +export declare class Pet { + 'id': number; + 'category': Category; + 'name': string; + 'photoUrls': Array; + 'tags': Array; + 'status': Pet.StatusEnum; +} +export declare namespace Pet { + enum StatusEnum { + StatusEnum_available, + StatusEnum_pending, + StatusEnum_sold, + } +} +export declare class Tag { + 'id': number; + 'name': string; +} +export declare class User { + 'id': number; + 'username': string; + 'firstName': string; + 'lastName': string; + 'email': string; + 'password': string; + 'phone': string; + 'userStatus': number; +} +export interface Authentication { + applyToRequest(requestOptions: request.Options): void; +} +export declare class HttpBasicAuth implements Authentication { + username: string; + password: string; + applyToRequest(requestOptions: request.Options): void; +} +export declare class ApiKeyAuth implements Authentication { + private location; + private paramName; + apiKey: string; + constructor(location: string, paramName: string); + applyToRequest(requestOptions: request.Options): void; +} +export declare class OAuth implements Authentication { + accessToken: string; + applyToRequest(requestOptions: request.Options): void; +} +export declare class VoidAuth implements Authentication { + username: string; + password: string; + applyToRequest(requestOptions: request.Options): void; +} +export declare enum PetApiApiKeys { + api_key = 0, +} +export declare class PetApi { + protected basePath: string; + protected defaultHeaders: any; + protected authentications: { + 'default': Authentication; + 'api_key': ApiKeyAuth; + 'petstore_auth': OAuth; + }; + constructor(basePath?: string); + setApiKey(key: PetApiApiKeys, value: string): void; + accessToken: string; + private extendObj(objA, objB); + addPet(body?: Pet): Promise<{ + response: http.ClientResponse; + body?: any; + }>; + deletePet(petId: number, apiKey?: string): Promise<{ + response: http.ClientResponse; + body?: any; + }>; + findPetsByStatus(status?: Array): Promise<{ + response: http.ClientResponse; + body: Array; + }>; + findPetsByTags(tags?: Array): Promise<{ + response: http.ClientResponse; + body: Array; + }>; + getPetById(petId: number): Promise<{ + response: http.ClientResponse; + body: Pet; + }>; + updatePet(body?: Pet): Promise<{ + response: http.ClientResponse; + body?: any; + }>; + updatePetWithForm(petId: string, name?: string, status?: string): Promise<{ + response: http.ClientResponse; + body?: any; + }>; + uploadFile(petId: number, additionalMetadata?: string, file?: any): Promise<{ + response: http.ClientResponse; + body?: any; + }>; +} +export declare enum StoreApiApiKeys { + api_key = 0, +} +export declare class StoreApi { + protected basePath: string; + protected defaultHeaders: any; + protected authentications: { + 'default': Authentication; + 'api_key': ApiKeyAuth; + 'petstore_auth': OAuth; + }; + constructor(basePath?: string); + setApiKey(key: StoreApiApiKeys, value: string): void; + accessToken: string; + private extendObj(objA, objB); + deleteOrder(orderId: string): Promise<{ + response: http.ClientResponse; + body?: any; + }>; + getInventory(): Promise<{ + response: http.ClientResponse; + body: { + [key: string]: number; + }; + }>; + getOrderById(orderId: string): Promise<{ + response: http.ClientResponse; + body: Order; + }>; + placeOrder(body?: Order): Promise<{ + response: http.ClientResponse; + body: Order; + }>; +} +export declare enum UserApiApiKeys { + api_key = 0, +} +export declare class UserApi { + protected basePath: string; + protected defaultHeaders: any; + protected authentications: { + 'default': Authentication; + 'api_key': ApiKeyAuth; + 'petstore_auth': OAuth; + }; + constructor(basePath?: string); + setApiKey(key: UserApiApiKeys, value: string): void; + accessToken: string; + private extendObj(objA, objB); + createUser(body?: User): Promise<{ + response: http.ClientResponse; + body?: any; + }>; + createUsersWithArrayInput(body?: Array): Promise<{ + response: http.ClientResponse; + body?: any; + }>; + createUsersWithListInput(body?: Array): Promise<{ + response: http.ClientResponse; + body?: any; + }>; + deleteUser(username: string): Promise<{ + response: http.ClientResponse; + body?: any; + }>; + getUserByName(username: string): Promise<{ + response: http.ClientResponse; + body: User; + }>; + loginUser(username?: string, password?: string): Promise<{ + response: http.ClientResponse; + body: string; + }>; + logoutUser(): Promise<{ + response: http.ClientResponse; + body?: any; + }>; + updateUser(username: string, body?: User): Promise<{ + response: http.ClientResponse; + body?: any; + }>; +} diff --git a/samples/client/petstore/typescript-node/npm/api.js b/samples/client/petstore/typescript-node/npm/api.js new file mode 100644 index 00000000000..b8426c2b644 --- /dev/null +++ b/samples/client/petstore/typescript-node/npm/api.js @@ -0,0 +1,1070 @@ +var request = require('request'); +var promise = require('bluebird'); +var defaultBasePath = 'http://petstore.swagger.io/v2'; +var Category = (function () { + function Category() { + } + return Category; +})(); +exports.Category = Category; +var Order = (function () { + function Order() { + } + return Order; +})(); +exports.Order = Order; +var Order; +(function (Order) { + (function (StatusEnum) { + StatusEnum[StatusEnum["StatusEnum_placed"] = 'placed'] = "StatusEnum_placed"; + StatusEnum[StatusEnum["StatusEnum_approved"] = 'approved'] = "StatusEnum_approved"; + StatusEnum[StatusEnum["StatusEnum_delivered"] = 'delivered'] = "StatusEnum_delivered"; + })(Order.StatusEnum || (Order.StatusEnum = {})); + var StatusEnum = Order.StatusEnum; +})(Order = exports.Order || (exports.Order = {})); +var Pet = (function () { + function Pet() { + } + return Pet; +})(); +exports.Pet = Pet; +var Pet; +(function (Pet) { + (function (StatusEnum) { + StatusEnum[StatusEnum["StatusEnum_available"] = 'available'] = "StatusEnum_available"; + StatusEnum[StatusEnum["StatusEnum_pending"] = 'pending'] = "StatusEnum_pending"; + StatusEnum[StatusEnum["StatusEnum_sold"] = 'sold'] = "StatusEnum_sold"; + })(Pet.StatusEnum || (Pet.StatusEnum = {})); + var StatusEnum = Pet.StatusEnum; +})(Pet = exports.Pet || (exports.Pet = {})); +var Tag = (function () { + function Tag() { + } + return Tag; +})(); +exports.Tag = Tag; +var User = (function () { + function User() { + } + return User; +})(); +exports.User = User; +var HttpBasicAuth = (function () { + function HttpBasicAuth() { + } + HttpBasicAuth.prototype.applyToRequest = function (requestOptions) { + requestOptions.auth = { + username: this.username, password: this.password + }; + }; + return HttpBasicAuth; +})(); +exports.HttpBasicAuth = HttpBasicAuth; +var ApiKeyAuth = (function () { + function ApiKeyAuth(location, paramName) { + this.location = location; + this.paramName = paramName; + } + ApiKeyAuth.prototype.applyToRequest = function (requestOptions) { + if (this.location == "query") { + requestOptions.qs[this.paramName] = this.apiKey; + } + else if (this.location == "header") { + requestOptions.headers[this.paramName] = this.apiKey; + } + }; + return ApiKeyAuth; +})(); +exports.ApiKeyAuth = ApiKeyAuth; +var OAuth = (function () { + function OAuth() { + } + OAuth.prototype.applyToRequest = function (requestOptions) { + requestOptions.headers["Authorization"] = "Bearer " + this.accessToken; + }; + return OAuth; +})(); +exports.OAuth = OAuth; +var VoidAuth = (function () { + function VoidAuth() { + } + VoidAuth.prototype.applyToRequest = function (requestOptions) { + }; + return VoidAuth; +})(); +exports.VoidAuth = VoidAuth; +(function (PetApiApiKeys) { + PetApiApiKeys[PetApiApiKeys["api_key"] = 0] = "api_key"; +})(exports.PetApiApiKeys || (exports.PetApiApiKeys = {})); +var PetApiApiKeys = exports.PetApiApiKeys; +var PetApi = (function () { + function PetApi(basePathOrUsername, password, basePath) { + this.basePath = defaultBasePath; + this.defaultHeaders = {}; + this.authentications = { + 'default': new VoidAuth(), + 'api_key': new ApiKeyAuth('header', 'api_key'), + 'petstore_auth': new OAuth(), + }; + if (password) { + if (basePath) { + this.basePath = basePath; + } + } + else { + if (basePathOrUsername) { + this.basePath = basePathOrUsername; + } + } + } + PetApi.prototype.setApiKey = function (key, value) { + this.authentications[PetApiApiKeys[key]].apiKey = value; + }; + Object.defineProperty(PetApi.prototype, "accessToken", { + set: function (token) { + this.authentications.petstore_auth.accessToken = token; + }, + enumerable: true, + configurable: true + }); + PetApi.prototype.extendObj = function (objA, objB) { + for (var key in objB) { + if (objB.hasOwnProperty(key)) { + objA[key] = objB[key]; + } + } + return objA; + }; + PetApi.prototype.addPet = function (body) { + var localVarPath = this.basePath + '/pet'; + var queryParameters = {}; + var headerParams = this.extendObj({}, this.defaultHeaders); + var formParams = {}; + var useFormData = false; + var localVarDeferred = promise.defer(); + var requestOptions = { + method: 'POST', + qs: queryParameters, + headers: headerParams, + uri: localVarPath, + json: true, + body: body, + }; + this.authentications.petstore_auth.applyToRequest(requestOptions); + this.authentications.default.applyToRequest(requestOptions); + if (Object.keys(formParams).length) { + if (useFormData) { + requestOptions.formData = formParams; + } + else { + requestOptions.form = formParams; + } + } + request(requestOptions, function (error, response, body) { + if (error) { + localVarDeferred.reject(error); + } + else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + localVarDeferred.resolve({ response: response, body: body }); + } + else { + localVarDeferred.reject({ response: response, body: body }); + } + } + }); + return localVarDeferred.promise; + }; + PetApi.prototype.deletePet = function (petId, apiKey) { + var localVarPath = this.basePath + '/pet/{petId}' + .replace('{' + 'petId' + '}', String(petId)); + var queryParameters = {}; + var headerParams = this.extendObj({}, this.defaultHeaders); + var formParams = {}; + if (petId === null || petId === undefined) { + throw new Error('Required parameter petId was null or undefined when calling deletePet.'); + } + headerParams['api_key'] = apiKey; + var useFormData = false; + var localVarDeferred = promise.defer(); + var requestOptions = { + method: 'DELETE', + qs: queryParameters, + headers: headerParams, + uri: localVarPath, + json: true, + }; + this.authentications.petstore_auth.applyToRequest(requestOptions); + this.authentications.default.applyToRequest(requestOptions); + if (Object.keys(formParams).length) { + if (useFormData) { + requestOptions.formData = formParams; + } + else { + requestOptions.form = formParams; + } + } + request(requestOptions, function (error, response, body) { + if (error) { + localVarDeferred.reject(error); + } + else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + localVarDeferred.resolve({ response: response, body: body }); + } + else { + localVarDeferred.reject({ response: response, body: body }); + } + } + }); + return localVarDeferred.promise; + }; + PetApi.prototype.findPetsByStatus = function (status) { + var localVarPath = this.basePath + '/pet/findByStatus'; + var queryParameters = {}; + var headerParams = this.extendObj({}, this.defaultHeaders); + var formParams = {}; + if (status !== undefined) { + queryParameters['status'] = status; + } + var useFormData = false; + var localVarDeferred = promise.defer(); + var requestOptions = { + method: 'GET', + qs: queryParameters, + headers: headerParams, + uri: localVarPath, + json: true, + }; + this.authentications.petstore_auth.applyToRequest(requestOptions); + this.authentications.default.applyToRequest(requestOptions); + if (Object.keys(formParams).length) { + if (useFormData) { + requestOptions.formData = formParams; + } + else { + requestOptions.form = formParams; + } + } + request(requestOptions, function (error, response, body) { + if (error) { + localVarDeferred.reject(error); + } + else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + localVarDeferred.resolve({ response: response, body: body }); + } + else { + localVarDeferred.reject({ response: response, body: body }); + } + } + }); + return localVarDeferred.promise; + }; + PetApi.prototype.findPetsByTags = function (tags) { + var localVarPath = this.basePath + '/pet/findByTags'; + var queryParameters = {}; + var headerParams = this.extendObj({}, this.defaultHeaders); + var formParams = {}; + if (tags !== undefined) { + queryParameters['tags'] = tags; + } + var useFormData = false; + var localVarDeferred = promise.defer(); + var requestOptions = { + method: 'GET', + qs: queryParameters, + headers: headerParams, + uri: localVarPath, + json: true, + }; + this.authentications.petstore_auth.applyToRequest(requestOptions); + this.authentications.default.applyToRequest(requestOptions); + if (Object.keys(formParams).length) { + if (useFormData) { + requestOptions.formData = formParams; + } + else { + requestOptions.form = formParams; + } + } + request(requestOptions, function (error, response, body) { + if (error) { + localVarDeferred.reject(error); + } + else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + localVarDeferred.resolve({ response: response, body: body }); + } + else { + localVarDeferred.reject({ response: response, body: body }); + } + } + }); + return localVarDeferred.promise; + }; + PetApi.prototype.getPetById = function (petId) { + var localVarPath = this.basePath + '/pet/{petId}' + .replace('{' + 'petId' + '}', String(petId)); + var queryParameters = {}; + var headerParams = this.extendObj({}, this.defaultHeaders); + var formParams = {}; + if (petId === null || petId === undefined) { + throw new Error('Required parameter petId was null or undefined when calling getPetById.'); + } + var useFormData = false; + var localVarDeferred = promise.defer(); + var requestOptions = { + method: 'GET', + qs: queryParameters, + headers: headerParams, + uri: localVarPath, + json: true, + }; + this.authentications.api_key.applyToRequest(requestOptions); + this.authentications.petstore_auth.applyToRequest(requestOptions); + this.authentications.default.applyToRequest(requestOptions); + if (Object.keys(formParams).length) { + if (useFormData) { + requestOptions.formData = formParams; + } + else { + requestOptions.form = formParams; + } + } + request(requestOptions, function (error, response, body) { + if (error) { + localVarDeferred.reject(error); + } + else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + localVarDeferred.resolve({ response: response, body: body }); + } + else { + localVarDeferred.reject({ response: response, body: body }); + } + } + }); + return localVarDeferred.promise; + }; + PetApi.prototype.updatePet = function (body) { + var localVarPath = this.basePath + '/pet'; + var queryParameters = {}; + var headerParams = this.extendObj({}, this.defaultHeaders); + var formParams = {}; + var useFormData = false; + var localVarDeferred = promise.defer(); + var requestOptions = { + method: 'PUT', + qs: queryParameters, + headers: headerParams, + uri: localVarPath, + json: true, + body: body, + }; + this.authentications.petstore_auth.applyToRequest(requestOptions); + this.authentications.default.applyToRequest(requestOptions); + if (Object.keys(formParams).length) { + if (useFormData) { + requestOptions.formData = formParams; + } + else { + requestOptions.form = formParams; + } + } + request(requestOptions, function (error, response, body) { + if (error) { + localVarDeferred.reject(error); + } + else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + localVarDeferred.resolve({ response: response, body: body }); + } + else { + localVarDeferred.reject({ response: response, body: body }); + } + } + }); + return localVarDeferred.promise; + }; + PetApi.prototype.updatePetWithForm = function (petId, name, status) { + var localVarPath = this.basePath + '/pet/{petId}' + .replace('{' + 'petId' + '}', String(petId)); + var queryParameters = {}; + var headerParams = this.extendObj({}, this.defaultHeaders); + var formParams = {}; + if (petId === null || petId === undefined) { + throw new Error('Required parameter petId was null or undefined when calling updatePetWithForm.'); + } + var useFormData = false; + if (name !== undefined) { + formParams['name'] = name; + } + if (status !== undefined) { + formParams['status'] = status; + } + var localVarDeferred = promise.defer(); + var requestOptions = { + method: 'POST', + qs: queryParameters, + headers: headerParams, + uri: localVarPath, + json: true, + }; + this.authentications.petstore_auth.applyToRequest(requestOptions); + this.authentications.default.applyToRequest(requestOptions); + if (Object.keys(formParams).length) { + if (useFormData) { + requestOptions.formData = formParams; + } + else { + requestOptions.form = formParams; + } + } + request(requestOptions, function (error, response, body) { + if (error) { + localVarDeferred.reject(error); + } + else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + localVarDeferred.resolve({ response: response, body: body }); + } + else { + localVarDeferred.reject({ response: response, body: body }); + } + } + }); + return localVarDeferred.promise; + }; + PetApi.prototype.uploadFile = function (petId, additionalMetadata, file) { + var localVarPath = this.basePath + '/pet/{petId}/uploadImage' + .replace('{' + 'petId' + '}', String(petId)); + var queryParameters = {}; + var headerParams = this.extendObj({}, this.defaultHeaders); + var formParams = {}; + if (petId === null || petId === undefined) { + throw new Error('Required parameter petId was null or undefined when calling uploadFile.'); + } + var useFormData = false; + if (additionalMetadata !== undefined) { + formParams['additionalMetadata'] = additionalMetadata; + } + if (file !== undefined) { + formParams['file'] = file; + } + useFormData = true; + var localVarDeferred = promise.defer(); + var requestOptions = { + method: 'POST', + qs: queryParameters, + headers: headerParams, + uri: localVarPath, + json: true, + }; + this.authentications.petstore_auth.applyToRequest(requestOptions); + this.authentications.default.applyToRequest(requestOptions); + if (Object.keys(formParams).length) { + if (useFormData) { + requestOptions.formData = formParams; + } + else { + requestOptions.form = formParams; + } + } + request(requestOptions, function (error, response, body) { + if (error) { + localVarDeferred.reject(error); + } + else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + localVarDeferred.resolve({ response: response, body: body }); + } + else { + localVarDeferred.reject({ response: response, body: body }); + } + } + }); + return localVarDeferred.promise; + }; + return PetApi; +})(); +exports.PetApi = PetApi; +(function (StoreApiApiKeys) { + StoreApiApiKeys[StoreApiApiKeys["api_key"] = 0] = "api_key"; +})(exports.StoreApiApiKeys || (exports.StoreApiApiKeys = {})); +var StoreApiApiKeys = exports.StoreApiApiKeys; +var StoreApi = (function () { + function StoreApi(basePathOrUsername, password, basePath) { + this.basePath = defaultBasePath; + this.defaultHeaders = {}; + this.authentications = { + 'default': new VoidAuth(), + 'api_key': new ApiKeyAuth('header', 'api_key'), + 'petstore_auth': new OAuth(), + }; + if (password) { + if (basePath) { + this.basePath = basePath; + } + } + else { + if (basePathOrUsername) { + this.basePath = basePathOrUsername; + } + } + } + StoreApi.prototype.setApiKey = function (key, value) { + this.authentications[StoreApiApiKeys[key]].apiKey = value; + }; + Object.defineProperty(StoreApi.prototype, "accessToken", { + set: function (token) { + this.authentications.petstore_auth.accessToken = token; + }, + enumerable: true, + configurable: true + }); + StoreApi.prototype.extendObj = function (objA, objB) { + for (var key in objB) { + if (objB.hasOwnProperty(key)) { + objA[key] = objB[key]; + } + } + return objA; + }; + StoreApi.prototype.deleteOrder = function (orderId) { + var localVarPath = this.basePath + '/store/order/{orderId}' + .replace('{' + 'orderId' + '}', String(orderId)); + var queryParameters = {}; + var headerParams = this.extendObj({}, this.defaultHeaders); + var formParams = {}; + if (orderId === null || orderId === undefined) { + throw new Error('Required parameter orderId was null or undefined when calling deleteOrder.'); + } + var useFormData = false; + var localVarDeferred = promise.defer(); + var requestOptions = { + method: 'DELETE', + qs: queryParameters, + headers: headerParams, + uri: localVarPath, + json: true, + }; + this.authentications.default.applyToRequest(requestOptions); + if (Object.keys(formParams).length) { + if (useFormData) { + requestOptions.formData = formParams; + } + else { + requestOptions.form = formParams; + } + } + request(requestOptions, function (error, response, body) { + if (error) { + localVarDeferred.reject(error); + } + else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + localVarDeferred.resolve({ response: response, body: body }); + } + else { + localVarDeferred.reject({ response: response, body: body }); + } + } + }); + return localVarDeferred.promise; + }; + StoreApi.prototype.getInventory = function () { + var localVarPath = this.basePath + '/store/inventory'; + var queryParameters = {}; + var headerParams = this.extendObj({}, this.defaultHeaders); + var formParams = {}; + var useFormData = false; + var localVarDeferred = promise.defer(); + var requestOptions = { + method: 'GET', + qs: queryParameters, + headers: headerParams, + uri: localVarPath, + json: true, + }; + this.authentications.api_key.applyToRequest(requestOptions); + this.authentications.default.applyToRequest(requestOptions); + if (Object.keys(formParams).length) { + if (useFormData) { + requestOptions.formData = formParams; + } + else { + requestOptions.form = formParams; + } + } + request(requestOptions, function (error, response, body) { + if (error) { + localVarDeferred.reject(error); + } + else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + localVarDeferred.resolve({ response: response, body: body }); + } + else { + localVarDeferred.reject({ response: response, body: body }); + } + } + }); + return localVarDeferred.promise; + }; + StoreApi.prototype.getOrderById = function (orderId) { + var localVarPath = this.basePath + '/store/order/{orderId}' + .replace('{' + 'orderId' + '}', String(orderId)); + var queryParameters = {}; + var headerParams = this.extendObj({}, this.defaultHeaders); + var formParams = {}; + if (orderId === null || orderId === undefined) { + throw new Error('Required parameter orderId was null or undefined when calling getOrderById.'); + } + var useFormData = false; + var localVarDeferred = promise.defer(); + var requestOptions = { + method: 'GET', + qs: queryParameters, + headers: headerParams, + uri: localVarPath, + json: true, + }; + this.authentications.default.applyToRequest(requestOptions); + if (Object.keys(formParams).length) { + if (useFormData) { + requestOptions.formData = formParams; + } + else { + requestOptions.form = formParams; + } + } + request(requestOptions, function (error, response, body) { + if (error) { + localVarDeferred.reject(error); + } + else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + localVarDeferred.resolve({ response: response, body: body }); + } + else { + localVarDeferred.reject({ response: response, body: body }); + } + } + }); + return localVarDeferred.promise; + }; + StoreApi.prototype.placeOrder = function (body) { + var localVarPath = this.basePath + '/store/order'; + var queryParameters = {}; + var headerParams = this.extendObj({}, this.defaultHeaders); + var formParams = {}; + var useFormData = false; + var localVarDeferred = promise.defer(); + var requestOptions = { + method: 'POST', + qs: queryParameters, + headers: headerParams, + uri: localVarPath, + json: true, + body: body, + }; + this.authentications.default.applyToRequest(requestOptions); + if (Object.keys(formParams).length) { + if (useFormData) { + requestOptions.formData = formParams; + } + else { + requestOptions.form = formParams; + } + } + request(requestOptions, function (error, response, body) { + if (error) { + localVarDeferred.reject(error); + } + else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + localVarDeferred.resolve({ response: response, body: body }); + } + else { + localVarDeferred.reject({ response: response, body: body }); + } + } + }); + return localVarDeferred.promise; + }; + return StoreApi; +})(); +exports.StoreApi = StoreApi; +(function (UserApiApiKeys) { + UserApiApiKeys[UserApiApiKeys["api_key"] = 0] = "api_key"; +})(exports.UserApiApiKeys || (exports.UserApiApiKeys = {})); +var UserApiApiKeys = exports.UserApiApiKeys; +var UserApi = (function () { + function UserApi(basePathOrUsername, password, basePath) { + this.basePath = defaultBasePath; + this.defaultHeaders = {}; + this.authentications = { + 'default': new VoidAuth(), + 'api_key': new ApiKeyAuth('header', 'api_key'), + 'petstore_auth': new OAuth(), + }; + if (password) { + if (basePath) { + this.basePath = basePath; + } + } + else { + if (basePathOrUsername) { + this.basePath = basePathOrUsername; + } + } + } + UserApi.prototype.setApiKey = function (key, value) { + this.authentications[UserApiApiKeys[key]].apiKey = value; + }; + Object.defineProperty(UserApi.prototype, "accessToken", { + set: function (token) { + this.authentications.petstore_auth.accessToken = token; + }, + enumerable: true, + configurable: true + }); + UserApi.prototype.extendObj = function (objA, objB) { + for (var key in objB) { + if (objB.hasOwnProperty(key)) { + objA[key] = objB[key]; + } + } + return objA; + }; + UserApi.prototype.createUser = function (body) { + var localVarPath = this.basePath + '/user'; + var queryParameters = {}; + var headerParams = this.extendObj({}, this.defaultHeaders); + var formParams = {}; + var useFormData = false; + var localVarDeferred = promise.defer(); + var requestOptions = { + method: 'POST', + qs: queryParameters, + headers: headerParams, + uri: localVarPath, + json: true, + body: body, + }; + this.authentications.default.applyToRequest(requestOptions); + if (Object.keys(formParams).length) { + if (useFormData) { + requestOptions.formData = formParams; + } + else { + requestOptions.form = formParams; + } + } + request(requestOptions, function (error, response, body) { + if (error) { + localVarDeferred.reject(error); + } + else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + localVarDeferred.resolve({ response: response, body: body }); + } + else { + localVarDeferred.reject({ response: response, body: body }); + } + } + }); + return localVarDeferred.promise; + }; + UserApi.prototype.createUsersWithArrayInput = function (body) { + var localVarPath = this.basePath + '/user/createWithArray'; + var queryParameters = {}; + var headerParams = this.extendObj({}, this.defaultHeaders); + var formParams = {}; + var useFormData = false; + var localVarDeferred = promise.defer(); + var requestOptions = { + method: 'POST', + qs: queryParameters, + headers: headerParams, + uri: localVarPath, + json: true, + body: body, + }; + this.authentications.default.applyToRequest(requestOptions); + if (Object.keys(formParams).length) { + if (useFormData) { + requestOptions.formData = formParams; + } + else { + requestOptions.form = formParams; + } + } + request(requestOptions, function (error, response, body) { + if (error) { + localVarDeferred.reject(error); + } + else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + localVarDeferred.resolve({ response: response, body: body }); + } + else { + localVarDeferred.reject({ response: response, body: body }); + } + } + }); + return localVarDeferred.promise; + }; + UserApi.prototype.createUsersWithListInput = function (body) { + var localVarPath = this.basePath + '/user/createWithList'; + var queryParameters = {}; + var headerParams = this.extendObj({}, this.defaultHeaders); + var formParams = {}; + var useFormData = false; + var localVarDeferred = promise.defer(); + var requestOptions = { + method: 'POST', + qs: queryParameters, + headers: headerParams, + uri: localVarPath, + json: true, + body: body, + }; + this.authentications.default.applyToRequest(requestOptions); + if (Object.keys(formParams).length) { + if (useFormData) { + requestOptions.formData = formParams; + } + else { + requestOptions.form = formParams; + } + } + request(requestOptions, function (error, response, body) { + if (error) { + localVarDeferred.reject(error); + } + else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + localVarDeferred.resolve({ response: response, body: body }); + } + else { + localVarDeferred.reject({ response: response, body: body }); + } + } + }); + return localVarDeferred.promise; + }; + UserApi.prototype.deleteUser = function (username) { + var localVarPath = this.basePath + '/user/{username}' + .replace('{' + 'username' + '}', String(username)); + var queryParameters = {}; + var headerParams = this.extendObj({}, this.defaultHeaders); + var formParams = {}; + if (username === null || username === undefined) { + throw new Error('Required parameter username was null or undefined when calling deleteUser.'); + } + var useFormData = false; + var localVarDeferred = promise.defer(); + var requestOptions = { + method: 'DELETE', + qs: queryParameters, + headers: headerParams, + uri: localVarPath, + json: true, + }; + this.authentications.default.applyToRequest(requestOptions); + if (Object.keys(formParams).length) { + if (useFormData) { + requestOptions.formData = formParams; + } + else { + requestOptions.form = formParams; + } + } + request(requestOptions, function (error, response, body) { + if (error) { + localVarDeferred.reject(error); + } + else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + localVarDeferred.resolve({ response: response, body: body }); + } + else { + localVarDeferred.reject({ response: response, body: body }); + } + } + }); + return localVarDeferred.promise; + }; + UserApi.prototype.getUserByName = function (username) { + var localVarPath = this.basePath + '/user/{username}' + .replace('{' + 'username' + '}', String(username)); + var queryParameters = {}; + var headerParams = this.extendObj({}, this.defaultHeaders); + var formParams = {}; + if (username === null || username === undefined) { + throw new Error('Required parameter username was null or undefined when calling getUserByName.'); + } + var useFormData = false; + var localVarDeferred = promise.defer(); + var requestOptions = { + method: 'GET', + qs: queryParameters, + headers: headerParams, + uri: localVarPath, + json: true, + }; + this.authentications.default.applyToRequest(requestOptions); + if (Object.keys(formParams).length) { + if (useFormData) { + requestOptions.formData = formParams; + } + else { + requestOptions.form = formParams; + } + } + request(requestOptions, function (error, response, body) { + if (error) { + localVarDeferred.reject(error); + } + else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + localVarDeferred.resolve({ response: response, body: body }); + } + else { + localVarDeferred.reject({ response: response, body: body }); + } + } + }); + return localVarDeferred.promise; + }; + UserApi.prototype.loginUser = function (username, password) { + var localVarPath = this.basePath + '/user/login'; + var queryParameters = {}; + var headerParams = this.extendObj({}, this.defaultHeaders); + var formParams = {}; + if (username !== undefined) { + queryParameters['username'] = username; + } + if (password !== undefined) { + queryParameters['password'] = password; + } + var useFormData = false; + var localVarDeferred = promise.defer(); + var requestOptions = { + method: 'GET', + qs: queryParameters, + headers: headerParams, + uri: localVarPath, + json: true, + }; + this.authentications.default.applyToRequest(requestOptions); + if (Object.keys(formParams).length) { + if (useFormData) { + requestOptions.formData = formParams; + } + else { + requestOptions.form = formParams; + } + } + request(requestOptions, function (error, response, body) { + if (error) { + localVarDeferred.reject(error); + } + else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + localVarDeferred.resolve({ response: response, body: body }); + } + else { + localVarDeferred.reject({ response: response, body: body }); + } + } + }); + return localVarDeferred.promise; + }; + UserApi.prototype.logoutUser = function () { + var localVarPath = this.basePath + '/user/logout'; + var queryParameters = {}; + var headerParams = this.extendObj({}, this.defaultHeaders); + var formParams = {}; + var useFormData = false; + var localVarDeferred = promise.defer(); + var requestOptions = { + method: 'GET', + qs: queryParameters, + headers: headerParams, + uri: localVarPath, + json: true, + }; + this.authentications.default.applyToRequest(requestOptions); + if (Object.keys(formParams).length) { + if (useFormData) { + requestOptions.formData = formParams; + } + else { + requestOptions.form = formParams; + } + } + request(requestOptions, function (error, response, body) { + if (error) { + localVarDeferred.reject(error); + } + else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + localVarDeferred.resolve({ response: response, body: body }); + } + else { + localVarDeferred.reject({ response: response, body: body }); + } + } + }); + return localVarDeferred.promise; + }; + UserApi.prototype.updateUser = function (username, body) { + var localVarPath = this.basePath + '/user/{username}' + .replace('{' + 'username' + '}', String(username)); + var queryParameters = {}; + var headerParams = this.extendObj({}, this.defaultHeaders); + var formParams = {}; + if (username === null || username === undefined) { + throw new Error('Required parameter username was null or undefined when calling updateUser.'); + } + var useFormData = false; + var localVarDeferred = promise.defer(); + var requestOptions = { + method: 'PUT', + qs: queryParameters, + headers: headerParams, + uri: localVarPath, + json: true, + body: body, + }; + this.authentications.default.applyToRequest(requestOptions); + if (Object.keys(formParams).length) { + if (useFormData) { + requestOptions.formData = formParams; + } + else { + requestOptions.form = formParams; + } + } + request(requestOptions, function (error, response, body) { + if (error) { + localVarDeferred.reject(error); + } + else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + localVarDeferred.resolve({ response: response, body: body }); + } + else { + localVarDeferred.reject({ response: response, body: body }); + } + } + }); + return localVarDeferred.promise; + }; + return UserApi; +})(); +exports.UserApi = UserApi; +//# sourceMappingURL=api.js.map \ No newline at end of file diff --git a/samples/client/petstore/typescript-node/npm/api.js.map b/samples/client/petstore/typescript-node/npm/api.js.map new file mode 100644 index 00000000000..850f5471489 --- /dev/null +++ b/samples/client/petstore/typescript-node/npm/api.js.map @@ -0,0 +1 @@ +{"version":3,"file":"api.js","sourceRoot":"","sources":["api.ts"],"names":["Category","Category.constructor","Order","Order.constructor","Order.StatusEnum","Pet","Pet.constructor","Pet.StatusEnum","Tag","Tag.constructor","User","User.constructor","HttpBasicAuth","HttpBasicAuth.constructor","HttpBasicAuth.applyToRequest","ApiKeyAuth","ApiKeyAuth.constructor","ApiKeyAuth.applyToRequest","OAuth","OAuth.constructor","OAuth.applyToRequest","VoidAuth","VoidAuth.constructor","VoidAuth.applyToRequest","PetApiApiKeys","PetApi","PetApi.constructor","PetApi.setApiKey","PetApi.accessToken","PetApi.extendObj","PetApi.addPet","PetApi.deletePet","PetApi.findPetsByStatus","PetApi.findPetsByTags","PetApi.getPetById","PetApi.updatePet","PetApi.updatePetWithForm","PetApi.uploadFile","StoreApiApiKeys","StoreApi","StoreApi.constructor","StoreApi.setApiKey","StoreApi.accessToken","StoreApi.extendObj","StoreApi.deleteOrder","StoreApi.getInventory","StoreApi.getOrderById","StoreApi.placeOrder","UserApiApiKeys","UserApi","UserApi.constructor","UserApi.setApiKey","UserApi.accessToken","UserApi.extendObj","UserApi.createUser","UserApi.createUsersWithArrayInput","UserApi.createUsersWithListInput","UserApi.deleteUser","UserApi.getUserByName","UserApi.loginUser","UserApi.logoutUser","UserApi.updateUser"],"mappings":"AAAA,IAAO,OAAO,WAAW,SAAS,CAAC,CAAC;AAEpC,IAAO,OAAO,WAAW,UAAU,CAAC,CAAC;AAErC,IAAI,eAAe,GAAG,+BAA+B,CAAC;AAQtD;IAAAA;IAGAC,CAACA;IAADD,eAACA;AAADA,CAACA,AAHD,IAGC;AAHY,gBAAQ,WAGpB,CAAA;AAED;IAAAE;IAUAC,CAACA;IAADD,YAACA;AAADA,CAACA,AAVD,IAUC;AAVY,aAAK,QAUjB,CAAA;AAED,IAAiB,KAAK,CAMrB;AAND,WAAiB,KAAK,EAAC,CAAC;IACpBA,WAAYA,UAAUA;QAClBE,6CAA0BA,QAAQA,uBAAAA,CAAAA;QAClCA,+CAA4BA,UAAUA,yBAAAA,CAAAA;QACtCA,gDAA6BA,WAAWA,0BAAAA,CAAAA;IAC5CA,CAACA,EAJWF,gBAAUA,KAAVA,gBAAUA,QAIrBA;IAJDA,IAAYA,UAAUA,GAAVA,gBAIXA,CAAAA;AACLA,CAACA,EANgB,KAAK,GAAL,aAAK,KAAL,aAAK,QAMrB;AACD;IAAAG;IAUAC,CAACA;IAADD,UAACA;AAADA,CAACA,AAVD,IAUC;AAVY,WAAG,MAUf,CAAA;AAED,IAAiB,GAAG,CAMnB;AAND,WAAiB,GAAG,EAAC,CAAC;IAClBA,WAAYA,UAAUA;QAClBE,gDAA6BA,WAAWA,0BAAAA,CAAAA;QACxCA,8CAA2BA,SAASA,wBAAAA,CAAAA;QACpCA,2CAAwBA,MAAMA,qBAAAA,CAAAA;IAClCA,CAACA,EAJWF,cAAUA,KAAVA,cAAUA,QAIrBA;IAJDA,IAAYA,UAAUA,GAAVA,cAIXA,CAAAA;AACLA,CAACA,EANgB,GAAG,GAAH,WAAG,KAAH,WAAG,QAMnB;AACD;IAAAG;IAGAC,CAACA;IAADD,UAACA;AAADA,CAACA,AAHD,IAGC;AAHY,WAAG,MAGf,CAAA;AAED;IAAAE;IAYAC,CAACA;IAADD,WAACA;AAADA,CAACA,AAZD,IAYC;AAZY,YAAI,OAYhB,CAAA;AAUD;IAAAE;IAQAC,CAACA;IALGD,sCAAcA,GAAdA,UAAeA,cAA+BA;QAC1CE,cAAcA,CAACA,IAAIA,GAAGA;YAClBA,QAAQA,EAAEA,IAAIA,CAACA,QAAQA,EAAEA,QAAQA,EAAEA,IAAIA,CAACA,QAAQA;SACnDA,CAAAA;IACLA,CAACA;IACLF,oBAACA;AAADA,CAACA,AARD,IAQC;AARY,qBAAa,gBAQzB,CAAA;AAED;IAGIG,oBAAoBA,QAAgBA,EAAUA,SAAiBA;QAA3CC,aAAQA,GAARA,QAAQA,CAAQA;QAAUA,cAASA,GAATA,SAASA,CAAQA;IAC/DA,CAACA;IAEDD,mCAAcA,GAAdA,UAAeA,cAA+BA;QAC1CE,EAAEA,CAACA,CAACA,IAAIA,CAACA,QAAQA,IAAIA,OAAOA,CAACA,CAACA,CAACA;YACrBA,cAAcA,CAACA,EAAGA,CAACA,IAAIA,CAACA,SAASA,CAACA,GAAGA,IAAIA,CAACA,MAAMA,CAACA;QAC3DA,CAACA;QAACA,IAAIA,CAACA,EAAEA,CAACA,CAACA,IAAIA,CAACA,QAAQA,IAAIA,QAAQA,CAACA,CAACA,CAACA;YACnCA,cAAcA,CAACA,OAAOA,CAACA,IAAIA,CAACA,SAASA,CAACA,GAAGA,IAAIA,CAACA,MAAMA,CAACA;QACzDA,CAACA;IACLA,CAACA;IACLF,iBAACA;AAADA,CAACA,AAbD,IAaC;AAbY,kBAAU,aAatB,CAAA;AAED;IAAAG;IAMAC,CAACA;IAHGD,8BAAcA,GAAdA,UAAeA,cAA+BA;QAC1CE,cAAcA,CAACA,OAAOA,CAACA,eAAeA,CAACA,GAAGA,SAASA,GAAGA,IAAIA,CAACA,WAAWA,CAACA;IAC3EA,CAACA;IACLF,YAACA;AAADA,CAACA,AAND,IAMC;AANY,aAAK,QAMjB,CAAA;AAED;IAAAG;IAMAC,CAACA;IAHGD,iCAAcA,GAAdA,UAAeA,cAA+BA;IAE9CE,CAACA;IACLF,eAACA;AAADA,CAACA,AAND,IAMC;AANY,gBAAQ,WAMpB,CAAA;AAED,WAAY,aAAa;IACrBG,uDAAOA,CAAAA;AACXA,CAACA,EAFW,qBAAa,KAAb,qBAAa,QAExB;AAFD,IAAY,aAAa,GAAb,qBAEX,CAAA;AAED;IAWIC,gBAAYA,kBAA0BA,EAAEA,QAAiBA,EAAEA,QAAiBA;QAVlEC,aAAQA,GAAGA,eAAeA,CAACA;QAC3BA,mBAAcA,GAASA,EAAEA,CAACA;QAE1BA,oBAAeA,GAAGA;YACxBA,SAASA,EAAkBA,IAAIA,QAAQA,EAAEA;YACzCA,SAASA,EAAEA,IAAIA,UAAUA,CAACA,QAAQA,EAAEA,SAASA,CAACA;YAC9CA,eAAeA,EAAEA,IAAIA,KAAKA,EAAEA;SAC/BA,CAAAA;QAIGA,EAAEA,CAACA,CAACA,QAAQA,CAACA,CAACA,CAACA;YACXA,EAAEA,CAACA,CAACA,QAAQA,CAACA,CAACA,CAACA;gBACXA,IAAIA,CAACA,QAAQA,GAAGA,QAAQA,CAACA;YAC7BA,CAACA;QACLA,CAACA;QAACA,IAAIA,CAACA,CAACA;YACJA,EAAEA,CAACA,CAACA,kBAAkBA,CAACA,CAACA,CAACA;gBACrBA,IAAIA,CAACA,QAAQA,GAAGA,kBAAkBA,CAAAA;YACtCA,CAACA;QACLA,CAACA;IACLA,CAACA;IAEMD,0BAASA,GAAhBA,UAAiBA,GAAkBA,EAAEA,KAAaA;QAC9CE,IAAIA,CAACA,eAAeA,CAACA,aAAaA,CAACA,GAAGA,CAACA,CAACA,CAACA,MAAMA,GAAGA,KAAKA,CAACA;IAC5DA,CAACA;IAEDF,sBAAIA,+BAAWA;aAAfA,UAAgBA,KAAaA;YACzBG,IAAIA,CAACA,eAAeA,CAACA,aAAaA,CAACA,WAAWA,GAAGA,KAAKA,CAACA;QAC3DA,CAACA;;;OAAAH;IACOA,0BAASA,GAAjBA,UAAyBA,IAAQA,EAAEA,IAAQA;QACvCI,GAAGA,CAAAA,CAACA,GAAGA,CAACA,GAAGA,IAAIA,IAAIA,CAACA,CAAAA,CAACA;YACjBA,EAAEA,CAAAA,CAACA,IAAIA,CAACA,cAAcA,CAACA,GAAGA,CAACA,CAACA,CAAAA,CAACA;gBACzBA,IAAIA,CAACA,GAAGA,CAACA,GAAGA,IAAIA,CAACA,GAAGA,CAACA,CAACA;YAC1BA,CAACA;QACLA,CAACA;QACDA,MAAMA,CAAQA,IAAIA,CAACA;IACvBA,CAACA;IAMMJ,uBAAMA,GAAbA,UAAeA,IAAUA;QACrBK,IAAMA,YAAYA,GAAGA,IAAIA,CAACA,QAAQA,GAAGA,MAAMA,CAACA;QAC5CA,IAAIA,eAAeA,GAAQA,EAAEA,CAACA;QAC9BA,IAAIA,YAAYA,GAAQA,IAAIA,CAACA,SAASA,CAACA,EAAEA,EAAEA,IAAIA,CAACA,cAAcA,CAACA,CAACA;QAChEA,IAAIA,UAAUA,GAAQA,EAAEA,CAACA;QAGzBA,IAAIA,WAAWA,GAAGA,KAAKA,CAACA;QAExBA,IAAIA,gBAAgBA,GAAGA,OAAOA,CAACA,KAAKA,EAAmDA,CAACA;QACxFA,IAAIA,cAAcA,GAAoBA;YAClCA,MAAMA,EAAEA,MAAMA;YACdA,EAAEA,EAAEA,eAAeA;YACnBA,OAAOA,EAAEA,YAAYA;YACrBA,GAAGA,EAAEA,YAAYA;YACjBA,IAAIA,EAAEA,IAAIA;YACVA,IAAIA,EAAEA,IAAIA;SACbA,CAACA;QAEFA,IAAIA,CAACA,eAAeA,CAACA,aAAaA,CAACA,cAAcA,CAACA,cAAcA,CAACA,CAACA;QAElEA,IAAIA,CAACA,eAAeA,CAACA,OAAOA,CAACA,cAAcA,CAACA,cAAcA,CAACA,CAACA;QAE5DA,EAAEA,CAACA,CAACA,MAAMA,CAACA,IAAIA,CAACA,UAAUA,CAACA,CAACA,MAAMA,CAACA,CAACA,CAACA;YACjCA,EAAEA,CAACA,CAACA,WAAWA,CAACA,CAACA,CAACA;gBACRA,cAAeA,CAACA,QAAQA,GAAGA,UAAUA,CAACA;YAChDA,CAACA;YAACA,IAAIA,CAACA,CAACA;gBACJA,cAAcA,CAACA,IAAIA,GAAGA,UAAUA,CAACA;YACrCA,CAACA;QACLA,CAACA;QACDA,OAAOA,CAACA,cAAcA,EAAEA,UAACA,KAAKA,EAAEA,QAAQA,EAAEA,IAAIA;YAC1CA,EAAEA,CAACA,CAACA,KAAKA,CAACA,CAACA,CAACA;gBACRA,gBAAgBA,CAACA,MAAMA,CAACA,KAAKA,CAACA,CAACA;YACnCA,CAACA;YAACA,IAAIA,CAACA,CAACA;gBACJA,EAAEA,CAACA,CAACA,QAAQA,CAACA,UAAUA,IAAIA,GAAGA,IAAIA,QAAQA,CAACA,UAAUA,IAAIA,GAAGA,CAACA,CAACA,CAACA;oBAC3DA,gBAAgBA,CAACA,OAAOA,CAACA,EAAEA,QAAQA,EAAEA,QAAQA,EAAEA,IAAIA,EAAEA,IAAIA,EAAEA,CAACA,CAACA;gBACjEA,CAACA;gBAACA,IAAIA,CAACA,CAACA;oBACJA,gBAAgBA,CAACA,MAAMA,CAACA,EAAEA,QAAQA,EAAEA,QAAQA,EAAEA,IAAIA,EAAEA,IAAIA,EAAEA,CAACA,CAACA;gBAChEA,CAACA;YACLA,CAACA;QACLA,CAACA,CAACA,CAACA;QACHA,MAAMA,CAACA,gBAAgBA,CAACA,OAAOA,CAACA;IACpCA,CAACA;IAOML,0BAASA,GAAhBA,UAAkBA,KAAaA,EAAEA,MAAeA;QAC5CM,IAAMA,YAAYA,GAAGA,IAAIA,CAACA,QAAQA,GAAGA,cAAcA;aAC9CA,OAAOA,CAACA,GAAGA,GAAGA,OAAOA,GAAGA,GAAGA,EAAEA,MAAMA,CAACA,KAAKA,CAACA,CAACA,CAACA;QACjDA,IAAIA,eAAeA,GAAQA,EAAEA,CAACA;QAC9BA,IAAIA,YAAYA,GAAQA,IAAIA,CAACA,SAASA,CAACA,EAAEA,EAAEA,IAAIA,CAACA,cAAcA,CAACA,CAACA;QAChEA,IAAIA,UAAUA,GAAQA,EAAEA,CAACA;QAIzBA,EAAEA,CAACA,CAACA,KAAKA,KAAKA,IAAIA,IAAIA,KAAKA,KAAKA,SAASA,CAACA,CAACA,CAACA;YACxCA,MAAMA,IAAIA,KAAKA,CAACA,wEAAwEA,CAACA,CAACA;QAC9FA,CAACA;QAEDA,YAAYA,CAACA,SAASA,CAACA,GAAGA,MAAMA,CAACA;QAEjCA,IAAIA,WAAWA,GAAGA,KAAKA,CAACA;QAExBA,IAAIA,gBAAgBA,GAAGA,OAAOA,CAACA,KAAKA,EAAmDA,CAACA;QACxFA,IAAIA,cAAcA,GAAoBA;YAClCA,MAAMA,EAAEA,QAAQA;YAChBA,EAAEA,EAAEA,eAAeA;YACnBA,OAAOA,EAAEA,YAAYA;YACrBA,GAAGA,EAAEA,YAAYA;YACjBA,IAAIA,EAAEA,IAAIA;SACbA,CAACA;QAEFA,IAAIA,CAACA,eAAeA,CAACA,aAAaA,CAACA,cAAcA,CAACA,cAAcA,CAACA,CAACA;QAElEA,IAAIA,CAACA,eAAeA,CAACA,OAAOA,CAACA,cAAcA,CAACA,cAAcA,CAACA,CAACA;QAE5DA,EAAEA,CAACA,CAACA,MAAMA,CAACA,IAAIA,CAACA,UAAUA,CAACA,CAACA,MAAMA,CAACA,CAACA,CAACA;YACjCA,EAAEA,CAACA,CAACA,WAAWA,CAACA,CAACA,CAACA;gBACRA,cAAeA,CAACA,QAAQA,GAAGA,UAAUA,CAACA;YAChDA,CAACA;YAACA,IAAIA,CAACA,CAACA;gBACJA,cAAcA,CAACA,IAAIA,GAAGA,UAAUA,CAACA;YACrCA,CAACA;QACLA,CAACA;QACDA,OAAOA,CAACA,cAAcA,EAAEA,UAACA,KAAKA,EAAEA,QAAQA,EAAEA,IAAIA;YAC1CA,EAAEA,CAACA,CAACA,KAAKA,CAACA,CAACA,CAACA;gBACRA,gBAAgBA,CAACA,MAAMA,CAACA,KAAKA,CAACA,CAACA;YACnCA,CAACA;YAACA,IAAIA,CAACA,CAACA;gBACJA,EAAEA,CAACA,CAACA,QAAQA,CAACA,UAAUA,IAAIA,GAAGA,IAAIA,QAAQA,CAACA,UAAUA,IAAIA,GAAGA,CAACA,CAACA,CAACA;oBAC3DA,gBAAgBA,CAACA,OAAOA,CAACA,EAAEA,QAAQA,EAAEA,QAAQA,EAAEA,IAAIA,EAAEA,IAAIA,EAAEA,CAACA,CAACA;gBACjEA,CAACA;gBAACA,IAAIA,CAACA,CAACA;oBACJA,gBAAgBA,CAACA,MAAMA,CAACA,EAAEA,QAAQA,EAAEA,QAAQA,EAAEA,IAAIA,EAAEA,IAAIA,EAAEA,CAACA,CAACA;gBAChEA,CAACA;YACLA,CAACA;QACLA,CAACA,CAACA,CAACA;QACHA,MAAMA,CAACA,gBAAgBA,CAACA,OAAOA,CAACA;IACpCA,CAACA;IAMMN,iCAAgBA,GAAvBA,UAAyBA,MAAsBA;QAC3CO,IAAMA,YAAYA,GAAGA,IAAIA,CAACA,QAAQA,GAAGA,mBAAmBA,CAACA;QACzDA,IAAIA,eAAeA,GAAQA,EAAEA,CAACA;QAC9BA,IAAIA,YAAYA,GAAQA,IAAIA,CAACA,SAASA,CAACA,EAAEA,EAAEA,IAAIA,CAACA,cAAcA,CAACA,CAACA;QAChEA,IAAIA,UAAUA,GAAQA,EAAEA,CAACA;QAGzBA,EAAEA,CAACA,CAACA,MAAMA,KAAKA,SAASA,CAACA,CAACA,CAACA;YACvBA,eAAeA,CAACA,QAAQA,CAACA,GAAGA,MAAMA,CAACA;QACvCA,CAACA;QAEDA,IAAIA,WAAWA,GAAGA,KAAKA,CAACA;QAExBA,IAAIA,gBAAgBA,GAAGA,OAAOA,CAACA,KAAKA,EAAyDA,CAACA;QAC9FA,IAAIA,cAAcA,GAAoBA;YAClCA,MAAMA,EAAEA,KAAKA;YACbA,EAAEA,EAAEA,eAAeA;YACnBA,OAAOA,EAAEA,YAAYA;YACrBA,GAAGA,EAAEA,YAAYA;YACjBA,IAAIA,EAAEA,IAAIA;SACbA,CAACA;QAEFA,IAAIA,CAACA,eAAeA,CAACA,aAAaA,CAACA,cAAcA,CAACA,cAAcA,CAACA,CAACA;QAElEA,IAAIA,CAACA,eAAeA,CAACA,OAAOA,CAACA,cAAcA,CAACA,cAAcA,CAACA,CAACA;QAE5DA,EAAEA,CAACA,CAACA,MAAMA,CAACA,IAAIA,CAACA,UAAUA,CAACA,CAACA,MAAMA,CAACA,CAACA,CAACA;YACjCA,EAAEA,CAACA,CAACA,WAAWA,CAACA,CAACA,CAACA;gBACRA,cAAeA,CAACA,QAAQA,GAAGA,UAAUA,CAACA;YAChDA,CAACA;YAACA,IAAIA,CAACA,CAACA;gBACJA,cAAcA,CAACA,IAAIA,GAAGA,UAAUA,CAACA;YACrCA,CAACA;QACLA,CAACA;QACDA,OAAOA,CAACA,cAAcA,EAAEA,UAACA,KAAKA,EAAEA,QAAQA,EAAEA,IAAIA;YAC1CA,EAAEA,CAACA,CAACA,KAAKA,CAACA,CAACA,CAACA;gBACRA,gBAAgBA,CAACA,MAAMA,CAACA,KAAKA,CAACA,CAACA;YACnCA,CAACA;YAACA,IAAIA,CAACA,CAACA;gBACJA,EAAEA,CAACA,CAACA,QAAQA,CAACA,UAAUA,IAAIA,GAAGA,IAAIA,QAAQA,CAACA,UAAUA,IAAIA,GAAGA,CAACA,CAACA,CAACA;oBAC3DA,gBAAgBA,CAACA,OAAOA,CAACA,EAAEA,QAAQA,EAAEA,QAAQA,EAAEA,IAAIA,EAAEA,IAAIA,EAAEA,CAACA,CAACA;gBACjEA,CAACA;gBAACA,IAAIA,CAACA,CAACA;oBACJA,gBAAgBA,CAACA,MAAMA,CAACA,EAAEA,QAAQA,EAAEA,QAAQA,EAAEA,IAAIA,EAAEA,IAAIA,EAAEA,CAACA,CAACA;gBAChEA,CAACA;YACLA,CAACA;QACLA,CAACA,CAACA,CAACA;QACHA,MAAMA,CAACA,gBAAgBA,CAACA,OAAOA,CAACA;IACpCA,CAACA;IAMMP,+BAAcA,GAArBA,UAAuBA,IAAoBA;QACvCQ,IAAMA,YAAYA,GAAGA,IAAIA,CAACA,QAAQA,GAAGA,iBAAiBA,CAACA;QACvDA,IAAIA,eAAeA,GAAQA,EAAEA,CAACA;QAC9BA,IAAIA,YAAYA,GAAQA,IAAIA,CAACA,SAASA,CAACA,EAAEA,EAAEA,IAAIA,CAACA,cAAcA,CAACA,CAACA;QAChEA,IAAIA,UAAUA,GAAQA,EAAEA,CAACA;QAGzBA,EAAEA,CAACA,CAACA,IAAIA,KAAKA,SAASA,CAACA,CAACA,CAACA;YACrBA,eAAeA,CAACA,MAAMA,CAACA,GAAGA,IAAIA,CAACA;QACnCA,CAACA;QAEDA,IAAIA,WAAWA,GAAGA,KAAKA,CAACA;QAExBA,IAAIA,gBAAgBA,GAAGA,OAAOA,CAACA,KAAKA,EAAyDA,CAACA;QAC9FA,IAAIA,cAAcA,GAAoBA;YAClCA,MAAMA,EAAEA,KAAKA;YACbA,EAAEA,EAAEA,eAAeA;YACnBA,OAAOA,EAAEA,YAAYA;YACrBA,GAAGA,EAAEA,YAAYA;YACjBA,IAAIA,EAAEA,IAAIA;SACbA,CAACA;QAEFA,IAAIA,CAACA,eAAeA,CAACA,aAAaA,CAACA,cAAcA,CAACA,cAAcA,CAACA,CAACA;QAElEA,IAAIA,CAACA,eAAeA,CAACA,OAAOA,CAACA,cAAcA,CAACA,cAAcA,CAACA,CAACA;QAE5DA,EAAEA,CAACA,CAACA,MAAMA,CAACA,IAAIA,CAACA,UAAUA,CAACA,CAACA,MAAMA,CAACA,CAACA,CAACA;YACjCA,EAAEA,CAACA,CAACA,WAAWA,CAACA,CAACA,CAACA;gBACRA,cAAeA,CAACA,QAAQA,GAAGA,UAAUA,CAACA;YAChDA,CAACA;YAACA,IAAIA,CAACA,CAACA;gBACJA,cAAcA,CAACA,IAAIA,GAAGA,UAAUA,CAACA;YACrCA,CAACA;QACLA,CAACA;QACDA,OAAOA,CAACA,cAAcA,EAAEA,UAACA,KAAKA,EAAEA,QAAQA,EAAEA,IAAIA;YAC1CA,EAAEA,CAACA,CAACA,KAAKA,CAACA,CAACA,CAACA;gBACRA,gBAAgBA,CAACA,MAAMA,CAACA,KAAKA,CAACA,CAACA;YACnCA,CAACA;YAACA,IAAIA,CAACA,CAACA;gBACJA,EAAEA,CAACA,CAACA,QAAQA,CAACA,UAAUA,IAAIA,GAAGA,IAAIA,QAAQA,CAACA,UAAUA,IAAIA,GAAGA,CAACA,CAACA,CAACA;oBAC3DA,gBAAgBA,CAACA,OAAOA,CAACA,EAAEA,QAAQA,EAAEA,QAAQA,EAAEA,IAAIA,EAAEA,IAAIA,EAAEA,CAACA,CAACA;gBACjEA,CAACA;gBAACA,IAAIA,CAACA,CAACA;oBACJA,gBAAgBA,CAACA,MAAMA,CAACA,EAAEA,QAAQA,EAAEA,QAAQA,EAAEA,IAAIA,EAAEA,IAAIA,EAAEA,CAACA,CAACA;gBAChEA,CAACA;YACLA,CAACA;QACLA,CAACA,CAACA,CAACA;QACHA,MAAMA,CAACA,gBAAgBA,CAACA,OAAOA,CAACA;IACpCA,CAACA;IAMMR,2BAAUA,GAAjBA,UAAmBA,KAAaA;QAC5BS,IAAMA,YAAYA,GAAGA,IAAIA,CAACA,QAAQA,GAAGA,cAAcA;aAC9CA,OAAOA,CAACA,GAAGA,GAAGA,OAAOA,GAAGA,GAAGA,EAAEA,MAAMA,CAACA,KAAKA,CAACA,CAACA,CAACA;QACjDA,IAAIA,eAAeA,GAAQA,EAAEA,CAACA;QAC9BA,IAAIA,YAAYA,GAAQA,IAAIA,CAACA,SAASA,CAACA,EAAEA,EAAEA,IAAIA,CAACA,cAAcA,CAACA,CAACA;QAChEA,IAAIA,UAAUA,GAAQA,EAAEA,CAACA;QAIzBA,EAAEA,CAACA,CAACA,KAAKA,KAAKA,IAAIA,IAAIA,KAAKA,KAAKA,SAASA,CAACA,CAACA,CAACA;YACxCA,MAAMA,IAAIA,KAAKA,CAACA,yEAAyEA,CAACA,CAACA;QAC/FA,CAACA;QAEDA,IAAIA,WAAWA,GAAGA,KAAKA,CAACA;QAExBA,IAAIA,gBAAgBA,GAAGA,OAAOA,CAACA,KAAKA,EAAkDA,CAACA;QACvFA,IAAIA,cAAcA,GAAoBA;YAClCA,MAAMA,EAAEA,KAAKA;YACbA,EAAEA,EAAEA,eAAeA;YACnBA,OAAOA,EAAEA,YAAYA;YACrBA,GAAGA,EAAEA,YAAYA;YACjBA,IAAIA,EAAEA,IAAIA;SACbA,CAACA;QAEFA,IAAIA,CAACA,eAAeA,CAACA,OAAOA,CAACA,cAAcA,CAACA,cAAcA,CAACA,CAACA;QAE5DA,IAAIA,CAACA,eAAeA,CAACA,aAAaA,CAACA,cAAcA,CAACA,cAAcA,CAACA,CAACA;QAElEA,IAAIA,CAACA,eAAeA,CAACA,OAAOA,CAACA,cAAcA,CAACA,cAAcA,CAACA,CAACA;QAE5DA,EAAEA,CAACA,CAACA,MAAMA,CAACA,IAAIA,CAACA,UAAUA,CAACA,CAACA,MAAMA,CAACA,CAACA,CAACA;YACjCA,EAAEA,CAACA,CAACA,WAAWA,CAACA,CAACA,CAACA;gBACRA,cAAeA,CAACA,QAAQA,GAAGA,UAAUA,CAACA;YAChDA,CAACA;YAACA,IAAIA,CAACA,CAACA;gBACJA,cAAcA,CAACA,IAAIA,GAAGA,UAAUA,CAACA;YACrCA,CAACA;QACLA,CAACA;QACDA,OAAOA,CAACA,cAAcA,EAAEA,UAACA,KAAKA,EAAEA,QAAQA,EAAEA,IAAIA;YAC1CA,EAAEA,CAACA,CAACA,KAAKA,CAACA,CAACA,CAACA;gBACRA,gBAAgBA,CAACA,MAAMA,CAACA,KAAKA,CAACA,CAACA;YACnCA,CAACA;YAACA,IAAIA,CAACA,CAACA;gBACJA,EAAEA,CAACA,CAACA,QAAQA,CAACA,UAAUA,IAAIA,GAAGA,IAAIA,QAAQA,CAACA,UAAUA,IAAIA,GAAGA,CAACA,CAACA,CAACA;oBAC3DA,gBAAgBA,CAACA,OAAOA,CAACA,EAAEA,QAAQA,EAAEA,QAAQA,EAAEA,IAAIA,EAAEA,IAAIA,EAAEA,CAACA,CAACA;gBACjEA,CAACA;gBAACA,IAAIA,CAACA,CAACA;oBACJA,gBAAgBA,CAACA,MAAMA,CAACA,EAAEA,QAAQA,EAAEA,QAAQA,EAAEA,IAAIA,EAAEA,IAAIA,EAAEA,CAACA,CAACA;gBAChEA,CAACA;YACLA,CAACA;QACLA,CAACA,CAACA,CAACA;QACHA,MAAMA,CAACA,gBAAgBA,CAACA,OAAOA,CAACA;IACpCA,CAACA;IAMMT,0BAASA,GAAhBA,UAAkBA,IAAUA;QACxBU,IAAMA,YAAYA,GAAGA,IAAIA,CAACA,QAAQA,GAAGA,MAAMA,CAACA;QAC5CA,IAAIA,eAAeA,GAAQA,EAAEA,CAACA;QAC9BA,IAAIA,YAAYA,GAAQA,IAAIA,CAACA,SAASA,CAACA,EAAEA,EAAEA,IAAIA,CAACA,cAAcA,CAACA,CAACA;QAChEA,IAAIA,UAAUA,GAAQA,EAAEA,CAACA;QAGzBA,IAAIA,WAAWA,GAAGA,KAAKA,CAACA;QAExBA,IAAIA,gBAAgBA,GAAGA,OAAOA,CAACA,KAAKA,EAAmDA,CAACA;QACxFA,IAAIA,cAAcA,GAAoBA;YAClCA,MAAMA,EAAEA,KAAKA;YACbA,EAAEA,EAAEA,eAAeA;YACnBA,OAAOA,EAAEA,YAAYA;YACrBA,GAAGA,EAAEA,YAAYA;YACjBA,IAAIA,EAAEA,IAAIA;YACVA,IAAIA,EAAEA,IAAIA;SACbA,CAACA;QAEFA,IAAIA,CAACA,eAAeA,CAACA,aAAaA,CAACA,cAAcA,CAACA,cAAcA,CAACA,CAACA;QAElEA,IAAIA,CAACA,eAAeA,CAACA,OAAOA,CAACA,cAAcA,CAACA,cAAcA,CAACA,CAACA;QAE5DA,EAAEA,CAACA,CAACA,MAAMA,CAACA,IAAIA,CAACA,UAAUA,CAACA,CAACA,MAAMA,CAACA,CAACA,CAACA;YACjCA,EAAEA,CAACA,CAACA,WAAWA,CAACA,CAACA,CAACA;gBACRA,cAAeA,CAACA,QAAQA,GAAGA,UAAUA,CAACA;YAChDA,CAACA;YAACA,IAAIA,CAACA,CAACA;gBACJA,cAAcA,CAACA,IAAIA,GAAGA,UAAUA,CAACA;YACrCA,CAACA;QACLA,CAACA;QACDA,OAAOA,CAACA,cAAcA,EAAEA,UAACA,KAAKA,EAAEA,QAAQA,EAAEA,IAAIA;YAC1CA,EAAEA,CAACA,CAACA,KAAKA,CAACA,CAACA,CAACA;gBACRA,gBAAgBA,CAACA,MAAMA,CAACA,KAAKA,CAACA,CAACA;YACnCA,CAACA;YAACA,IAAIA,CAACA,CAACA;gBACJA,EAAEA,CAACA,CAACA,QAAQA,CAACA,UAAUA,IAAIA,GAAGA,IAAIA,QAAQA,CAACA,UAAUA,IAAIA,GAAGA,CAACA,CAACA,CAACA;oBAC3DA,gBAAgBA,CAACA,OAAOA,CAACA,EAAEA,QAAQA,EAAEA,QAAQA,EAAEA,IAAIA,EAAEA,IAAIA,EAAEA,CAACA,CAACA;gBACjEA,CAACA;gBAACA,IAAIA,CAACA,CAACA;oBACJA,gBAAgBA,CAACA,MAAMA,CAACA,EAAEA,QAAQA,EAAEA,QAAQA,EAAEA,IAAIA,EAAEA,IAAIA,EAAEA,CAACA,CAACA;gBAChEA,CAACA;YACLA,CAACA;QACLA,CAACA,CAACA,CAACA;QACHA,MAAMA,CAACA,gBAAgBA,CAACA,OAAOA,CAACA;IACpCA,CAACA;IAQMV,kCAAiBA,GAAxBA,UAA0BA,KAAaA,EAAEA,IAAaA,EAAEA,MAAeA;QACnEW,IAAMA,YAAYA,GAAGA,IAAIA,CAACA,QAAQA,GAAGA,cAAcA;aAC9CA,OAAOA,CAACA,GAAGA,GAAGA,OAAOA,GAAGA,GAAGA,EAAEA,MAAMA,CAACA,KAAKA,CAACA,CAACA,CAACA;QACjDA,IAAIA,eAAeA,GAAQA,EAAEA,CAACA;QAC9BA,IAAIA,YAAYA,GAAQA,IAAIA,CAACA,SAASA,CAACA,EAAEA,EAAEA,IAAIA,CAACA,cAAcA,CAACA,CAACA;QAChEA,IAAIA,UAAUA,GAAQA,EAAEA,CAACA;QAIzBA,EAAEA,CAACA,CAACA,KAAKA,KAAKA,IAAIA,IAAIA,KAAKA,KAAKA,SAASA,CAACA,CAACA,CAACA;YACxCA,MAAMA,IAAIA,KAAKA,CAACA,gFAAgFA,CAACA,CAACA;QACtGA,CAACA;QAEDA,IAAIA,WAAWA,GAAGA,KAAKA,CAACA;QAExBA,EAAEA,CAACA,CAACA,IAAIA,KAAKA,SAASA,CAACA,CAACA,CAACA;YACrBA,UAAUA,CAACA,MAAMA,CAACA,GAAGA,IAAIA,CAACA;QAC9BA,CAACA;QAEDA,EAAEA,CAACA,CAACA,MAAMA,KAAKA,SAASA,CAACA,CAACA,CAACA;YACvBA,UAAUA,CAACA,QAAQA,CAACA,GAAGA,MAAMA,CAACA;QAClCA,CAACA;QAEDA,IAAIA,gBAAgBA,GAAGA,OAAOA,CAACA,KAAKA,EAAmDA,CAACA;QACxFA,IAAIA,cAAcA,GAAoBA;YAClCA,MAAMA,EAAEA,MAAMA;YACdA,EAAEA,EAAEA,eAAeA;YACnBA,OAAOA,EAAEA,YAAYA;YACrBA,GAAGA,EAAEA,YAAYA;YACjBA,IAAIA,EAAEA,IAAIA;SACbA,CAACA;QAEFA,IAAIA,CAACA,eAAeA,CAACA,aAAaA,CAACA,cAAcA,CAACA,cAAcA,CAACA,CAACA;QAElEA,IAAIA,CAACA,eAAeA,CAACA,OAAOA,CAACA,cAAcA,CAACA,cAAcA,CAACA,CAACA;QAE5DA,EAAEA,CAACA,CAACA,MAAMA,CAACA,IAAIA,CAACA,UAAUA,CAACA,CAACA,MAAMA,CAACA,CAACA,CAACA;YACjCA,EAAEA,CAACA,CAACA,WAAWA,CAACA,CAACA,CAACA;gBACRA,cAAeA,CAACA,QAAQA,GAAGA,UAAUA,CAACA;YAChDA,CAACA;YAACA,IAAIA,CAACA,CAACA;gBACJA,cAAcA,CAACA,IAAIA,GAAGA,UAAUA,CAACA;YACrCA,CAACA;QACLA,CAACA;QACDA,OAAOA,CAACA,cAAcA,EAAEA,UAACA,KAAKA,EAAEA,QAAQA,EAAEA,IAAIA;YAC1CA,EAAEA,CAACA,CAACA,KAAKA,CAACA,CAACA,CAACA;gBACRA,gBAAgBA,CAACA,MAAMA,CAACA,KAAKA,CAACA,CAACA;YACnCA,CAACA;YAACA,IAAIA,CAACA,CAACA;gBACJA,EAAEA,CAACA,CAACA,QAAQA,CAACA,UAAUA,IAAIA,GAAGA,IAAIA,QAAQA,CAACA,UAAUA,IAAIA,GAAGA,CAACA,CAACA,CAACA;oBAC3DA,gBAAgBA,CAACA,OAAOA,CAACA,EAAEA,QAAQA,EAAEA,QAAQA,EAAEA,IAAIA,EAAEA,IAAIA,EAAEA,CAACA,CAACA;gBACjEA,CAACA;gBAACA,IAAIA,CAACA,CAACA;oBACJA,gBAAgBA,CAACA,MAAMA,CAACA,EAAEA,QAAQA,EAAEA,QAAQA,EAAEA,IAAIA,EAAEA,IAAIA,EAAEA,CAACA,CAACA;gBAChEA,CAACA;YACLA,CAACA;QACLA,CAACA,CAACA,CAACA;QACHA,MAAMA,CAACA,gBAAgBA,CAACA,OAAOA,CAACA;IACpCA,CAACA;IAQMX,2BAAUA,GAAjBA,UAAmBA,KAAaA,EAAEA,kBAA2BA,EAAEA,IAAUA;QACrEY,IAAMA,YAAYA,GAAGA,IAAIA,CAACA,QAAQA,GAAGA,0BAA0BA;aAC1DA,OAAOA,CAACA,GAAGA,GAAGA,OAAOA,GAAGA,GAAGA,EAAEA,MAAMA,CAACA,KAAKA,CAACA,CAACA,CAACA;QACjDA,IAAIA,eAAeA,GAAQA,EAAEA,CAACA;QAC9BA,IAAIA,YAAYA,GAAQA,IAAIA,CAACA,SAASA,CAACA,EAAEA,EAAEA,IAAIA,CAACA,cAAcA,CAACA,CAACA;QAChEA,IAAIA,UAAUA,GAAQA,EAAEA,CAACA;QAIzBA,EAAEA,CAACA,CAACA,KAAKA,KAAKA,IAAIA,IAAIA,KAAKA,KAAKA,SAASA,CAACA,CAACA,CAACA;YACxCA,MAAMA,IAAIA,KAAKA,CAACA,yEAAyEA,CAACA,CAACA;QAC/FA,CAACA;QAEDA,IAAIA,WAAWA,GAAGA,KAAKA,CAACA;QAExBA,EAAEA,CAACA,CAACA,kBAAkBA,KAAKA,SAASA,CAACA,CAACA,CAACA;YACnCA,UAAUA,CAACA,oBAAoBA,CAACA,GAAGA,kBAAkBA,CAACA;QAC1DA,CAACA;QAEDA,EAAEA,CAACA,CAACA,IAAIA,KAAKA,SAASA,CAACA,CAACA,CAACA;YACrBA,UAAUA,CAACA,MAAMA,CAACA,GAAGA,IAAIA,CAACA;QAC9BA,CAACA;QACDA,WAAWA,GAAGA,IAAIA,CAACA;QAEnBA,IAAIA,gBAAgBA,GAAGA,OAAOA,CAACA,KAAKA,EAAmDA,CAACA;QACxFA,IAAIA,cAAcA,GAAoBA;YAClCA,MAAMA,EAAEA,MAAMA;YACdA,EAAEA,EAAEA,eAAeA;YACnBA,OAAOA,EAAEA,YAAYA;YACrBA,GAAGA,EAAEA,YAAYA;YACjBA,IAAIA,EAAEA,IAAIA;SACbA,CAACA;QAEFA,IAAIA,CAACA,eAAeA,CAACA,aAAaA,CAACA,cAAcA,CAACA,cAAcA,CAACA,CAACA;QAElEA,IAAIA,CAACA,eAAeA,CAACA,OAAOA,CAACA,cAAcA,CAACA,cAAcA,CAACA,CAACA;QAE5DA,EAAEA,CAACA,CAACA,MAAMA,CAACA,IAAIA,CAACA,UAAUA,CAACA,CAACA,MAAMA,CAACA,CAACA,CAACA;YACjCA,EAAEA,CAACA,CAACA,WAAWA,CAACA,CAACA,CAACA;gBACRA,cAAeA,CAACA,QAAQA,GAAGA,UAAUA,CAACA;YAChDA,CAACA;YAACA,IAAIA,CAACA,CAACA;gBACJA,cAAcA,CAACA,IAAIA,GAAGA,UAAUA,CAACA;YACrCA,CAACA;QACLA,CAACA;QACDA,OAAOA,CAACA,cAAcA,EAAEA,UAACA,KAAKA,EAAEA,QAAQA,EAAEA,IAAIA;YAC1CA,EAAEA,CAACA,CAACA,KAAKA,CAACA,CAACA,CAACA;gBACRA,gBAAgBA,CAACA,MAAMA,CAACA,KAAKA,CAACA,CAACA;YACnCA,CAACA;YAACA,IAAIA,CAACA,CAACA;gBACJA,EAAEA,CAACA,CAACA,QAAQA,CAACA,UAAUA,IAAIA,GAAGA,IAAIA,QAAQA,CAACA,UAAUA,IAAIA,GAAGA,CAACA,CAACA,CAACA;oBAC3DA,gBAAgBA,CAACA,OAAOA,CAACA,EAAEA,QAAQA,EAAEA,QAAQA,EAAEA,IAAIA,EAAEA,IAAIA,EAAEA,CAACA,CAACA;gBACjEA,CAACA;gBAACA,IAAIA,CAACA,CAACA;oBACJA,gBAAgBA,CAACA,MAAMA,CAACA,EAAEA,QAAQA,EAAEA,QAAQA,EAAEA,IAAIA,EAAEA,IAAIA,EAAEA,CAACA,CAACA;gBAChEA,CAACA;YACLA,CAACA;QACLA,CAACA,CAACA,CAACA;QACHA,MAAMA,CAACA,gBAAgBA,CAACA,OAAOA,CAACA;IACpCA,CAACA;IACLZ,aAACA;AAADA,CAACA,AA1dD,IA0dC;AA1dY,cAAM,SA0dlB,CAAA;AACD,WAAY,eAAe;IACvBa,2DAAOA,CAAAA;AACXA,CAACA,EAFW,uBAAe,KAAf,uBAAe,QAE1B;AAFD,IAAY,eAAe,GAAf,uBAEX,CAAA;AAED;IAWIC,kBAAYA,kBAA0BA,EAAEA,QAAiBA,EAAEA,QAAiBA;QAVlEC,aAAQA,GAAGA,eAAeA,CAACA;QAC3BA,mBAAcA,GAASA,EAAEA,CAACA;QAE1BA,oBAAeA,GAAGA;YACxBA,SAASA,EAAkBA,IAAIA,QAAQA,EAAEA;YACzCA,SAASA,EAAEA,IAAIA,UAAUA,CAACA,QAAQA,EAAEA,SAASA,CAACA;YAC9CA,eAAeA,EAAEA,IAAIA,KAAKA,EAAEA;SAC/BA,CAAAA;QAIGA,EAAEA,CAACA,CAACA,QAAQA,CAACA,CAACA,CAACA;YACXA,EAAEA,CAACA,CAACA,QAAQA,CAACA,CAACA,CAACA;gBACXA,IAAIA,CAACA,QAAQA,GAAGA,QAAQA,CAACA;YAC7BA,CAACA;QACLA,CAACA;QAACA,IAAIA,CAACA,CAACA;YACJA,EAAEA,CAACA,CAACA,kBAAkBA,CAACA,CAACA,CAACA;gBACrBA,IAAIA,CAACA,QAAQA,GAAGA,kBAAkBA,CAAAA;YACtCA,CAACA;QACLA,CAACA;IACLA,CAACA;IAEMD,4BAASA,GAAhBA,UAAiBA,GAAoBA,EAAEA,KAAaA;QAChDE,IAAIA,CAACA,eAAeA,CAACA,eAAeA,CAACA,GAAGA,CAACA,CAACA,CAACA,MAAMA,GAAGA,KAAKA,CAACA;IAC9DA,CAACA;IAEDF,sBAAIA,iCAAWA;aAAfA,UAAgBA,KAAaA;YACzBG,IAAIA,CAACA,eAAeA,CAACA,aAAaA,CAACA,WAAWA,GAAGA,KAAKA,CAACA;QAC3DA,CAACA;;;OAAAH;IACOA,4BAASA,GAAjBA,UAAyBA,IAAQA,EAAEA,IAAQA;QACvCI,GAAGA,CAAAA,CAACA,GAAGA,CAACA,GAAGA,IAAIA,IAAIA,CAACA,CAAAA,CAACA;YACjBA,EAAEA,CAAAA,CAACA,IAAIA,CAACA,cAAcA,CAACA,GAAGA,CAACA,CAACA,CAAAA,CAACA;gBACzBA,IAAIA,CAACA,GAAGA,CAACA,GAAGA,IAAIA,CAACA,GAAGA,CAACA,CAACA;YAC1BA,CAACA;QACLA,CAACA;QACDA,MAAMA,CAAQA,IAAIA,CAACA;IACvBA,CAACA;IAMMJ,8BAAWA,GAAlBA,UAAoBA,OAAeA;QAC/BK,IAAMA,YAAYA,GAAGA,IAAIA,CAACA,QAAQA,GAAGA,wBAAwBA;aACxDA,OAAOA,CAACA,GAAGA,GAAGA,SAASA,GAAGA,GAAGA,EAAEA,MAAMA,CAACA,OAAOA,CAACA,CAACA,CAACA;QACrDA,IAAIA,eAAeA,GAAQA,EAAEA,CAACA;QAC9BA,IAAIA,YAAYA,GAAQA,IAAIA,CAACA,SAASA,CAACA,EAAEA,EAAEA,IAAIA,CAACA,cAAcA,CAACA,CAACA;QAChEA,IAAIA,UAAUA,GAAQA,EAAEA,CAACA;QAIzBA,EAAEA,CAACA,CAACA,OAAOA,KAAKA,IAAIA,IAAIA,OAAOA,KAAKA,SAASA,CAACA,CAACA,CAACA;YAC5CA,MAAMA,IAAIA,KAAKA,CAACA,4EAA4EA,CAACA,CAACA;QAClGA,CAACA;QAEDA,IAAIA,WAAWA,GAAGA,KAAKA,CAACA;QAExBA,IAAIA,gBAAgBA,GAAGA,OAAOA,CAACA,KAAKA,EAAmDA,CAACA;QACxFA,IAAIA,cAAcA,GAAoBA;YAClCA,MAAMA,EAAEA,QAAQA;YAChBA,EAAEA,EAAEA,eAAeA;YACnBA,OAAOA,EAAEA,YAAYA;YACrBA,GAAGA,EAAEA,YAAYA;YACjBA,IAAIA,EAAEA,IAAIA;SACbA,CAACA;QAEFA,IAAIA,CAACA,eAAeA,CAACA,OAAOA,CAACA,cAAcA,CAACA,cAAcA,CAACA,CAACA;QAE5DA,EAAEA,CAACA,CAACA,MAAMA,CAACA,IAAIA,CAACA,UAAUA,CAACA,CAACA,MAAMA,CAACA,CAACA,CAACA;YACjCA,EAAEA,CAACA,CAACA,WAAWA,CAACA,CAACA,CAACA;gBACRA,cAAeA,CAACA,QAAQA,GAAGA,UAAUA,CAACA;YAChDA,CAACA;YAACA,IAAIA,CAACA,CAACA;gBACJA,cAAcA,CAACA,IAAIA,GAAGA,UAAUA,CAACA;YACrCA,CAACA;QACLA,CAACA;QACDA,OAAOA,CAACA,cAAcA,EAAEA,UAACA,KAAKA,EAAEA,QAAQA,EAAEA,IAAIA;YAC1CA,EAAEA,CAACA,CAACA,KAAKA,CAACA,CAACA,CAACA;gBACRA,gBAAgBA,CAACA,MAAMA,CAACA,KAAKA,CAACA,CAACA;YACnCA,CAACA;YAACA,IAAIA,CAACA,CAACA;gBACJA,EAAEA,CAACA,CAACA,QAAQA,CAACA,UAAUA,IAAIA,GAAGA,IAAIA,QAAQA,CAACA,UAAUA,IAAIA,GAAGA,CAACA,CAACA,CAACA;oBAC3DA,gBAAgBA,CAACA,OAAOA,CAACA,EAAEA,QAAQA,EAAEA,QAAQA,EAAEA,IAAIA,EAAEA,IAAIA,EAAEA,CAACA,CAACA;gBACjEA,CAACA;gBAACA,IAAIA,CAACA,CAACA;oBACJA,gBAAgBA,CAACA,MAAMA,CAACA,EAAEA,QAAQA,EAAEA,QAAQA,EAAEA,IAAIA,EAAEA,IAAIA,EAAEA,CAACA,CAACA;gBAChEA,CAACA;YACLA,CAACA;QACLA,CAACA,CAACA,CAACA;QACHA,MAAMA,CAACA,gBAAgBA,CAACA,OAAOA,CAACA;IACpCA,CAACA;IAKML,+BAAYA,GAAnBA;QACIM,IAAMA,YAAYA,GAAGA,IAAIA,CAACA,QAAQA,GAAGA,kBAAkBA,CAACA;QACxDA,IAAIA,eAAeA,GAAQA,EAAEA,CAACA;QAC9BA,IAAIA,YAAYA,GAAQA,IAAIA,CAACA,SAASA,CAACA,EAAEA,EAAEA,IAAIA,CAACA,cAAcA,CAACA,CAACA;QAChEA,IAAIA,UAAUA,GAAQA,EAAEA,CAACA;QAGzBA,IAAIA,WAAWA,GAAGA,KAAKA,CAACA;QAExBA,IAAIA,gBAAgBA,GAAGA,OAAOA,CAACA,KAAKA,EAAyEA,CAACA;QAC9GA,IAAIA,cAAcA,GAAoBA;YAClCA,MAAMA,EAAEA,KAAKA;YACbA,EAAEA,EAAEA,eAAeA;YACnBA,OAAOA,EAAEA,YAAYA;YACrBA,GAAGA,EAAEA,YAAYA;YACjBA,IAAIA,EAAEA,IAAIA;SACbA,CAACA;QAEFA,IAAIA,CAACA,eAAeA,CAACA,OAAOA,CAACA,cAAcA,CAACA,cAAcA,CAACA,CAACA;QAE5DA,IAAIA,CAACA,eAAeA,CAACA,OAAOA,CAACA,cAAcA,CAACA,cAAcA,CAACA,CAACA;QAE5DA,EAAEA,CAACA,CAACA,MAAMA,CAACA,IAAIA,CAACA,UAAUA,CAACA,CAACA,MAAMA,CAACA,CAACA,CAACA;YACjCA,EAAEA,CAACA,CAACA,WAAWA,CAACA,CAACA,CAACA;gBACRA,cAAeA,CAACA,QAAQA,GAAGA,UAAUA,CAACA;YAChDA,CAACA;YAACA,IAAIA,CAACA,CAACA;gBACJA,cAAcA,CAACA,IAAIA,GAAGA,UAAUA,CAACA;YACrCA,CAACA;QACLA,CAACA;QACDA,OAAOA,CAACA,cAAcA,EAAEA,UAACA,KAAKA,EAAEA,QAAQA,EAAEA,IAAIA;YAC1CA,EAAEA,CAACA,CAACA,KAAKA,CAACA,CAACA,CAACA;gBACRA,gBAAgBA,CAACA,MAAMA,CAACA,KAAKA,CAACA,CAACA;YACnCA,CAACA;YAACA,IAAIA,CAACA,CAACA;gBACJA,EAAEA,CAACA,CAACA,QAAQA,CAACA,UAAUA,IAAIA,GAAGA,IAAIA,QAAQA,CAACA,UAAUA,IAAIA,GAAGA,CAACA,CAACA,CAACA;oBAC3DA,gBAAgBA,CAACA,OAAOA,CAACA,EAAEA,QAAQA,EAAEA,QAAQA,EAAEA,IAAIA,EAAEA,IAAIA,EAAEA,CAACA,CAACA;gBACjEA,CAACA;gBAACA,IAAIA,CAACA,CAACA;oBACJA,gBAAgBA,CAACA,MAAMA,CAACA,EAAEA,QAAQA,EAAEA,QAAQA,EAAEA,IAAIA,EAAEA,IAAIA,EAAEA,CAACA,CAACA;gBAChEA,CAACA;YACLA,CAACA;QACLA,CAACA,CAACA,CAACA;QACHA,MAAMA,CAACA,gBAAgBA,CAACA,OAAOA,CAACA;IACpCA,CAACA;IAMMN,+BAAYA,GAAnBA,UAAqBA,OAAeA;QAChCO,IAAMA,YAAYA,GAAGA,IAAIA,CAACA,QAAQA,GAAGA,wBAAwBA;aACxDA,OAAOA,CAACA,GAAGA,GAAGA,SAASA,GAAGA,GAAGA,EAAEA,MAAMA,CAACA,OAAOA,CAACA,CAACA,CAACA;QACrDA,IAAIA,eAAeA,GAAQA,EAAEA,CAACA;QAC9BA,IAAIA,YAAYA,GAAQA,IAAIA,CAACA,SAASA,CAACA,EAAEA,EAAEA,IAAIA,CAACA,cAAcA,CAACA,CAACA;QAChEA,IAAIA,UAAUA,GAAQA,EAAEA,CAACA;QAIzBA,EAAEA,CAACA,CAACA,OAAOA,KAAKA,IAAIA,IAAIA,OAAOA,KAAKA,SAASA,CAACA,CAACA,CAACA;YAC5CA,MAAMA,IAAIA,KAAKA,CAACA,6EAA6EA,CAACA,CAACA;QACnGA,CAACA;QAEDA,IAAIA,WAAWA,GAAGA,KAAKA,CAACA;QAExBA,IAAIA,gBAAgBA,GAAGA,OAAOA,CAACA,KAAKA,EAAoDA,CAACA;QACzFA,IAAIA,cAAcA,GAAoBA;YAClCA,MAAMA,EAAEA,KAAKA;YACbA,EAAEA,EAAEA,eAAeA;YACnBA,OAAOA,EAAEA,YAAYA;YACrBA,GAAGA,EAAEA,YAAYA;YACjBA,IAAIA,EAAEA,IAAIA;SACbA,CAACA;QAEFA,IAAIA,CAACA,eAAeA,CAACA,OAAOA,CAACA,cAAcA,CAACA,cAAcA,CAACA,CAACA;QAE5DA,EAAEA,CAACA,CAACA,MAAMA,CAACA,IAAIA,CAACA,UAAUA,CAACA,CAACA,MAAMA,CAACA,CAACA,CAACA;YACjCA,EAAEA,CAACA,CAACA,WAAWA,CAACA,CAACA,CAACA;gBACRA,cAAeA,CAACA,QAAQA,GAAGA,UAAUA,CAACA;YAChDA,CAACA;YAACA,IAAIA,CAACA,CAACA;gBACJA,cAAcA,CAACA,IAAIA,GAAGA,UAAUA,CAACA;YACrCA,CAACA;QACLA,CAACA;QACDA,OAAOA,CAACA,cAAcA,EAAEA,UAACA,KAAKA,EAAEA,QAAQA,EAAEA,IAAIA;YAC1CA,EAAEA,CAACA,CAACA,KAAKA,CAACA,CAACA,CAACA;gBACRA,gBAAgBA,CAACA,MAAMA,CAACA,KAAKA,CAACA,CAACA;YACnCA,CAACA;YAACA,IAAIA,CAACA,CAACA;gBACJA,EAAEA,CAACA,CAACA,QAAQA,CAACA,UAAUA,IAAIA,GAAGA,IAAIA,QAAQA,CAACA,UAAUA,IAAIA,GAAGA,CAACA,CAACA,CAACA;oBAC3DA,gBAAgBA,CAACA,OAAOA,CAACA,EAAEA,QAAQA,EAAEA,QAAQA,EAAEA,IAAIA,EAAEA,IAAIA,EAAEA,CAACA,CAACA;gBACjEA,CAACA;gBAACA,IAAIA,CAACA,CAACA;oBACJA,gBAAgBA,CAACA,MAAMA,CAACA,EAAEA,QAAQA,EAAEA,QAAQA,EAAEA,IAAIA,EAAEA,IAAIA,EAAEA,CAACA,CAACA;gBAChEA,CAACA;YACLA,CAACA;QACLA,CAACA,CAACA,CAACA;QACHA,MAAMA,CAACA,gBAAgBA,CAACA,OAAOA,CAACA;IACpCA,CAACA;IAMMP,6BAAUA,GAAjBA,UAAmBA,IAAYA;QAC3BQ,IAAMA,YAAYA,GAAGA,IAAIA,CAACA,QAAQA,GAAGA,cAAcA,CAACA;QACpDA,IAAIA,eAAeA,GAAQA,EAAEA,CAACA;QAC9BA,IAAIA,YAAYA,GAAQA,IAAIA,CAACA,SAASA,CAACA,EAAEA,EAAEA,IAAIA,CAACA,cAAcA,CAACA,CAACA;QAChEA,IAAIA,UAAUA,GAAQA,EAAEA,CAACA;QAGzBA,IAAIA,WAAWA,GAAGA,KAAKA,CAACA;QAExBA,IAAIA,gBAAgBA,GAAGA,OAAOA,CAACA,KAAKA,EAAoDA,CAACA;QACzFA,IAAIA,cAAcA,GAAoBA;YAClCA,MAAMA,EAAEA,MAAMA;YACdA,EAAEA,EAAEA,eAAeA;YACnBA,OAAOA,EAAEA,YAAYA;YACrBA,GAAGA,EAAEA,YAAYA;YACjBA,IAAIA,EAAEA,IAAIA;YACVA,IAAIA,EAAEA,IAAIA;SACbA,CAACA;QAEFA,IAAIA,CAACA,eAAeA,CAACA,OAAOA,CAACA,cAAcA,CAACA,cAAcA,CAACA,CAACA;QAE5DA,EAAEA,CAACA,CAACA,MAAMA,CAACA,IAAIA,CAACA,UAAUA,CAACA,CAACA,MAAMA,CAACA,CAACA,CAACA;YACjCA,EAAEA,CAACA,CAACA,WAAWA,CAACA,CAACA,CAACA;gBACRA,cAAeA,CAACA,QAAQA,GAAGA,UAAUA,CAACA;YAChDA,CAACA;YAACA,IAAIA,CAACA,CAACA;gBACJA,cAAcA,CAACA,IAAIA,GAAGA,UAAUA,CAACA;YACrCA,CAACA;QACLA,CAACA;QACDA,OAAOA,CAACA,cAAcA,EAAEA,UAACA,KAAKA,EAAEA,QAAQA,EAAEA,IAAIA;YAC1CA,EAAEA,CAACA,CAACA,KAAKA,CAACA,CAACA,CAACA;gBACRA,gBAAgBA,CAACA,MAAMA,CAACA,KAAKA,CAACA,CAACA;YACnCA,CAACA;YAACA,IAAIA,CAACA,CAACA;gBACJA,EAAEA,CAACA,CAACA,QAAQA,CAACA,UAAUA,IAAIA,GAAGA,IAAIA,QAAQA,CAACA,UAAUA,IAAIA,GAAGA,CAACA,CAACA,CAACA;oBAC3DA,gBAAgBA,CAACA,OAAOA,CAACA,EAAEA,QAAQA,EAAEA,QAAQA,EAAEA,IAAIA,EAAEA,IAAIA,EAAEA,CAACA,CAACA;gBACjEA,CAACA;gBAACA,IAAIA,CAACA,CAACA;oBACJA,gBAAgBA,CAACA,MAAMA,CAACA,EAAEA,QAAQA,EAAEA,QAAQA,EAAEA,IAAIA,EAAEA,IAAIA,EAAEA,CAACA,CAACA;gBAChEA,CAACA;YACLA,CAACA;QACLA,CAACA,CAACA,CAACA;QACHA,MAAMA,CAACA,gBAAgBA,CAACA,OAAOA,CAACA;IACpCA,CAACA;IACLR,eAACA;AAADA,CAACA,AAxOD,IAwOC;AAxOY,gBAAQ,WAwOpB,CAAA;AACD,WAAY,cAAc;IACtBS,yDAAOA,CAAAA;AACXA,CAACA,EAFW,sBAAc,KAAd,sBAAc,QAEzB;AAFD,IAAY,cAAc,GAAd,sBAEX,CAAA;AAED;IAWIC,iBAAYA,kBAA0BA,EAAEA,QAAiBA,EAAEA,QAAiBA;QAVlEC,aAAQA,GAAGA,eAAeA,CAACA;QAC3BA,mBAAcA,GAASA,EAAEA,CAACA;QAE1BA,oBAAeA,GAAGA;YACxBA,SAASA,EAAkBA,IAAIA,QAAQA,EAAEA;YACzCA,SAASA,EAAEA,IAAIA,UAAUA,CAACA,QAAQA,EAAEA,SAASA,CAACA;YAC9CA,eAAeA,EAAEA,IAAIA,KAAKA,EAAEA;SAC/BA,CAAAA;QAIGA,EAAEA,CAACA,CAACA,QAAQA,CAACA,CAACA,CAACA;YACXA,EAAEA,CAACA,CAACA,QAAQA,CAACA,CAACA,CAACA;gBACXA,IAAIA,CAACA,QAAQA,GAAGA,QAAQA,CAACA;YAC7BA,CAACA;QACLA,CAACA;QAACA,IAAIA,CAACA,CAACA;YACJA,EAAEA,CAACA,CAACA,kBAAkBA,CAACA,CAACA,CAACA;gBACrBA,IAAIA,CAACA,QAAQA,GAAGA,kBAAkBA,CAAAA;YACtCA,CAACA;QACLA,CAACA;IACLA,CAACA;IAEMD,2BAASA,GAAhBA,UAAiBA,GAAmBA,EAAEA,KAAaA;QAC/CE,IAAIA,CAACA,eAAeA,CAACA,cAAcA,CAACA,GAAGA,CAACA,CAACA,CAACA,MAAMA,GAAGA,KAAKA,CAACA;IAC7DA,CAACA;IAEDF,sBAAIA,gCAAWA;aAAfA,UAAgBA,KAAaA;YACzBG,IAAIA,CAACA,eAAeA,CAACA,aAAaA,CAACA,WAAWA,GAAGA,KAAKA,CAACA;QAC3DA,CAACA;;;OAAAH;IACOA,2BAASA,GAAjBA,UAAyBA,IAAQA,EAAEA,IAAQA;QACvCI,GAAGA,CAAAA,CAACA,GAAGA,CAACA,GAAGA,IAAIA,IAAIA,CAACA,CAAAA,CAACA;YACjBA,EAAEA,CAAAA,CAACA,IAAIA,CAACA,cAAcA,CAACA,GAAGA,CAACA,CAACA,CAAAA,CAACA;gBACzBA,IAAIA,CAACA,GAAGA,CAACA,GAAGA,IAAIA,CAACA,GAAGA,CAACA,CAACA;YAC1BA,CAACA;QACLA,CAACA;QACDA,MAAMA,CAAQA,IAAIA,CAACA;IACvBA,CAACA;IAMMJ,4BAAUA,GAAjBA,UAAmBA,IAAWA;QAC1BK,IAAMA,YAAYA,GAAGA,IAAIA,CAACA,QAAQA,GAAGA,OAAOA,CAACA;QAC7CA,IAAIA,eAAeA,GAAQA,EAAEA,CAACA;QAC9BA,IAAIA,YAAYA,GAAQA,IAAIA,CAACA,SAASA,CAACA,EAAEA,EAAEA,IAAIA,CAACA,cAAcA,CAACA,CAACA;QAChEA,IAAIA,UAAUA,GAAQA,EAAEA,CAACA;QAGzBA,IAAIA,WAAWA,GAAGA,KAAKA,CAACA;QAExBA,IAAIA,gBAAgBA,GAAGA,OAAOA,CAACA,KAAKA,EAAmDA,CAACA;QACxFA,IAAIA,cAAcA,GAAoBA;YAClCA,MAAMA,EAAEA,MAAMA;YACdA,EAAEA,EAAEA,eAAeA;YACnBA,OAAOA,EAAEA,YAAYA;YACrBA,GAAGA,EAAEA,YAAYA;YACjBA,IAAIA,EAAEA,IAAIA;YACVA,IAAIA,EAAEA,IAAIA;SACbA,CAACA;QAEFA,IAAIA,CAACA,eAAeA,CAACA,OAAOA,CAACA,cAAcA,CAACA,cAAcA,CAACA,CAACA;QAE5DA,EAAEA,CAACA,CAACA,MAAMA,CAACA,IAAIA,CAACA,UAAUA,CAACA,CAACA,MAAMA,CAACA,CAACA,CAACA;YACjCA,EAAEA,CAACA,CAACA,WAAWA,CAACA,CAACA,CAACA;gBACRA,cAAeA,CAACA,QAAQA,GAAGA,UAAUA,CAACA;YAChDA,CAACA;YAACA,IAAIA,CAACA,CAACA;gBACJA,cAAcA,CAACA,IAAIA,GAAGA,UAAUA,CAACA;YACrCA,CAACA;QACLA,CAACA;QACDA,OAAOA,CAACA,cAAcA,EAAEA,UAACA,KAAKA,EAAEA,QAAQA,EAAEA,IAAIA;YAC1CA,EAAEA,CAACA,CAACA,KAAKA,CAACA,CAACA,CAACA;gBACRA,gBAAgBA,CAACA,MAAMA,CAACA,KAAKA,CAACA,CAACA;YACnCA,CAACA;YAACA,IAAIA,CAACA,CAACA;gBACJA,EAAEA,CAACA,CAACA,QAAQA,CAACA,UAAUA,IAAIA,GAAGA,IAAIA,QAAQA,CAACA,UAAUA,IAAIA,GAAGA,CAACA,CAACA,CAACA;oBAC3DA,gBAAgBA,CAACA,OAAOA,CAACA,EAAEA,QAAQA,EAAEA,QAAQA,EAAEA,IAAIA,EAAEA,IAAIA,EAAEA,CAACA,CAACA;gBACjEA,CAACA;gBAACA,IAAIA,CAACA,CAACA;oBACJA,gBAAgBA,CAACA,MAAMA,CAACA,EAAEA,QAAQA,EAAEA,QAAQA,EAAEA,IAAIA,EAAEA,IAAIA,EAAEA,CAACA,CAACA;gBAChEA,CAACA;YACLA,CAACA;QACLA,CAACA,CAACA,CAACA;QACHA,MAAMA,CAACA,gBAAgBA,CAACA,OAAOA,CAACA;IACpCA,CAACA;IAMML,2CAAyBA,GAAhCA,UAAkCA,IAAkBA;QAChDM,IAAMA,YAAYA,GAAGA,IAAIA,CAACA,QAAQA,GAAGA,uBAAuBA,CAACA;QAC7DA,IAAIA,eAAeA,GAAQA,EAAEA,CAACA;QAC9BA,IAAIA,YAAYA,GAAQA,IAAIA,CAACA,SAASA,CAACA,EAAEA,EAAEA,IAAIA,CAACA,cAAcA,CAACA,CAACA;QAChEA,IAAIA,UAAUA,GAAQA,EAAEA,CAACA;QAGzBA,IAAIA,WAAWA,GAAGA,KAAKA,CAACA;QAExBA,IAAIA,gBAAgBA,GAAGA,OAAOA,CAACA,KAAKA,EAAmDA,CAACA;QACxFA,IAAIA,cAAcA,GAAoBA;YAClCA,MAAMA,EAAEA,MAAMA;YACdA,EAAEA,EAAEA,eAAeA;YACnBA,OAAOA,EAAEA,YAAYA;YACrBA,GAAGA,EAAEA,YAAYA;YACjBA,IAAIA,EAAEA,IAAIA;YACVA,IAAIA,EAAEA,IAAIA;SACbA,CAACA;QAEFA,IAAIA,CAACA,eAAeA,CAACA,OAAOA,CAACA,cAAcA,CAACA,cAAcA,CAACA,CAACA;QAE5DA,EAAEA,CAACA,CAACA,MAAMA,CAACA,IAAIA,CAACA,UAAUA,CAACA,CAACA,MAAMA,CAACA,CAACA,CAACA;YACjCA,EAAEA,CAACA,CAACA,WAAWA,CAACA,CAACA,CAACA;gBACRA,cAAeA,CAACA,QAAQA,GAAGA,UAAUA,CAACA;YAChDA,CAACA;YAACA,IAAIA,CAACA,CAACA;gBACJA,cAAcA,CAACA,IAAIA,GAAGA,UAAUA,CAACA;YACrCA,CAACA;QACLA,CAACA;QACDA,OAAOA,CAACA,cAAcA,EAAEA,UAACA,KAAKA,EAAEA,QAAQA,EAAEA,IAAIA;YAC1CA,EAAEA,CAACA,CAACA,KAAKA,CAACA,CAACA,CAACA;gBACRA,gBAAgBA,CAACA,MAAMA,CAACA,KAAKA,CAACA,CAACA;YACnCA,CAACA;YAACA,IAAIA,CAACA,CAACA;gBACJA,EAAEA,CAACA,CAACA,QAAQA,CAACA,UAAUA,IAAIA,GAAGA,IAAIA,QAAQA,CAACA,UAAUA,IAAIA,GAAGA,CAACA,CAACA,CAACA;oBAC3DA,gBAAgBA,CAACA,OAAOA,CAACA,EAAEA,QAAQA,EAAEA,QAAQA,EAAEA,IAAIA,EAAEA,IAAIA,EAAEA,CAACA,CAACA;gBACjEA,CAACA;gBAACA,IAAIA,CAACA,CAACA;oBACJA,gBAAgBA,CAACA,MAAMA,CAACA,EAAEA,QAAQA,EAAEA,QAAQA,EAAEA,IAAIA,EAAEA,IAAIA,EAAEA,CAACA,CAACA;gBAChEA,CAACA;YACLA,CAACA;QACLA,CAACA,CAACA,CAACA;QACHA,MAAMA,CAACA,gBAAgBA,CAACA,OAAOA,CAACA;IACpCA,CAACA;IAMMN,0CAAwBA,GAA/BA,UAAiCA,IAAkBA;QAC/CO,IAAMA,YAAYA,GAAGA,IAAIA,CAACA,QAAQA,GAAGA,sBAAsBA,CAACA;QAC5DA,IAAIA,eAAeA,GAAQA,EAAEA,CAACA;QAC9BA,IAAIA,YAAYA,GAAQA,IAAIA,CAACA,SAASA,CAACA,EAAEA,EAAEA,IAAIA,CAACA,cAAcA,CAACA,CAACA;QAChEA,IAAIA,UAAUA,GAAQA,EAAEA,CAACA;QAGzBA,IAAIA,WAAWA,GAAGA,KAAKA,CAACA;QAExBA,IAAIA,gBAAgBA,GAAGA,OAAOA,CAACA,KAAKA,EAAmDA,CAACA;QACxFA,IAAIA,cAAcA,GAAoBA;YAClCA,MAAMA,EAAEA,MAAMA;YACdA,EAAEA,EAAEA,eAAeA;YACnBA,OAAOA,EAAEA,YAAYA;YACrBA,GAAGA,EAAEA,YAAYA;YACjBA,IAAIA,EAAEA,IAAIA;YACVA,IAAIA,EAAEA,IAAIA;SACbA,CAACA;QAEFA,IAAIA,CAACA,eAAeA,CAACA,OAAOA,CAACA,cAAcA,CAACA,cAAcA,CAACA,CAACA;QAE5DA,EAAEA,CAACA,CAACA,MAAMA,CAACA,IAAIA,CAACA,UAAUA,CAACA,CAACA,MAAMA,CAACA,CAACA,CAACA;YACjCA,EAAEA,CAACA,CAACA,WAAWA,CAACA,CAACA,CAACA;gBACRA,cAAeA,CAACA,QAAQA,GAAGA,UAAUA,CAACA;YAChDA,CAACA;YAACA,IAAIA,CAACA,CAACA;gBACJA,cAAcA,CAACA,IAAIA,GAAGA,UAAUA,CAACA;YACrCA,CAACA;QACLA,CAACA;QACDA,OAAOA,CAACA,cAAcA,EAAEA,UAACA,KAAKA,EAAEA,QAAQA,EAAEA,IAAIA;YAC1CA,EAAEA,CAACA,CAACA,KAAKA,CAACA,CAACA,CAACA;gBACRA,gBAAgBA,CAACA,MAAMA,CAACA,KAAKA,CAACA,CAACA;YACnCA,CAACA;YAACA,IAAIA,CAACA,CAACA;gBACJA,EAAEA,CAACA,CAACA,QAAQA,CAACA,UAAUA,IAAIA,GAAGA,IAAIA,QAAQA,CAACA,UAAUA,IAAIA,GAAGA,CAACA,CAACA,CAACA;oBAC3DA,gBAAgBA,CAACA,OAAOA,CAACA,EAAEA,QAAQA,EAAEA,QAAQA,EAAEA,IAAIA,EAAEA,IAAIA,EAAEA,CAACA,CAACA;gBACjEA,CAACA;gBAACA,IAAIA,CAACA,CAACA;oBACJA,gBAAgBA,CAACA,MAAMA,CAACA,EAAEA,QAAQA,EAAEA,QAAQA,EAAEA,IAAIA,EAAEA,IAAIA,EAAEA,CAACA,CAACA;gBAChEA,CAACA;YACLA,CAACA;QACLA,CAACA,CAACA,CAACA;QACHA,MAAMA,CAACA,gBAAgBA,CAACA,OAAOA,CAACA;IACpCA,CAACA;IAMMP,4BAAUA,GAAjBA,UAAmBA,QAAgBA;QAC/BQ,IAAMA,YAAYA,GAAGA,IAAIA,CAACA,QAAQA,GAAGA,kBAAkBA;aAClDA,OAAOA,CAACA,GAAGA,GAAGA,UAAUA,GAAGA,GAAGA,EAAEA,MAAMA,CAACA,QAAQA,CAACA,CAACA,CAACA;QACvDA,IAAIA,eAAeA,GAAQA,EAAEA,CAACA;QAC9BA,IAAIA,YAAYA,GAAQA,IAAIA,CAACA,SAASA,CAACA,EAAEA,EAAEA,IAAIA,CAACA,cAAcA,CAACA,CAACA;QAChEA,IAAIA,UAAUA,GAAQA,EAAEA,CAACA;QAIzBA,EAAEA,CAACA,CAACA,QAAQA,KAAKA,IAAIA,IAAIA,QAAQA,KAAKA,SAASA,CAACA,CAACA,CAACA;YAC9CA,MAAMA,IAAIA,KAAKA,CAACA,4EAA4EA,CAACA,CAACA;QAClGA,CAACA;QAEDA,IAAIA,WAAWA,GAAGA,KAAKA,CAACA;QAExBA,IAAIA,gBAAgBA,GAAGA,OAAOA,CAACA,KAAKA,EAAmDA,CAACA;QACxFA,IAAIA,cAAcA,GAAoBA;YAClCA,MAAMA,EAAEA,QAAQA;YAChBA,EAAEA,EAAEA,eAAeA;YACnBA,OAAOA,EAAEA,YAAYA;YACrBA,GAAGA,EAAEA,YAAYA;YACjBA,IAAIA,EAAEA,IAAIA;SACbA,CAACA;QAEFA,IAAIA,CAACA,eAAeA,CAACA,OAAOA,CAACA,cAAcA,CAACA,cAAcA,CAACA,CAACA;QAE5DA,EAAEA,CAACA,CAACA,MAAMA,CAACA,IAAIA,CAACA,UAAUA,CAACA,CAACA,MAAMA,CAACA,CAACA,CAACA;YACjCA,EAAEA,CAACA,CAACA,WAAWA,CAACA,CAACA,CAACA;gBACRA,cAAeA,CAACA,QAAQA,GAAGA,UAAUA,CAACA;YAChDA,CAACA;YAACA,IAAIA,CAACA,CAACA;gBACJA,cAAcA,CAACA,IAAIA,GAAGA,UAAUA,CAACA;YACrCA,CAACA;QACLA,CAACA;QACDA,OAAOA,CAACA,cAAcA,EAAEA,UAACA,KAAKA,EAAEA,QAAQA,EAAEA,IAAIA;YAC1CA,EAAEA,CAACA,CAACA,KAAKA,CAACA,CAACA,CAACA;gBACRA,gBAAgBA,CAACA,MAAMA,CAACA,KAAKA,CAACA,CAACA;YACnCA,CAACA;YAACA,IAAIA,CAACA,CAACA;gBACJA,EAAEA,CAACA,CAACA,QAAQA,CAACA,UAAUA,IAAIA,GAAGA,IAAIA,QAAQA,CAACA,UAAUA,IAAIA,GAAGA,CAACA,CAACA,CAACA;oBAC3DA,gBAAgBA,CAACA,OAAOA,CAACA,EAAEA,QAAQA,EAAEA,QAAQA,EAAEA,IAAIA,EAAEA,IAAIA,EAAEA,CAACA,CAACA;gBACjEA,CAACA;gBAACA,IAAIA,CAACA,CAACA;oBACJA,gBAAgBA,CAACA,MAAMA,CAACA,EAAEA,QAAQA,EAAEA,QAAQA,EAAEA,IAAIA,EAAEA,IAAIA,EAAEA,CAACA,CAACA;gBAChEA,CAACA;YACLA,CAACA;QACLA,CAACA,CAACA,CAACA;QACHA,MAAMA,CAACA,gBAAgBA,CAACA,OAAOA,CAACA;IACpCA,CAACA;IAMMR,+BAAaA,GAApBA,UAAsBA,QAAgBA;QAClCS,IAAMA,YAAYA,GAAGA,IAAIA,CAACA,QAAQA,GAAGA,kBAAkBA;aAClDA,OAAOA,CAACA,GAAGA,GAAGA,UAAUA,GAAGA,GAAGA,EAAEA,MAAMA,CAACA,QAAQA,CAACA,CAACA,CAACA;QACvDA,IAAIA,eAAeA,GAAQA,EAAEA,CAACA;QAC9BA,IAAIA,YAAYA,GAAQA,IAAIA,CAACA,SAASA,CAACA,EAAEA,EAAEA,IAAIA,CAACA,cAAcA,CAACA,CAACA;QAChEA,IAAIA,UAAUA,GAAQA,EAAEA,CAACA;QAIzBA,EAAEA,CAACA,CAACA,QAAQA,KAAKA,IAAIA,IAAIA,QAAQA,KAAKA,SAASA,CAACA,CAACA,CAACA;YAC9CA,MAAMA,IAAIA,KAAKA,CAACA,+EAA+EA,CAACA,CAACA;QACrGA,CAACA;QAEDA,IAAIA,WAAWA,GAAGA,KAAKA,CAACA;QAExBA,IAAIA,gBAAgBA,GAAGA,OAAOA,CAACA,KAAKA,EAAmDA,CAACA;QACxFA,IAAIA,cAAcA,GAAoBA;YAClCA,MAAMA,EAAEA,KAAKA;YACbA,EAAEA,EAAEA,eAAeA;YACnBA,OAAOA,EAAEA,YAAYA;YACrBA,GAAGA,EAAEA,YAAYA;YACjBA,IAAIA,EAAEA,IAAIA;SACbA,CAACA;QAEFA,IAAIA,CAACA,eAAeA,CAACA,OAAOA,CAACA,cAAcA,CAACA,cAAcA,CAACA,CAACA;QAE5DA,EAAEA,CAACA,CAACA,MAAMA,CAACA,IAAIA,CAACA,UAAUA,CAACA,CAACA,MAAMA,CAACA,CAACA,CAACA;YACjCA,EAAEA,CAACA,CAACA,WAAWA,CAACA,CAACA,CAACA;gBACRA,cAAeA,CAACA,QAAQA,GAAGA,UAAUA,CAACA;YAChDA,CAACA;YAACA,IAAIA,CAACA,CAACA;gBACJA,cAAcA,CAACA,IAAIA,GAAGA,UAAUA,CAACA;YACrCA,CAACA;QACLA,CAACA;QACDA,OAAOA,CAACA,cAAcA,EAAEA,UAACA,KAAKA,EAAEA,QAAQA,EAAEA,IAAIA;YAC1CA,EAAEA,CAACA,CAACA,KAAKA,CAACA,CAACA,CAACA;gBACRA,gBAAgBA,CAACA,MAAMA,CAACA,KAAKA,CAACA,CAACA;YACnCA,CAACA;YAACA,IAAIA,CAACA,CAACA;gBACJA,EAAEA,CAACA,CAACA,QAAQA,CAACA,UAAUA,IAAIA,GAAGA,IAAIA,QAAQA,CAACA,UAAUA,IAAIA,GAAGA,CAACA,CAACA,CAACA;oBAC3DA,gBAAgBA,CAACA,OAAOA,CAACA,EAAEA,QAAQA,EAAEA,QAAQA,EAAEA,IAAIA,EAAEA,IAAIA,EAAEA,CAACA,CAACA;gBACjEA,CAACA;gBAACA,IAAIA,CAACA,CAACA;oBACJA,gBAAgBA,CAACA,MAAMA,CAACA,EAAEA,QAAQA,EAAEA,QAAQA,EAAEA,IAAIA,EAAEA,IAAIA,EAAEA,CAACA,CAACA;gBAChEA,CAACA;YACLA,CAACA;QACLA,CAACA,CAACA,CAACA;QACHA,MAAMA,CAACA,gBAAgBA,CAACA,OAAOA,CAACA;IACpCA,CAACA;IAOMT,2BAASA,GAAhBA,UAAkBA,QAAiBA,EAAEA,QAAiBA;QAClDU,IAAMA,YAAYA,GAAGA,IAAIA,CAACA,QAAQA,GAAGA,aAAaA,CAACA;QACnDA,IAAIA,eAAeA,GAAQA,EAAEA,CAACA;QAC9BA,IAAIA,YAAYA,GAAQA,IAAIA,CAACA,SAASA,CAACA,EAAEA,EAAEA,IAAIA,CAACA,cAAcA,CAACA,CAACA;QAChEA,IAAIA,UAAUA,GAAQA,EAAEA,CAACA;QAGzBA,EAAEA,CAACA,CAACA,QAAQA,KAAKA,SAASA,CAACA,CAACA,CAACA;YACzBA,eAAeA,CAACA,UAAUA,CAACA,GAAGA,QAAQA,CAACA;QAC3CA,CAACA;QAEDA,EAAEA,CAACA,CAACA,QAAQA,KAAKA,SAASA,CAACA,CAACA,CAACA;YACzBA,eAAeA,CAACA,UAAUA,CAACA,GAAGA,QAAQA,CAACA;QAC3CA,CAACA;QAEDA,IAAIA,WAAWA,GAAGA,KAAKA,CAACA;QAExBA,IAAIA,gBAAgBA,GAAGA,OAAOA,CAACA,KAAKA,EAAqDA,CAACA;QAC1FA,IAAIA,cAAcA,GAAoBA;YAClCA,MAAMA,EAAEA,KAAKA;YACbA,EAAEA,EAAEA,eAAeA;YACnBA,OAAOA,EAAEA,YAAYA;YACrBA,GAAGA,EAAEA,YAAYA;YACjBA,IAAIA,EAAEA,IAAIA;SACbA,CAACA;QAEFA,IAAIA,CAACA,eAAeA,CAACA,OAAOA,CAACA,cAAcA,CAACA,cAAcA,CAACA,CAACA;QAE5DA,EAAEA,CAACA,CAACA,MAAMA,CAACA,IAAIA,CAACA,UAAUA,CAACA,CAACA,MAAMA,CAACA,CAACA,CAACA;YACjCA,EAAEA,CAACA,CAACA,WAAWA,CAACA,CAACA,CAACA;gBACRA,cAAeA,CAACA,QAAQA,GAAGA,UAAUA,CAACA;YAChDA,CAACA;YAACA,IAAIA,CAACA,CAACA;gBACJA,cAAcA,CAACA,IAAIA,GAAGA,UAAUA,CAACA;YACrCA,CAACA;QACLA,CAACA;QACDA,OAAOA,CAACA,cAAcA,EAAEA,UAACA,KAAKA,EAAEA,QAAQA,EAAEA,IAAIA;YAC1CA,EAAEA,CAACA,CAACA,KAAKA,CAACA,CAACA,CAACA;gBACRA,gBAAgBA,CAACA,MAAMA,CAACA,KAAKA,CAACA,CAACA;YACnCA,CAACA;YAACA,IAAIA,CAACA,CAACA;gBACJA,EAAEA,CAACA,CAACA,QAAQA,CAACA,UAAUA,IAAIA,GAAGA,IAAIA,QAAQA,CAACA,UAAUA,IAAIA,GAAGA,CAACA,CAACA,CAACA;oBAC3DA,gBAAgBA,CAACA,OAAOA,CAACA,EAAEA,QAAQA,EAAEA,QAAQA,EAAEA,IAAIA,EAAEA,IAAIA,EAAEA,CAACA,CAACA;gBACjEA,CAACA;gBAACA,IAAIA,CAACA,CAACA;oBACJA,gBAAgBA,CAACA,MAAMA,CAACA,EAAEA,QAAQA,EAAEA,QAAQA,EAAEA,IAAIA,EAAEA,IAAIA,EAAEA,CAACA,CAACA;gBAChEA,CAACA;YACLA,CAACA;QACLA,CAACA,CAACA,CAACA;QACHA,MAAMA,CAACA,gBAAgBA,CAACA,OAAOA,CAACA;IACpCA,CAACA;IAKMV,4BAAUA,GAAjBA;QACIW,IAAMA,YAAYA,GAAGA,IAAIA,CAACA,QAAQA,GAAGA,cAAcA,CAACA;QACpDA,IAAIA,eAAeA,GAAQA,EAAEA,CAACA;QAC9BA,IAAIA,YAAYA,GAAQA,IAAIA,CAACA,SAASA,CAACA,EAAEA,EAAEA,IAAIA,CAACA,cAAcA,CAACA,CAACA;QAChEA,IAAIA,UAAUA,GAAQA,EAAEA,CAACA;QAGzBA,IAAIA,WAAWA,GAAGA,KAAKA,CAACA;QAExBA,IAAIA,gBAAgBA,GAAGA,OAAOA,CAACA,KAAKA,EAAmDA,CAACA;QACxFA,IAAIA,cAAcA,GAAoBA;YAClCA,MAAMA,EAAEA,KAAKA;YACbA,EAAEA,EAAEA,eAAeA;YACnBA,OAAOA,EAAEA,YAAYA;YACrBA,GAAGA,EAAEA,YAAYA;YACjBA,IAAIA,EAAEA,IAAIA;SACbA,CAACA;QAEFA,IAAIA,CAACA,eAAeA,CAACA,OAAOA,CAACA,cAAcA,CAACA,cAAcA,CAACA,CAACA;QAE5DA,EAAEA,CAACA,CAACA,MAAMA,CAACA,IAAIA,CAACA,UAAUA,CAACA,CAACA,MAAMA,CAACA,CAACA,CAACA;YACjCA,EAAEA,CAACA,CAACA,WAAWA,CAACA,CAACA,CAACA;gBACRA,cAAeA,CAACA,QAAQA,GAAGA,UAAUA,CAACA;YAChDA,CAACA;YAACA,IAAIA,CAACA,CAACA;gBACJA,cAAcA,CAACA,IAAIA,GAAGA,UAAUA,CAACA;YACrCA,CAACA;QACLA,CAACA;QACDA,OAAOA,CAACA,cAAcA,EAAEA,UAACA,KAAKA,EAAEA,QAAQA,EAAEA,IAAIA;YAC1CA,EAAEA,CAACA,CAACA,KAAKA,CAACA,CAACA,CAACA;gBACRA,gBAAgBA,CAACA,MAAMA,CAACA,KAAKA,CAACA,CAACA;YACnCA,CAACA;YAACA,IAAIA,CAACA,CAACA;gBACJA,EAAEA,CAACA,CAACA,QAAQA,CAACA,UAAUA,IAAIA,GAAGA,IAAIA,QAAQA,CAACA,UAAUA,IAAIA,GAAGA,CAACA,CAACA,CAACA;oBAC3DA,gBAAgBA,CAACA,OAAOA,CAACA,EAAEA,QAAQA,EAAEA,QAAQA,EAAEA,IAAIA,EAAEA,IAAIA,EAAEA,CAACA,CAACA;gBACjEA,CAACA;gBAACA,IAAIA,CAACA,CAACA;oBACJA,gBAAgBA,CAACA,MAAMA,CAACA,EAAEA,QAAQA,EAAEA,QAAQA,EAAEA,IAAIA,EAAEA,IAAIA,EAAEA,CAACA,CAACA;gBAChEA,CAACA;YACLA,CAACA;QACLA,CAACA,CAACA,CAACA;QACHA,MAAMA,CAACA,gBAAgBA,CAACA,OAAOA,CAACA;IACpCA,CAACA;IAOMX,4BAAUA,GAAjBA,UAAmBA,QAAgBA,EAAEA,IAAWA;QAC5CY,IAAMA,YAAYA,GAAGA,IAAIA,CAACA,QAAQA,GAAGA,kBAAkBA;aAClDA,OAAOA,CAACA,GAAGA,GAAGA,UAAUA,GAAGA,GAAGA,EAAEA,MAAMA,CAACA,QAAQA,CAACA,CAACA,CAACA;QACvDA,IAAIA,eAAeA,GAAQA,EAAEA,CAACA;QAC9BA,IAAIA,YAAYA,GAAQA,IAAIA,CAACA,SAASA,CAACA,EAAEA,EAAEA,IAAIA,CAACA,cAAcA,CAACA,CAACA;QAChEA,IAAIA,UAAUA,GAAQA,EAAEA,CAACA;QAIzBA,EAAEA,CAACA,CAACA,QAAQA,KAAKA,IAAIA,IAAIA,QAAQA,KAAKA,SAASA,CAACA,CAACA,CAACA;YAC9CA,MAAMA,IAAIA,KAAKA,CAACA,4EAA4EA,CAACA,CAACA;QAClGA,CAACA;QAEDA,IAAIA,WAAWA,GAAGA,KAAKA,CAACA;QAExBA,IAAIA,gBAAgBA,GAAGA,OAAOA,CAACA,KAAKA,EAAmDA,CAACA;QACxFA,IAAIA,cAAcA,GAAoBA;YAClCA,MAAMA,EAAEA,KAAKA;YACbA,EAAEA,EAAEA,eAAeA;YACnBA,OAAOA,EAAEA,YAAYA;YACrBA,GAAGA,EAAEA,YAAYA;YACjBA,IAAIA,EAAEA,IAAIA;YACVA,IAAIA,EAAEA,IAAIA;SACbA,CAACA;QAEFA,IAAIA,CAACA,eAAeA,CAACA,OAAOA,CAACA,cAAcA,CAACA,cAAcA,CAACA,CAACA;QAE5DA,EAAEA,CAACA,CAACA,MAAMA,CAACA,IAAIA,CAACA,UAAUA,CAACA,CAACA,MAAMA,CAACA,CAACA,CAACA;YACjCA,EAAEA,CAACA,CAACA,WAAWA,CAACA,CAACA,CAACA;gBACRA,cAAeA,CAACA,QAAQA,GAAGA,UAAUA,CAACA;YAChDA,CAACA;YAACA,IAAIA,CAACA,CAACA;gBACJA,cAAcA,CAACA,IAAIA,GAAGA,UAAUA,CAACA;YACrCA,CAACA;QACLA,CAACA;QACDA,OAAOA,CAACA,cAAcA,EAAEA,UAACA,KAAKA,EAAEA,QAAQA,EAAEA,IAAIA;YAC1CA,EAAEA,CAACA,CAACA,KAAKA,CAACA,CAACA,CAACA;gBACRA,gBAAgBA,CAACA,MAAMA,CAACA,KAAKA,CAACA,CAACA;YACnCA,CAACA;YAACA,IAAIA,CAACA,CAACA;gBACJA,EAAEA,CAACA,CAACA,QAAQA,CAACA,UAAUA,IAAIA,GAAGA,IAAIA,QAAQA,CAACA,UAAUA,IAAIA,GAAGA,CAACA,CAACA,CAACA;oBAC3DA,gBAAgBA,CAACA,OAAOA,CAACA,EAAEA,QAAQA,EAAEA,QAAQA,EAAEA,IAAIA,EAAEA,IAAIA,EAAEA,CAACA,CAACA;gBACjEA,CAACA;gBAACA,IAAIA,CAACA,CAACA;oBACJA,gBAAgBA,CAACA,MAAMA,CAACA,EAAEA,QAAQA,EAAEA,QAAQA,EAAEA,IAAIA,EAAEA,IAAIA,EAAEA,CAACA,CAACA;gBAChEA,CAACA;YACLA,CAACA;QACLA,CAACA,CAACA,CAACA;QACHA,MAAMA,CAACA,gBAAgBA,CAACA,OAAOA,CAACA;IACpCA,CAACA;IACLZ,cAACA;AAADA,CAACA,AA7aD,IA6aC;AA7aY,eAAO,UA6anB,CAAA"} \ No newline at end of file diff --git a/samples/client/petstore/typescript-node/npm/api.ts b/samples/client/petstore/typescript-node/npm/api.ts index c2bd53e8ca2..cc9b954165b 100644 --- a/samples/client/petstore/typescript-node/npm/api.ts +++ b/samples/client/petstore/typescript-node/npm/api.ts @@ -1,6 +1,8 @@ import request = require('request'); -import promise = require('bluebird'); import http = require('http'); +import promise = require('bluebird'); + +let defaultBasePath = 'http://petstore.swagger.io/v2'; // =============================================== // This file is autogenerated - Please do not edit @@ -9,65 +11,65 @@ import http = require('http'); /* tslint:disable:no-unused-variable */ export class Category { - "id": number; - "name": string; + 'id': number; + 'name': string; } export class Order { - "id": number; - "petId": number; - "quantity": number; - "shipDate": Date; + 'id': number; + 'petId': number; + 'quantity': number; + 'shipDate': Date; /** * Order Status */ - "status": Order.StatusEnum; - "complete": boolean; + 'status': Order.StatusEnum; + 'complete': boolean; } export namespace Order { export enum StatusEnum { - placed = 'placed', - approved = 'approved', - delivered = 'delivered' + StatusEnum_placed = 'placed', + StatusEnum_approved = 'approved', + StatusEnum_delivered = 'delivered' } } export class Pet { - "id": number; - "category": Category; - "name": string; - "photoUrls": Array; - "tags": Array; + 'id': number; + 'category': Category; + 'name': string; + 'photoUrls': Array; + 'tags': Array; /** * pet status in the store */ - "status": Pet.StatusEnum; + 'status': Pet.StatusEnum; } export namespace Pet { export enum StatusEnum { - available = 'available', - pending = 'pending', - sold = 'sold' + StatusEnum_available = 'available', + StatusEnum_pending = 'pending', + StatusEnum_sold = 'sold' } } export class Tag { - "id": number; - "name": string; + 'id': number; + 'name': string; } export class User { - "id": number; - "username": string; - "firstName": string; - "lastName": string; - "email": string; - "password": string; - "phone": string; + 'id': number; + 'username': string; + 'firstName': string; + 'lastName': string; + 'email': string; + 'password': string; + 'phone': string; /** * User Status */ - "userStatus": number; + 'userStatus': number; } @@ -124,13 +126,13 @@ export enum PetApiApiKeys { } export class PetApi { - protected basePath = 'http://petstore.swagger.io/v2'; + protected basePath = defaultBasePath; protected defaultHeaders : any = {}; protected authentications = { 'default': new VoidAuth(), - 'api_key': new ApiKeyAuth('header', 'api_key'), 'petstore_auth': new OAuth(), + 'api_key': new ApiKeyAuth('header', 'api_key'), } constructor(basePath?: string); @@ -176,7 +178,6 @@ export class PetApi { let useFormData = false; let localVarDeferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); - let requestOptions: request.Options = { method: 'POST', qs: queryParameters, @@ -184,7 +185,7 @@ export class PetApi { uri: localVarPath, json: true, body: body, - } + }; this.authentications.petstore_auth.applyToRequest(requestOptions); @@ -197,7 +198,6 @@ export class PetApi { requestOptions.form = formParams; } } - request(requestOptions, (error, response, body) => { if (error) { localVarDeferred.reject(error); @@ -209,7 +209,6 @@ export class PetApi { } } }); - return localVarDeferred.promise; } /** @@ -236,14 +235,13 @@ export class PetApi { let useFormData = false; let localVarDeferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); - let requestOptions: request.Options = { method: 'DELETE', qs: queryParameters, headers: headerParams, uri: localVarPath, json: true, - } + }; this.authentications.petstore_auth.applyToRequest(requestOptions); @@ -256,7 +254,6 @@ export class PetApi { requestOptions.form = formParams; } } - request(requestOptions, (error, response, body) => { if (error) { localVarDeferred.reject(error); @@ -268,7 +265,6 @@ export class PetApi { } } }); - return localVarDeferred.promise; } /** @@ -290,14 +286,13 @@ export class PetApi { let useFormData = false; let localVarDeferred = promise.defer<{ response: http.ClientResponse; body: Array; }>(); - let requestOptions: request.Options = { method: 'GET', qs: queryParameters, headers: headerParams, uri: localVarPath, json: true, - } + }; this.authentications.petstore_auth.applyToRequest(requestOptions); @@ -310,7 +305,6 @@ export class PetApi { requestOptions.form = formParams; } } - request(requestOptions, (error, response, body) => { if (error) { localVarDeferred.reject(error); @@ -322,7 +316,6 @@ export class PetApi { } } }); - return localVarDeferred.promise; } /** @@ -344,14 +337,13 @@ export class PetApi { let useFormData = false; let localVarDeferred = promise.defer<{ response: http.ClientResponse; body: Array; }>(); - let requestOptions: request.Options = { method: 'GET', qs: queryParameters, headers: headerParams, uri: localVarPath, json: true, - } + }; this.authentications.petstore_auth.applyToRequest(requestOptions); @@ -364,7 +356,6 @@ export class PetApi { requestOptions.form = formParams; } } - request(requestOptions, (error, response, body) => { if (error) { localVarDeferred.reject(error); @@ -376,7 +367,6 @@ export class PetApi { } } }); - return localVarDeferred.promise; } /** @@ -400,19 +390,18 @@ export class PetApi { let useFormData = false; let localVarDeferred = promise.defer<{ response: http.ClientResponse; body: Pet; }>(); - let requestOptions: request.Options = { method: 'GET', qs: queryParameters, headers: headerParams, uri: localVarPath, json: true, - } - - this.authentications.api_key.applyToRequest(requestOptions); + }; this.authentications.petstore_auth.applyToRequest(requestOptions); + this.authentications.api_key.applyToRequest(requestOptions); + this.authentications.default.applyToRequest(requestOptions); if (Object.keys(formParams).length) { @@ -422,7 +411,6 @@ export class PetApi { requestOptions.form = formParams; } } - request(requestOptions, (error, response, body) => { if (error) { localVarDeferred.reject(error); @@ -434,7 +422,6 @@ export class PetApi { } } }); - return localVarDeferred.promise; } /** @@ -452,7 +439,6 @@ export class PetApi { let useFormData = false; let localVarDeferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); - let requestOptions: request.Options = { method: 'PUT', qs: queryParameters, @@ -460,7 +446,7 @@ export class PetApi { uri: localVarPath, json: true, body: body, - } + }; this.authentications.petstore_auth.applyToRequest(requestOptions); @@ -473,7 +459,6 @@ export class PetApi { requestOptions.form = formParams; } } - request(requestOptions, (error, response, body) => { if (error) { localVarDeferred.reject(error); @@ -485,7 +470,6 @@ export class PetApi { } } }); - return localVarDeferred.promise; } /** @@ -519,14 +503,13 @@ export class PetApi { } let localVarDeferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); - let requestOptions: request.Options = { method: 'POST', qs: queryParameters, headers: headerParams, uri: localVarPath, json: true, - } + }; this.authentications.petstore_auth.applyToRequest(requestOptions); @@ -539,7 +522,6 @@ export class PetApi { requestOptions.form = formParams; } } - request(requestOptions, (error, response, body) => { if (error) { localVarDeferred.reject(error); @@ -551,7 +533,6 @@ export class PetApi { } } }); - return localVarDeferred.promise; } /** @@ -586,14 +567,13 @@ export class PetApi { useFormData = true; let localVarDeferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); - let requestOptions: request.Options = { method: 'POST', qs: queryParameters, headers: headerParams, uri: localVarPath, json: true, - } + }; this.authentications.petstore_auth.applyToRequest(requestOptions); @@ -606,7 +586,6 @@ export class PetApi { requestOptions.form = formParams; } } - request(requestOptions, (error, response, body) => { if (error) { localVarDeferred.reject(error); @@ -618,7 +597,6 @@ export class PetApi { } } }); - return localVarDeferred.promise; } } @@ -627,13 +605,13 @@ export enum StoreApiApiKeys { } export class StoreApi { - protected basePath = 'http://petstore.swagger.io/v2'; + protected basePath = defaultBasePath; protected defaultHeaders : any = {}; protected authentications = { 'default': new VoidAuth(), - 'api_key': new ApiKeyAuth('header', 'api_key'), 'petstore_auth': new OAuth(), + 'api_key': new ApiKeyAuth('header', 'api_key'), } constructor(basePath?: string); @@ -685,14 +663,13 @@ export class StoreApi { let useFormData = false; let localVarDeferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); - let requestOptions: request.Options = { method: 'DELETE', qs: queryParameters, headers: headerParams, uri: localVarPath, json: true, - } + }; this.authentications.default.applyToRequest(requestOptions); @@ -703,7 +680,6 @@ export class StoreApi { requestOptions.form = formParams; } } - request(requestOptions, (error, response, body) => { if (error) { localVarDeferred.reject(error); @@ -715,7 +691,6 @@ export class StoreApi { } } }); - return localVarDeferred.promise; } /** @@ -732,14 +707,13 @@ export class StoreApi { let useFormData = false; let localVarDeferred = promise.defer<{ response: http.ClientResponse; body: { [key: string]: number; }; }>(); - let requestOptions: request.Options = { method: 'GET', qs: queryParameters, headers: headerParams, uri: localVarPath, json: true, - } + }; this.authentications.api_key.applyToRequest(requestOptions); @@ -752,7 +726,6 @@ export class StoreApi { requestOptions.form = formParams; } } - request(requestOptions, (error, response, body) => { if (error) { localVarDeferred.reject(error); @@ -764,7 +737,6 @@ export class StoreApi { } } }); - return localVarDeferred.promise; } /** @@ -788,14 +760,13 @@ export class StoreApi { let useFormData = false; let localVarDeferred = promise.defer<{ response: http.ClientResponse; body: Order; }>(); - let requestOptions: request.Options = { method: 'GET', qs: queryParameters, headers: headerParams, uri: localVarPath, json: true, - } + }; this.authentications.default.applyToRequest(requestOptions); @@ -806,7 +777,6 @@ export class StoreApi { requestOptions.form = formParams; } } - request(requestOptions, (error, response, body) => { if (error) { localVarDeferred.reject(error); @@ -818,7 +788,6 @@ export class StoreApi { } } }); - return localVarDeferred.promise; } /** @@ -836,7 +805,6 @@ export class StoreApi { let useFormData = false; let localVarDeferred = promise.defer<{ response: http.ClientResponse; body: Order; }>(); - let requestOptions: request.Options = { method: 'POST', qs: queryParameters, @@ -844,7 +812,7 @@ export class StoreApi { uri: localVarPath, json: true, body: body, - } + }; this.authentications.default.applyToRequest(requestOptions); @@ -855,7 +823,6 @@ export class StoreApi { requestOptions.form = formParams; } } - request(requestOptions, (error, response, body) => { if (error) { localVarDeferred.reject(error); @@ -867,7 +834,6 @@ export class StoreApi { } } }); - return localVarDeferred.promise; } } @@ -876,13 +842,13 @@ export enum UserApiApiKeys { } export class UserApi { - protected basePath = 'http://petstore.swagger.io/v2'; + protected basePath = defaultBasePath; protected defaultHeaders : any = {}; protected authentications = { 'default': new VoidAuth(), - 'api_key': new ApiKeyAuth('header', 'api_key'), 'petstore_auth': new OAuth(), + 'api_key': new ApiKeyAuth('header', 'api_key'), } constructor(basePath?: string); @@ -928,7 +894,6 @@ export class UserApi { let useFormData = false; let localVarDeferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); - let requestOptions: request.Options = { method: 'POST', qs: queryParameters, @@ -936,7 +901,7 @@ export class UserApi { uri: localVarPath, json: true, body: body, - } + }; this.authentications.default.applyToRequest(requestOptions); @@ -947,7 +912,6 @@ export class UserApi { requestOptions.form = formParams; } } - request(requestOptions, (error, response, body) => { if (error) { localVarDeferred.reject(error); @@ -959,7 +923,6 @@ export class UserApi { } } }); - return localVarDeferred.promise; } /** @@ -977,7 +940,6 @@ export class UserApi { let useFormData = false; let localVarDeferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); - let requestOptions: request.Options = { method: 'POST', qs: queryParameters, @@ -985,7 +947,7 @@ export class UserApi { uri: localVarPath, json: true, body: body, - } + }; this.authentications.default.applyToRequest(requestOptions); @@ -996,7 +958,6 @@ export class UserApi { requestOptions.form = formParams; } } - request(requestOptions, (error, response, body) => { if (error) { localVarDeferred.reject(error); @@ -1008,7 +969,6 @@ export class UserApi { } } }); - return localVarDeferred.promise; } /** @@ -1026,7 +986,6 @@ export class UserApi { let useFormData = false; let localVarDeferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); - let requestOptions: request.Options = { method: 'POST', qs: queryParameters, @@ -1034,7 +993,7 @@ export class UserApi { uri: localVarPath, json: true, body: body, - } + }; this.authentications.default.applyToRequest(requestOptions); @@ -1045,7 +1004,6 @@ export class UserApi { requestOptions.form = formParams; } } - request(requestOptions, (error, response, body) => { if (error) { localVarDeferred.reject(error); @@ -1057,7 +1015,6 @@ export class UserApi { } } }); - return localVarDeferred.promise; } /** @@ -1081,14 +1038,13 @@ export class UserApi { let useFormData = false; let localVarDeferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); - let requestOptions: request.Options = { method: 'DELETE', qs: queryParameters, headers: headerParams, uri: localVarPath, json: true, - } + }; this.authentications.default.applyToRequest(requestOptions); @@ -1099,7 +1055,6 @@ export class UserApi { requestOptions.form = formParams; } } - request(requestOptions, (error, response, body) => { if (error) { localVarDeferred.reject(error); @@ -1111,7 +1066,6 @@ export class UserApi { } } }); - return localVarDeferred.promise; } /** @@ -1135,14 +1089,13 @@ export class UserApi { let useFormData = false; let localVarDeferred = promise.defer<{ response: http.ClientResponse; body: User; }>(); - let requestOptions: request.Options = { method: 'GET', qs: queryParameters, headers: headerParams, uri: localVarPath, json: true, - } + }; this.authentications.default.applyToRequest(requestOptions); @@ -1153,7 +1106,6 @@ export class UserApi { requestOptions.form = formParams; } } - request(requestOptions, (error, response, body) => { if (error) { localVarDeferred.reject(error); @@ -1165,7 +1117,6 @@ export class UserApi { } } }); - return localVarDeferred.promise; } /** @@ -1192,14 +1143,13 @@ export class UserApi { let useFormData = false; let localVarDeferred = promise.defer<{ response: http.ClientResponse; body: string; }>(); - let requestOptions: request.Options = { method: 'GET', qs: queryParameters, headers: headerParams, uri: localVarPath, json: true, - } + }; this.authentications.default.applyToRequest(requestOptions); @@ -1210,7 +1160,6 @@ export class UserApi { requestOptions.form = formParams; } } - request(requestOptions, (error, response, body) => { if (error) { localVarDeferred.reject(error); @@ -1222,7 +1171,6 @@ export class UserApi { } } }); - return localVarDeferred.promise; } /** @@ -1239,14 +1187,13 @@ export class UserApi { let useFormData = false; let localVarDeferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); - let requestOptions: request.Options = { method: 'GET', qs: queryParameters, headers: headerParams, uri: localVarPath, json: true, - } + }; this.authentications.default.applyToRequest(requestOptions); @@ -1257,7 +1204,6 @@ export class UserApi { requestOptions.form = formParams; } } - request(requestOptions, (error, response, body) => { if (error) { localVarDeferred.reject(error); @@ -1269,7 +1215,6 @@ export class UserApi { } } }); - return localVarDeferred.promise; } /** @@ -1294,7 +1239,6 @@ export class UserApi { let useFormData = false; let localVarDeferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); - let requestOptions: request.Options = { method: 'PUT', qs: queryParameters, @@ -1302,7 +1246,7 @@ export class UserApi { uri: localVarPath, json: true, body: body, - } + }; this.authentications.default.applyToRequest(requestOptions); @@ -1313,7 +1257,6 @@ export class UserApi { requestOptions.form = formParams; } } - request(requestOptions, (error, response, body) => { if (error) { localVarDeferred.reject(error); @@ -1325,7 +1268,6 @@ export class UserApi { } } }); - return localVarDeferred.promise; } } diff --git a/samples/client/petstore/typescript-node/npm/client.ts b/samples/client/petstore/typescript-node/npm/client.ts new file mode 100644 index 00000000000..51a7f687e09 --- /dev/null +++ b/samples/client/petstore/typescript-node/npm/client.ts @@ -0,0 +1,59 @@ +import api = require('./api'); +import fs = require('fs'); + +var petApi = new api.PetApi(); +petApi.setApiKey(api.PetApiApiKeys.api_key, 'special-key'); +petApi.setApiKey(api.PetApiApiKeys.test_api_key_header, 'query-key'); + +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; + +var exitCode = 0; + +// Test various API calls to the petstore +petApi.addPet(pet) + .then((res) => { + var newPet = res.body; + petId = newPet.id; + console.log(`Created pet with ID ${petId}`); + newPet.status = api.Pet.StatusEnum.available; + return petApi.updatePet(newPet); + }) + .then((res) => { + console.log('Updated pet using POST body'); + return petApi.updatePetWithForm(petId, undefined, "pending"); + }) + .then((res) => { + console.log('Updated pet using POST form'); + return petApi.uploadFile(petId, undefined, fs.createReadStream('sample.png')); + }) + .then((res) => { + console.log('Uploaded image'); + return petApi.getPetById(petId); + }) + .then((res) => { + console.log('Got pet by ID: ' + JSON.stringify(res.body)); + if (res.body.status != api.Pet.StatusEnum.pending) { + throw new Error("Unexpected pet status"); + } + }) + .catch((err: any) => { + console.error(err); + exitCode = 1; + }) + .finally(() => { + return petApi.deletePet(petId); + }) + .then((res) => { + console.log('Deleted pet'); + process.exit(exitCode); + }); diff --git a/samples/client/petstore/typescript-node/npm/package.json b/samples/client/petstore/typescript-node/npm/package.json index 5654c9ed4a3..440f9d15e0a 100644 --- a/samples/client/petstore/typescript-node/npm/package.json +++ b/samples/client/petstore/typescript-node/npm/package.json @@ -1,6 +1,6 @@ { "name": "@swagger/angular2-typescript-petstore", - "version": "0.0.1-SNAPSHOT.201605022215", + "version": "0.0.1-SNAPSHOT.201605031634", "description": "NodeJS client for @swagger/angular2-typescript-petstore", "main": "api.js", "scripts": { diff --git a/samples/server/petstore/haskell-servant/README.md b/samples/server/petstore/haskell-servant/README.md index c8f4b4bbb9d..a99fc8935be 100644 --- a/samples/server/petstore/haskell-servant/README.md +++ b/samples/server/petstore/haskell-servant/README.md @@ -1,7 +1,79 @@ -# Generated Servant Codes +# Auto-Generated Swagger Bindings to `SwaggerPetstore` -## How to use +The library in `lib` provides auto-generated-from-Swagger bindings to the SwaggerPetstore API. -0. Install haskell-stack -1. stack build -2. stack exec client +## Installation + +Installation follows the standard approach to installing Stack-based projects. + +1. Install the [Haskell `stack` tool](http://docs.haskellstack.org/en/stable/README). +2. Run `stack install` to install this package. + +## Main Interface + +The main interface to this library is in the `SwaggerPetstore.API` module, which exports the SwaggerPetstoreBackend type. The SwaggerPetstoreBackend +type can be used to create and define servers and clients for the API. + +## Creating a Client + +A client can be created via the `createSwaggerPetstoreClient` function, which, if provided with a hostname and a port, will generate +a client that can be used to access the API if it is being served at that hostname / port combination. For example, if +`localhost:8080` is serving the SwaggerPetstore API, you can write: + +```haskell +{-# LANGUAGE RecordWildCards #-} + +import SwaggerPetstore.API + +main :: IO () +main = do + SwaggerPetstoreBackend{..} <- createSwaggerPetstoreClient (ServerConfig "localhost" 8080) + -- Any SwaggerPetstore API call can go here. + return () +``` + +## Creating a Server + +In order to create a server, you must use the `runSwaggerPetstoreServer` function. However, you unlike the client, in which case you *got* a `SwaggerPetstoreBackend` +from the library, you must instead *provide* a `SwaggerPetstoreBackend`. For example, if you have defined handler functions for all the +functions in `SwaggerPetstore.Handlers`, you can write: + +```haskell +{-# LANGUAGE RecordWildCards #-} + +import SwaggerPetstore.API + +-- A module you wrote yourself, containing all handlers needed for the SwaggerPetstoreBackend type. +import SwaggerPetstore.Handlers + +-- Run a SwaggerPetstore server on localhost:8080 +main :: IO () +main = do + let server = SwaggerPetstoreBackend{..} + runSwaggerPetstoreServer (ServerConfig "localhost" 8080) server +``` + +You could use `optparse-applicative` or a similar library to read the host and port from command-line arguments: +``` +{-# LANGUAGE RecordWildCards #-} + +module Main (main) where + +import SwaggerPetstore.API (runSwaggerPetstoreServer, SwaggerPetstoreBackend(..), ServerConfig(..)) + +import Control.Applicative ((<$>), (<*>)) +import Options.Applicative (execParser, option, str, auto, long, metavar, help) + +main :: IO () +main = do + config <- parseArguments + runSwaggerPetstoreServer config SwaggerPetstoreBackend{} + +-- | Parse host and port from the command line arguments. +parseArguments :: IO ServerConfig +parseArguments = + execParser $ + ServerConfig + <$> option str (long "host" <> metavar "HOST" <> help "Host to serve on") + <*> option auto (long "port" <> metavar "PORT" <> help "Port to serve on") +``` diff --git a/samples/server/petstore/haskell-servant/stack.yaml b/samples/server/petstore/haskell-servant/stack.yaml index 00448df3e95..bed581391ca 100644 --- a/samples/server/petstore/haskell-servant/stack.yaml +++ b/samples/server/petstore/haskell-servant/stack.yaml @@ -1,33 +1,8 @@ -# For more information, see: https://github.com/commercialhaskell/stack/blob/release/doc/yaml_configuration.md - -# Specifies the GHC version and set of packages available (e.g., lts-3.5, nightly-2015-09-21, ghc-7.10.2) -resolver: lts-3.17 - -# Local packages, usually specified by relative directory name +resolver: lts-5.11 +extra-deps: +- servant-0.6 +- servant-client-0.6 +- servant-server-0.6 +- http-api-data-0.2.2 packages: - '.' - -# Packages to be pulled from upstream that are not in the resolver (e.g., acme-missiles-0.3) -extra-deps: -- servant-mock-0.4.4.6 - -# Override default flag values for local packages and extra-deps -flags: {} - -# Extra package databases containing global packages -extra-package-dbs: [] - -# Control whether we use the GHC we find on the path -# system-ghc: true - -# Require a specific version of stack, using version ranges -# require-stack-version: -any # Default -# require-stack-version: >= 0.1.10.0 - -# Override the architecture used by stack, especially useful on Windows -# arch: i386 -# arch: x86_64 - -# Extra directories used by stack for building -# extra-include-dirs: [/path/to/dir] -# extra-lib-dirs: [/path/to/dir] diff --git a/samples/server/petstore/haskell-servant/swagger-petstore.cabal b/samples/server/petstore/haskell-servant/swagger-petstore.cabal new file mode 100644 index 00000000000..4351d73c0d5 --- /dev/null +++ b/samples/server/petstore/haskell-servant/swagger-petstore.cabal @@ -0,0 +1,33 @@ +name: swagger-petstore +version: 0.1.0.0 +synopsis: Auto-generated API bindings for swagger-petstore +description: Please see README.md +homepage: https://github.com/swagger-api/swagger-codegen#readme +author: Author Name Here +maintainer: author.name@email.com +copyright: YEAR - AUTHOR +category: Web +build-type: Simple +cabal-version: >=1.10 + +library + hs-source-dirs: lib + exposed-modules: SwaggerPetstore.API + , SwaggerPetstore.Types + ghc-options: -Wall + build-depends: base + , aeson + , text + , containers + , network-uri + , servant + , http-api-data + , servant-client + , servant-server + , servant + , warp + , transformers + , mtl + , http-client + , http-types + default-language: Haskell2010 diff --git a/samples/server/petstore/nodejs/api/swagger.yaml b/samples/server/petstore/nodejs/api/swagger.yaml index 1aad0a1d4f4..f6987daa915 100644 --- a/samples/server/petstore/nodejs/api/swagger.yaml +++ b/samples/server/petstore/nodejs/api/swagger.yaml @@ -587,10 +587,6 @@ paths: description: "User not found" x-swagger-router-controller: "User" securityDefinitions: - api_key: - type: "apiKey" - name: "api_key" - in: "header" petstore_auth: type: "oauth2" authorizationUrl: "http://petstore.swagger.io/api/oauth/dialog" @@ -598,6 +594,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: Order: type: "object" diff --git a/samples/server/petstore/nodejs/controllers/PetService.js b/samples/server/petstore/nodejs/controllers/PetService.js index 95f42f6a038..2c464714aa7 100644 --- a/samples/server/petstore/nodejs/controllers/PetService.js +++ b/samples/server/petstore/nodejs/controllers/PetService.js @@ -13,7 +13,7 @@ exports.deletePet = function(args, res, next) { /** * parameters expected in the args: * petId (Long) - * apiKey (String) + * api_key (String) **/ // no response value expected for this operation res.end(); @@ -26,18 +26,18 @@ exports.findPetsByStatus = function(args, res, next) { **/ var examples = {}; examples['application/json'] = [ { - "tags" : [ { - "id" : 123456789, - "name" : "aeiou" - } ], + "photoUrls" : [ "aeiou" ], + "name" : "doggie", "id" : 123456789, "category" : { - "id" : 123456789, - "name" : "aeiou" + "name" : "aeiou", + "id" : 123456789 }, - "status" : "aeiou", - "name" : "doggie", - "photoUrls" : [ "aeiou" ] + "tags" : [ { + "name" : "aeiou", + "id" : 123456789 + } ], + "status" : "aeiou" } ]; if(Object.keys(examples).length > 0) { res.setHeader('Content-Type', 'application/json'); @@ -56,18 +56,18 @@ exports.findPetsByTags = function(args, res, next) { **/ var examples = {}; examples['application/json'] = [ { - "tags" : [ { - "id" : 123456789, - "name" : "aeiou" - } ], + "photoUrls" : [ "aeiou" ], + "name" : "doggie", "id" : 123456789, "category" : { - "id" : 123456789, - "name" : "aeiou" + "name" : "aeiou", + "id" : 123456789 }, - "status" : "aeiou", - "name" : "doggie", - "photoUrls" : [ "aeiou" ] + "tags" : [ { + "name" : "aeiou", + "id" : 123456789 + } ], + "status" : "aeiou" } ]; if(Object.keys(examples).length > 0) { res.setHeader('Content-Type', 'application/json'); @@ -86,18 +86,18 @@ exports.getPetById = function(args, res, next) { **/ var examples = {}; examples['application/json'] = { - "tags" : [ { - "id" : 123456789, - "name" : "aeiou" - } ], + "photoUrls" : [ "aeiou" ], + "name" : "doggie", "id" : 123456789, "category" : { - "id" : 123456789, - "name" : "aeiou" + "name" : "aeiou", + "id" : 123456789 }, - "status" : "aeiou", - "name" : "doggie", - "photoUrls" : [ "aeiou" ] + "tags" : [ { + "name" : "aeiou", + "id" : 123456789 + } ], + "status" : "aeiou" }; if(Object.keys(examples).length > 0) { res.setHeader('Content-Type', 'application/json'); @@ -138,9 +138,9 @@ exports.uploadFile = function(args, res, next) { **/ var examples = {}; examples['application/json'] = { - "message" : "aeiou", "code" : 123, - "type" : "aeiou" + "type" : "aeiou", + "message" : "aeiou" }; if(Object.keys(examples).length > 0) { res.setHeader('Content-Type', 'application/json'); diff --git a/samples/server/petstore/nodejs/controllers/StoreService.js b/samples/server/petstore/nodejs/controllers/StoreService.js index 01759173bd4..d20619ceb9b 100644 --- a/samples/server/petstore/nodejs/controllers/StoreService.js +++ b/samples/server/petstore/nodejs/controllers/StoreService.js @@ -34,12 +34,12 @@ exports.getOrderById = function(args, res, next) { **/ var examples = {}; examples['application/json'] = { - "id" : 123456789, "petId" : 123456789, - "complete" : true, - "status" : "aeiou", "quantity" : 123, - "shipDate" : "2000-01-23T04:56:07.000+0000" + "id" : 123456789, + "shipDate" : "2000-01-23T04:56:07.000+0000", + "complete" : true, + "status" : "aeiou" }; if(Object.keys(examples).length > 0) { res.setHeader('Content-Type', 'application/json'); @@ -58,12 +58,12 @@ exports.placeOrder = function(args, res, next) { **/ var examples = {}; examples['application/json'] = { - "id" : 123456789, "petId" : 123456789, - "complete" : true, - "status" : "aeiou", "quantity" : 123, - "shipDate" : "2000-01-23T04:56:07.000+0000" + "id" : 123456789, + "shipDate" : "2000-01-23T04:56:07.000+0000", + "complete" : true, + "status" : "aeiou" }; if(Object.keys(examples).length > 0) { res.setHeader('Content-Type', 'application/json'); diff --git a/samples/server/petstore/nodejs/controllers/UserService.js b/samples/server/petstore/nodejs/controllers/UserService.js index 69fc1a81391..3a62feeaf3f 100644 --- a/samples/server/petstore/nodejs/controllers/UserService.js +++ b/samples/server/petstore/nodejs/controllers/UserService.js @@ -43,14 +43,14 @@ exports.getUserByName = function(args, res, next) { **/ var examples = {}; examples['application/json'] = { - "id" : 123456789, - "lastName" : "aeiou", - "phone" : "aeiou", - "username" : "aeiou", - "email" : "aeiou", - "userStatus" : 123, "firstName" : "aeiou", - "password" : "aeiou" + "lastName" : "aeiou", + "password" : "aeiou", + "userStatus" : 123, + "phone" : "aeiou", + "id" : 123456789, + "email" : "aeiou", + "username" : "aeiou" }; if(Object.keys(examples).length > 0) { res.setHeader('Content-Type', 'application/json'); diff --git a/samples/server/petstore/nodejs/package.json b/samples/server/petstore/nodejs/package.json index 293316dac0e..c5884b196b9 100644 --- a/samples/server/petstore/nodejs/package.json +++ b/samples/server/petstore/nodejs/package.json @@ -11,6 +11,6 @@ "dependencies": { "connect": "^3.2.0", "js-yaml": "^3.3.0", - "swagger-tools": "0.9.*" + "swagger-tools": "0.10.1" } } diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/ApiException.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/ApiException.java index 7fa9d6b24cc..608a7957017 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/ApiException.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/ApiException.java @@ -1,6 +1,6 @@ package io.swagger.api; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-04-28T15:08:30.859+02:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-03T13:42:56.594+02:00") public class ApiException extends Exception{ private int code; public ApiException (int code, String msg) { diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/ApiOriginFilter.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/ApiOriginFilter.java index 12e868926e9..0a2894d0be4 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/ApiOriginFilter.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/ApiOriginFilter.java @@ -5,7 +5,7 @@ import java.io.IOException; import javax.servlet.*; import javax.servlet.http.HttpServletResponse; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-04-28T15:08:30.859+02:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-03T13:42:56.594+02:00") public class ApiOriginFilter implements javax.servlet.Filter { @Override public void doFilter(ServletRequest request, ServletResponse response, diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/ApiResponseMessage.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/ApiResponseMessage.java index a9baf798c66..9bc56631d29 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/ApiResponseMessage.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/ApiResponseMessage.java @@ -3,7 +3,7 @@ package io.swagger.api; import javax.xml.bind.annotation.XmlTransient; @javax.xml.bind.annotation.XmlRootElement -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-04-28T15:08:30.859+02:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-03T13:42:56.594+02:00") public class ApiResponseMessage { public static final int ERROR = 1; public static final int WARNING = 2; diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/NotFoundException.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/NotFoundException.java index af4fba57283..72ca217e7c0 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/NotFoundException.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/NotFoundException.java @@ -1,6 +1,6 @@ package io.swagger.api; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-04-28T15:08:30.859+02:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-03T13:42:56.594+02:00") public class NotFoundException extends ApiException { private int code; public NotFoundException (int code, String msg) { diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/PetApi.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/PetApi.java index bc264595a44..c3d4887b35f 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/PetApi.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/PetApi.java @@ -34,7 +34,7 @@ import static org.springframework.http.MediaType.*; @Controller @RequestMapping(value = "/pet", produces = {APPLICATION_JSON_VALUE}) @Api(value = "/pet", description = "the pet API") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-04-28T15:08:30.859+02:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-03T13:42:56.594+02:00") public interface PetApi { @ApiOperation(value = "Add a new pet to the store", notes = "", response = Void.class, authorizations = { diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/StoreApi.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/StoreApi.java index 5b4e2ae6aef..4eb6c73849a 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/StoreApi.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/StoreApi.java @@ -34,7 +34,7 @@ import static org.springframework.http.MediaType.*; @Controller @RequestMapping(value = "/store", produces = {APPLICATION_JSON_VALUE}) @Api(value = "/store", description = "the store API") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-04-28T15:08:30.859+02:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-03T13:42:56.594+02:00") public interface StoreApi { @ApiOperation(value = "Delete purchase order by ID", notes = "For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors", response = Void.class) diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/UserApi.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/UserApi.java index 5ef98712f28..b24082923dc 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/UserApi.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/UserApi.java @@ -34,7 +34,7 @@ import static org.springframework.http.MediaType.*; @Controller @RequestMapping(value = "/user", produces = {APPLICATION_JSON_VALUE}) @Api(value = "/user", description = "the user API") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-04-28T15:08:30.859+02:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-03T13:42:56.594+02:00") public interface UserApi { @ApiOperation(value = "Create user", notes = "This can only be done by the logged in user.", response = Void.class) diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/configuration/SwaggerConfig.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/configuration/SwaggerConfig.java index 87096d41260..5004845542f 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/configuration/SwaggerConfig.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/configuration/SwaggerConfig.java @@ -20,7 +20,7 @@ import springfox.documentation.swagger2.annotations.EnableSwagger2; @EnableSwagger2 //Loads the spring beans required by the framework @PropertySource("classpath:swagger.properties") @Import(SwaggerUiConfiguration.class) -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-04-28T15:08:30.859+02:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-03T13:42:56.594+02:00") public class SwaggerConfig { @Bean ApiInfo apiInfo() { diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/configuration/SwaggerUiConfiguration.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/configuration/SwaggerUiConfiguration.java index f2cb3004e64..6b3b305942f 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/configuration/SwaggerUiConfiguration.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/configuration/SwaggerUiConfiguration.java @@ -8,7 +8,7 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter @Configuration @EnableWebMvc -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-04-28T15:08:30.859+02:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-03T13:42:56.594+02:00") public class SwaggerUiConfiguration extends WebMvcConfigurerAdapter { private static final String[] SERVLET_RESOURCE_LOCATIONS = { "/" }; diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/configuration/WebApplication.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/configuration/WebApplication.java index 48bad4bb263..7e437ae6b14 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/configuration/WebApplication.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/configuration/WebApplication.java @@ -2,7 +2,7 @@ package io.swagger.configuration; import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-04-28T15:08:30.859+02:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-03T13:42:56.594+02:00") public class WebApplication extends AbstractAnnotationConfigDispatcherServletInitializer { @Override diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/configuration/WebMvcConfiguration.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/configuration/WebMvcConfiguration.java index 64f96fe37f3..40f8a10a438 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/configuration/WebMvcConfiguration.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/configuration/WebMvcConfiguration.java @@ -3,7 +3,7 @@ package io.swagger.configuration; import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer; import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-04-28T15:08:30.859+02:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-03T13:42:56.594+02:00") public class WebMvcConfiguration extends WebMvcConfigurationSupport { @Override public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Category.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Category.java index 850c801606e..18f08f895e1 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Category.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Category.java @@ -10,7 +10,7 @@ import java.util.Objects; @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-04-28T15:08:30.859+02:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-03T13:42:56.594+02:00") public class Category { private Long id = null; diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Order.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Order.java index 72ed79b768b..738a9e81f96 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Order.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Order.java @@ -11,7 +11,7 @@ import java.util.Objects; @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-04-28T15:08:30.859+02:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-03T13:42:56.594+02:00") public class Order { private Long id = null; diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Pet.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Pet.java index aca7ff86695..26e4d3c529e 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Pet.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Pet.java @@ -14,7 +14,7 @@ import java.util.Objects; @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-04-28T15:08:30.859+02:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-03T13:42:56.594+02:00") public class Pet { private Long id = null; diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Tag.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Tag.java index d688eb2ee02..2f39f45a1f8 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Tag.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Tag.java @@ -10,7 +10,7 @@ import java.util.Objects; @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-04-28T15:08:30.859+02:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-03T13:42:56.594+02:00") public class Tag { private Long id = null; diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/User.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/User.java index 9a477831569..eee7800acbf 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/User.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/User.java @@ -10,7 +10,7 @@ import java.util.Objects; @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-04-28T15:08:30.859+02:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-03T13:42:56.594+02:00") public class User { private Long id = null; diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/ApiException.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/ApiException.java index 25f2efe14cd..b83f1890525 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/ApiException.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/ApiException.java @@ -1,6 +1,6 @@ package io.swagger.api; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-04-28T15:08:37.024+02:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-03T13:43:02.966+02:00") public class ApiException extends Exception{ private int code; public ApiException (int code, String msg) { diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/ApiOriginFilter.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/ApiOriginFilter.java index ccc0cbbb7aa..9b91bee0559 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/ApiOriginFilter.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/ApiOriginFilter.java @@ -5,7 +5,7 @@ import java.io.IOException; import javax.servlet.*; import javax.servlet.http.HttpServletResponse; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-04-28T15:08:37.024+02:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-03T13:43:02.966+02:00") public class ApiOriginFilter implements javax.servlet.Filter { @Override public void doFilter(ServletRequest request, ServletResponse response, diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/ApiResponseMessage.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/ApiResponseMessage.java index 2b007cb749a..1e34ed21964 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/ApiResponseMessage.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/ApiResponseMessage.java @@ -3,7 +3,7 @@ package io.swagger.api; import javax.xml.bind.annotation.XmlTransient; @javax.xml.bind.annotation.XmlRootElement -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-04-28T15:08:37.024+02:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-03T13:43:02.966+02:00") public class ApiResponseMessage { public static final int ERROR = 1; public static final int WARNING = 2; diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/NotFoundException.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/NotFoundException.java index 9ec36e8ab35..8adb7dfcdec 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/NotFoundException.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/NotFoundException.java @@ -1,6 +1,6 @@ package io.swagger.api; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-04-28T15:08:37.024+02:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-03T13:43:02.966+02:00") public class NotFoundException extends ApiException { private int code; public NotFoundException (int code, String msg) { diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/PetApi.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/PetApi.java index f50ce573df5..b4520b2b578 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/PetApi.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/PetApi.java @@ -31,7 +31,7 @@ import static org.springframework.http.MediaType.*; @Controller @RequestMapping(value = "/pet", produces = {APPLICATION_JSON_VALUE}) @Api(value = "/pet", description = "the pet API") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-04-28T15:08:37.024+02:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-03T13:43:02.966+02:00") public class PetApi { @ApiOperation(value = "Add a new pet to the store", notes = "", response = Void.class, authorizations = { diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/StoreApi.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/StoreApi.java index 254d8822b5c..48085e9dda1 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/StoreApi.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/StoreApi.java @@ -31,7 +31,7 @@ import static org.springframework.http.MediaType.*; @Controller @RequestMapping(value = "/store", produces = {APPLICATION_JSON_VALUE}) @Api(value = "/store", description = "the store API") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-04-28T15:08:37.024+02:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-03T13:43:02.966+02:00") public class StoreApi { @ApiOperation(value = "Delete purchase order by ID", notes = "For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors", response = Void.class) diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/UserApi.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/UserApi.java index a87eed542e2..235ccbfb0af 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/UserApi.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/UserApi.java @@ -31,7 +31,7 @@ import static org.springframework.http.MediaType.*; @Controller @RequestMapping(value = "/user", produces = {APPLICATION_JSON_VALUE}) @Api(value = "/user", description = "the user API") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-04-28T15:08:37.024+02:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-03T13:43:02.966+02:00") public class UserApi { @ApiOperation(value = "Create user", notes = "This can only be done by the logged in user.", response = Void.class) diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/configuration/SwaggerConfig.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/configuration/SwaggerConfig.java index e55006ed86e..7d5f58101ac 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/configuration/SwaggerConfig.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/configuration/SwaggerConfig.java @@ -20,7 +20,7 @@ import springfox.documentation.swagger2.annotations.EnableSwagger2; @EnableSwagger2 //Loads the spring beans required by the framework @PropertySource("classpath:swagger.properties") @Import(SwaggerUiConfiguration.class) -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-04-28T15:08:37.024+02:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-03T13:43:02.966+02:00") public class SwaggerConfig { @Bean ApiInfo apiInfo() { diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/configuration/SwaggerUiConfiguration.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/configuration/SwaggerUiConfiguration.java index bd977dde85d..ebae7c559ae 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/configuration/SwaggerUiConfiguration.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/configuration/SwaggerUiConfiguration.java @@ -8,7 +8,7 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter @Configuration @EnableWebMvc -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-04-28T15:08:37.024+02:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-03T13:43:02.966+02:00") public class SwaggerUiConfiguration extends WebMvcConfigurerAdapter { private static final String[] SERVLET_RESOURCE_LOCATIONS = { "/" }; diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/configuration/WebApplication.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/configuration/WebApplication.java index dd1da23da94..c672d78518c 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/configuration/WebApplication.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/configuration/WebApplication.java @@ -2,7 +2,7 @@ package io.swagger.configuration; import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-04-28T15:08:37.024+02:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-03T13:43:02.966+02:00") public class WebApplication extends AbstractAnnotationConfigDispatcherServletInitializer { @Override diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/configuration/WebMvcConfiguration.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/configuration/WebMvcConfiguration.java index e4f224f5947..047f95c58f9 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/configuration/WebMvcConfiguration.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/configuration/WebMvcConfiguration.java @@ -3,7 +3,7 @@ package io.swagger.configuration; import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer; import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-04-28T15:08:37.024+02:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-03T13:43:02.966+02:00") public class WebMvcConfiguration extends WebMvcConfigurationSupport { @Override public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Category.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Category.java index bae60f19a80..be118387fb5 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Category.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Category.java @@ -11,7 +11,7 @@ import java.util.Objects; @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-04-28T15:08:37.024+02:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-03T13:43:02.966+02:00") public class Category { private Long id = null; diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Order.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Order.java index 9787055aa3a..b0cc5d7b558 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Order.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Order.java @@ -13,7 +13,7 @@ import java.util.Objects; @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-04-28T15:08:37.024+02:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-03T13:43:02.966+02:00") public class Order { private Long id = null; diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Pet.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Pet.java index 3948dba37da..aabd1a9be1b 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Pet.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Pet.java @@ -16,7 +16,7 @@ import java.util.Objects; @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-04-28T15:08:37.024+02:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-03T13:43:02.966+02:00") public class Pet { private Long id = null; diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Tag.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Tag.java index 5547993d18a..df87b351c30 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Tag.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Tag.java @@ -11,7 +11,7 @@ import java.util.Objects; @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-04-28T15:08:37.024+02:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-03T13:43:02.966+02:00") public class Tag { private Long id = null; diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/User.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/User.java index 448ba1dceec..8458048efc2 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/User.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/User.java @@ -11,7 +11,7 @@ import java.util.Objects; @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-04-28T15:08:37.024+02:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-03T13:43:02.966+02:00") public class User { private Long id = null; diff --git a/samples/server/petstore/springboot/README.md b/samples/server/petstore/springboot/README.md new file mode 100644 index 00000000000..8f9855eedf9 --- /dev/null +++ b/samples/server/petstore/springboot/README.md @@ -0,0 +1,18 @@ +# Swagger generated server + +Spring Boot Server + + +## Overview +This server was generated by the [swagger-codegen](https://github.com/swagger-api/swagger-codegen) project. +By using the [OpenAPI-Spec](https://github.com/swagger-api/swagger-core), you can easily generate a server stub. +This is an example of building a swagger-enabled server in Java using the SpringBoot framework. + +The underlying library integrating swagger to SpringBoot is [springfox](https://github.com/springfox/springfox) + +Start your server as an simple java application + +You can view the api documentation in swagger-ui by pointing to +http://localhost:8080/ + +Change default port value in application.properties \ No newline at end of file diff --git a/samples/server/petstore/springboot/pom.xml b/samples/server/petstore/springboot/pom.xml new file mode 100644 index 00000000000..139b3da9ab4 --- /dev/null +++ b/samples/server/petstore/springboot/pom.xml @@ -0,0 +1,54 @@ + + 4.0.0 + io.swagger + swagger-springboot-server + jar + swagger-springboot-server + 1.0.0 + + 2.4.0 + + + org.springframework.boot + spring-boot-starter-parent + 1.3.3.RELEASE + + + src/main/java + + + org.springframework.boot + spring-boot-maven-plugin + + + + repackage + + + + + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-tomcat + provided + + + + io.springfox + springfox-swagger2 + ${springfox-version} + + + io.springfox + springfox-swagger-ui + ${springfox-version} + + + \ No newline at end of file diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/Swagger2SpringBoot.java b/samples/server/petstore/springboot/src/main/java/io/swagger/Swagger2SpringBoot.java new file mode 100644 index 00000000000..2cc65db2b81 --- /dev/null +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/Swagger2SpringBoot.java @@ -0,0 +1,36 @@ +package io.swagger; + +import org.springframework.boot.CommandLineRunner; +import org.springframework.boot.ExitCodeGenerator; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.ComponentScan; + +import springfox.documentation.swagger2.annotations.EnableSwagger2; + +@SpringBootApplication +@EnableSwagger2 +@ComponentScan(basePackages = "io.swagger") +public class Swagger2SpringBoot implements CommandLineRunner { + + @Override + public void run(String... arg0) throws Exception { + if (arg0.length > 0 && arg0[0].equals("exitcode")) { + throw new ExitException(); + } + } + + public static void main(String[] args) throws Exception { + new SpringApplication(Swagger2SpringBoot.class).run(args); + } + + class ExitException extends RuntimeException implements ExitCodeGenerator { + private static final long serialVersionUID = 1L; + + @Override + public int getExitCode() { + return 10; + } + + } +} \ No newline at end of file diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/api/ApiException.java b/samples/server/petstore/springboot/src/main/java/io/swagger/api/ApiException.java new file mode 100644 index 00000000000..1652afba0ad --- /dev/null +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/api/ApiException.java @@ -0,0 +1,10 @@ +package io.swagger.api; + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringBootServerCodegen", date = "2016-05-05T15:30:42.322+08:00") +public class ApiException extends Exception{ + private int code; + public ApiException (int code, String msg) { + super(msg); + this.code = code; + } +} diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/api/ApiOriginFilter.java b/samples/server/petstore/springboot/src/main/java/io/swagger/api/ApiOriginFilter.java new file mode 100644 index 00000000000..d18415d8e7c --- /dev/null +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/api/ApiOriginFilter.java @@ -0,0 +1,27 @@ +package io.swagger.api; + +import java.io.IOException; + +import javax.servlet.*; +import javax.servlet.http.HttpServletResponse; + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringBootServerCodegen", date = "2016-05-05T15:30:42.322+08:00") +public class ApiOriginFilter implements javax.servlet.Filter { + @Override + public void doFilter(ServletRequest request, ServletResponse response, + FilterChain chain) throws IOException, ServletException { + HttpServletResponse res = (HttpServletResponse) response; + res.addHeader("Access-Control-Allow-Origin", "*"); + res.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT"); + res.addHeader("Access-Control-Allow-Headers", "Content-Type"); + chain.doFilter(request, response); + } + + @Override + public void destroy() { + } + + @Override + public void init(FilterConfig filterConfig) throws ServletException { + } +} \ No newline at end of file diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/api/ApiResponseMessage.java b/samples/server/petstore/springboot/src/main/java/io/swagger/api/ApiResponseMessage.java new file mode 100644 index 00000000000..a58b9c19e97 --- /dev/null +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/api/ApiResponseMessage.java @@ -0,0 +1,69 @@ +package io.swagger.api; + +import javax.xml.bind.annotation.XmlTransient; + +@javax.xml.bind.annotation.XmlRootElement +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringBootServerCodegen", date = "2016-05-05T15:30:42.322+08:00") +public class ApiResponseMessage { + public static final int ERROR = 1; + public static final int WARNING = 2; + public static final int INFO = 3; + public static final int OK = 4; + public static final int TOO_BUSY = 5; + + int code; + String type; + String message; + + public ApiResponseMessage(){} + + public ApiResponseMessage(int code, String message){ + this.code = code; + switch(code){ + case ERROR: + setType("error"); + break; + case WARNING: + setType("warning"); + break; + case INFO: + setType("info"); + break; + case OK: + setType("ok"); + break; + case TOO_BUSY: + setType("too busy"); + break; + default: + setType("unknown"); + break; + } + this.message = message; + } + + @XmlTransient + public int getCode() { + return code; + } + + public void setCode(int code) { + this.code = code; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } +} diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/api/NotFoundException.java b/samples/server/petstore/springboot/src/main/java/io/swagger/api/NotFoundException.java new file mode 100644 index 00000000000..8770f484be1 --- /dev/null +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/api/NotFoundException.java @@ -0,0 +1,10 @@ +package io.swagger.api; + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringBootServerCodegen", date = "2016-05-05T15:30:42.322+08:00") +public class NotFoundException extends ApiException { + private int code; + public NotFoundException (int code, String msg) { + super(code, msg); + this.code = code; + } +} diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/api/PetApi.java b/samples/server/petstore/springboot/src/main/java/io/swagger/api/PetApi.java new file mode 100644 index 00000000000..7f66bdc75f7 --- /dev/null +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/api/PetApi.java @@ -0,0 +1,234 @@ +package io.swagger.api; + +import io.swagger.model.*; + +import io.swagger.model.Pet; +import java.io.File; +import io.swagger.model.ModelApiResponse; + +import io.swagger.annotations.*; + +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RequestPart; +import org.springframework.web.multipart.MultipartFile; + +import java.util.List; + +import static org.springframework.http.MediaType.*; + +@Controller +@RequestMapping(value = "/pet", produces = {APPLICATION_JSON_VALUE}) +@Api(value = "/pet", description = "the pet API") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringBootServerCodegen", date = "2016-05-05T15:30:42.322+08:00") +public class PetApi { + + @ApiOperation(value = "Add a new pet to the store", notes = "", response = Void.class, authorizations = { + @Authorization(value = "petstore_auth", scopes = { + @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }) + @ApiResponses(value = { + @ApiResponse(code = 405, message = "Invalid input", response = Void.class) }) + @RequestMapping(value = "", + produces = { "application/xml", "application/json" }, + consumes = { "application/json", "application/xml" }, + method = RequestMethod.POST) + public ResponseEntity addPet( + +@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @RequestBody Pet body +) + throws NotFoundException { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + + + @ApiOperation(value = "Deletes a pet", notes = "", response = Void.class, authorizations = { + @Authorization(value = "petstore_auth", scopes = { + @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }) + @ApiResponses(value = { + @ApiResponse(code = 400, message = "Invalid pet value", response = Void.class) }) + @RequestMapping(value = "/{petId}", + produces = { "application/xml", "application/json" }, + + method = RequestMethod.DELETE) + public ResponseEntity deletePet( +@ApiParam(value = "Pet id to delete",required=true ) @PathVariable("petId") Long petId + +, + +@ApiParam(value = "" ) @RequestHeader(value="api_key", required=false) String apiKey + +) + throws NotFoundException { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + + + @ApiOperation(value = "Finds Pets by status", notes = "Multiple status values can be provided with comma separated strings", response = Pet.class, responseContainer = "List", authorizations = { + @Authorization(value = "petstore_auth", scopes = { + @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Pet.class), + @ApiResponse(code = 400, message = "Invalid status value", response = Pet.class) }) + @RequestMapping(value = "/findByStatus", + produces = { "application/xml", "application/json" }, + + method = RequestMethod.GET) + public ResponseEntity> findPetsByStatus(@ApiParam(value = "Status values that need to be considered for filter", required = true) @RequestParam(value = "status", required = true) List status + + +) + throws NotFoundException { + // do some magic! + return new ResponseEntity>(HttpStatus.OK); + } + + + @ApiOperation(value = "Finds Pets by tags", notes = "Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.", response = Pet.class, responseContainer = "List", authorizations = { + @Authorization(value = "petstore_auth", scopes = { + @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Pet.class), + @ApiResponse(code = 400, message = "Invalid tag value", response = Pet.class) }) + @RequestMapping(value = "/findByTags", + produces = { "application/xml", "application/json" }, + + method = RequestMethod.GET) + public ResponseEntity> findPetsByTags(@ApiParam(value = "Tags to filter by", required = true) @RequestParam(value = "tags", required = true) List tags + + +) + throws NotFoundException { + // do some magic! + return new ResponseEntity>(HttpStatus.OK); + } + + + @ApiOperation(value = "Find pet by ID", notes = "Returns a single pet", response = Pet.class, authorizations = { + @Authorization(value = "api_key") + }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Pet.class), + @ApiResponse(code = 400, message = "Invalid ID supplied", response = Pet.class), + @ApiResponse(code = 404, message = "Pet not found", response = Pet.class) }) + @RequestMapping(value = "/{petId}", + produces = { "application/xml", "application/json" }, + + method = RequestMethod.GET) + public ResponseEntity getPetById( +@ApiParam(value = "ID of pet to return",required=true ) @PathVariable("petId") Long petId + +) + throws NotFoundException { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + + + @ApiOperation(value = "Update an existing pet", notes = "", response = Void.class, authorizations = { + @Authorization(value = "petstore_auth", scopes = { + @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }) + @ApiResponses(value = { + @ApiResponse(code = 400, message = "Invalid ID supplied", response = Void.class), + @ApiResponse(code = 404, message = "Pet not found", response = Void.class), + @ApiResponse(code = 405, message = "Validation exception", response = Void.class) }) + @RequestMapping(value = "", + produces = { "application/xml", "application/json" }, + consumes = { "application/json", "application/xml" }, + method = RequestMethod.PUT) + public ResponseEntity updatePet( + +@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @RequestBody Pet body +) + throws NotFoundException { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + + + @ApiOperation(value = "Updates a pet in the store with form data", notes = "", response = Void.class, authorizations = { + @Authorization(value = "petstore_auth", scopes = { + @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }) + @ApiResponses(value = { + @ApiResponse(code = 405, message = "Invalid input", response = Void.class) }) + @RequestMapping(value = "/{petId}", + produces = { "application/xml", "application/json" }, + consumes = { "application/x-www-form-urlencoded" }, + method = RequestMethod.POST) + public ResponseEntity updatePetWithForm( +@ApiParam(value = "ID of pet that needs to be updated",required=true ) @PathVariable("petId") Long petId + +, + + + +@ApiParam(value = "Updated name of the pet" ) @RequestPart(value="name", required=false) String name +, + + + +@ApiParam(value = "Updated status of the pet" ) @RequestPart(value="status", required=false) String status +) + throws NotFoundException { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + + + @ApiOperation(value = "uploads an image", notes = "", response = ModelApiResponse.class, authorizations = { + @Authorization(value = "petstore_auth", scopes = { + @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = ModelApiResponse.class) }) + @RequestMapping(value = "/{petId}/uploadImage", + produces = { "application/json" }, + consumes = { "multipart/form-data" }, + method = RequestMethod.POST) + public ResponseEntity uploadFile( +@ApiParam(value = "ID of pet to update",required=true ) @PathVariable("petId") Long petId + +, + + + +@ApiParam(value = "Additional data to pass to server" ) @RequestPart(value="additionalMetadata", required=false) String additionalMetadata +, + + +@ApiParam(value = "file detail") @RequestPart("file") MultipartFile file +) + throws NotFoundException { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + +} diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/api/StoreApi.java b/samples/server/petstore/springboot/src/main/java/io/swagger/api/StoreApi.java new file mode 100644 index 00000000000..8cf2283e4fe --- /dev/null +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/api/StoreApi.java @@ -0,0 +1,102 @@ +package io.swagger.api; + +import io.swagger.model.*; + +import java.util.Map; +import io.swagger.model.Order; + +import io.swagger.annotations.*; + +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RequestPart; +import org.springframework.web.multipart.MultipartFile; + +import java.util.List; + +import static org.springframework.http.MediaType.*; + +@Controller +@RequestMapping(value = "/store", produces = {APPLICATION_JSON_VALUE}) +@Api(value = "/store", description = "the store API") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringBootServerCodegen", date = "2016-05-05T15:30:42.322+08:00") +public class StoreApi { + + @ApiOperation(value = "Delete purchase order by ID", notes = "For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors", response = Void.class) + @ApiResponses(value = { + @ApiResponse(code = 400, message = "Invalid ID supplied", response = Void.class), + @ApiResponse(code = 404, message = "Order not found", response = Void.class) }) + @RequestMapping(value = "/order/{orderId}", + produces = { "application/xml", "application/json" }, + + method = RequestMethod.DELETE) + public ResponseEntity deleteOrder( +@ApiParam(value = "ID of the order that needs to be deleted",required=true ) @PathVariable("orderId") String orderId + +) + throws NotFoundException { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + + + @ApiOperation(value = "Returns pet inventories by status", notes = "Returns a map of status codes to quantities", response = Integer.class, responseContainer = "Map", authorizations = { + @Authorization(value = "api_key") + }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Integer.class) }) + @RequestMapping(value = "/inventory", + produces = { "application/json" }, + + method = RequestMethod.GET) + public ResponseEntity> getInventory() + throws NotFoundException { + // do some magic! + return new ResponseEntity>(HttpStatus.OK); + } + + + @ApiOperation(value = "Find purchase order by ID", notes = "For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions", response = Order.class) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Order.class), + @ApiResponse(code = 400, message = "Invalid ID supplied", response = Order.class), + @ApiResponse(code = 404, message = "Order not found", response = Order.class) }) + @RequestMapping(value = "/order/{orderId}", + produces = { "application/xml", "application/json" }, + + method = RequestMethod.GET) + public ResponseEntity getOrderById( +@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathVariable("orderId") Long orderId + +) + throws NotFoundException { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + + + @ApiOperation(value = "Place an order for a pet", notes = "", response = Order.class) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Order.class), + @ApiResponse(code = 400, message = "Invalid Order", response = Order.class) }) + @RequestMapping(value = "/order", + produces = { "application/xml", "application/json" }, + + method = RequestMethod.POST) + public ResponseEntity placeOrder( + +@ApiParam(value = "order placed for purchasing the pet" ,required=true ) @RequestBody Order body +) + throws NotFoundException { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + +} diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/api/UserApi.java b/samples/server/petstore/springboot/src/main/java/io/swagger/api/UserApi.java new file mode 100644 index 00000000000..36c500faded --- /dev/null +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/api/UserApi.java @@ -0,0 +1,177 @@ +package io.swagger.api; + +import io.swagger.model.*; + +import io.swagger.model.User; +import java.util.List; + +import io.swagger.annotations.*; + +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RequestPart; +import org.springframework.web.multipart.MultipartFile; + +import java.util.List; + +import static org.springframework.http.MediaType.*; + +@Controller +@RequestMapping(value = "/user", produces = {APPLICATION_JSON_VALUE}) +@Api(value = "/user", description = "the user API") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringBootServerCodegen", date = "2016-05-05T15:30:42.322+08:00") +public class UserApi { + + @ApiOperation(value = "Create user", notes = "This can only be done by the logged in user.", response = Void.class) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Void.class) }) + @RequestMapping(value = "", + produces = { "application/xml", "application/json" }, + + method = RequestMethod.POST) + public ResponseEntity createUser( + +@ApiParam(value = "Created user object" ,required=true ) @RequestBody User body +) + throws NotFoundException { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + + + @ApiOperation(value = "Creates list of users with given input array", notes = "", response = Void.class) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Void.class) }) + @RequestMapping(value = "/createWithArray", + produces = { "application/xml", "application/json" }, + + method = RequestMethod.POST) + public ResponseEntity createUsersWithArrayInput( + +@ApiParam(value = "List of user object" ,required=true ) @RequestBody List body +) + throws NotFoundException { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + + + @ApiOperation(value = "Creates list of users with given input array", notes = "", response = Void.class) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Void.class) }) + @RequestMapping(value = "/createWithList", + produces = { "application/xml", "application/json" }, + + method = RequestMethod.POST) + public ResponseEntity createUsersWithListInput( + +@ApiParam(value = "List of user object" ,required=true ) @RequestBody List body +) + throws NotFoundException { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + + + @ApiOperation(value = "Delete user", notes = "This can only be done by the logged in user.", response = Void.class) + @ApiResponses(value = { + @ApiResponse(code = 400, message = "Invalid username supplied", response = Void.class), + @ApiResponse(code = 404, message = "User not found", response = Void.class) }) + @RequestMapping(value = "/{username}", + produces = { "application/xml", "application/json" }, + + method = RequestMethod.DELETE) + public ResponseEntity deleteUser( +@ApiParam(value = "The name that needs to be deleted",required=true ) @PathVariable("username") String username + +) + throws NotFoundException { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + + + @ApiOperation(value = "Get user by user name", notes = "", response = User.class) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = User.class), + @ApiResponse(code = 400, message = "Invalid username supplied", response = User.class), + @ApiResponse(code = 404, message = "User not found", response = User.class) }) + @RequestMapping(value = "/{username}", + produces = { "application/xml", "application/json" }, + + method = RequestMethod.GET) + public ResponseEntity getUserByName( +@ApiParam(value = "The name that needs to be fetched. Use user1 for testing. ",required=true ) @PathVariable("username") String username + +) + throws NotFoundException { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + + + @ApiOperation(value = "Logs user into the system", notes = "", response = String.class) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = String.class), + @ApiResponse(code = 400, message = "Invalid username/password supplied", response = String.class) }) + @RequestMapping(value = "/login", + produces = { "application/xml", "application/json" }, + + method = RequestMethod.GET) + public ResponseEntity loginUser(@ApiParam(value = "The user name for login", required = true) @RequestParam(value = "username", required = true) String username + + +, + @ApiParam(value = "The password for login in clear text", required = true) @RequestParam(value = "password", required = true) String password + + +) + throws NotFoundException { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + + + @ApiOperation(value = "Logs out current logged in user session", notes = "", response = Void.class) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Void.class) }) + @RequestMapping(value = "/logout", + produces = { "application/xml", "application/json" }, + + method = RequestMethod.GET) + public ResponseEntity logoutUser() + throws NotFoundException { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + + + @ApiOperation(value = "Updated user", notes = "This can only be done by the logged in user.", response = Void.class) + @ApiResponses(value = { + @ApiResponse(code = 400, message = "Invalid user supplied", response = Void.class), + @ApiResponse(code = 404, message = "User not found", response = Void.class) }) + @RequestMapping(value = "/{username}", + produces = { "application/xml", "application/json" }, + + method = RequestMethod.PUT) + public ResponseEntity updateUser( +@ApiParam(value = "name that need to be deleted",required=true ) @PathVariable("username") String username + +, + + +@ApiParam(value = "Updated user object" ,required=true ) @RequestBody User body +) + throws NotFoundException { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + +} diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/configuration/HomeController.java b/samples/server/petstore/springboot/src/main/java/io/swagger/configuration/HomeController.java new file mode 100644 index 00000000000..14fcf37acff --- /dev/null +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/configuration/HomeController.java @@ -0,0 +1,16 @@ +package io.swagger.configuration; + +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; + +/** + * Home redirection to swagger api documentation + */ +@Controller +public class HomeController { + @RequestMapping(value = "/") + public String index() { + System.out.println("swagger-ui.html"); + return "redirect:swagger-ui.html"; + } +} \ No newline at end of file diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/configuration/SwaggerDocumentationConfig.java b/samples/server/petstore/springboot/src/main/java/io/swagger/configuration/SwaggerDocumentationConfig.java new file mode 100644 index 00000000000..185c0e08794 --- /dev/null +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/configuration/SwaggerDocumentationConfig.java @@ -0,0 +1,40 @@ +package io.swagger.configuration; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import springfox.documentation.builders.ApiInfoBuilder; +import springfox.documentation.builders.RequestHandlerSelectors; +import springfox.documentation.service.ApiInfo; +import springfox.documentation.service.Contact; +import springfox.documentation.spi.DocumentationType; +import springfox.documentation.spring.web.plugins.Docket; + + + +@Configuration +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringBootServerCodegen", date = "2016-05-05T15:30:42.322+08:00") +public class SwaggerDocumentationConfig { + + ApiInfo apiInfo() { + return new ApiInfoBuilder() + .title("Swagger Petstore") + .description("This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.") + .license("Apache 2.0") + .licenseUrl("http://www.apache.org/licenses/LICENSE-2.0.html") + .termsOfServiceUrl("") + .version("1.0.0") + .contact(new Contact("","", "apiteam@swagger.io")) + .build(); + } + + @Bean + public Docket customImplementation(){ + return new Docket(DocumentationType.SWAGGER_2) + .select() + .apis(RequestHandlerSelectors.basePackage("io.swagger.api")) + .build() + .apiInfo(apiInfo()); + } + +} diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/model/Category.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/Category.java new file mode 100644 index 00000000000..411a206a7f6 --- /dev/null +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/Category.java @@ -0,0 +1,71 @@ +package io.swagger.model; + +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +import io.swagger.annotations.*; +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.util.Objects; + + +@ApiModel(description = "") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringBootServerCodegen", date = "2016-05-05T15:30:42.322+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(id).append("\n"); + sb.append(" name: ").append(name).append("\n"); + sb.append("}\n"); + return sb.toString(); + } +} diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/model/ModelApiResponse.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/ModelApiResponse.java new file mode 100644 index 00000000000..73a0717d5e5 --- /dev/null +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/ModelApiResponse.java @@ -0,0 +1,85 @@ +package io.swagger.model; + +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +import io.swagger.annotations.*; +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.util.Objects; + + +@ApiModel(description = "") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringBootServerCodegen", date = "2016-05-05T15:30:42.322+08:00") +public class ModelApiResponse { + + private Integer code = null; + private String type = null; + private String message = null; + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("code") + public Integer getCode() { + return code; + } + public void setCode(Integer code) { + this.code = code; + } + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("type") + public String getType() { + return type; + } + public void setType(String type) { + this.type = type; + } + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("message") + public String getMessage() { + return message; + } + public void setMessage(String message) { + this.message = message; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ModelApiResponse _apiResponse = (ModelApiResponse) o; + return Objects.equals(code, _apiResponse.code) && + Objects.equals(type, _apiResponse.type) && + Objects.equals(message, _apiResponse.message); + } + + @Override + public int hashCode() { + return Objects.hash(code, type, message); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ModelApiResponse {\n"); + + sb.append(" code: ").append(code).append("\n"); + sb.append(" type: ").append(type).append("\n"); + sb.append(" message: ").append(message).append("\n"); + sb.append("}\n"); + return sb.toString(); + } +} diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/model/Order.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/Order.java new file mode 100644 index 00000000000..3f8bbd49e37 --- /dev/null +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/Order.java @@ -0,0 +1,134 @@ +package io.swagger.model; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.util.Date; + +import io.swagger.annotations.*; +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.util.Objects; + + +@ApiModel(description = "") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringBootServerCodegen", date = "2016-05-05T15:30:42.322+08:00") +public class Order { + + private Long id = null; + private Long petId = null; + private Integer quantity = null; + private Date shipDate = null; + public enum StatusEnum { + placed, approved, delivered, + }; + + private StatusEnum status = null; + private Boolean complete = false; + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("id") + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("petId") + public Long getPetId() { + return petId; + } + public void setPetId(Long petId) { + this.petId = petId; + } + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("quantity") + public Integer getQuantity() { + return quantity; + } + public void setQuantity(Integer quantity) { + this.quantity = quantity; + } + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("shipDate") + public Date getShipDate() { + return shipDate; + } + public void setShipDate(Date shipDate) { + this.shipDate = shipDate; + } + + /** + * Order Status + **/ + @ApiModelProperty(value = "Order Status") + @JsonProperty("status") + public StatusEnum getStatus() { + return status; + } + public void setStatus(StatusEnum status) { + this.status = status; + } + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("complete") + public Boolean getComplete() { + return complete; + } + public void setComplete(Boolean complete) { + this.complete = complete; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Order order = (Order) o; + return Objects.equals(id, order.id) && + Objects.equals(petId, order.petId) && + Objects.equals(quantity, order.quantity) && + Objects.equals(shipDate, order.shipDate) && + Objects.equals(status, order.status) && + Objects.equals(complete, order.complete); + } + + @Override + public int hashCode() { + return Objects.hash(id, petId, quantity, shipDate, status, complete); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Order {\n"); + + sb.append(" id: ").append(id).append("\n"); + sb.append(" petId: ").append(petId).append("\n"); + sb.append(" quantity: ").append(quantity).append("\n"); + sb.append(" shipDate: ").append(shipDate).append("\n"); + sb.append(" status: ").append(status).append("\n"); + sb.append(" complete: ").append(complete).append("\n"); + sb.append("}\n"); + return sb.toString(); + } +} diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/model/Pet.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/Pet.java new file mode 100644 index 00000000000..1507c988f3b --- /dev/null +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/Pet.java @@ -0,0 +1,137 @@ +package io.swagger.model; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.model.Category; +import io.swagger.model.Tag; +import java.util.ArrayList; +import java.util.List; + +import io.swagger.annotations.*; +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.util.Objects; + + +@ApiModel(description = "") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringBootServerCodegen", date = "2016-05-05T15:30:42.322+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, pending, sold, + }; + + private StatusEnum status = null; + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("id") + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("category") + public Category getCategory() { + return category; + } + public void setCategory(Category category) { + this.category = category; + } + + /** + **/ + @ApiModelProperty(required = true, value = "") + @JsonProperty("name") + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + + /** + **/ + @ApiModelProperty(required = true, value = "") + @JsonProperty("photoUrls") + public List getPhotoUrls() { + return photoUrls; + } + public void setPhotoUrls(List photoUrls) { + this.photoUrls = photoUrls; + } + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("tags") + public List getTags() { + return tags; + } + public void setTags(List tags) { + this.tags = tags; + } + + /** + * pet status in the store + **/ + @ApiModelProperty(value = "pet status in the store") + @JsonProperty("status") + public StatusEnum getStatus() { + return status; + } + public void setStatus(StatusEnum status) { + this.status = status; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Pet pet = (Pet) o; + return Objects.equals(id, pet.id) && + Objects.equals(category, pet.category) && + Objects.equals(name, pet.name) && + Objects.equals(photoUrls, pet.photoUrls) && + Objects.equals(tags, pet.tags) && + Objects.equals(status, pet.status); + } + + @Override + public int hashCode() { + return Objects.hash(id, category, name, photoUrls, tags, status); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Pet {\n"); + + sb.append(" id: ").append(id).append("\n"); + sb.append(" category: ").append(category).append("\n"); + sb.append(" name: ").append(name).append("\n"); + sb.append(" photoUrls: ").append(photoUrls).append("\n"); + sb.append(" tags: ").append(tags).append("\n"); + sb.append(" status: ").append(status).append("\n"); + sb.append("}\n"); + return sb.toString(); + } +} diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/model/Tag.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/Tag.java new file mode 100644 index 00000000000..665a5c00270 --- /dev/null +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/Tag.java @@ -0,0 +1,71 @@ +package io.swagger.model; + +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +import io.swagger.annotations.*; +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.util.Objects; + + +@ApiModel(description = "") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringBootServerCodegen", date = "2016-05-05T15:30:42.322+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(id).append("\n"); + sb.append(" name: ").append(name).append("\n"); + sb.append("}\n"); + return sb.toString(); + } +} diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/model/User.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/User.java new file mode 100644 index 00000000000..dd8cd876e7b --- /dev/null +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/User.java @@ -0,0 +1,156 @@ +package io.swagger.model; + +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +import io.swagger.annotations.*; +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.util.Objects; + + +@ApiModel(description = "") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringBootServerCodegen", date = "2016-05-05T15:30:42.322+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(id).append("\n"); + sb.append(" username: ").append(username).append("\n"); + sb.append(" firstName: ").append(firstName).append("\n"); + sb.append(" lastName: ").append(lastName).append("\n"); + sb.append(" email: ").append(email).append("\n"); + sb.append(" password: ").append(password).append("\n"); + sb.append(" phone: ").append(phone).append("\n"); + sb.append(" userStatus: ").append(userStatus).append("\n"); + sb.append("}\n"); + return sb.toString(); + } +} diff --git a/samples/server/petstore/springboot/src/main/resources/application.properties b/samples/server/petstore/springboot/src/main/resources/application.properties new file mode 100644 index 00000000000..858a5f007b5 --- /dev/null +++ b/samples/server/petstore/springboot/src/main/resources/application.properties @@ -0,0 +1,2 @@ +springfox.documentation.swagger.v2.path=/api-docs +#server.port=8090 \ No newline at end of file