diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md index 9f573cea189..9a56dca7f02 100644 --- a/.github/ISSUE_TEMPLATE.md +++ b/.github/ISSUE_TEMPLATE.md @@ -13,7 +13,19 @@ Also please indicate in the issue title which language/library is concerned. Eg: ##### Swagger declaration file content or url - + ##### Command line used for generation diff --git a/.gitignore b/.gitignore index 4e650733033..3118eafbcfd 100644 --- a/.gitignore +++ b/.gitignore @@ -63,6 +63,12 @@ samples/client/petstore/java/jersey2/.gradle/ samples/client/petstore/java/jersey2/build/ samples/client/petstore/java/okhttp-gson/.gradle/ samples/client/petstore/java/okhttp-gson/build/ +samples/client/petstore/java/feign/build/ +samples/client/petstore/java/retrofit/build/ +samples/client/petstore/java/retrofit2/build/ +samples/client/petstore/java/retrofit2rx/build/ +samples/client/petstore/java/default/build/ +samples/client/petstore/scala/build/ #PHP samples/client/petstore/php/SwaggerClient-php/composer.lock @@ -106,6 +112,7 @@ 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 +samples/client/petstore/csharp/SwaggerClient/TestResult.xml # Python *.pyc diff --git a/.travis.yml b/.travis.yml index ea9cf505b82..1a0be745a6e 100644 --- a/.travis.yml +++ b/.travis.yml @@ -11,6 +11,7 @@ before_install: # required when sudo: required for the Ruby petstore tests - gem install bundler - npm install -g typescript + - sudo pip install virtualenv install: diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 4cf901c2d3f..a40a96f7b38 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -2,12 +2,10 @@ ## Before submitting an issue + - If you're not using the latest master to generate API clients or server stubs, please give it another try by pulling the latest master as the issue may have already been addressed. Ref: [Getting Started](https://github.com/swagger-api/swagger-codegen#getting-started) - Search the [open issue](https://github.com/swagger-api/swagger-codegen/issues) and [closed issue](https://github.com/swagger-api/swagger-codegen/issues?q=is%3Aissue+is%3Aclosed) to ensure no one else has reported something similar before. - - The issue should contain details on how to repeat the issue, e.g. - - the OpenAPI Spec for reproducing the issue (:bulb: use [Gist](https://gist.github.com) to share). If the OpenAPI Spec cannot be shared publicly, it will be hard for the community to help - - version of Swagger Codegen - - language (`-l` in the command line, e.g. java, csharp, php) - - You can also make a suggestion or ask a question by opening an "issue" + - File an [issue ticket](https://github.com/swagger-api/swagger-codegen/issues/new) by providing all the required information. + - You can also make a suggestion or ask a question by opening an "issue". ## Before submitting a PR @@ -42,11 +40,14 @@ Code change should conform to the programming style guide of the respective lang - Swift: https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html - TypeScript: https://github.com/Microsoft/TypeScript/wiki/Coding-guidelines - For other languages, feel free to suggest. You may find the current code base not 100% conform to the coding style and we welcome contributions to fix those. +For [Vendor Extensions](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#vendorExtensions), please follow the naming convention below: +- For general vendor extension, use lower case and hyphen. e.g. `x-is-unique`, `x-content-type` +- For language-specified vendor extension, put it in the form of `x-{lang}-{extension-name}`. e.g. `x-objc-operation-id`, `x-java-feign-retry-limit` + ### Testing To add test cases (optional) covering the change in the code generator, please refer to [modules/swagger-codegen/src/test/java/io/swagger/codegen](https://github.com/swagger-api/swagger-codegen/tree/master/modules/swagger-codegen/src/test/java/io/swagger/codegen) diff --git a/README.md b/README.md index 3a8e9d4c629..ece108666e1 100644 --- a/README.md +++ b/README.md @@ -860,6 +860,7 @@ Here are some companies/projects using Swagger Codegen in production. To add you - [everystory.us](http://everystory.us) - [Expected Behavior](http://www.expectedbehavior.com/) - [FH Münster - University of Applied Sciences](http://www.fh-muenster.de) +- [GraphHopper](https://graphhopper.com/) - [IMS Health](http://www.imshealth.com/en/solution-areas/technology-and-applications) - [Interactive Intelligence](http://developer.mypurecloud.com/) - [LANDR Audio](https://www.landr.com/) diff --git a/bin/java-petstore-feign.sh b/bin/java-petstore-feign.sh index 063b85f70a1..61c4621a1f6 100755 --- a/bin/java-petstore-feign.sh +++ b/bin/java-petstore-feign.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 java -c bin/java-petstore-feign.json -o samples/client/petstore/java/feign" +ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l java -c bin/java-petstore-feign.json -o samples/client/petstore/java/feign -DhideGenerationTimestamp=true" java $JAVA_OPTS -jar $executable $ags diff --git a/bin/java-petstore-jersey2.sh b/bin/java-petstore-jersey2.sh index a715e7ff545..0850bdbb4f4 100755 --- a/bin/java-petstore-jersey2.sh +++ b/bin/java-petstore-jersey2.sh @@ -26,6 +26,9 @@ fi # if you've executed sbt assembly previously it will use that instead. export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" -ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l java -c bin/java-petstore-jersey2.json -o samples/client/petstore/java/jersey2" +ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l java -c bin/java-petstore-jersey2.json -o samples/client/petstore/java/jersey2 -DhideGenerationTimestamp=true" +echo "Removing files and folders under samples/client/petstore/java/jersey2/src/main" +rm -rf samples/client/petstore/java/jersey2/src/main +find samples/client/petstore/java/jersey2 -maxdepth 1 -type f ! -name "README.md" -exec rm {} + java $JAVA_OPTS -jar $executable $ags diff --git a/bin/java-petstore-okhttp-gson.sh b/bin/java-petstore-okhttp-gson.sh index f656624a6c6..492cd5ff4a4 100755 --- a/bin/java-petstore-okhttp-gson.sh +++ b/bin/java-petstore-okhttp-gson.sh @@ -26,6 +26,8 @@ fi # if you've executed sbt assembly previously it will use that instead. export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" -ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l java -c bin/java-petstore-okhttp-gson.json -o samples/client/petstore/java/okhttp-gson" +ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l java -c bin/java-petstore-okhttp-gson.json -o samples/client/petstore/java/okhttp-gson -DhideGenerationTimestamp=true" +rm -rf samples/client/petstore/java/okhttp-gson/src/main +find samples/client/petstore/java/okhttp-gson -maxdepth 1 -type f ! -name "README.md" -exec rm {} + java $JAVA_OPTS -jar $executable $ags diff --git a/bin/java-petstore-retrofit.sh b/bin/java-petstore-retrofit.sh index db4001e4c9e..3b370fde7dd 100755 --- a/bin/java-petstore-retrofit.sh +++ b/bin/java-petstore-retrofit.sh @@ -26,6 +26,9 @@ fi # if you've executed sbt assembly previously it will use that instead. export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" -ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l java -c bin/java-petstore-retrofit.json -o samples/client/petstore/java/retrofit" +ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l java -c bin/java-petstore-retrofit.json -o samples/client/petstore/java/retrofit -DhideGenerationTimestamp=true" +echo "Removing files and folders under samples/client/petstore/java/retrofit/src/main" +rm -rf samples/client/petstore/java/retrofit/src/main +find samples/client/petstore/java/retrofit -maxdepth 1 -type f ! -name "README.md" -exec rm {} + java $JAVA_OPTS -jar $executable $ags diff --git a/bin/java-petstore-retrofit2.sh b/bin/java-petstore-retrofit2.sh index 3fda4df3166..8cf9468c3a1 100755 --- a/bin/java-petstore-retrofit2.sh +++ b/bin/java-petstore-retrofit2.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 java -c bin/java-petstore-retrofit2.json -o samples/client/petstore/java/retrofit2" +ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l java -c bin/java-petstore-retrofit2.json -o samples/client/petstore/java/retrofit2 -DhideGenerationTimestamp=true" java $JAVA_OPTS -jar $executable $ags diff --git a/bin/java-petstore-retrofit2rx.sh b/bin/java-petstore-retrofit2rx.sh index d714cc33455..af62352c03f 100755 --- a/bin/java-petstore-retrofit2rx.sh +++ b/bin/java-petstore-retrofit2rx.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 java -c bin/java-petstore-retrofit2rx.json -o samples/client/petstore/java/retrofit2rx -DuseRxJava=true" +ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l java -c bin/java-petstore-retrofit2rx.json -o samples/client/petstore/java/retrofit2rx -DuseRxJava=true,hideGenerationTimestamp=true" java $JAVA_OPTS -jar $executable $ags diff --git a/bin/java-petstore.sh b/bin/java-petstore.sh index ed80c841df6..be6472d7aad 100755 --- a/bin/java-petstore.sh +++ b/bin/java-petstore.sh @@ -28,4 +28,7 @@ fi export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l java -o samples/client/petstore/java/default -DhideGenerationTimestamp=true" +echo "Removing files and folders under samples/client/petstore/java/default/src/main" +rm -rf samples/client/petstore/java/default/src/main +find samples/client/petstore/java/default -maxdepth 1 -type f ! -name "README.md" -exec rm {} + java $JAVA_OPTS -jar $executable $ags diff --git a/bin/python-petstore.sh b/bin/python-petstore.sh index ef120089f45..0fe89ea39ed 100755 --- a/bin/python-petstore.sh +++ b/bin/python-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/python -i modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l python -o samples/client/petstore/python" +ags="$@ generate -t modules/swagger-codegen/src/main/resources/python -i modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l python -o samples/client/petstore/python -DpackageName=petstore_api" java $JAVA_OPTS -jar $executable $ags diff --git a/bin/spring-stubs.sh b/bin/spring-stubs.sh new file mode 100755 index 00000000000..3d13f2fe8b9 --- /dev/null +++ b/bin/spring-stubs.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.yaml -l springboot -o samples/client/petstore/spring-stubs -DinterfaceOnly=true,singleContentTypes=true" + +java $JAVA_OPTS -jar $executable $ags diff --git a/bin/springboot-petstore-server.sh b/bin/springboot-petstore-server.sh index 83d810ba595..7fe3ac60e53 100755 --- a/bin/springboot-petstore-server.sh +++ b/bin/springboot-petstore-server.sh @@ -26,6 +26,9 @@ 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" +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 -DhideGenerationTimestamp=true" +echo "Removing files and folders under samples/server/petstore/springboot/src/main" +rm -rf samples/server/petstore/springboot/src/main +find samples/server/petstore/springboot -maxdepth 1 -type f ! -name "README.md" -exec rm {} + java $JAVA_OPTS -jar $executable $ags diff --git a/bin/swift-petstore.sh b/bin/swift-petstore.sh old mode 100644 new mode 100755 diff --git a/bin/windows/java-petstore-okhttp-gson.bat b/bin/windows/java-petstore-okhttp-gson.bat new file mode 100755 index 00000000000..e7c1dde982a --- /dev/null +++ b/bin/windows/java-petstore-okhttp-gson.bat @@ -0,0 +1,10 @@ +set executable=.\modules\swagger-codegen-cli\target\swagger-codegen-cli.jar + +If Not Exist %executable% ( + mvn clean package +) + +set JAVA_OPTS=%JAVA_OPTS% -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties +set ags=generate -t modules\swagger-codegen\src\main\resources\java -i modules\swagger-codegen\src\test\resources\2_0\petstore.json -l java -o samples\client\petstore\java --library=okhttp-gson -DdateLibrary=joda,hideGenerationTimestamp=true + +java %JAVA_OPTS% -jar %executable% %ags% diff --git a/bin/windows/java-petstore.bat b/bin/windows/java-petstore.bat index 18544cbad36..02a81e1adbf 100755 --- a/bin/windows/java-petstore.bat +++ b/bin/windows/java-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\java -i modules\swagger-codegen\src\test\resources\2_0\petstore.json -l java -o samples\client\petstore\java +set ags=generate -t modules\swagger-codegen\src\main\resources\java -i modules\swagger-codegen\src\test\resources\2_0\petstore.json -l java -o samples\client\petstore\java -DdateLibrary=joda,hideGenerationTimestamp=true java %JAVA_OPTS% -jar %executable% %ags% diff --git a/bin/windows/rails5-petstore-server.bat b/bin/windows/rails5-petstore-server.bat new file mode 100755 index 00000000000..a0316279784 --- /dev/null +++ b/bin/windows/rails5-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\rails5 -i modules\swagger-codegen\src\test\resources\2_0\petstore.json -l rails5 -o samples\server\petstore\rails5\ + +java %JAVA_OPTS% -jar %executable% %ags% diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/AbstractGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/AbstractGenerator.java index 40b59435c44..849651baa9d 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/AbstractGenerator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/AbstractGenerator.java @@ -72,28 +72,20 @@ public abstract class AbstractGenerator { * @return String Full template file path */ public String getFullTemplateFile(CodegenConfig config, String templateFile) { - String library = config.getLibrary(); - if (library != null && !"".equals(library)) { - String libTemplateFile = config.templateDir() + File.separator + - "libraries" + File.separator + library + File.separator + - templateFile; - - if (new File(libTemplateFile).exists()) { - return libTemplateFile; - } - - libTemplateFile = config.embeddedTemplateDir() + File.separator + - "libraries" + File.separator + library + File.separator + - templateFile; - if (embeddedTemplateExists(libTemplateFile)) { - // Fall back to the template file embedded/packaged in the JAR file... - return libTemplateFile; - } - } String template = config.templateDir() + File.separator + templateFile; if (new File(template).exists()) { return template; } else { + String library = config.getLibrary(); + if (library != null && !"".equals(library)) { + String libTemplateFile = config.embeddedTemplateDir() + File.separator + + "libraries" + File.separator + library + File.separator + + templateFile; + if (embeddedTemplateExists(libTemplateFile)) { + // Fall back to the template file embedded/packaged in the JAR file... + return libTemplateFile; + } + } // Fall back to the template file embedded/packaged in the JAR file... return config.embeddedTemplateDir() + File.separator + templateFile; } 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 fceb69ac8db..8304849a14c 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 @@ -792,7 +792,11 @@ public class DefaultCodegen { importMapping.put("LocalDate", "org.joda.time.*"); importMapping.put("LocalTime", "org.joda.time.*"); - supportingFiles.add(new GlobalSupportingFile("LICENSE", "LICENSE")); + // we've used the .swagger-codegen-ignore approach as + // suppportingFiles can be cleared by code generator that extends + // the default codegen, leaving the commented code below for + // future reference + //supportingFiles.add(new GlobalSupportingFile("LICENSE", "LICENSE")); cliOptions.add(CliOption.newBoolean(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG_DESC).defaultValue(Boolean.TRUE.toString())); @@ -1960,7 +1964,7 @@ public class DefaultCodegen { } } r.dataType = cm.datatype; - r.isBinary = cm.datatype.toLowerCase().startsWith("byte"); + r.isBinary = isDataTypeBinary(cm.datatype); if (cm.isContainer != null) { r.simpleType = false; r.containerType = cm.containerType; @@ -2129,7 +2133,7 @@ public class DefaultCodegen { p.baseType = cp.baseType; p.dataType = cp.datatype; p.isPrimitiveType = cp.isPrimitiveType; - p.isBinary = cp.datatype.toLowerCase().startsWith("byte"); + p.isBinary = isDataTypeBinary(cp.datatype); } // set boolean flag (e.g. isString) @@ -2226,7 +2230,7 @@ public class DefaultCodegen { p.isCookieParam = true; } else if (param instanceof BodyParameter) { p.isBodyParam = true; - p.isBinary = p.dataType.toLowerCase().startsWith("byte"); + p.isBinary = isDataTypeBinary(p.dataType); } else if (param instanceof FormParameter) { if ("file".equalsIgnoreCase(((FormParameter) param).getType())) { p.isFile = true; @@ -2242,6 +2246,10 @@ public class DefaultCodegen { return p; } + public boolean isDataTypeBinary(String dataType) { + return dataType.toLowerCase().startsWith("byte"); + } + /** * Convert map of Swagger SecuritySchemeDefinition objects to a list of Codegen Security objects * diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaJAXRSServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaJAXRSServerCodegen.java index 27f435250a0..fbb2831ab8b 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaJAXRSServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaJAXRSServerCodegen.java @@ -26,6 +26,7 @@ public abstract class AbstractJavaJAXRSServerCodegen extends JavaClientCodegen { public AbstractJavaJAXRSServerCodegen() { super(); + dateLibrary = "legacy"; apiTestTemplateFiles.clear(); // TODO: add test template } 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 e926235ba90..4265f67709c 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 @@ -233,12 +233,18 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen { clientPackageDir, "ApiException.cs")); supportingFiles.add(new SupportingFile("ApiResponse.mustache", clientPackageDir, "ApiResponse.cs")); + supportingFiles.add(new SupportingFile("ExceptionFactory.mustache", + clientPackageDir, "ExceptionFactory.cs")); supportingFiles.add(new SupportingFile("compile.mustache", "", "build.bat")); supportingFiles.add(new SupportingFile("compile-mono.sh.mustache", "", "build.sh")); + // shell script to run the nunit test + supportingFiles.add(new SupportingFile("mono_nunit_test.mustache", "", "mono_nunit_test.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")); + // .travis.yml for travis-ci.org CI + supportingFiles.add(new SupportingFile("travis.mustache", "", ".travis.yml")); if(Boolean.FALSE.equals(excludeTests)) { supportingFiles.add(new SupportingFile("packages_test.config.mustache", testPackageFolder + File.separator, "packages.config")); @@ -248,7 +254,8 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen { supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore")); // apache v2 license - supportingFiles.add(new SupportingFile("LICENSE", "", "LICENSE")); + // UPDATE (20160612) no longer needed as the Apache v2 LICENSE is added globally + //supportingFiles.add(new SupportingFile("LICENSE", "", "LICENSE")); if (optionalAssemblyInfoFlag) { supportingFiles.add(new SupportingFile("AssemblyInfo.mustache", packageFolder + File.separator + "Properties", "AssemblyInfo.cs")); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GroovyClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GroovyClientCodegen.java index 1ed9604fbf4..5b26662531f 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GroovyClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GroovyClientCodegen.java @@ -27,6 +27,7 @@ public class GroovyClientCodegen extends JavaClientCodegen { configPackage = "io.swagger.configuration"; invokerPackage = "io.swagger.api"; artifactId = "swagger-spring-mvc-server"; + dateLibrary = "legacy"; additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, invokerPackage); additionalProperties.put(CodegenConstants.GROUP_ID, groupId); 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 903eb1f8942..c80bb0ed23f 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 @@ -30,7 +30,7 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { public static final String RETROFIT_1 = "retrofit"; public static final String RETROFIT_2 = "retrofit2"; - protected String dateLibrary = "default"; + protected String dateLibrary = "joda"; protected String invokerPackage = "io.swagger.client"; protected String groupId = "io.swagger"; protected String artifactId = "swagger-java-client"; @@ -128,6 +128,7 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { Map dateOptions = new HashMap(); dateOptions.put("java8", "Java 8 native"); dateOptions.put("joda", "Joda"); + dateOptions.put("legacy", "Legacy java.util.Date"); dateLibrary.setEnum(dateOptions); cliOptions.add(dateLibrary); @@ -261,7 +262,7 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { writeOptional(outputFolder, new SupportingFile("settings.gradle.mustache", "", "settings.gradle")); writeOptional(outputFolder, new SupportingFile("gradle.properties.mustache", "", "gradle.properties")); writeOptional(outputFolder, new SupportingFile("manifest.mustache", projectFolder, "AndroidManifest.xml")); - writeOptional(outputFolder, new SupportingFile("ApiClient.mustache", invokerFolder, "ApiClient.java")); + supportingFiles.add(new SupportingFile("ApiClient.mustache", invokerFolder, "ApiClient.java")); supportingFiles.add(new SupportingFile("StringUtil.mustache", invokerFolder, "StringUtil.java")); final String authFolder = (sourceFolder + '/' + invokerPackage + ".auth").replace(".", "/"); @@ -275,6 +276,8 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { gradleWrapperPackage.replace( ".", File.separator ), "gradle-wrapper.properties") ); supportingFiles.add( new SupportingFile( "gradle-wrapper.jar", gradleWrapperPackage.replace( ".", File.separator ), "gradle-wrapper.jar") ); + // "build.sbt" is for development with SBT + supportingFiles.add(new SupportingFile("build.sbt.mustache", "", "build.sbt")); } supportingFiles.add(new SupportingFile("auth/HttpBasicAuth.mustache", authFolder, "HttpBasicAuth.java")); supportingFiles.add(new SupportingFile("auth/ApiKeyAuth.mustache", authFolder, "ApiKeyAuth.java")); @@ -332,6 +335,8 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { gradleWrapperPackage.replace( ".", File.separator ), "gradle-wrapper.properties") ); supportingFiles.add( new SupportingFile( "gradle-wrapper.jar", gradleWrapperPackage.replace( ".", File.separator ), "gradle-wrapper.jar") ); + // "build.sbt" is for development with SBT + supportingFiles.add(new SupportingFile("build.sbt.mustache", "", "build.sbt")); //generate markdown docs for retrofit2 if ( usesRetrofit2Library() ){ diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaInflectorServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaInflectorServerCodegen.java index bb32ee9ab8d..8a08bf758a3 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaInflectorServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaInflectorServerCodegen.java @@ -29,6 +29,7 @@ public class JavaInflectorServerCodegen extends JavaClientCodegen { embeddedTemplateDir = templateDir = "JavaInflector"; invokerPackage = "io.swagger.handler"; artifactId = "swagger-inflector-server"; + dateLibrary = "legacy"; apiPackage = System.getProperty("swagger.codegen.inflector.apipackage", "io.swagger.handler"); modelPackage = System.getProperty("swagger.codegen.inflector.modelpackage", "io.swagger.model"); 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 5717c902740..4c13fd50f0b 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 @@ -34,6 +34,7 @@ public class JavaResteasyServerCodegen extends JavaClientCodegen implements Code apiTestTemplateFiles.clear(); // TODO: add test template apiPackage = "io.swagger.api"; modelPackage = "io.swagger.model"; + dateLibrary = "legacy"; additionalProperties.put("title", title); 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 67cf272c0ba..cc1e77649e5 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 @@ -23,7 +23,6 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { public static final String GIT_REPO_URL = "gitRepoURL"; public static final String DEFAULT_LICENSE = "Apache License, Version 2.0"; public static final String CORE_DATA = "coreData"; - public static final String BinaryDataType = "ObjcClientCodegenBinaryData"; protected Set foundationClasses = new HashSet(); protected String podName = "SwaggerClient"; @@ -70,8 +69,7 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { defaultIncludes.add("NSMutableArray"); defaultIncludes.add("NSMutableDictionary"); defaultIncludes.add("NSManagedObject"); - - defaultIncludes.add(BinaryDataType); + defaultIncludes.add("NSData"); advancedMapingTypes.add("NSDictionary"); advancedMapingTypes.add("NSArray"); @@ -88,6 +86,7 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { languageSpecificPrimitives.add("NSString"); languageSpecificPrimitives.add("NSObject"); languageSpecificPrimitives.add("NSDate"); + languageSpecificPrimitives.add("NSData"); languageSpecificPrimitives.add("NSURL"); languageSpecificPrimitives.add("bool"); languageSpecificPrimitives.add("BOOL"); @@ -109,8 +108,9 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { typeMapping.put("List", "NSArray"); typeMapping.put("object", "NSObject"); typeMapping.put("file", "NSURL"); - typeMapping.put("binary", BinaryDataType); - typeMapping.put("ByteArray", BinaryDataType); + typeMapping.put("binary", "NSData"); + typeMapping.put("ByteArray", "NSData"); + typeMapping.put("byte", "NSData"); // ref: http://www.tutorialspoint.com/objective_c/objective_c_basic_syntax.htm setReservedWordsLowerCase( @@ -143,6 +143,7 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { "NSObject", "NSString", "NSDate", + "NSData", "NSURL", "NSDictionary") ); @@ -317,16 +318,10 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { if (p instanceof ArrayProperty) { ArrayProperty ap = (ArrayProperty) p; Property inner = ap.getItems(); - 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 condition, type of property p is array of primitive, // return container type with pointer, e.g. `NSArray**' if (languageSpecificPrimitives.contains(innerTypeDeclaration)) { @@ -363,7 +358,6 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { } } else { String swaggerType = getSwaggerType(p); - // In this condition, type of p is objective-c primitive type, e.g. `NSSNumber', // return type of p with pointer, e.g. `NSNumber*' if (languageSpecificPrimitives.contains(swaggerType) && @@ -394,10 +388,6 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { 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**' if (languageSpecificPrimitives.contains(innerTypeDeclaration)) { @@ -454,6 +444,11 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { } } + @Override + public boolean isDataTypeBinary(String dataType) { + return dataType.toLowerCase().startsWith("nsdata"); + } + @Override public String toModelName(String type) { // model name cannot use reserved keyword diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Rails5ServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Rails5ServerCodegen.java index cbf77338ab3..4bb4c8e883c 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Rails5ServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Rails5ServerCodegen.java @@ -1,5 +1,7 @@ package io.swagger.codegen.languages; +import java.text.SimpleDateFormat; +import java.util.Date; import com.fasterxml.jackson.core.JsonProcessingException; import io.swagger.codegen.CodegenConfig; @@ -24,6 +26,7 @@ import org.slf4j.LoggerFactory; public class Rails5ServerCodegen extends DefaultCodegen implements CodegenConfig { private static final Logger LOGGER = LoggerFactory.getLogger(Rails5ServerCodegen.class); + private static final SimpleDateFormat MIGRATE_FILE_NAME_FORMAT = new SimpleDateFormat("yyyyMMddHHmmss"); protected String gemName; protected String moduleName; @@ -57,12 +60,13 @@ public class Rails5ServerCodegen extends DefaultCodegen implements CodegenConfig public Rails5ServerCodegen() { super(); - apiPackage = "app/controllers"; outputFolder = "generated-code" + File.separator + "rails5"; - - // no model - modelTemplateFiles.clear(); + apiPackage = "app/controllers"; apiTemplateFiles.put("controller.mustache", ".rb"); + + modelPackage = "app/models"; + modelTemplateFiles.put("model.mustache", ".rb"); + embeddedTemplateDir = templateDir = "rails5"; typeMapping.clear(); @@ -77,21 +81,21 @@ public class Rails5ServerCodegen extends DefaultCodegen implements CodegenConfig "if", "not", "return", "undef", "yield") ); - languageSpecificPrimitives.add("int"); - languageSpecificPrimitives.add("array"); - languageSpecificPrimitives.add("map"); - languageSpecificPrimitives.add("string"); - languageSpecificPrimitives.add("DateTime"); - - typeMapping.put("long", "int"); - typeMapping.put("integer", "int"); - typeMapping.put("Array", "array"); - typeMapping.put("String", "string"); - typeMapping.put("List", "array"); - typeMapping.put("map", "map"); - //TODO binary should be mapped to byte array - // mapped to String as a workaround + typeMapping.put("string", "string"); + typeMapping.put("char", "string"); + typeMapping.put("int", "integer"); + typeMapping.put("integer", "integer"); + typeMapping.put("long", "integer"); + typeMapping.put("short", "integer"); + typeMapping.put("float", "float"); + typeMapping.put("double", "decimal"); + typeMapping.put("number", "float"); + typeMapping.put("date", "date"); + typeMapping.put("DateTime", "datetime"); + typeMapping.put("boolean", "boolean"); typeMapping.put("binary", "string"); + typeMapping.put("ByteArray", "string"); + typeMapping.put("UUID", "string"); // remove modelPackage and apiPackage added by default cliOptions.clear(); @@ -145,6 +149,7 @@ public class Rails5ServerCodegen extends DefaultCodegen implements CodegenConfig supportingFiles.add(new SupportingFile("secrets.yml", configFolder, "secrets.yml")); supportingFiles.add(new SupportingFile("spring.rb", configFolder, "spring.rb")); supportingFiles.add(new SupportingFile(".keep", migrateFolder, ".keep")); + supportingFiles.add(new SupportingFile("migrate.mustache", migrateFolder, "0_init_tables.rb")); supportingFiles.add(new SupportingFile("schema.rb", dbFolder, "schema.rb")); supportingFiles.add(new SupportingFile("seeds.rb", dbFolder, "seeds.rb")); supportingFiles.add(new SupportingFile(".keep", tasksFolder, ".keep")); @@ -204,24 +209,6 @@ public class Rails5ServerCodegen extends DefaultCodegen implements CodegenConfig return super.getTypeDeclaration(p); } - @Override - public String getSwaggerType(Property p) { - String swaggerType = super.getSwaggerType(p); - String type = null; - if (typeMapping.containsKey(swaggerType)) { - type = typeMapping.get(swaggerType); - if (languageSpecificPrimitives.contains(type)) { - return type; - } - } else { - type = swaggerType; - } - if (type == null) { - return null; - } - return type; - } - @Override public String toDefaultValue(Property p) { return "null"; @@ -249,6 +236,16 @@ public class Rails5ServerCodegen extends DefaultCodegen implements CodegenConfig return name; } + @Override + public String getSwaggerType(Property p) { + String swaggerType = super.getSwaggerType(p); + String type = null; + if (typeMapping.containsKey(swaggerType)) { + return typeMapping.get(swaggerType); + } + return "string"; + } + @Override public String toParamName(String name) { // should be the same as variable name 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 992693810da..12467f12efe 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 @@ -35,6 +35,7 @@ public class ScalaClientCodegen extends DefaultCodegen implements CodegenConfig protected String artifactVersion = "1.0.0"; protected String sourceFolder = "src/main/scala"; protected String authScheme = ""; + protected String gradleWrapperPackage = "gradle.wrapper"; protected boolean authPreemptive; protected boolean asyncHttpClient = !authScheme.isEmpty(); @@ -74,6 +75,17 @@ public class ScalaClientCodegen extends DefaultCodegen implements CodegenConfig (sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "ApiInvoker.scala")); supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore")); + // gradle settings + supportingFiles.add(new SupportingFile("build.gradle.mustache", "", "build.gradle")); + supportingFiles.add(new SupportingFile("settings.gradle.mustache", "", "settings.gradle")); + supportingFiles.add(new SupportingFile("gradle.properties.mustache", "", "gradle.properties")); + // gradleWrapper files + supportingFiles.add(new SupportingFile( "gradlew.mustache", "", "gradlew") ); + supportingFiles.add(new SupportingFile( "gradlew.bat.mustache", "", "gradlew.bat") ); + supportingFiles.add(new SupportingFile( "gradle-wrapper.properties.mustache", + gradleWrapperPackage.replace( ".", File.separator ), "gradle-wrapper.properties") ); + supportingFiles.add(new SupportingFile( "gradle-wrapper.jar", + gradleWrapperPackage.replace( ".", File.separator ), "gradle-wrapper.jar") ); importMapping.remove("List"); importMapping.remove("Set"); 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 index 7a487494a5b..dbed6bc98c4 100644 --- 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 @@ -10,15 +10,18 @@ import java.util.*; public class SpringBootServerCodegen extends JavaClientCodegen implements CodegenConfig{ public static final String CONFIG_PACKAGE = "configPackage"; public static final String BASE_PACKAGE = "basePackage"; + public static final String INTERFACE_ONLY = "interfaceOnly"; + public static final String SINGLE_CONTENT_TYPES = "singleContentTypes"; protected String title = "Petstore Server"; protected String configPackage = ""; protected String basePackage = ""; + protected boolean interfaceOnly = false; + protected boolean singleContentTypes = false; protected String templateFileName = "api.mustache"; public SpringBootServerCodegen() { super(); outputFolder = "generated-code/javaSpringBoot"; - modelTemplateFiles.put("model.mustache", ".java"); apiTemplateFiles.put(templateFileName, ".java"); apiTestTemplateFiles.clear(); // TODO: add test template embeddedTemplateDir = templateDir = "JavaSpringBoot"; @@ -40,7 +43,9 @@ public class SpringBootServerCodegen extends JavaClientCodegen implements Codege cliOptions.add(new CliOption(CONFIG_PACKAGE, "configuration package for generated code")); cliOptions.add(new CliOption(BASE_PACKAGE, "base package for generated code")); - + cliOptions.add(CliOption.newBoolean(INTERFACE_ONLY, "Whether to generate only API interface stubs without the server files.")); + cliOptions.add(CliOption.newBoolean(SINGLE_CONTENT_TYPES, "Whether to select only one produces/consumes content-type by operation.")); + 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 " + @@ -79,30 +84,37 @@ public class SpringBootServerCodegen extends JavaClientCodegen implements Codege this.setBasePackage((String) additionalProperties.get(BASE_PACKAGE)); } + if (additionalProperties.containsKey(INTERFACE_ONLY)) { + this.setInterfaceOnly(Boolean.valueOf(additionalProperties.get(INTERFACE_ONLY).toString())); + } + + if (additionalProperties.containsKey(SINGLE_CONTENT_TYPES)) { + this.setSingleContentTypes(Boolean.valueOf(additionalProperties.get(SINGLE_CONTENT_TYPES).toString())); + } + 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")); + if(!this.interfaceOnly) { + apiTemplateFiles.put("apiController.mustache", "Controller.java"); + supportingFiles.add(new SupportingFile("apiException.mustache", + (sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "ApiException.java")); + supportingFiles.add(new SupportingFile("apiOriginFilter.mustache", + (sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "ApiOriginFilter.java")); + supportingFiles.add(new SupportingFile("apiResponseMessage.mustache", + (sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "ApiResponseMessage.java")); + supportingFiles.add(new SupportingFile("notFoundException.mustache", + (sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "NotFoundException.java")); + supportingFiles.add(new SupportingFile("swaggerDocumentationConfig.mustache", + (sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "SwaggerDocumentationConfig.java")); + 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 @@ -119,9 +131,6 @@ public class SpringBootServerCodegen extends JavaClientCodegen implements Codege 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); @@ -132,10 +141,10 @@ public class SpringBootServerCodegen extends JavaClientCodegen implements Codege opList.add(co); co.baseName = basePath; } - + @Override public void preprocessSwagger(Swagger swagger) { - System.out.println("preprocessSwagger"); + super.preprocessSwagger(swagger); if ("/".equals(swagger.getBasePath())) { swagger.setBasePath(""); } @@ -148,7 +157,7 @@ public class SpringBootServerCodegen extends JavaClientCodegen implements Codege port = parts[1]; } } - + this.additionalProperties.put("serverPort", port); if (swagger != null && swagger.getPaths() != null) { for (String pathname : swagger.getPaths().keySet()) { @@ -256,6 +265,14 @@ public class SpringBootServerCodegen extends JavaClientCodegen implements Codege public void setBasePackage(String configPackage) { this.basePackage = configPackage; } + + public void setInterfaceOnly(boolean interfaceOnly) { + this.interfaceOnly = interfaceOnly; + } + + public void setSingleContentTypes(boolean singleContentTypes) { + this.singleContentTypes = singleContentTypes; + } @Override public Map postProcessModels(Map 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 18b2f872d56..47c67a4ec6d 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 @@ -25,6 +25,7 @@ public class SpringMVCServerCodegen extends JavaClientCodegen implements Codegen configPackage = "io.swagger.configuration"; invokerPackage = "io.swagger.api"; artifactId = "swagger-spring-mvc-server"; + dateLibrary = "legacy"; additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, invokerPackage); additionalProperties.put(CodegenConstants.GROUP_ID, groupId); diff --git a/modules/swagger-codegen/src/main/resources/Java/Configuration.mustache b/modules/swagger-codegen/src/main/resources/Java/Configuration.mustache index 4629c4e17be..cb425df3563 100644 --- a/modules/swagger-codegen/src/main/resources/Java/Configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/Configuration.mustache @@ -1,22 +1,28 @@ +{{>licenseInfo}} + package {{invokerPackage}}; {{>generatedAnnotation}} public class Configuration { - private static ApiClient defaultApiClient = new ApiClient(); + private static ApiClient defaultApiClient = new ApiClient(); - /** - * Get the default API client, which would be used when creating API - * instances without providing an API client. - */ - public static ApiClient getDefaultApiClient() { - return defaultApiClient; - } + /** + * Get the default API client, which would be used when creating API + * instances without providing an API client. + * + * @return Default API client + */ + public static ApiClient getDefaultApiClient() { + return defaultApiClient; + } - /** - * Set the default API client, which would be used when creating API - * instances without providing an API client. - */ - public static void setDefaultApiClient(ApiClient apiClient) { - defaultApiClient = apiClient; - } + /** + * Set the default API client, which would be used when creating API + * instances without providing an API client. + * + * @param apiClient API client + */ + public static void setDefaultApiClient(ApiClient apiClient) { + defaultApiClient = apiClient; + } } diff --git a/modules/swagger-codegen/src/main/resources/Java/Pair.mustache b/modules/swagger-codegen/src/main/resources/Java/Pair.mustache index e2a47317afe..c08f145a482 100644 --- a/modules/swagger-codegen/src/main/resources/Java/Pair.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/Pair.mustache @@ -1,3 +1,5 @@ +{{>licenseInfo}} + package {{invokerPackage}}; {{>generatedAnnotation}} diff --git a/modules/swagger-codegen/src/main/resources/Java/StringUtil.mustache b/modules/swagger-codegen/src/main/resources/Java/StringUtil.mustache index 073966b0c21..7b72a7bab45 100644 --- a/modules/swagger-codegen/src/main/resources/Java/StringUtil.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/StringUtil.mustache @@ -1,3 +1,5 @@ +{{>licenseInfo}} + package {{invokerPackage}}; {{>generatedAnnotation}} diff --git a/modules/swagger-codegen/src/main/resources/Java/apiException.mustache b/modules/swagger-codegen/src/main/resources/Java/apiException.mustache index b9a62a6b231..89ed524d37e 100644 --- a/modules/swagger-codegen/src/main/resources/Java/apiException.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/apiException.mustache @@ -1,3 +1,5 @@ +{{>licenseInfo}} + package {{invokerPackage}}; import java.util.Map; @@ -5,65 +7,74 @@ import java.util.List; {{>generatedAnnotation}} public class ApiException extends Exception { - private int code = 0; - private Map> responseHeaders = null; - private String responseBody = null; + private int code = 0; + private Map> responseHeaders = null; + private String responseBody = null; - public ApiException() {} + public ApiException() {} - public ApiException(Throwable throwable) { - super(throwable); - } + public ApiException(Throwable throwable) { + super(throwable); + } - public ApiException(String message) { - super(message); - } + public ApiException(String message) { + super(message); + } - public ApiException(String message, Throwable throwable, int code, Map> responseHeaders, String responseBody) { - super(message, throwable); - this.code = code; - this.responseHeaders = responseHeaders; - this.responseBody = responseBody; - } + public ApiException(String message, Throwable throwable, int code, Map> responseHeaders, String responseBody) { + super(message, throwable); + this.code = code; + this.responseHeaders = responseHeaders; + this.responseBody = responseBody; + } - public ApiException(String message, int code, Map> responseHeaders, String responseBody) { - this(message, (Throwable) null, code, responseHeaders, responseBody); - } + public ApiException(String message, int code, Map> responseHeaders, String responseBody) { + this(message, (Throwable) null, code, responseHeaders, responseBody); + } - public ApiException(String message, Throwable throwable, int code, Map> responseHeaders) { - this(message, throwable, code, responseHeaders, null); - } + public ApiException(String message, Throwable throwable, int code, Map> responseHeaders) { + this(message, throwable, code, responseHeaders, null); + } - public ApiException(int code, Map> responseHeaders, String responseBody) { - this((String) null, (Throwable) null, code, responseHeaders, responseBody); - } + public ApiException(int code, Map> responseHeaders, String responseBody) { + this((String) null, (Throwable) null, code, responseHeaders, responseBody); + } - public ApiException(int code, String message) { - super(message); - this.code = code; - } + public ApiException(int code, String message) { + super(message); + this.code = code; + } - public ApiException(int code, String message, Map> responseHeaders, String responseBody) { - this(code, message); - this.responseHeaders = responseHeaders; - this.responseBody = responseBody; - } + public ApiException(int code, String message, Map> responseHeaders, String responseBody) { + this(code, message); + this.responseHeaders = responseHeaders; + this.responseBody = responseBody; + } - public int getCode() { - return code; - } + /** + * Get the HTTP status code. + * + * @return HTTP status code + */ + public int getCode() { + return code; + } - /** - * Get the HTTP response headers. - */ - public Map> getResponseHeaders() { - return responseHeaders; - } + /** + * Get the HTTP response headers. + * + * @return A map of list of string + */ + public Map> getResponseHeaders() { + return responseHeaders; + } - /** - * Get the HTTP response body. - */ - public String getResponseBody() { - return responseBody; - } + /** + * Get the HTTP response body. + * + * @return Response body in the form of string + */ + public String getResponseBody() { + return responseBody; + } } diff --git a/modules/swagger-codegen/src/main/resources/Java/api_test.mustache b/modules/swagger-codegen/src/main/resources/Java/api_test.mustache index f9e00ef2979..0a7639e0ec1 100644 --- a/modules/swagger-codegen/src/main/resources/Java/api_test.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/api_test.mustache @@ -1,3 +1,5 @@ +{{>licenseInfo}} + package {{package}}; import {{invokerPackage}}.ApiException; diff --git a/modules/swagger-codegen/src/main/resources/Java/auth/ApiKeyAuth.mustache b/modules/swagger-codegen/src/main/resources/Java/auth/ApiKeyAuth.mustache index 931d17b0d04..f73a6f5b3f8 100644 --- a/modules/swagger-codegen/src/main/resources/Java/auth/ApiKeyAuth.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/auth/ApiKeyAuth.mustache @@ -1,3 +1,5 @@ +{{>licenseInfo}} + package {{invokerPackage}}.auth; import {{invokerPackage}}.Pair; diff --git a/modules/swagger-codegen/src/main/resources/Java/auth/Authentication.mustache b/modules/swagger-codegen/src/main/resources/Java/auth/Authentication.mustache index 265c74cb76f..26174fa3b59 100644 --- a/modules/swagger-codegen/src/main/resources/Java/auth/Authentication.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/auth/Authentication.mustache @@ -1,3 +1,5 @@ +{{>licenseInfo}} + package {{invokerPackage}}.auth; import {{invokerPackage}}.Pair; @@ -6,6 +8,11 @@ import java.util.Map; import java.util.List; public interface Authentication { - /** Apply authentication settings to header and query params. */ - void applyToParams(List queryParams, Map headerParams); + /** + * Apply authentication settings to header and query params. + * + * @param queryParams List of query parameters + * @param headerParams Map of header parameters + */ + void applyToParams(List queryParams, Map headerParams); } diff --git a/modules/swagger-codegen/src/main/resources/Java/auth/HttpBasicAuth.mustache b/modules/swagger-codegen/src/main/resources/Java/auth/HttpBasicAuth.mustache index febabe33d64..0438f6a40b7 100644 --- a/modules/swagger-codegen/src/main/resources/Java/auth/HttpBasicAuth.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/auth/HttpBasicAuth.mustache @@ -1,3 +1,5 @@ +{{>licenseInfo}} + package {{invokerPackage}}.auth; import {{invokerPackage}}.Pair; diff --git a/modules/swagger-codegen/src/main/resources/Java/auth/OAuth.mustache b/modules/swagger-codegen/src/main/resources/Java/auth/OAuth.mustache index 902f54a2e3a..ffc9923d1fe 100644 --- a/modules/swagger-codegen/src/main/resources/Java/auth/OAuth.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/auth/OAuth.mustache @@ -1,3 +1,5 @@ +{{>licenseInfo}} + package {{invokerPackage}}.auth; import {{invokerPackage}}.Pair; diff --git a/modules/swagger-codegen/src/main/resources/Java/auth/OAuthFlow.mustache b/modules/swagger-codegen/src/main/resources/Java/auth/OAuthFlow.mustache index 7ab35f6d890..002e9572f33 100644 --- a/modules/swagger-codegen/src/main/resources/Java/auth/OAuthFlow.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/auth/OAuthFlow.mustache @@ -1,5 +1,7 @@ +{{>licenseInfo}} + package {{invokerPackage}}.auth; public enum OAuthFlow { accessCode, implicit, password, application -} \ No newline at end of file +} diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/feign/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/ApiClient.mustache index 61781ac9b70..be2e2d5e3ab 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/feign/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/ApiClient.mustache @@ -9,6 +9,7 @@ import org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuil import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; +import com.fasterxml.jackson.datatype.joda.JodaModule; import feign.Feign; import feign.RequestInterceptor; @@ -129,6 +130,8 @@ public class ApiClient { objectMapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING); objectMapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING); objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); + objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); + objectMapper.registerModule(new JodaModule()); return objectMapper; } diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/feign/build.sbt.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/build.sbt.mustache new file mode 100644 index 00000000000..37eabbd27b2 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/build.sbt.mustache @@ -0,0 +1,26 @@ +lazy val root = (project in file(".")). + settings( + organization := "{{groupId}}", + name := "{{artifactId}}", + version := "{{artifactVersion}}", + scalaVersion := "2.11.4", + scalacOptions ++= Seq("-feature"), + javacOptions in compile ++= Seq("-Xlint:deprecation"), + publishArtifact in (Compile, packageDoc) := false, + resolvers += Resolver.mavenLocal, + libraryDependencies ++= Seq( + "io.swagger" % "swagger-annotations" % "1.5.8" % "compile", + "com.netflix.feign" % "feign-core" % "8.16.0" % "compile", + "com.netflix.feign" % "feign-jackson" % "8.16.0" % "compile", + "com.netflix.feign" % "feign-slf4j" % "8.16.0" % "compile", + "com.fasterxml.jackson.core" % "jackson-core" % "2.7.0" % "compile", + "com.fasterxml.jackson.core" % "jackson-annotations" % "2.7.0" % "compile", + "com.fasterxml.jackson.core" % "jackson-databind" % "2.7.0" % "compile", + "com.fasterxml.jackson.datatype" % "jackson-datatype-joda" % "2.1.5" % "compile", + "joda-time" % "joda-time" % "2.9.3" % "compile", + "org.apache.oltu.oauth2" % "org.apache.oltu.oauth2.client" % "1.0.1" % "compile", + "com.brsanthu" % "migbase64" % "2.2" % "compile", + "junit" % "junit" % "4.12" % "test", + "com.novocode" % "junit-interface" % "0.10" % "test" + ) + ) diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/feign/pom.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/pom.mustache index 03323a65a03..df5b965984e 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/feign/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/pom.mustache @@ -149,19 +149,7 @@ com.fasterxml.jackson.datatype jackson-datatype-joda - 2.1.5 - - - joda-time - joda-time - ${jodatime-version} - - - - - com.brsanthu - migbase64 - 2.2 + ${jackson-version} diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ApiCallback.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ApiCallback.mustache index bfc1aedbc11..4cc99a76ec3 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ApiCallback.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ApiCallback.mustache @@ -1,3 +1,5 @@ +{{>licenseInfo}} + package {{invokerPackage}}; import java.io.IOException; @@ -11,39 +13,39 @@ import java.util.List; * @param The return type */ public interface ApiCallback { - /** - * This is called when the API call fails. - * - * @param e The exception causing the failure - * @param statusCode Status code of the response if available, otherwise it would be 0 - * @param responseHeaders Headers of the response if available, otherwise it would be null - */ - void onFailure(ApiException e, int statusCode, Map> responseHeaders); + /** + * This is called when the API call fails. + * + * @param e The exception causing the failure + * @param statusCode Status code of the response if available, otherwise it would be 0 + * @param responseHeaders Headers of the response if available, otherwise it would be null + */ + void onFailure(ApiException e, int statusCode, Map> responseHeaders); - /** - * This is called when the API call succeeded. - * - * @param result The result deserialized from response - * @param statusCode Status code of the response - * @param responseHeaders Headers of the response - */ - void onSuccess(T result, int statusCode, Map> responseHeaders); + /** + * This is called when the API call succeeded. + * + * @param result The result deserialized from response + * @param statusCode Status code of the response + * @param responseHeaders Headers of the response + */ + void onSuccess(T result, int statusCode, Map> responseHeaders); - /** - * This is called when the API upload processing. - * - * @param bytesWritten bytes Written - * @param contentLength content length of request body - * @param done write end - */ - void onUploadProgress(long bytesWritten, long contentLength, boolean done); + /** + * This is called when the API upload processing. + * + * @param bytesWritten bytes Written + * @param contentLength content length of request body + * @param done write end + */ + void onUploadProgress(long bytesWritten, long contentLength, boolean done); - /** - * This is called when the API downlond processing. - * - * @param bytesRead bytes Read - * @param contentLength content lenngth of the response - * @param done Read end - */ - void onDownloadProgress(long bytesRead, long contentLength, boolean done); + /** + * This is called when the API downlond processing. + * + * @param bytesRead bytes Read + * @param contentLength content lenngth of the response + * @param done Read end + */ + void onDownloadProgress(long bytesRead, long contentLength, boolean done); } diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ApiClient.mustache index 4c8e304ed97..3d6b3fe17f0 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ApiClient.mustache @@ -1,3 +1,5 @@ +{{>licenseInfo}} + package {{invokerPackage}}; import com.squareup.okhttp.Call; @@ -67,1073 +69,1234 @@ import {{invokerPackage}}.auth.ApiKeyAuth; import {{invokerPackage}}.auth.OAuth; public class ApiClient { - public static final double JAVA_VERSION; - public static final boolean IS_ANDROID; - public static final int ANDROID_SDK_VERSION; + public static final double JAVA_VERSION; + public static final boolean IS_ANDROID; + public static final int ANDROID_SDK_VERSION; - static { - JAVA_VERSION = Double.parseDouble(System.getProperty("java.specification.version")); - boolean isAndroid; - try { - Class.forName("android.app.Activity"); - isAndroid = true; - } catch (ClassNotFoundException e) { - isAndroid = false; - } - IS_ANDROID = isAndroid; - int sdkVersion = 0; - if (IS_ANDROID) { - try { - sdkVersion = Class.forName("android.os.Build$VERSION").getField("SDK_INT").getInt(null); - } catch (Exception e) { + static { + JAVA_VERSION = Double.parseDouble(System.getProperty("java.specification.version")); + boolean isAndroid; try { - sdkVersion = Integer.parseInt((String) Class.forName("android.os.Build$VERSION").getField("SDK").get(null)); - } catch (Exception e2) { } - } + Class.forName("android.app.Activity"); + isAndroid = true; + } catch (ClassNotFoundException e) { + isAndroid = false; + } + IS_ANDROID = isAndroid; + int sdkVersion = 0; + if (IS_ANDROID) { + try { + sdkVersion = Class.forName("android.os.Build$VERSION").getField("SDK_INT").getInt(null); + } catch (Exception e) { + try { + sdkVersion = Integer.parseInt((String) Class.forName("android.os.Build$VERSION").getField("SDK").get(null)); + } catch (Exception e2) { } + } + } + ANDROID_SDK_VERSION = sdkVersion; } - ANDROID_SDK_VERSION = sdkVersion; - } - /** - * The datetime format to be used when lenientDatetimeFormat is enabled. - */ - public static final String LENIENT_DATETIME_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"; + /** + * The datetime format to be used when lenientDatetimeFormat is enabled. + */ + public static final String LENIENT_DATETIME_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"; - private String basePath = "{{basePath}}"; - private boolean lenientOnJson = false; - private boolean debugging = false; - private Map defaultHeaderMap = new HashMap(); - private String tempFolderPath = null; + private String basePath = "{{basePath}}"; + private boolean lenientOnJson = false; + private boolean debugging = false; + private Map defaultHeaderMap = new HashMap(); + private String tempFolderPath = null; - private Map authentications; + private Map authentications; - private DateFormat dateFormat; - private DateFormat datetimeFormat; - private boolean lenientDatetimeFormat; - private int dateLength; + private DateFormat dateFormat; + private DateFormat datetimeFormat; + private boolean lenientDatetimeFormat; + private int dateLength; - private InputStream sslCaCert; - private boolean verifyingSsl; + private InputStream sslCaCert; + private boolean verifyingSsl; - private OkHttpClient httpClient; - private JSON json; + private OkHttpClient httpClient; + private JSON json; - private HttpLoggingInterceptor loggingInterceptor; - - public ApiClient() { - httpClient = new OkHttpClient(); - - verifyingSsl = true; - - json = new JSON(this); + private HttpLoggingInterceptor loggingInterceptor; /* - * Use RFC3339 format for date and datetime. - * See http://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14 + * Constructor for ApiClient */ - this.dateFormat = new SimpleDateFormat("yyyy-MM-dd"); - // Always use UTC as the default time zone when dealing with date (without time). - this.dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); - initDatetimeFormat(); + public ApiClient() { + httpClient = new OkHttpClient(); - // Be lenient on datetime formats when parsing datetime from string. - // See parseDatetime. - this.lenientDatetimeFormat = true; + verifyingSsl = true; - // Set default User-Agent. - setUserAgent("{{#httpUserAgent}}{{{.}}}{{/httpUserAgent}}{{^httpUserAgent}}Swagger-Codegen/{{{artifactVersion}}}/java{{/httpUserAgent}}"); + json = new JSON(this); - // Setup authentications (key: authentication name, value: authentication). - authentications = new HashMap();{{#authMethods}}{{#isBasic}} - authentications.put("{{name}}", new HttpBasicAuth());{{/isBasic}}{{#isApiKey}} - authentications.put("{{name}}", new ApiKeyAuth({{#isKeyInHeader}}"header"{{/isKeyInHeader}}{{^isKeyInHeader}}"query"{{/isKeyInHeader}}, "{{keyParamName}}"));{{/isApiKey}}{{#isOAuth}} - authentications.put("{{name}}", new OAuth());{{/isOAuth}}{{/authMethods}} - // Prevent the authentications from being modified. - authentications = Collections.unmodifiableMap(authentications); - } + /* + * Use RFC3339 format for date and datetime. + * See http://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14 + */ + this.dateFormat = new SimpleDateFormat("yyyy-MM-dd"); + // Always use UTC as the default time zone when dealing with date (without time). + this.dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); + initDatetimeFormat(); - public String getBasePath() { - return basePath; - } + // Be lenient on datetime formats when parsing datetime from string. + // See parseDatetime. + this.lenientDatetimeFormat = true; - public ApiClient setBasePath(String basePath) { - this.basePath = basePath; - return this; - } + // Set default User-Agent. + setUserAgent("{{#httpUserAgent}}{{{.}}}{{/httpUserAgent}}{{^httpUserAgent}}Swagger-Codegen/{{{artifactVersion}}}/java{{/httpUserAgent}}"); - public OkHttpClient getHttpClient() { - return httpClient; - } - - public ApiClient setHttpClient(OkHttpClient httpClient) { - this.httpClient = httpClient; - return this; - } - - public JSON getJSON() { - return json; - } - - public ApiClient setJSON(JSON json) { - this.json = json; - return this; - } - - public boolean isVerifyingSsl() { - return verifyingSsl; - } - - /** - * Configure whether to verify certificate and hostname when making https requests. - * Default to true. - * NOTE: Do NOT set to false in production code, otherwise you would face multiple types of cryptographic attacks. - */ - public ApiClient setVerifyingSsl(boolean verifyingSsl) { - this.verifyingSsl = verifyingSsl; - applySslSettings(); - return this; - } - - public InputStream getSslCaCert() { - return sslCaCert; - } - - /** - * Configure the CA certificate to be trusted when making https requests. - * Use null to reset to default. - */ - public ApiClient setSslCaCert(InputStream sslCaCert) { - this.sslCaCert = sslCaCert; - applySslSettings(); - return this; - } - - public DateFormat getDateFormat() { - return dateFormat; - } - - public ApiClient setDateFormat(DateFormat dateFormat) { - this.dateFormat = dateFormat; - this.dateLength = this.dateFormat.format(new Date()).length(); - return this; - } - - public DateFormat getDatetimeFormat() { - return datetimeFormat; - } - - public ApiClient setDatetimeFormat(DateFormat datetimeFormat) { - this.datetimeFormat = datetimeFormat; - return this; - } - - /** - * Whether to allow various ISO 8601 datetime formats when parsing a datetime string. - * @see #parseDatetime(String) - */ - public boolean isLenientDatetimeFormat() { - return lenientDatetimeFormat; - } - - public ApiClient setLenientDatetimeFormat(boolean lenientDatetimeFormat) { - this.lenientDatetimeFormat = lenientDatetimeFormat; - return this; - } - - /** - * Parse the given date string into Date object. - * The default dateFormat supports these ISO 8601 date formats: - * 2015-08-16 - * 2015-8-16 - */ - public Date parseDate(String str) { - if (str == null) - return null; - try { - return dateFormat.parse(str); - } catch (ParseException e) { - throw new RuntimeException(e); - } - } - - /** - * Parse the given datetime string into Date object. - * When lenientDatetimeFormat is enabled, the following ISO 8601 datetime formats are supported: - * 2015-08-16T08:20:05Z - * 2015-8-16T8:20:05Z - * 2015-08-16T08:20:05+00:00 - * 2015-08-16T08:20:05+0000 - * 2015-08-16T08:20:05.376Z - * 2015-08-16T08:20:05.376+00:00 - * 2015-08-16T08:20:05.376+00 - * Note: The 3-digit milli-seconds is optional. Time zone is required and can be in one of - * these formats: - * Z (same with +0000) - * +08:00 (same with +0800) - * -02 (same with -0200) - * -0200 - * @see https://en.wikipedia.org/wiki/ISO_8601 - */ - public Date parseDatetime(String str) { - if (str == null) - return null; - - DateFormat format; - if (lenientDatetimeFormat) { - /* - * When lenientDatetimeFormat is enabled, normalize the date string - * into LENIENT_DATETIME_FORMAT to support various formats - * defined by ISO 8601. - */ - // normalize time zone - // trailing "Z": 2015-08-16T08:20:05Z => 2015-08-16T08:20:05+0000 - str = str.replaceAll("[zZ]\\z", "+0000"); - // remove colon in time zone: 2015-08-16T08:20:05+00:00 => 2015-08-16T08:20:05+0000 - str = str.replaceAll("([+-]\\d{2}):(\\d{2})\\z", "$1$2"); - // expand time zone: 2015-08-16T08:20:05+00 => 2015-08-16T08:20:05+0000 - str = str.replaceAll("([+-]\\d{2})\\z", "$100"); - // add milliseconds when missing - // 2015-08-16T08:20:05+0000 => 2015-08-16T08:20:05.000+0000 - str = str.replaceAll("(:\\d{1,2})([+-]\\d{4})\\z", "$1.000$2"); - format = new SimpleDateFormat(LENIENT_DATETIME_FORMAT); - } else { - format = this.datetimeFormat; + // Setup authentications (key: authentication name, value: authentication). + authentications = new HashMap();{{#authMethods}}{{#isBasic}} + authentications.put("{{name}}", new HttpBasicAuth());{{/isBasic}}{{#isApiKey}} + authentications.put("{{name}}", new ApiKeyAuth({{#isKeyInHeader}}"header"{{/isKeyInHeader}}{{^isKeyInHeader}}"query"{{/isKeyInHeader}}, "{{keyParamName}}"));{{/isApiKey}}{{#isOAuth}} + authentications.put("{{name}}", new OAuth());{{/isOAuth}}{{/authMethods}} + // Prevent the authentications from being modified. + authentications = Collections.unmodifiableMap(authentications); } - try { - return format.parse(str); - } catch (ParseException e) { - throw new RuntimeException(e); - } - } - - public Date parseDateOrDatetime(String str) { - if (str == null) - return null; - else if (str.length() <= dateLength) - return parseDate(str); - else - return parseDatetime(str); - } - - /** - * Format the given Date object into string. - */ - public String formatDate(Date date) { - return dateFormat.format(date); - } - - /** - * Format the given Date object into string. - */ - public String formatDatetime(Date date) { - return datetimeFormat.format(date); - } - - /** - * Get authentications (key: authentication name, value: authentication). - */ - public Map getAuthentications() { - return authentications; - } - - /** - * Get authentication for the given name. - * - * @param authName The authentication name - * @return The authentication, null if not found - */ - public Authentication getAuthentication(String authName) { - return authentications.get(authName); - } - - /** - * Helper method to set username for the first HTTP basic authentication. - */ - public void setUsername(String username) { - for (Authentication auth : authentications.values()) { - if (auth instanceof HttpBasicAuth) { - ((HttpBasicAuth) auth).setUsername(username); - return; - } - } - throw new RuntimeException("No HTTP basic authentication configured!"); - } - - /** - * Helper method to set password for the first HTTP basic authentication. - */ - public void setPassword(String password) { - for (Authentication auth : authentications.values()) { - if (auth instanceof HttpBasicAuth) { - ((HttpBasicAuth) auth).setPassword(password); - return; - } - } - throw new RuntimeException("No HTTP basic authentication configured!"); - } - - /** - * Helper method to set API key value for the first API key authentication. - */ - public void setApiKey(String apiKey) { - for (Authentication auth : authentications.values()) { - if (auth instanceof ApiKeyAuth) { - ((ApiKeyAuth) auth).setApiKey(apiKey); - return; - } - } - throw new RuntimeException("No API key authentication configured!"); - } - - /** - * Helper method to set API key prefix for the first API key authentication. - */ - public void setApiKeyPrefix(String apiKeyPrefix) { - for (Authentication auth : authentications.values()) { - if (auth instanceof ApiKeyAuth) { - ((ApiKeyAuth) auth).setApiKeyPrefix(apiKeyPrefix); - return; - } - } - throw new RuntimeException("No API key authentication configured!"); - } - - /** - * Helper method to set access token for the first OAuth2 authentication. - */ - public void setAccessToken(String accessToken) { - for (Authentication auth : authentications.values()) { - if (auth instanceof OAuth) { - ((OAuth) auth).setAccessToken(accessToken); - return; - } - } - throw new RuntimeException("No OAuth2 authentication configured!"); - } - - /** - * Set the User-Agent header's value (by adding to the default header map). - */ - public ApiClient setUserAgent(String userAgent) { - addDefaultHeader("User-Agent", userAgent); - return this; - } - - /** - * Add a default header. - * - * @param key The header's key - * @param value The header's value - */ - public ApiClient addDefaultHeader(String key, String value) { - defaultHeaderMap.put(key, value); - return this; - } - - /** - * @see https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/stream/JsonReader.html#setLenient(boolean) - */ - public boolean isLenientOnJson() { - return lenientOnJson; - } - - public ApiClient setLenientOnJson(boolean lenient) { - this.lenientOnJson = lenient; - return this; - } - - /** - * Check that whether debugging is enabled for this API client. - */ - public boolean isDebugging() { - return debugging; - } - - /** - * Enable/disable debugging for this API client. - * - * @param debugging To enable (true) or disable (false) debugging - */ - public ApiClient setDebugging(boolean debugging) { - if (debugging != this.debugging) { - if (debugging) { - loggingInterceptor = new HttpLoggingInterceptor(); - loggingInterceptor.setLevel(Level.BODY); - httpClient.interceptors().add(loggingInterceptor); - } else { - httpClient.interceptors().remove(loggingInterceptor); - loggingInterceptor = null; - } - } - this.debugging = debugging; - return this; - } - - /** - * The path of temporary folder used to store downloaded files from endpoints - * with file response. The default value is null, i.e. using - * the system's default tempopary folder. - * - * @see https://docs.oracle.com/javase/7/docs/api/java/io/File.html#createTempFile(java.lang.String,%20java.lang.String,%20java.io.File) - */ - public String getTempFolderPath() { - return tempFolderPath; - } - - public ApiClient setTempFolderPath(String tempFolderPath) { - this.tempFolderPath = tempFolderPath; - return this; - } - - /** - * Connect timeout (in milliseconds). - */ - public int getConnectTimeout() { - return httpClient.getConnectTimeout(); - } - - /** - * Sets the connect timeout (in milliseconds). - * A value of 0 means no timeout, otherwise values must be between 1 and - * {@link Integer#MAX_VALUE}. - */ - public ApiClient setConnectTimeout(int connectionTimeout) { - httpClient.setConnectTimeout(connectionTimeout, TimeUnit.MILLISECONDS); - return this; - } - - /** - * Format the given parameter object into string. - */ - public String parameterToString(Object param) { - if (param == null) { - return ""; - } else if (param instanceof Date) { - return formatDatetime((Date) param); - } else if (param instanceof Collection) { - StringBuilder b = new StringBuilder(); - for (Object o : (Collection)param) { - if (b.length() > 0) { - b.append(","); - } - b.append(String.valueOf(o)); - } - return b.toString(); - } else { - return String.valueOf(param); - } - } - - /* - Format to {@code Pair} objects. - */ - public List parameterToPairs(String collectionFormat, String name, Object value){ - List params = new ArrayList(); - - // preconditions - if (name == null || name.isEmpty() || value == null) return params; - - Collection valueCollection = null; - if (value instanceof Collection) { - valueCollection = (Collection) value; - } else { - params.add(new Pair(name, parameterToString(value))); - return params; + /** + * Get base path + * + * @return Baes path + */ + public String getBasePath() { + return basePath; } - if (valueCollection.isEmpty()){ - return params; + /** + * Set base path + * + * @param basePath Base path of the URL (e.g {{basePath}}) + * @return An instance of OkHttpClient + */ + public ApiClient setBasePath(String basePath) { + this.basePath = basePath; + return this; } - // get the collection format - collectionFormat = (collectionFormat == null || collectionFormat.isEmpty() ? "csv" : collectionFormat); // default: csv - - // create the params based on the collection format - if (collectionFormat.equals("multi")) { - for (Object item : valueCollection) { - params.add(new Pair(name, parameterToString(item))); - } - - return params; + /** + * Get HTTP client + * + * @return An instance of OkHttpClient + */ + public OkHttpClient getHttpClient() { + return httpClient; } - String delimiter = ","; - - if (collectionFormat.equals("csv")) { - delimiter = ","; - } else if (collectionFormat.equals("ssv")) { - delimiter = " "; - } else if (collectionFormat.equals("tsv")) { - delimiter = "\t"; - } else if (collectionFormat.equals("pipes")) { - delimiter = "|"; + /** + * Set HTTP client + * + * @param httpClient An instance of OkHttpClient + * @return Api Client + */ + public ApiClient setHttpClient(OkHttpClient httpClient) { + this.httpClient = httpClient; + return this; } - StringBuilder sb = new StringBuilder() ; - for (Object item : valueCollection) { - sb.append(delimiter); - sb.append(parameterToString(item)); + /** + * Get JSON + * + * @return JSON object + */ + public JSON getJSON() { + return json; } - params.add(new Pair(name, sb.substring(1))); - - return params; - } - - /** - * Sanitize filename by removing path. - * e.g. ../../sun.gif becomes sun.gif - * - * @param filename The filename to be sanitized - * @return The sanitized filename - */ - public String sanitizeFilename(String filename) { - return filename.replaceAll(".*[/\\\\]", ""); - } - - /** - * Check if the given MIME is a JSON MIME. - * JSON MIME examples: - * application/json - * application/json; charset=UTF8 - * APPLICATION/JSON - */ - public boolean isJsonMime(String mime) { - return mime != null && mime.matches("(?i)application\\/json(;.*)?"); - } - - /** - * Select the Accept header's value from the given accepts array: - * if JSON exists in the given array, use it; - * otherwise use all of them (joining into a string) - * - * @param accepts The accepts array to select from - * @return The Accept header to use. If the given array is empty, - * null will be returned (not to set the Accept header explicitly). - */ - public String selectHeaderAccept(String[] accepts) { - if (accepts.length == 0) { - return null; - } - for (String accept : accepts) { - if (isJsonMime(accept)) { - return accept; - } - } - return StringUtil.join(accepts, ","); - } - - /** - * Select the Content-Type header's value from the given array: - * if JSON exists in the given array, use it; - * otherwise use the first one of the array. - * - * @param contentTypes The Content-Type array to select from - * @return The Content-Type header to use. If the given array is empty, - * JSON will be used. - */ - public String selectHeaderContentType(String[] contentTypes) { - if (contentTypes.length == 0) { - return "application/json"; - } - for (String contentType : contentTypes) { - if (isJsonMime(contentType)) { - return contentType; - } - } - return contentTypes[0]; - } - - /** - * Escape the given string to be used as URL query value. - */ - public String escapeString(String str) { - try { - return URLEncoder.encode(str, "utf8").replaceAll("\\+", "%20"); - } catch (UnsupportedEncodingException e) { - return str; - } - } - - /** - * Deserialize response body to Java object, according to the return type and - * the Content-Type response header. - * - * @param response HTTP response - * @param returnType The type of the Java object - * @return The deserialized Java object - * @throws ApiException If fail to deserialize response body, i.e. cannot read response body - * or the Content-Type of the response is not supported. - */ - public T deserialize(Response response, Type returnType) throws ApiException { - if (response == null || returnType == null) { - return null; + /** + * Set JSON + * + * @param json JSON object + * @return Api client + */ + public ApiClient setJSON(JSON json) { + this.json = json; + return this; } - if ("byte[]".equals(returnType.toString())) { - // Handle binary response (byte array). - try { - return (T) response.body().bytes(); - } catch (IOException e) { - throw new ApiException(e); - } - } else if (returnType.equals(File.class)) { - // Handle file downloading. - return (T) downloadFileFromResponse(response); + /** + * True if isVerifyingSsl flag is on + * + * @return True if isVerifySsl flag is on + */ + public boolean isVerifyingSsl() { + return verifyingSsl; } - String respBody; - try { - if (response.body() != null) - respBody = response.body().string(); - else - respBody = null; - } catch (IOException e) { - throw new ApiException(e); + /** + * Configure whether to verify certificate and hostname when making https requests. + * Default to true. + * NOTE: Do NOT set to false in production code, otherwise you would face multiple types of cryptographic attacks. + * + * @param verifyingSsl True to verify TLS/SSL connection + * @return ApiClient + */ + public ApiClient setVerifyingSsl(boolean verifyingSsl) { + this.verifyingSsl = verifyingSsl; + applySslSettings(); + return this; } - if (respBody == null || "".equals(respBody)) { - return null; + /** + * Get SSL CA cert. + * + * @return Input stream to the SSL CA cert + */ + public InputStream getSslCaCert() { + return sslCaCert; } - String contentType = response.headers().get("Content-Type"); - if (contentType == null) { - // ensuring a default content type - contentType = "application/json"; - } - if (isJsonMime(contentType)) { - return json.deserialize(respBody, returnType); - } else if (returnType.equals(String.class)) { - // Expecting string, return the raw response body. - return (T) respBody; - } else { - throw new ApiException( - "Content type \"" + contentType + "\" is not supported for type: " + returnType, - response.code(), - response.headers().toMultimap(), - respBody); - } - } - - /** - * Serialize the given Java object into request body according to the object's - * class and the request Content-Type. - * - * @param obj The Java object - * @param contentType The request Content-Type - * @return The serialized request body - * @throws ApiException If fail to serialize the given object - */ - public RequestBody serialize(Object obj, String contentType) throws ApiException { - if (obj instanceof byte[]) { - // Binary (byte array) body parameter support. - return RequestBody.create(MediaType.parse(contentType), (byte[]) obj); - } else if (obj instanceof File) { - // File body parameter support. - return RequestBody.create(MediaType.parse(contentType), (File) obj); - } else if (isJsonMime(contentType)) { - String content; - if (obj != null) { - content = json.serialize(obj); - } else { - content = null; - } - return RequestBody.create(MediaType.parse(contentType), content); - } else { - throw new ApiException("Content type \"" + contentType + "\" is not supported"); - } - } - - /** - * Download file from the given response. - * @throws ApiException If fail to read file content from response and write to disk - */ - public File downloadFileFromResponse(Response response) throws ApiException { - try { - File file = prepareDownloadFile(response); - BufferedSink sink = Okio.buffer(Okio.sink(file)); - sink.writeAll(response.body().source()); - sink.close(); - return file; - } catch (IOException e) { - throw new ApiException(e); - } - } - - public File prepareDownloadFile(Response response) throws IOException { - String filename = null; - String contentDisposition = response.header("Content-Disposition"); - if (contentDisposition != null && !"".equals(contentDisposition)) { - // Get filename from the Content-Disposition header. - Pattern pattern = Pattern.compile("filename=['\"]?([^'\"\\s]+)['\"]?"); - Matcher matcher = pattern.matcher(contentDisposition); - if (matcher.find()) { - filename = sanitizeFilename(matcher.group(1)); - } + /** + * Configure the CA certificate to be trusted when making https requests. + * Use null to reset to default. + * + * @param sslCaCert input stream for SSL CA cert + * @return ApiClient + */ + public ApiClient setSslCaCert(InputStream sslCaCert) { + this.sslCaCert = sslCaCert; + applySslSettings(); + return this; } - String prefix = null; - String suffix = null; - if (filename == null) { - prefix = "download-"; - suffix = ""; - } else { - int pos = filename.lastIndexOf("."); - if (pos == -1) { - prefix = filename + "-"; - } else { - prefix = filename.substring(0, pos) + "-"; - suffix = filename.substring(pos); - } - // File.createTempFile requires the prefix to be at least three characters long - if (prefix.length() < 3) - prefix = "download-"; + public DateFormat getDateFormat() { + return dateFormat; } - if (tempFolderPath == null) - return File.createTempFile(prefix, suffix); - else - return File.createTempFile(prefix, suffix, new File(tempFolderPath)); - } - - /** - * @see #execute(Call, Type) - */ - public ApiResponse execute(Call call) throws ApiException { - return execute(call, null); - } - - /** - * Execute HTTP call and deserialize the HTTP response body into the given return type. - * - * @param returnType The return type used to deserialize HTTP response body - * @param The return type corresponding to (same with) returnType - * @return ApiResponse object containing response status, headers and - * data, which is a Java object deserialized from response body and would be null - * when returnType is null. - * @throws ApiException If fail to execute the call - */ - public ApiResponse execute(Call call, Type returnType) throws ApiException { - try { - Response response = call.execute(); - T data = handleResponse(response, returnType); - return new ApiResponse(response.code(), response.headers().toMultimap(), data); - } catch (IOException e) { - throw new ApiException(e); + public ApiClient setDateFormat(DateFormat dateFormat) { + this.dateFormat = dateFormat; + this.dateLength = this.dateFormat.format(new Date()).length(); + return this; } - } - /** - * #see executeAsync(Call, Type, ApiCallback) - */ - public void executeAsync(Call call, ApiCallback callback) { - executeAsync(call, null, callback); - } + public DateFormat getDatetimeFormat() { + return datetimeFormat; + } - /** - * Execute HTTP call asynchronously. - * - * @see #execute(Call, Type) - * @param The callback to be executed when the API call finishes - */ - public void executeAsync(Call call, final Type returnType, final ApiCallback callback) { - call.enqueue(new Callback() { - @Override - public void onFailure(Request request, IOException e) { - callback.onFailure(new ApiException(e), 0, null); - } + public ApiClient setDatetimeFormat(DateFormat datetimeFormat) { + this.datetimeFormat = datetimeFormat; + return this; + } - @Override - public void onResponse(Response response) throws IOException { - T result; + /** + * Whether to allow various ISO 8601 datetime formats when parsing a datetime string. + * @see #parseDatetime(String) + * @return True if lenientDatetimeFormat flag is set to true + */ + public boolean isLenientDatetimeFormat() { + return lenientDatetimeFormat; + } + + public ApiClient setLenientDatetimeFormat(boolean lenientDatetimeFormat) { + this.lenientDatetimeFormat = lenientDatetimeFormat; + return this; + } + + /** + * Parse the given date string into Date object. + * The default dateFormat supports these ISO 8601 date formats: + * 2015-08-16 + * 2015-8-16 + * @param str String to be parsed + * @return Date + */ + public Date parseDate(String str) { + if (str == null) + return null; try { - result = (T) handleResponse(response, returnType); - } catch (ApiException e) { - callback.onFailure(e, response.code(), response.headers().toMultimap()); - return; + return dateFormat.parse(str); + } catch (ParseException e) { + throw new RuntimeException(e); + } + } + + /** + * Parse the given datetime string into Date object. + * When lenientDatetimeFormat is enabled, the following ISO 8601 datetime formats are supported: + * 2015-08-16T08:20:05Z + * 2015-8-16T8:20:05Z + * 2015-08-16T08:20:05+00:00 + * 2015-08-16T08:20:05+0000 + * 2015-08-16T08:20:05.376Z + * 2015-08-16T08:20:05.376+00:00 + * 2015-08-16T08:20:05.376+00 + * Note: The 3-digit milli-seconds is optional. Time zone is required and can be in one of + * these formats: + * Z (same with +0000) + * +08:00 (same with +0800) + * -02 (same with -0200) + * -0200 + * @see ISO 8601 + * @param str Date time string to be parsed + * @return Date representation of the string + */ + public Date parseDatetime(String str) { + if (str == null) + return null; + + DateFormat format; + if (lenientDatetimeFormat) { + /* + * When lenientDatetimeFormat is enabled, normalize the date string + * into LENIENT_DATETIME_FORMAT to support various formats + * defined by ISO 8601. + */ + // normalize time zone + // trailing "Z": 2015-08-16T08:20:05Z => 2015-08-16T08:20:05+0000 + str = str.replaceAll("[zZ]\\z", "+0000"); + // remove colon in time zone: 2015-08-16T08:20:05+00:00 => 2015-08-16T08:20:05+0000 + str = str.replaceAll("([+-]\\d{2}):(\\d{2})\\z", "$1$2"); + // expand time zone: 2015-08-16T08:20:05+00 => 2015-08-16T08:20:05+0000 + str = str.replaceAll("([+-]\\d{2})\\z", "$100"); + // add milliseconds when missing + // 2015-08-16T08:20:05+0000 => 2015-08-16T08:20:05.000+0000 + str = str.replaceAll("(:\\d{1,2})([+-]\\d{4})\\z", "$1.000$2"); + format = new SimpleDateFormat(LENIENT_DATETIME_FORMAT); + } else { + format = this.datetimeFormat; } - callback.onSuccess(result, response.code(), response.headers().toMultimap()); - } - }); - } - /** - * Handle the given response, return the deserialized object when the response is successful. - * - * @throws ApiException If the response has a unsuccessful status code or - * fail to deserialize the response body - */ - public T handleResponse(Response response, Type returnType) throws ApiException { - if (response.isSuccessful()) { - if (returnType == null || response.code() == 204) { - // returning null if the returnType is not defined, - // or the status code is 204 (No Content) - return null; - } else { - return deserialize(response, returnType); - } - } else { - String respBody = null; - if (response.body() != null) { try { - respBody = response.body().string(); + return format.parse(str); + } catch (ParseException e) { + throw new RuntimeException(e); + } + } + + /* + * Parse date or date time in string format into Date object. + * + * @param str Date time string to be parsed + * @return Date representation of the string + */ + public Date parseDateOrDatetime(String str) { + if (str == null) + return null; + else if (str.length() <= dateLength) + return parseDate(str); + else + return parseDatetime(str); + } + + /** + * Format the given Date object into string (Date format). + * + * @param date Date object + * @return Formatted date in string representation + */ + public String formatDate(Date date) { + return dateFormat.format(date); + } + + /** + * Format the given Date object into string (Datetime format). + * + * @param date Date object + * @return Formatted datetime in string representation + */ + public String formatDatetime(Date date) { + return datetimeFormat.format(date); + } + + /** + * Get authentications (key: authentication name, value: authentication). + * + * @return Map of authentication objects + */ + public Map getAuthentications() { + return authentications; + } + + /** + * Get authentication for the given name. + * + * @param authName The authentication name + * @return The authentication, null if not found + */ + public Authentication getAuthentication(String authName) { + return authentications.get(authName); + } + + /** + * Helper method to set username for the first HTTP basic authentication. + * + * @param username Username + */ + public void setUsername(String username) { + for (Authentication auth : authentications.values()) { + if (auth instanceof HttpBasicAuth) { + ((HttpBasicAuth) auth).setUsername(username); + return; + } + } + throw new RuntimeException("No HTTP basic authentication configured!"); + } + + /** + * Helper method to set password for the first HTTP basic authentication. + * + * @param password Password + */ + public void setPassword(String password) { + for (Authentication auth : authentications.values()) { + if (auth instanceof HttpBasicAuth) { + ((HttpBasicAuth) auth).setPassword(password); + return; + } + } + throw new RuntimeException("No HTTP basic authentication configured!"); + } + + /** + * Helper method to set API key value for the first API key authentication. + * + * @param apiKey API key + */ + public void setApiKey(String apiKey) { + for (Authentication auth : authentications.values()) { + if (auth instanceof ApiKeyAuth) { + ((ApiKeyAuth) auth).setApiKey(apiKey); + return; + } + } + throw new RuntimeException("No API key authentication configured!"); + } + + /** + * Helper method to set API key prefix for the first API key authentication. + * + * @param apiKeyPrefix API key prefix + */ + public void setApiKeyPrefix(String apiKeyPrefix) { + for (Authentication auth : authentications.values()) { + if (auth instanceof ApiKeyAuth) { + ((ApiKeyAuth) auth).setApiKeyPrefix(apiKeyPrefix); + return; + } + } + throw new RuntimeException("No API key authentication configured!"); + } + + /** + * Helper method to set access token for the first OAuth2 authentication. + * + * @param accessToken Access token + */ + public void setAccessToken(String accessToken) { + for (Authentication auth : authentications.values()) { + if (auth instanceof OAuth) { + ((OAuth) auth).setAccessToken(accessToken); + return; + } + } + throw new RuntimeException("No OAuth2 authentication configured!"); + } + + /** + * Set the User-Agent header's value (by adding to the default header map). + * + * @param userAgent HTTP request's user agent + * @return ApiClient + */ + public ApiClient setUserAgent(String userAgent) { + addDefaultHeader("User-Agent", userAgent); + return this; + } + + /** + * Add a default header. + * + * @param key The header's key + * @param value The header's value + * @return ApiClient + */ + public ApiClient addDefaultHeader(String key, String value) { + defaultHeaderMap.put(key, value); + return this; + } + + /** + * @see setLenient + * + * @return True if lenientOnJson is enabled, false otherwise. + */ + public boolean isLenientOnJson() { + return lenientOnJson; + } + + /** + * Set LenientOnJson + * + * @param lenient True to enable lenientOnJson + * @return ApiClient + */ + public ApiClient setLenientOnJson(boolean lenient) { + this.lenientOnJson = lenient; + return this; + } + + /** + * Check that whether debugging is enabled for this API client. + * + * @return True if debugging is enabled, false otherwise. + */ + public boolean isDebugging() { + return debugging; + } + + /** + * Enable/disable debugging for this API client. + * + * @param debugging To enable (true) or disable (false) debugging + * @return ApiClient + */ + public ApiClient setDebugging(boolean debugging) { + if (debugging != this.debugging) { + if (debugging) { + loggingInterceptor = new HttpLoggingInterceptor(); + loggingInterceptor.setLevel(Level.BODY); + httpClient.interceptors().add(loggingInterceptor); + } else { + httpClient.interceptors().remove(loggingInterceptor); + loggingInterceptor = null; + } + } + this.debugging = debugging; + return this; + } + + /** + * The path of temporary folder used to store downloaded files from endpoints + * with file response. The default value is null, i.e. using + * the system's default tempopary folder. + * + * @see createTempFile + * @return Temporary folder path + */ + public String getTempFolderPath() { + return tempFolderPath; + } + + /** + * Set the tempoaray folder path (for downloading files) + * + * @param tempFolderPath Temporary folder path + * @return ApiClient + */ + public ApiClient setTempFolderPath(String tempFolderPath) { + this.tempFolderPath = tempFolderPath; + return this; + } + + /** + * Get connection timeout (in milliseconds). + * + * @return Timeout in milliseconds + */ + public int getConnectTimeout() { + return httpClient.getConnectTimeout(); + } + + /** + * Sets the connect timeout (in milliseconds). + * A value of 0 means no timeout, otherwise values must be between 1 and + * + * @param connectionTimeout connection timeout in milliseconds + * @return Api client + */ + public ApiClient setConnectTimeout(int connectionTimeout) { + httpClient.setConnectTimeout(connectionTimeout, TimeUnit.MILLISECONDS); + return this; + } + + /** + * Format the given parameter object into string. + * + * @param param Parameter + * @return String representation of the parameter + */ + public String parameterToString(Object param) { + if (param == null) { + return ""; + } else if (param instanceof Date) { + return formatDatetime((Date) param); + } else if (param instanceof Collection) { + StringBuilder b = new StringBuilder(); + for (Object o : (Collection)param) { + if (b.length() > 0) { + b.append(","); + } + b.append(String.valueOf(o)); + } + return b.toString(); + } else { + return String.valueOf(param); + } + } + + /** + * Format to {@code Pair} objects. + * + * @param collectionFormat collection format (e.g. csv, tsv) + * @param name Name + * @param value Value + * @return A list of Pair objects + */ + public List parameterToPairs(String collectionFormat, String name, Object value){ + List params = new ArrayList(); + + // preconditions + if (name == null || name.isEmpty() || value == null) return params; + + Collection valueCollection = null; + if (value instanceof Collection) { + valueCollection = (Collection) value; + } else { + params.add(new Pair(name, parameterToString(value))); + return params; + } + + if (valueCollection.isEmpty()){ + return params; + } + + // get the collection format + collectionFormat = (collectionFormat == null || collectionFormat.isEmpty() ? "csv" : collectionFormat); // default: csv + + // create the params based on the collection format + if (collectionFormat.equals("multi")) { + for (Object item : valueCollection) { + params.add(new Pair(name, parameterToString(item))); + } + + return params; + } + + String delimiter = ","; + + if (collectionFormat.equals("csv")) { + delimiter = ","; + } else if (collectionFormat.equals("ssv")) { + delimiter = " "; + } else if (collectionFormat.equals("tsv")) { + delimiter = "\t"; + } else if (collectionFormat.equals("pipes")) { + delimiter = "|"; + } + + StringBuilder sb = new StringBuilder() ; + for (Object item : valueCollection) { + sb.append(delimiter); + sb.append(parameterToString(item)); + } + + params.add(new Pair(name, sb.substring(1))); + + return params; + } + + /** + * Sanitize filename by removing path. + * e.g. ../../sun.gif becomes sun.gif + * + * @param filename The filename to be sanitized + * @return The sanitized filename + */ + public String sanitizeFilename(String filename) { + return filename.replaceAll(".*[/\\\\]", ""); + } + + /** + * Check if the given MIME is a JSON MIME. + * JSON MIME examples: + * application/json + * application/json; charset=UTF8 + * APPLICATION/JSON + * + * @param mime MIME (Multipurpose Internet Mail Extensions) + * @return True if the given MIME is JSON, false otherwise. + */ + public boolean isJsonMime(String mime) { + return mime != null && mime.matches("(?i)application\\/json(;.*)?"); + } + + /** + * Select the Accept header's value from the given accepts array: + * if JSON exists in the given array, use it; + * otherwise use all of them (joining into a string) + * + * @param accepts The accepts array to select from + * @return The Accept header to use. If the given array is empty, + * null will be returned (not to set the Accept header explicitly). + */ + public String selectHeaderAccept(String[] accepts) { + if (accepts.length == 0) { + return null; + } + for (String accept : accepts) { + if (isJsonMime(accept)) { + return accept; + } + } + return StringUtil.join(accepts, ","); + } + + /** + * Select the Content-Type header's value from the given array: + * if JSON exists in the given array, use it; + * otherwise use the first one of the array. + * + * @param contentTypes The Content-Type array to select from + * @return The Content-Type header to use. If the given array is empty, + * JSON will be used. + */ + public String selectHeaderContentType(String[] contentTypes) { + if (contentTypes.length == 0) { + return "application/json"; + } + for (String contentType : contentTypes) { + if (isJsonMime(contentType)) { + return contentType; + } + } + return contentTypes[0]; + } + + /** + * Escape the given string to be used as URL query value. + * + * @param str String to be escaped + * @return Escaped string + */ + public String escapeString(String str) { + try { + return URLEncoder.encode(str, "utf8").replaceAll("\\+", "%20"); + } catch (UnsupportedEncodingException e) { + return str; + } + } + + /** + * Deserialize response body to Java object, according to the return type and + * the Content-Type response header. + * + * @param Type + * @param response HTTP response + * @param returnType The type of the Java object + * @return The deserialized Java object + * @throws ApiException If fail to deserialize response body, i.e. cannot read response body + * or the Content-Type of the response is not supported. + */ + public T deserialize(Response response, Type returnType) throws ApiException { + if (response == null || returnType == null) { + return null; + } + + if ("byte[]".equals(returnType.toString())) { + // Handle binary response (byte array). + try { + return (T) response.body().bytes(); + } catch (IOException e) { + throw new ApiException(e); + } + } else if (returnType.equals(File.class)) { + // Handle file downloading. + return (T) downloadFileFromResponse(response); + } + + String respBody; + try { + if (response.body() != null) + respBody = response.body().string(); + else + respBody = null; } catch (IOException e) { - throw new ApiException(response.message(), e, response.code(), response.headers().toMultimap()); + throw new ApiException(e); } - } - throw new ApiException(response.message(), response.code(), response.headers().toMultimap(), respBody); - } - } - /** - * Build HTTP call with the given options. - * - * @param path The sub-path of the HTTP URL - * @param method The request method, one of "GET", "HEAD", "OPTIONS", "POST", "PUT", "PATCH" and "DELETE" - * @param queryParams The query parameters - * @param body The request body object - * @param headerParams The header parameters - * @param formParams The form parameters - * @param authNames The authentications to apply - * @return The HTTP call - * @throws ApiException If fail to serialize the request body object - */ - public Call buildCall(String path, String method, List queryParams, Object body, Map headerParams, Map formParams, String[] authNames, ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - updateParamsForAuth(authNames, queryParams, headerParams); - - final String url = buildUrl(path, queryParams); - final Request.Builder reqBuilder = new Request.Builder().url(url); - processHeaderParams(headerParams, reqBuilder); - - String contentType = (String) headerParams.get("Content-Type"); - // ensuring a default content type - if (contentType == null) { - contentType = "application/json"; - } - - RequestBody reqBody; - if (!HttpMethod.permitsRequestBody(method)) { - reqBody = null; - } else if ("application/x-www-form-urlencoded".equals(contentType)) { - reqBody = buildRequestBodyFormEncoding(formParams); - } else if ("multipart/form-data".equals(contentType)) { - reqBody = buildRequestBodyMultipart(formParams); - } else if (body == null) { - if ("DELETE".equals(method)) { - // allow calling DELETE without sending a request body - reqBody = null; - } else { - // use an empty request body (for POST, PUT and PATCH) - reqBody = RequestBody.create(MediaType.parse(contentType), ""); - } - } else { - reqBody = serialize(body, contentType); - } - - Request request = null; - - if(progressRequestListener != null && reqBody != null) { - ProgressRequestBody progressRequestBody = new ProgressRequestBody(reqBody, progressRequestListener); - request = reqBuilder.method(method, progressRequestBody).build(); - } else { - request = reqBuilder.method(method, reqBody).build(); - } - - return httpClient.newCall(request); - } - - /** - * Build full URL by concatenating base path, the given sub path and query parameters. - * - * @param path The sub path - * @param queryParams The query parameters - * @return The full URL - */ - public String buildUrl(String path, List queryParams) { - final StringBuilder url = new StringBuilder(); - url.append(basePath).append(path); - - if (queryParams != null && !queryParams.isEmpty()) { - // support (constant) query string in `path`, e.g. "/posts?draft=1" - String prefix = path.contains("?") ? "&" : "?"; - for (Pair param : queryParams) { - if (param.getValue() != null) { - if (prefix != null) { - url.append(prefix); - prefix = null; - } else { - url.append("&"); - } - String value = parameterToString(param.getValue()); - url.append(escapeString(param.getName())).append("=").append(escapeString(value)); + if (respBody == null || "".equals(respBody)) { + return null; } - } - } - return url.toString(); - } - - /** - * Set header parameters to the request builder, including default headers. - */ - public void processHeaderParams(Map headerParams, Request.Builder reqBuilder) { - for (Entry param : headerParams.entrySet()) { - reqBuilder.header(param.getKey(), parameterToString(param.getValue())); - } - for (Entry header : defaultHeaderMap.entrySet()) { - if (!headerParams.containsKey(header.getKey())) { - reqBuilder.header(header.getKey(), parameterToString(header.getValue())); - } - } - } - - /** - * Update query and header parameters based on authentication settings. - * - * @param authNames The authentications to apply - */ - public void updateParamsForAuth(String[] authNames, List queryParams, Map headerParams) { - for (String authName : authNames) { - Authentication auth = authentications.get(authName); - if (auth == null) throw new RuntimeException("Authentication undefined: " + authName); - auth.applyToParams(queryParams, headerParams); - } - } - - /** - * Build a form-encoding request body with the given form parameters. - */ - public RequestBody buildRequestBodyFormEncoding(Map formParams) { - FormEncodingBuilder formBuilder = new FormEncodingBuilder(); - for (Entry param : formParams.entrySet()) { - formBuilder.add(param.getKey(), parameterToString(param.getValue())); - } - return formBuilder.build(); - } - - /** - * Build a multipart (file uploading) request body with the given form parameters, - * which could contain text fields and file fields. - */ - public RequestBody buildRequestBodyMultipart(Map formParams) { - MultipartBuilder mpBuilder = new MultipartBuilder().type(MultipartBuilder.FORM); - for (Entry param : formParams.entrySet()) { - if (param.getValue() instanceof File) { - File file = (File) param.getValue(); - Headers partHeaders = Headers.of("Content-Disposition", "form-data; name=\"" + param.getKey() + "\"; filename=\"" + file.getName() + "\""); - MediaType mediaType = MediaType.parse(guessContentTypeFromFile(file)); - mpBuilder.addPart(partHeaders, RequestBody.create(mediaType, file)); - } else { - Headers partHeaders = Headers.of("Content-Disposition", "form-data; name=\"" + param.getKey() + "\""); - mpBuilder.addPart(partHeaders, RequestBody.create(null, parameterToString(param.getValue()))); - } - } - return mpBuilder.build(); - } - - /** - * Guess Content-Type header from the given file (defaults to "application/octet-stream"). - * - * @param file The given file - * @return The Content-Type guessed - */ - public String guessContentTypeFromFile(File file) { - String contentType = URLConnection.guessContentTypeFromName(file.getName()); - if (contentType == null) { - return "application/octet-stream"; - } else { - return contentType; - } - } - - /** - * Initialize datetime format according to the current environment, e.g. Java 1.7 and Android. - */ - private void initDatetimeFormat() { - String formatWithTimeZone = null; - if (IS_ANDROID) { - if (ANDROID_SDK_VERSION >= 18) { - // The time zone format "ZZZZZ" is available since Android 4.3 (SDK version 18) - formatWithTimeZone = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ"; - } - } else if (JAVA_VERSION >= 1.7) { - // The time zone format "XXX" is available since Java 1.7 - formatWithTimeZone = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX"; - } - if (formatWithTimeZone != null) { - this.datetimeFormat = new SimpleDateFormat(formatWithTimeZone); - // NOTE: Use the system's default time zone (mainly for datetime formatting). - } else { - // Use a common format that works across all systems. - this.datetimeFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); - // Always use the UTC time zone as we are using a constant trailing "Z" here. - this.datetimeFormat.setTimeZone(TimeZone.getTimeZone("UTC")); - } - } - - /** - * Apply SSL related settings to httpClient according to the current values of - * verifyingSsl and sslCaCert. - */ - private void applySslSettings() { - try { - KeyManager[] keyManagers = null; - TrustManager[] trustManagers = null; - HostnameVerifier hostnameVerifier = null; - if (!verifyingSsl) { - TrustManager trustAll = new X509TrustManager() { - @Override - public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {} - @Override - public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {} - @Override - public X509Certificate[] getAcceptedIssuers() { return null; } - }; - SSLContext sslContext = SSLContext.getInstance("TLS"); - trustManagers = new TrustManager[]{ trustAll }; - hostnameVerifier = new HostnameVerifier() { - @Override - public boolean verify(String hostname, SSLSession session) { return true; } - }; - } else if (sslCaCert != null) { - char[] password = null; // Any password will work. - CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); - Collection certificates = certificateFactory.generateCertificates(sslCaCert); - if (certificates.isEmpty()) { - throw new IllegalArgumentException("expected non-empty set of trusted certificates"); + String contentType = response.headers().get("Content-Type"); + if (contentType == null) { + // ensuring a default content type + contentType = "application/json"; } - KeyStore caKeyStore = newEmptyKeyStore(password); - int index = 0; - for (Certificate certificate : certificates) { - String certificateAlias = "ca" + Integer.toString(index++); - caKeyStore.setCertificateEntry(certificateAlias, certificate); + if (isJsonMime(contentType)) { + return json.deserialize(respBody, returnType); + } else if (returnType.equals(String.class)) { + // Expecting string, return the raw response body. + return (T) respBody; + } else { + throw new ApiException( + "Content type \"" + contentType + "\" is not supported for type: " + returnType, + response.code(), + response.headers().toMultimap(), + respBody); } - TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); - trustManagerFactory.init(caKeyStore); - trustManagers = trustManagerFactory.getTrustManagers(); - } - - if (keyManagers != null || trustManagers != null) { - SSLContext sslContext = SSLContext.getInstance("TLS"); - sslContext.init(keyManagers, trustManagers, new SecureRandom()); - httpClient.setSslSocketFactory(sslContext.getSocketFactory()); - } else { - httpClient.setSslSocketFactory(null); - } - httpClient.setHostnameVerifier(hostnameVerifier); - } catch (GeneralSecurityException e) { - throw new RuntimeException(e); } - } - private KeyStore newEmptyKeyStore(char[] password) throws GeneralSecurityException { - try { - KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); - keyStore.load(null, password); - return keyStore; - } catch (IOException e) { - throw new AssertionError(e); + /** + * Serialize the given Java object into request body according to the object's + * class and the request Content-Type. + * + * @param obj The Java object + * @param contentType The request Content-Type + * @return The serialized request body + * @throws ApiException If fail to serialize the given object + */ + public RequestBody serialize(Object obj, String contentType) throws ApiException { + if (obj instanceof byte[]) { + // Binary (byte array) body parameter support. + return RequestBody.create(MediaType.parse(contentType), (byte[]) obj); + } else if (obj instanceof File) { + // File body parameter support. + return RequestBody.create(MediaType.parse(contentType), (File) obj); + } else if (isJsonMime(contentType)) { + String content; + if (obj != null) { + content = json.serialize(obj); + } else { + content = null; + } + return RequestBody.create(MediaType.parse(contentType), content); + } else { + throw new ApiException("Content type \"" + contentType + "\" is not supported"); + } + } + + /** + * Download file from the given response. + * + * @param response An instance of the Response object + * @throws ApiException If fail to read file content from response and write to disk + * @return Downloaded file + */ + public File downloadFileFromResponse(Response response) throws ApiException { + try { + File file = prepareDownloadFile(response); + BufferedSink sink = Okio.buffer(Okio.sink(file)); + sink.writeAll(response.body().source()); + sink.close(); + return file; + } catch (IOException e) { + throw new ApiException(e); + } + } + + /** + * Prepare file for download + * + * @param response An instance of the Response object + * @throws IOException If fail to prepare file for download + * @return Prepared file for the download + */ + public File prepareDownloadFile(Response response) throws IOException { + String filename = null; + String contentDisposition = response.header("Content-Disposition"); + if (contentDisposition != null && !"".equals(contentDisposition)) { + // Get filename from the Content-Disposition header. + Pattern pattern = Pattern.compile("filename=['\"]?([^'\"\\s]+)['\"]?"); + Matcher matcher = pattern.matcher(contentDisposition); + if (matcher.find()) { + filename = sanitizeFilename(matcher.group(1)); + } + } + + String prefix = null; + String suffix = null; + if (filename == null) { + prefix = "download-"; + suffix = ""; + } else { + int pos = filename.lastIndexOf("."); + if (pos == -1) { + prefix = filename + "-"; + } else { + prefix = filename.substring(0, pos) + "-"; + suffix = filename.substring(pos); + } + // File.createTempFile requires the prefix to be at least three characters long + if (prefix.length() < 3) + prefix = "download-"; + } + + if (tempFolderPath == null) + return File.createTempFile(prefix, suffix); + else + return File.createTempFile(prefix, suffix, new File(tempFolderPath)); + } + + /** + * {@link #execute(Call, Type)} + * + * @param Type + * @param call An instance of the Call object + * @throws ApiException If fail to execute the call + * @return ApiResponse<T> + */ + public ApiResponse execute(Call call) throws ApiException { + return execute(call, null); + } + + /** + * Execute HTTP call and deserialize the HTTP response body into the given return type. + * + * @param returnType The return type used to deserialize HTTP response body + * @param The return type corresponding to (same with) returnType + * @param call Call + * @return ApiResponse object containing response status, headers and + * data, which is a Java object deserialized from response body and would be null + * when returnType is null. + * @throws ApiException If fail to execute the call + */ + public ApiResponse execute(Call call, Type returnType) throws ApiException { + try { + Response response = call.execute(); + T data = handleResponse(response, returnType); + return new ApiResponse(response.code(), response.headers().toMultimap(), data); + } catch (IOException e) { + throw new ApiException(e); + } + } + + /** + * {@link #executeAsync(Call, Type, ApiCallback)} + * + * @param Type + * @param call An instance of the Call object + * @param callback ApiCallback<T> + */ + public void executeAsync(Call call, ApiCallback callback) { + executeAsync(call, null, callback); + } + + /** + * Execute HTTP call asynchronously. + * + * @see #execute(Call, Type) + * @param Type + * @param call The callback to be executed when the API call finishes + * @param returnType Return type + * @param callback ApiCallback + */ + public void executeAsync(Call call, final Type returnType, final ApiCallback callback) { + call.enqueue(new Callback() { + @Override + public void onFailure(Request request, IOException e) { + callback.onFailure(new ApiException(e), 0, null); + } + + @Override + public void onResponse(Response response) throws IOException { + T result; + try { + result = (T) handleResponse(response, returnType); + } catch (ApiException e) { + callback.onFailure(e, response.code(), response.headers().toMultimap()); + return; + } + callback.onSuccess(result, response.code(), response.headers().toMultimap()); + } + }); + } + + /** + * Handle the given response, return the deserialized object when the response is successful. + * + * @param Type + * @param response Response + * @param returnType Return type + * @throws ApiException If the response has a unsuccessful status code or + * fail to deserialize the response body + * @return Type + */ + public T handleResponse(Response response, Type returnType) throws ApiException { + if (response.isSuccessful()) { + if (returnType == null || response.code() == 204) { + // returning null if the returnType is not defined, + // or the status code is 204 (No Content) + return null; + } else { + return deserialize(response, returnType); + } + } else { + String respBody = null; + if (response.body() != null) { + try { + respBody = response.body().string(); + } catch (IOException e) { + throw new ApiException(response.message(), e, response.code(), response.headers().toMultimap()); + } + } + throw new ApiException(response.message(), response.code(), response.headers().toMultimap(), respBody); + } + } + + /** + * Build HTTP call with the given options. + * + * @param path The sub-path of the HTTP URL + * @param method The request method, one of "GET", "HEAD", "OPTIONS", "POST", "PUT", "PATCH" and "DELETE" + * @param queryParams The query parameters + * @param body The request body object + * @param headerParams The header parameters + * @param formParams The form parameters + * @param authNames The authentications to apply + * @param progressRequestListener Progress request listener + * @return The HTTP call + * @throws ApiException If fail to serialize the request body object + */ + public Call buildCall(String path, String method, List queryParams, Object body, Map headerParams, Map formParams, String[] authNames, ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + updateParamsForAuth(authNames, queryParams, headerParams); + + final String url = buildUrl(path, queryParams); + final Request.Builder reqBuilder = new Request.Builder().url(url); + processHeaderParams(headerParams, reqBuilder); + + String contentType = (String) headerParams.get("Content-Type"); + // ensuring a default content type + if (contentType == null) { + contentType = "application/json"; + } + + RequestBody reqBody; + if (!HttpMethod.permitsRequestBody(method)) { + reqBody = null; + } else if ("application/x-www-form-urlencoded".equals(contentType)) { + reqBody = buildRequestBodyFormEncoding(formParams); + } else if ("multipart/form-data".equals(contentType)) { + reqBody = buildRequestBodyMultipart(formParams); + } else if (body == null) { + if ("DELETE".equals(method)) { + // allow calling DELETE without sending a request body + reqBody = null; + } else { + // use an empty request body (for POST, PUT and PATCH) + reqBody = RequestBody.create(MediaType.parse(contentType), ""); + } + } else { + reqBody = serialize(body, contentType); + } + + Request request = null; + + if(progressRequestListener != null && reqBody != null) { + ProgressRequestBody progressRequestBody = new ProgressRequestBody(reqBody, progressRequestListener); + request = reqBuilder.method(method, progressRequestBody).build(); + } else { + request = reqBuilder.method(method, reqBody).build(); + } + + return httpClient.newCall(request); + } + + /** + * Build full URL by concatenating base path, the given sub path and query parameters. + * + * @param path The sub path + * @param queryParams The query parameters + * @return The full URL + */ + public String buildUrl(String path, List queryParams) { + final StringBuilder url = new StringBuilder(); + url.append(basePath).append(path); + + if (queryParams != null && !queryParams.isEmpty()) { + // support (constant) query string in `path`, e.g. "/posts?draft=1" + String prefix = path.contains("?") ? "&" : "?"; + for (Pair param : queryParams) { + if (param.getValue() != null) { + if (prefix != null) { + url.append(prefix); + prefix = null; + } else { + url.append("&"); + } + String value = parameterToString(param.getValue()); + url.append(escapeString(param.getName())).append("=").append(escapeString(value)); + } + } + } + + return url.toString(); + } + + /** + * Set header parameters to the request builder, including default headers. + * + * @param headerParams Header parameters in the ofrm of Map + * @param reqBuilder Reqeust.Builder + */ + public void processHeaderParams(Map headerParams, Request.Builder reqBuilder) { + for (Entry param : headerParams.entrySet()) { + reqBuilder.header(param.getKey(), parameterToString(param.getValue())); + } + for (Entry header : defaultHeaderMap.entrySet()) { + if (!headerParams.containsKey(header.getKey())) { + reqBuilder.header(header.getKey(), parameterToString(header.getValue())); + } + } + } + + /** + * Update query and header parameters based on authentication settings. + * + * @param authNames The authentications to apply + * @param queryParams List of query parameters + * @param headerParams Map of header parameters + */ + public void updateParamsForAuth(String[] authNames, List queryParams, Map headerParams) { + for (String authName : authNames) { + Authentication auth = authentications.get(authName); + if (auth == null) throw new RuntimeException("Authentication undefined: " + authName); + auth.applyToParams(queryParams, headerParams); + } + } + + /** + * Build a form-encoding request body with the given form parameters. + * + * @param formParams Form parameters in the form of Map + * @return RequestBody + */ + public RequestBody buildRequestBodyFormEncoding(Map formParams) { + FormEncodingBuilder formBuilder = new FormEncodingBuilder(); + for (Entry param : formParams.entrySet()) { + formBuilder.add(param.getKey(), parameterToString(param.getValue())); + } + return formBuilder.build(); + } + + /** + * Build a multipart (file uploading) request body with the given form parameters, + * which could contain text fields and file fields. + * + * @param formParams Form parameters in the form of Map + * @return RequestBody + */ + public RequestBody buildRequestBodyMultipart(Map formParams) { + MultipartBuilder mpBuilder = new MultipartBuilder().type(MultipartBuilder.FORM); + for (Entry param : formParams.entrySet()) { + if (param.getValue() instanceof File) { + File file = (File) param.getValue(); + Headers partHeaders = Headers.of("Content-Disposition", "form-data; name=\"" + param.getKey() + "\"; filename=\"" + file.getName() + "\""); + MediaType mediaType = MediaType.parse(guessContentTypeFromFile(file)); + mpBuilder.addPart(partHeaders, RequestBody.create(mediaType, file)); + } else { + Headers partHeaders = Headers.of("Content-Disposition", "form-data; name=\"" + param.getKey() + "\""); + mpBuilder.addPart(partHeaders, RequestBody.create(null, parameterToString(param.getValue()))); + } + } + return mpBuilder.build(); + } + + /** + * Guess Content-Type header from the given file (defaults to "application/octet-stream"). + * + * @param file The given file + * @return The guessed Content-Type + */ + public String guessContentTypeFromFile(File file) { + String contentType = URLConnection.guessContentTypeFromName(file.getName()); + if (contentType == null) { + return "application/octet-stream"; + } else { + return contentType; + } + } + + /** + * Initialize datetime format according to the current environment, e.g. Java 1.7 and Android. + */ + private void initDatetimeFormat() { + String formatWithTimeZone = null; + if (IS_ANDROID) { + if (ANDROID_SDK_VERSION >= 18) { + // The time zone format "ZZZZZ" is available since Android 4.3 (SDK version 18) + formatWithTimeZone = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ"; + } + } else if (JAVA_VERSION >= 1.7) { + // The time zone format "XXX" is available since Java 1.7 + formatWithTimeZone = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX"; + } + if (formatWithTimeZone != null) { + this.datetimeFormat = new SimpleDateFormat(formatWithTimeZone); + // NOTE: Use the system's default time zone (mainly for datetime formatting). + } else { + // Use a common format that works across all systems. + this.datetimeFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); + // Always use the UTC time zone as we are using a constant trailing "Z" here. + this.datetimeFormat.setTimeZone(TimeZone.getTimeZone("UTC")); + } + } + + /** + * Apply SSL related settings to httpClient according to the current values of + * verifyingSsl and sslCaCert. + */ + private void applySslSettings() { + try { + KeyManager[] keyManagers = null; + TrustManager[] trustManagers = null; + HostnameVerifier hostnameVerifier = null; + if (!verifyingSsl) { + TrustManager trustAll = new X509TrustManager() { + @Override + public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {} + @Override + public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {} + @Override + public X509Certificate[] getAcceptedIssuers() { return null; } + }; + SSLContext sslContext = SSLContext.getInstance("TLS"); + trustManagers = new TrustManager[]{ trustAll }; + hostnameVerifier = new HostnameVerifier() { + @Override + public boolean verify(String hostname, SSLSession session) { return true; } + }; + } else if (sslCaCert != null) { + char[] password = null; // Any password will work. + CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); + Collection certificates = certificateFactory.generateCertificates(sslCaCert); + if (certificates.isEmpty()) { + throw new IllegalArgumentException("expected non-empty set of trusted certificates"); + } + KeyStore caKeyStore = newEmptyKeyStore(password); + int index = 0; + for (Certificate certificate : certificates) { + String certificateAlias = "ca" + Integer.toString(index++); + caKeyStore.setCertificateEntry(certificateAlias, certificate); + } + TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); + trustManagerFactory.init(caKeyStore); + trustManagers = trustManagerFactory.getTrustManagers(); + } + + if (keyManagers != null || trustManagers != null) { + SSLContext sslContext = SSLContext.getInstance("TLS"); + sslContext.init(keyManagers, trustManagers, new SecureRandom()); + httpClient.setSslSocketFactory(sslContext.getSocketFactory()); + } else { + httpClient.setSslSocketFactory(null); + } + httpClient.setHostnameVerifier(hostnameVerifier); + } catch (GeneralSecurityException e) { + throw new RuntimeException(e); + } + } + + private KeyStore newEmptyKeyStore(char[] password) throws GeneralSecurityException { + try { + KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); + keyStore.load(null, password); + return keyStore; + } catch (IOException e) { + throw new AssertionError(e); + } } - } } diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ApiResponse.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ApiResponse.mustache index 452f4e1e982..82c86b3e215 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ApiResponse.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ApiResponse.mustache @@ -1,3 +1,5 @@ +{{>licenseInfo}} + package {{invokerPackage}}; import java.util.List; @@ -9,38 +11,38 @@ import java.util.Map; * @param T The type of data that is deserialized from response body */ public class ApiResponse { - final private int statusCode; - final private Map> headers; - final private T data; + final private int statusCode; + final private Map> headers; + final private T data; - /** - * @param statusCode The status code of HTTP response - * @param headers The headers of HTTP response - */ - public ApiResponse(int statusCode, Map> headers) { - this(statusCode, headers, null); - } + /** + * @param statusCode The status code of HTTP response + * @param headers The headers of HTTP response + */ + public ApiResponse(int statusCode, Map> headers) { + this(statusCode, headers, null); + } - /** - * @param statusCode The status code of HTTP response - * @param headers The headers of HTTP response - * @param data The object deserialized from response bod - */ - public ApiResponse(int statusCode, Map> headers, T data) { - this.statusCode = statusCode; - this.headers = headers; - this.data = data; - } + /** + * @param statusCode The status code of HTTP response + * @param headers The headers of HTTP response + * @param data The object deserialized from response bod + */ + public ApiResponse(int statusCode, Map> headers, T data) { + this.statusCode = statusCode; + this.headers = headers; + this.data = data; + } - public int getStatusCode() { - return statusCode; - } + public int getStatusCode() { + return statusCode; + } - public Map> getHeaders() { - return headers; - } + public Map> getHeaders() { + return headers; + } - public T getData() { - return data; - } + public T getData() { + return data; + } } diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/JSON.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/JSON.mustache index 9cc1324acb6..b1be00ea985 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/JSON.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/JSON.mustache @@ -1,3 +1,5 @@ +{{>licenseInfo}} + package {{invokerPackage}}; import com.google.gson.Gson; @@ -10,76 +12,118 @@ import com.google.gson.JsonParseException; import com.google.gson.JsonPrimitive; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; +import com.google.gson.TypeAdapter; import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; import java.io.StringReader; import java.lang.reflect.Type; import java.util.Date; +import org.joda.time.DateTime; +import org.joda.time.LocalDate; +import org.joda.time.format.DateTimeFormatter; +import org.joda.time.format.ISODateTimeFormat; + public class JSON { - private ApiClient apiClient; - private Gson gson; + private ApiClient apiClient; + private Gson gson; - public JSON(ApiClient apiClient) { - this.apiClient = apiClient; - gson = new GsonBuilder() - .registerTypeAdapter(Date.class, new DateAdapter(apiClient)) - .create(); - } - - public Gson getGson() { - return gson; - } - - public void setGson(Gson gson) { - this.gson = gson; - } - - /** - * Serialize the given Java object into JSON string. - */ - public String serialize(Object obj) { - return gson.toJson(obj); - } - - /** - * Deserialize the given JSON string to Java object. - * - * @param body The JSON string - * @param returnType The type to deserialize inot - * @return The deserialized Java object - */ - public T deserialize(String body, Type returnType) { - try { - if (apiClient.isLenientOnJson()) { - JsonReader jsonReader = new JsonReader(new StringReader(body)); - // see https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/stream/JsonReader.html#setLenient(boolean) - jsonReader.setLenient(true); - return gson.fromJson(jsonReader, returnType); - } else { - return gson.fromJson(body, returnType); - } - } catch (JsonParseException e) { - // Fallback processing when failed to parse JSON form response body: - // return the response body string directly for the String return type; - // parse response body into date or datetime for the Date return type. - if (returnType.equals(String.class)) - return (T) body; - else if (returnType.equals(Date.class)) - return (T) apiClient.parseDateOrDatetime(body); - else throw(e); + /** + * JSON constructor. + * + * @param apiClient An instance of ApiClient + */ + public JSON(ApiClient apiClient) { + this.apiClient = apiClient; + gson = new GsonBuilder() + .registerTypeAdapter(Date.class, new DateAdapter(apiClient)) + .registerTypeAdapter(DateTime.class, new DateTimeTypeAdapter()) + .registerTypeAdapter(LocalDate.class, new LocalDateTypeAdapter()) + .create(); + } + + /** + * Get Gson. + * + * @return Gson + */ + public Gson getGson() { + return gson; + } + + /** + * Set Gson. + * + * @param gson Gson + */ + public void setGson(Gson gson) { + this.gson = gson; + } + + /** + * Serialize the given Java object into JSON string. + * + * @param obj Object + * @return String representation of the JSON + */ + public String serialize(Object obj) { + return gson.toJson(obj); + } + + /** + * Deserialize the given JSON string to Java object. + * + * @param Type + * @param body The JSON string + * @param returnType The type to deserialize inot + * @return The deserialized Java object + */ + public T deserialize(String body, Type returnType) { + try { + if (apiClient.isLenientOnJson()) { + JsonReader jsonReader = new JsonReader(new StringReader(body)); + // see https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/stream/JsonReader.html#setLenient(boolean) + jsonReader.setLenient(true); + return gson.fromJson(jsonReader, returnType); + } else { + return gson.fromJson(body, returnType); + } + } catch (JsonParseException e) { + // Fallback processing when failed to parse JSON form response body: + // return the response body string directly for the String return type; + // parse response body into date or datetime for the Date return type. + if (returnType.equals(String.class)) + return (T) body; + else if (returnType.equals(Date.class)) + return (T) apiClient.parseDateOrDatetime(body); + else throw(e); + } } - } } class DateAdapter implements JsonSerializer, JsonDeserializer { private final ApiClient apiClient; + /** + * Constructor for DateAdapter + * + * @param apiClient Api client + */ public DateAdapter(ApiClient apiClient) { super(); this.apiClient = apiClient; } + /** + * Serialize + * + * @param src Date + * @param typeOfSrc Type + * @param context Json Serialization Context + * @return Json Element + */ @Override public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) { if (src == null) { @@ -89,6 +133,16 @@ class DateAdapter implements JsonSerializer, JsonDeserializer { } } + /** + * Deserialize + * + * @param json Json element + * @param date Type + * @param typeOfSrc Type + * @param context Json Serialization Context + * @return Date + * @throw JsonParseException if fail to parse + */ @Override public Date deserialize(JsonElement json, Type date, JsonDeserializationContext context) throws JsonParseException { String str = json.getAsJsonPrimitive().getAsString(); @@ -99,3 +153,62 @@ class DateAdapter implements JsonSerializer, JsonDeserializer { } } } + +/** + * Gson TypeAdapter for Joda DateTime type + */ +class DateTimeTypeAdapter extends TypeAdapter { + + private final DateTimeFormatter formatter = ISODateTimeFormat.dateTime(); + + @Override + public void write(JsonWriter out, DateTime date) throws IOException { + if (date == null) { + out.nullValue(); + } else { + out.value(formatter.print(date)); + } + } + + @Override + public DateTime read(JsonReader in) throws IOException { + switch (in.peek()) { + case NULL: + in.nextNull(); + return null; + default: + String date = in.nextString(); + return formatter.parseDateTime(date); + } + } +} + +/** + * Gson TypeAdapter for Joda LocalDate type + */ +class LocalDateTypeAdapter extends TypeAdapter { + + private final DateTimeFormatter formatter = ISODateTimeFormat.date(); + + @Override + public void write(JsonWriter out, LocalDate date) throws IOException { + if (date == null) { + out.nullValue(); + } else { + out.value(formatter.print(date)); + } + } + + @Override + public LocalDate read(JsonReader in) throws IOException { + switch (in.peek()) { + case NULL: + in.nextNull(); + return null; + default: + String date = in.nextString(); + return formatter.parseLocalDate(date); + } + } +} + diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ProgressRequestBody.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ProgressRequestBody.mustache index 57931ef4cfc..d6570bd0d3b 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ProgressRequestBody.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ProgressRequestBody.mustache @@ -1,3 +1,5 @@ +{{>licenseInfo}} + package {{invokerPackage}}; import com.squareup.okhttp.MediaType; @@ -18,9 +20,9 @@ public class ProgressRequestBody extends RequestBody { } private final RequestBody requestBody; - + private final ProgressRequestListener progressListener; - + private BufferedSink bufferedSink; public ProgressRequestBody(RequestBody requestBody, ProgressRequestListener progressListener) { @@ -43,7 +45,7 @@ public class ProgressRequestBody extends RequestBody { if (bufferedSink == null) { bufferedSink = Okio.buffer(sink(sink)); } - + requestBody.writeTo(bufferedSink); bufferedSink.flush(); @@ -51,7 +53,7 @@ public class ProgressRequestBody extends RequestBody { private Sink sink(Sink sink) { return new ForwardingSink(sink) { - + long bytesWritten = 0L; long contentLength = 0L; diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ProgressResponseBody.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ProgressResponseBody.mustache index 061a95ac299..3f53133697c 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ProgressResponseBody.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ProgressResponseBody.mustache @@ -1,3 +1,5 @@ +{{>licenseInfo}} + package {{invokerPackage}}; import com.squareup.okhttp.MediaType; diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/api.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/api.mustache index dd9141bd3dc..7abe897d42e 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/api.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/api.mustache @@ -1,3 +1,5 @@ +{{>licenseInfo}} + package {{package}}; import {{invokerPackage}}.ApiCallback; @@ -11,10 +13,6 @@ import {{invokerPackage}}.ProgressResponseBody; import com.google.gson.reflect.TypeToken; -import com.squareup.okhttp.Call; -import com.squareup.okhttp.Interceptor; -import com.squareup.okhttp.Response; - import java.io.IOException; {{#imports}}import {{import}}; @@ -30,138 +28,138 @@ import java.util.Map; {{#operations}} public class {{classname}} { - private ApiClient {{localVariablePrefix}}apiClient; + private ApiClient {{localVariablePrefix}}apiClient; - public {{classname}}() { - this(Configuration.getDefaultApiClient()); - } - - public {{classname}}(ApiClient apiClient) { - this.{{localVariablePrefix}}apiClient = apiClient; - } - - public ApiClient getApiClient() { - return {{localVariablePrefix}}apiClient; - } - - public void setApiClient(ApiClient apiClient) { - this.{{localVariablePrefix}}apiClient = apiClient; - } - - {{#operation}} - /* Build call for {{operationId}} */ - private Call {{operationId}}Call({{#allParams}}{{{dataType}}} {{paramName}}, {{/allParams}}final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object {{localVariablePrefix}}localVarPostBody = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}}; - {{#allParams}}{{#required}} - // verify the required parameter '{{paramName}}' is set - if ({{paramName}} == null) { - throw new ApiException("Missing the required parameter '{{paramName}}' when calling {{operationId}}(Async)"); - } - {{/required}}{{/allParams}} - - // create path and map variables - String {{localVariablePrefix}}localVarPath = "{{path}}".replaceAll("\\{format\\}","json"){{#pathParams}} - .replaceAll("\\{" + "{{baseName}}" + "\\}", {{localVariablePrefix}}apiClient.escapeString({{{paramName}}}.toString())){{/pathParams}}; - - {{javaUtilPrefix}}List {{localVariablePrefix}}localVarQueryParams = new {{javaUtilPrefix}}ArrayList();{{#queryParams}} - if ({{paramName}} != null) - {{localVariablePrefix}}localVarQueryParams.addAll({{localVariablePrefix}}apiClient.parameterToPairs("{{#collectionFormat}}{{{collectionFormat}}}{{/collectionFormat}}", "{{baseName}}", {{paramName}}));{{/queryParams}} - - {{javaUtilPrefix}}Map {{localVariablePrefix}}localVarHeaderParams = new {{javaUtilPrefix}}HashMap();{{#headerParams}} - if ({{paramName}} != null) - {{localVariablePrefix}}localVarHeaderParams.put("{{baseName}}", {{localVariablePrefix}}apiClient.parameterToString({{paramName}}));{{/headerParams}} - - {{javaUtilPrefix}}Map {{localVariablePrefix}}localVarFormParams = new {{javaUtilPrefix}}HashMap();{{#formParams}} - if ({{paramName}} != null) - {{localVariablePrefix}}localVarFormParams.put("{{baseName}}", {{paramName}});{{/formParams}} - - final String[] {{localVariablePrefix}}localVarAccepts = { - {{#produces}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/produces}} - }; - final String {{localVariablePrefix}}localVarAccept = {{localVariablePrefix}}apiClient.selectHeaderAccept({{localVariablePrefix}}localVarAccepts); - if ({{localVariablePrefix}}localVarAccept != null) {{localVariablePrefix}}localVarHeaderParams.put("Accept", {{localVariablePrefix}}localVarAccept); - - final String[] {{localVariablePrefix}}localVarContentTypes = { - {{#consumes}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} - }; - final String {{localVariablePrefix}}localVarContentType = {{localVariablePrefix}}apiClient.selectHeaderContentType({{localVariablePrefix}}localVarContentTypes); - {{localVariablePrefix}}localVarHeaderParams.put("Content-Type", {{localVariablePrefix}}localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new Interceptor() { - @Override - public Response intercept(Interceptor.Chain chain) throws IOException { - Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); + public {{classname}}() { + this(Configuration.getDefaultApiClient()); } - String[] {{localVariablePrefix}}localVarAuthNames = new String[] { {{#authMethods}}"{{name}}"{{#hasMore}}, {{/hasMore}}{{/authMethods}} }; - return {{localVariablePrefix}}apiClient.buildCall({{localVariablePrefix}}localVarPath, "{{httpMethod}}", {{localVariablePrefix}}localVarQueryParams, {{localVariablePrefix}}localVarPostBody, {{localVariablePrefix}}localVarHeaderParams, {{localVariablePrefix}}localVarFormParams, {{localVariablePrefix}}localVarAuthNames, progressRequestListener); - } - - /** - * {{summary}} - * {{notes}}{{#allParams}} - * @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}{{/allParams}}{{#returnType}} - * @return {{{returnType}}}{{/returnType}} - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}}{{operationId}}({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) throws ApiException { - {{#returnType}}ApiResponse<{{{returnType}}}> {{localVariablePrefix}}resp = {{/returnType}}{{operationId}}WithHttpInfo({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}});{{#returnType}} - return {{localVariablePrefix}}resp.getData();{{/returnType}} - } - - /** - * {{summary}} - * {{notes}}{{#allParams}} - * @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}{{/allParams}} - * @return ApiResponse<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> {{operationId}}WithHttpInfo({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) throws ApiException { - Call {{localVariablePrefix}}call = {{operationId}}Call({{#allParams}}{{paramName}}, {{/allParams}}null, null); - {{#returnType}}Type {{localVariablePrefix}}localVarReturnType = new TypeToken<{{{returnType}}}>(){}.getType(); - return {{localVariablePrefix}}apiClient.execute({{localVariablePrefix}}call, {{localVariablePrefix}}localVarReturnType);{{/returnType}}{{^returnType}}return {{localVariablePrefix}}apiClient.execute({{localVariablePrefix}}call);{{/returnType}} - } - - /** - * {{summary}} (asynchronously) - * {{notes}}{{#allParams}} - * @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}{{/allParams}} - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public Call {{operationId}}Async({{#allParams}}{{{dataType}}} {{paramName}}, {{/allParams}}final ApiCallback<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> {{localVariablePrefix}}callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; + public {{classname}}(ApiClient apiClient) { + this.{{localVariablePrefix}}apiClient = apiClient; } - Call {{localVariablePrefix}}call = {{operationId}}Call({{#allParams}}{{paramName}}, {{/allParams}}progressListener, progressRequestListener); - {{#returnType}}Type {{localVariablePrefix}}localVarReturnType = new TypeToken<{{{returnType}}}>(){}.getType(); - {{localVariablePrefix}}apiClient.executeAsync({{localVariablePrefix}}call, {{localVariablePrefix}}localVarReturnType, {{localVariablePrefix}}callback);{{/returnType}}{{^returnType}}{{localVariablePrefix}}apiClient.executeAsync({{localVariablePrefix}}call, {{localVariablePrefix}}callback);{{/returnType}} - return {{localVariablePrefix}}call; - } - {{/operation}} + public ApiClient getApiClient() { + return {{localVariablePrefix}}apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.{{localVariablePrefix}}apiClient = apiClient; + } + + {{#operation}} + /* Build call for {{operationId}} */ + private com.squareup.okhttp.Call {{operationId}}Call({{#allParams}}{{{dataType}}} {{paramName}}, {{/allParams}}final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object {{localVariablePrefix}}localVarPostBody = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}}; + {{#allParams}}{{#required}} + // verify the required parameter '{{paramName}}' is set + if ({{paramName}} == null) { + throw new ApiException("Missing the required parameter '{{paramName}}' when calling {{operationId}}(Async)"); + } + {{/required}}{{/allParams}} + + // create path and map variables + String {{localVariablePrefix}}localVarPath = "{{path}}".replaceAll("\\{format\\}","json"){{#pathParams}} + .replaceAll("\\{" + "{{baseName}}" + "\\}", {{localVariablePrefix}}apiClient.escapeString({{{paramName}}}.toString())){{/pathParams}}; + + {{javaUtilPrefix}}List {{localVariablePrefix}}localVarQueryParams = new {{javaUtilPrefix}}ArrayList();{{#queryParams}} + if ({{paramName}} != null) + {{localVariablePrefix}}localVarQueryParams.addAll({{localVariablePrefix}}apiClient.parameterToPairs("{{#collectionFormat}}{{{collectionFormat}}}{{/collectionFormat}}", "{{baseName}}", {{paramName}}));{{/queryParams}} + + {{javaUtilPrefix}}Map {{localVariablePrefix}}localVarHeaderParams = new {{javaUtilPrefix}}HashMap();{{#headerParams}} + if ({{paramName}} != null) + {{localVariablePrefix}}localVarHeaderParams.put("{{baseName}}", {{localVariablePrefix}}apiClient.parameterToString({{paramName}}));{{/headerParams}} + + {{javaUtilPrefix}}Map {{localVariablePrefix}}localVarFormParams = new {{javaUtilPrefix}}HashMap();{{#formParams}} + if ({{paramName}} != null) + {{localVariablePrefix}}localVarFormParams.put("{{baseName}}", {{paramName}});{{/formParams}} + + final String[] {{localVariablePrefix}}localVarAccepts = { + {{#produces}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/produces}} + }; + final String {{localVariablePrefix}}localVarAccept = {{localVariablePrefix}}apiClient.selectHeaderAccept({{localVariablePrefix}}localVarAccepts); + if ({{localVariablePrefix}}localVarAccept != null) {{localVariablePrefix}}localVarHeaderParams.put("Accept", {{localVariablePrefix}}localVarAccept); + + final String[] {{localVariablePrefix}}localVarContentTypes = { + {{#consumes}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} + }; + final String {{localVariablePrefix}}localVarContentType = {{localVariablePrefix}}apiClient.selectHeaderContentType({{localVariablePrefix}}localVarContentTypes); + {{localVariablePrefix}}localVarHeaderParams.put("Content-Type", {{localVariablePrefix}}localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] {{localVariablePrefix}}localVarAuthNames = new String[] { {{#authMethods}}"{{name}}"{{#hasMore}}, {{/hasMore}}{{/authMethods}} }; + return {{localVariablePrefix}}apiClient.buildCall({{localVariablePrefix}}localVarPath, "{{httpMethod}}", {{localVariablePrefix}}localVarQueryParams, {{localVariablePrefix}}localVarPostBody, {{localVariablePrefix}}localVarHeaderParams, {{localVariablePrefix}}localVarFormParams, {{localVariablePrefix}}localVarAuthNames, progressRequestListener); + } + + /** + * {{summary}} + * {{notes}}{{#allParams}} + * @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}{{/allParams}}{{#returnType}} + * @return {{returnType}}{{/returnType}} + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}}{{operationId}}({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) throws ApiException { + {{#returnType}}ApiResponse<{{{returnType}}}> {{localVariablePrefix}}resp = {{/returnType}}{{operationId}}WithHttpInfo({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}});{{#returnType}} + return {{localVariablePrefix}}resp.getData();{{/returnType}} + } + + /** + * {{summary}} + * {{notes}}{{#allParams}} + * @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}{{/allParams}} + * @return ApiResponse<{{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}Void{{/returnType}}> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> {{operationId}}WithHttpInfo({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) throws ApiException { + com.squareup.okhttp.Call {{localVariablePrefix}}call = {{operationId}}Call({{#allParams}}{{paramName}}, {{/allParams}}null, null); + {{#returnType}}Type {{localVariablePrefix}}localVarReturnType = new TypeToken<{{{returnType}}}>(){}.getType(); + return {{localVariablePrefix}}apiClient.execute({{localVariablePrefix}}call, {{localVariablePrefix}}localVarReturnType);{{/returnType}}{{^returnType}}return {{localVariablePrefix}}apiClient.execute({{localVariablePrefix}}call);{{/returnType}} + } + + /** + * {{summary}} (asynchronously) + * {{notes}}{{#allParams}} + * @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}{{/allParams}} + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call {{operationId}}Async({{#allParams}}{{{dataType}}} {{paramName}}, {{/allParams}}final ApiCallback<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> {{localVariablePrefix}}callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call {{localVariablePrefix}}call = {{operationId}}Call({{#allParams}}{{paramName}}, {{/allParams}}progressListener, progressRequestListener); + {{#returnType}}Type {{localVariablePrefix}}localVarReturnType = new TypeToken<{{{returnType}}}>(){}.getType(); + {{localVariablePrefix}}apiClient.executeAsync({{localVariablePrefix}}call, {{localVariablePrefix}}localVarReturnType, {{localVariablePrefix}}callback);{{/returnType}}{{^returnType}}{{localVariablePrefix}}apiClient.executeAsync({{localVariablePrefix}}call, {{localVariablePrefix}}callback);{{/returnType}} + return {{localVariablePrefix}}call; + } + {{/operation}} } {{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/auth/HttpBasicAuth.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/auth/HttpBasicAuth.mustache index f3ed85d980b..320903b0319 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/auth/HttpBasicAuth.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/auth/HttpBasicAuth.mustache @@ -1,3 +1,5 @@ +{{>licenseInfo}} + package {{invokerPackage}}.auth; import {{invokerPackage}}.Pair; @@ -10,32 +12,32 @@ import java.util.List; import java.io.UnsupportedEncodingException; public class HttpBasicAuth implements Authentication { - private String username; - private String password; + private String username; + private String password; - public String getUsername() { - return username; - } - - public void setUsername(String username) { - this.username = username; - } - - public String getPassword() { - return password; - } - - public void setPassword(String password) { - this.password = password; - } - - @Override - public void applyToParams(List queryParams, Map headerParams) { - if (username == null && password == null) { - return; + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + @Override + public void applyToParams(List queryParams, Map headerParams) { + if (username == null && password == null) { + return; + } + headerParams.put("Authorization", Credentials.basic( + username == null ? "" : username, + password == null ? "" : password)); } - headerParams.put("Authorization", Credentials.basic( - username == null ? "" : username, - password == null ? "" : password)); - } } diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/build.gradle.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/build.gradle.mustache index 4e7b0d1c395..d05d7746e89 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/build.gradle.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/build.gradle.mustache @@ -98,5 +98,6 @@ dependencies { compile 'com.squareup.okhttp:okhttp:2.7.5' compile 'com.squareup.okhttp:logging-interceptor:2.7.5' compile 'com.google.code.gson:gson:2.6.2' + compile 'joda-time:joda-time:2.9.3' testCompile 'junit:junit:4.12' } diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/build.sbt.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/build.sbt.mustache index 4673864fdd6..1352db97988 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/build.sbt.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/build.sbt.mustache @@ -13,6 +13,7 @@ lazy val root = (project in file(".")). "com.squareup.okhttp" % "okhttp" % "2.7.5", "com.squareup.okhttp" % "logging-interceptor" % "2.7.5", "com.google.code.gson" % "gson" % "2.6.2", + "joda-time" % "joda-time" % "2.9.3" % "compile", "junit" % "junit" % "4.12" % "test", "com.novocode" % "junit-interface" % "0.10" % "test" ) diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/model.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/model.mustache index 4bd6d5638b4..0c262eaa3a3 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/model.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/model.mustache @@ -1,3 +1,5 @@ +{{>licenseInfo}} + package {{package}}; import java.util.Objects; diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/modelEnum.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/modelEnum.mustache index f7af4c89f2f..213acb31568 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/modelEnum.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/modelEnum.mustache @@ -2,19 +2,19 @@ * {{^description}}Gets or Sets {{name}}{{/description}}{{#description}}{{description}}{{/description}} */ public enum {{#datatypeWithEnum}}{{.}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}} { - {{#allowableValues}}{{#enumVars}}@SerializedName({{#isInteger}}"{{/isInteger}}{{#isDouble}}"{{/isDouble}}{{#isLong}}"{{/isLong}}{{#isFloat}}"{{/isFloat}}{{{value}}}{{#isInteger}}"{{/isInteger}}{{#isDouble}}"{{/isDouble}}{{#isLong}}"{{/isLong}}{{#isFloat}}"{{/isFloat}}) - {{{name}}}({{{value}}}){{^-last}}, + {{#allowableValues}}{{#enumVars}}@SerializedName({{#isInteger}}"{{/isInteger}}{{#isDouble}}"{{/isDouble}}{{#isLong}}"{{/isLong}}{{#isFloat}}"{{/isFloat}}{{{value}}}{{#isInteger}}"{{/isInteger}}{{#isDouble}}"{{/isDouble}}{{#isLong}}"{{/isLong}}{{#isFloat}}"{{/isFloat}}) + {{{name}}}({{{value}}}){{^-last}}, - {{/-last}}{{#-last}};{{/-last}}{{/enumVars}}{{/allowableValues}} + {{/-last}}{{#-last}};{{/-last}}{{/enumVars}}{{/allowableValues}} - private {{dataType}} value; + private {{dataType}} value; - {{#datatypeWithEnum}}{{.}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}({{dataType}} value) { - this.value = value; - } + {{#datatypeWithEnum}}{{.}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}({{dataType}} value) { + this.value = value; + } - @Override - public String toString() { - return String.valueOf(value); - } + @Override + public String toString() { + return String.valueOf(value); + } } diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/modelInnerEnum.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/modelInnerEnum.mustache index 30ebf3febb6..bb69f71d24b 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/modelInnerEnum.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/modelInnerEnum.mustache @@ -1,20 +1,20 @@ - /** - * {{^description}}Gets or Sets {{{name}}}{{/description}}{{#description}}{{{description}}}{{/description}} - */ - public enum {{#datatypeWithEnum}}{{.}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}} { - {{#allowableValues}}{{#enumVars}}@SerializedName({{#isInteger}}"{{/isInteger}}{{#isDouble}}"{{/isDouble}}{{#isLong}}"{{/isLong}}{{#isFloat}}"{{/isFloat}}{{{value}}}{{#isInteger}}"{{/isInteger}}{{#isDouble}}"{{/isDouble}}{{#isLong}}"{{/isLong}}{{#isFloat}}"{{/isFloat}}) - {{{name}}}({{{value}}}){{^-last}}, + /** + * {{^description}}Gets or Sets {{{name}}}{{/description}}{{#description}}{{{description}}}{{/description}} + */ + public enum {{#datatypeWithEnum}}{{.}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}} { + {{#allowableValues}}{{#enumVars}}@SerializedName({{#isInteger}}"{{/isInteger}}{{#isDouble}}"{{/isDouble}}{{#isLong}}"{{/isLong}}{{#isFloat}}"{{/isFloat}}{{{value}}}{{#isInteger}}"{{/isInteger}}{{#isDouble}}"{{/isDouble}}{{#isLong}}"{{/isLong}}{{#isFloat}}"{{/isFloat}}) + {{{name}}}({{{value}}}){{^-last}}, - {{/-last}}{{#-last}};{{/-last}}{{/enumVars}}{{/allowableValues}} + {{/-last}}{{#-last}};{{/-last}}{{/enumVars}}{{/allowableValues}} - private {{datatype}} value; + private {{datatype}} value; - {{#datatypeWithEnum}}{{.}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}({{datatype}} value) { - this.value = value; + {{#datatypeWithEnum}}{{.}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}({{datatype}} value) { + this.value = value; + } + + @Override + public String toString() { + return String.valueOf(value); + } } - - @Override - public String toString() { - return String.valueOf(value); - } - } diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/pojo.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/pojo.mustache index b20499078a2..f2aad04d54b 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/pojo.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/pojo.mustache @@ -3,69 +3,93 @@ */{{#description}} @ApiModel(description = "{{{description}}}"){{/description}} public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#serializableModel}}implements Serializable{{/serializableModel}} { - {{#vars}}{{#isEnum}} + {{#vars}} + {{#isEnum}} +{{>libraries/common/modelInnerEnum}} + {{/isEnum}} + {{#items.isEnum}} + {{#items}} +{{>libraries/common/modelInnerEnum}} + {{/items}} + {{/items.isEnum}} + @SerializedName("{{baseName}}") + private {{{datatypeWithEnum}}} {{name}} = {{{defaultValue}}}; + {{/vars}} -{{>libraries/common/modelInnerEnum}}{{/isEnum}}{{#items.isEnum}}{{#items}} - -{{>libraries/common/modelInnerEnum}}{{/items}}{{/items.isEnum}} - @SerializedName("{{baseName}}") - private {{{datatypeWithEnum}}} {{name}} = {{{defaultValue}}}; - {{/vars}} - - {{#vars}} - /**{{#description}} - * {{{description}}}{{/description}}{{#minimum}} - * minimum: {{minimum}}{{/minimum}}{{#maximum}} - * maximum: {{maximum}}{{/maximum}} - **/ - @ApiModelProperty({{#required}}required = {{required}}, {{/required}}value = "{{{description}}}") - public {{{datatypeWithEnum}}} {{getter}}() { - return {{name}}; - }{{^isReadOnly}} - public void {{setter}}({{{datatypeWithEnum}}} {{name}}) { - this.{{name}} = {{name}}; - }{{/isReadOnly}} - - {{/vars}} - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; + {{#vars}} + /** + {{#description}} + * {{{description}}} + {{/description}} + {{^description}} + * Get {{name}} + {{/description}} + {{#minimum}} + * minimum: {{minimum}} + {{/minimum}} + {{#maximum}} + * maximum: {{maximum}} + {{/maximum}} + * @return {{name}} + **/ + @ApiModelProperty({{#required}}required = {{required}}, {{/required}}value = "{{{description}}}") + public {{{datatypeWithEnum}}} {{getter}}() { + return {{name}}; } - if (o == null || getClass() != o.getClass()) { - return false; - }{{#hasVars}} - {{classname}} {{classVarName}} = ({{classname}}) o; - return {{#vars}}Objects.equals(this.{{name}}, {{classVarName}}.{{name}}){{#hasMore}} && + + {{^isReadOnly}} + /** + * Set {{name}} + * + * @param {{name}} {{name}} + */ + public void {{setter}}({{{datatypeWithEnum}}} {{name}}) { + this.{{name}} = {{name}}; + } + + {{/isReadOnly}} + {{/vars}} + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + }{{#hasVars}} + {{classname}} {{classVarName}} = ({{classname}}) o; + return {{#vars}}Objects.equals(this.{{name}}, {{classVarName}}.{{name}}){{#hasMore}} && {{/hasMore}}{{/vars}}{{#parent}} && super.equals(o){{/parent}};{{/hasVars}}{{^hasVars}} - return true;{{/hasVars}} - } - - @Override - public int hashCode() { - return Objects.hash({{#vars}}{{name}}{{#hasMore}}, {{/hasMore}}{{/vars}}{{#parent}}{{#hasVars}}, {{/hasVars}}super.hashCode(){{/parent}}); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class {{classname}} {\n"); - {{#parent}}sb.append(" ").append(toIndentedString(super.toString())).append("\n");{{/parent}} - {{#vars}}sb.append(" {{name}}: ").append(toIndentedString({{name}})).append("\n"); - {{/vars}}sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; + return true;{{/hasVars}} + } + + @Override + public int hashCode() { + return Objects.hash({{#vars}}{{name}}{{#hasMore}}, {{/hasMore}}{{/vars}}{{#parent}}{{#hasVars}}, {{/hasVars}}super.hashCode(){{/parent}}); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class {{classname}} {\n"); + {{#parent}}sb.append(" ").append(toIndentedString(super.toString())).append("\n");{{/parent}} + {{#vars}}sb.append(" {{name}}: ").append(toIndentedString({{name}})).append("\n"); + {{/vars}}sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + * + * @param o Object to be converted to indented string + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); } - return o.toString().replace("\n", "\n "); - } } diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/pom.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/pom.mustache index cfe169c5eca..b1ec0b62461 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/pom.mustache @@ -105,40 +105,6 @@ 1.7 - - - org.codehaus.mojo - exec-maven-plugin - 1.2.1 - - - gradle-test - integration-test - - exec - - - gradle - - check - - - - - sbt-test - integration-test - - exec - - - sbt - - publishLocal - - - - - @@ -162,6 +128,11 @@ gson ${gson-version} + + joda-time + joda-time + ${jodatime-version} + @@ -172,9 +143,10 @@ - 1.5.8 + 1.5.9 2.7.5 2.6.2 + 2.9.3 1.0.0 4.12 UTF-8 diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/ApiClient.mustache index 183fb5f27ce..c7b86b66b9c 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/ApiClient.mustache @@ -9,6 +9,10 @@ import java.util.Map; import org.apache.oltu.oauth2.client.request.OAuthClientRequest.AuthenticationRequestBuilder; import org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuilder; +import org.joda.time.DateTime; +import org.joda.time.LocalDate; +import org.joda.time.format.DateTimeFormatter; +import org.joda.time.format.ISODateTimeFormat; import retrofit.RestAdapter; import retrofit.client.OkClient; @@ -22,6 +26,9 @@ import retrofit.mime.TypedOutput; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; import com.squareup.okhttp.Interceptor; import com.squareup.okhttp.OkHttpClient; @@ -108,6 +115,8 @@ public class ApiClient { public void createDefaultAdapter() { Gson gson = new GsonBuilder() .setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ") + .registerTypeAdapter(DateTime.class, new DateTimeTypeAdapter()) + .registerTypeAdapter(LocalDate.class, new LocalDateTypeAdapter()) .create(); okClient = new OkHttpClient(); @@ -339,3 +348,61 @@ class GsonConverterWrapper implements Converter { } } + +/** + * Gson TypeAdapter for Joda DateTime type + */ +class DateTimeTypeAdapter extends TypeAdapter { + + private final DateTimeFormatter formatter = ISODateTimeFormat.dateTime(); + + @Override + public void write(JsonWriter out, DateTime date) throws IOException { + if (date == null) { + out.nullValue(); + } else { + out.value(formatter.print(date)); + } + } + + @Override + public DateTime read(JsonReader in) throws IOException { + switch (in.peek()) { + case NULL: + in.nextNull(); + return null; + default: + String date = in.nextString(); + return formatter.parseDateTime(date); + } + } +} + +/** + * Gson TypeAdapter for Joda DateTime type + */ +class LocalDateTypeAdapter extends TypeAdapter { + + private final DateTimeFormatter formatter = ISODateTimeFormat.date(); + + @Override + public void write(JsonWriter out, LocalDate date) throws IOException { + if (date == null) { + out.nullValue(); + } else { + out.value(formatter.print(date)); + } + } + + @Override + public LocalDate read(JsonReader in) throws IOException { + switch (in.peek()) { + case NULL: + in.nextNull(); + return null; + default: + String date = in.nextString(); + return formatter.parseLocalDate(date); + } + } +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/build.gradle.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/build.gradle.mustache index 6be9ba586f3..179bda3b8d8 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/build.gradle.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/build.gradle.mustache @@ -99,6 +99,7 @@ ext { retrofit_version = "1.9.0" swagger_annotations_version = "1.5.8" junit_version = "4.12" + jodatime_version = "2.9.3" } dependencies { @@ -106,5 +107,6 @@ dependencies { compile "com.squareup.retrofit:retrofit:$retrofit_version" compile "io.swagger:swagger-annotations:$swagger_annotations_version" compile "org.apache.oltu.oauth2:org.apache.oltu.oauth2.client:$oltu_version" + compile "joda-time:joda-time:$jodatime_version" testCompile "junit:junit:$junit_version" } diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/build.sbt.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/build.sbt.mustache new file mode 100644 index 00000000000..56f6cee13ab --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/build.sbt.mustache @@ -0,0 +1,20 @@ +lazy val root = (project in file(".")). + settings( + organization := "{{groupId}}", + name := "{{artifactId}}", + version := "{{artifactVersion}}", + scalaVersion := "2.11.4", + scalacOptions ++= Seq("-feature"), + javacOptions in compile ++= Seq("-Xlint:deprecation"), + publishArtifact in (Compile, packageDoc) := false, + resolvers += Resolver.mavenLocal, + libraryDependencies ++= Seq( + "com.squareup.okhttp" % "okhttp" % "2.7.5" % "compile", + "com.squareup.retrofit" % "retrofit" % "1.9.0" % "compile", + "io.swagger" % "swagger-annotations" % "1.5.8" % "compile", + "org.apache.oltu.oauth2" % "org.apache.oltu.oauth2.client" % "1.0.1" % "compile", + "joda-time" % "joda-time" % "2.9.3" % "compile", + "junit" % "junit" % "4.12" % "test", + "com.novocode" % "junit-interface" % "0.10" % "test" + ) + ) diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/pom.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/pom.mustache index 9a917f19caf..c9991c230e5 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/pom.mustache @@ -127,6 +127,11 @@ okhttp ${okhttp-version} + + joda-time + joda-time + ${jodatime-version} + @@ -140,6 +145,7 @@ 1.5.8 1.9.0 2.7.5 + 2.9.3 1.0.1 1.0.0 4.12 diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/ApiClient.mustache index ad5f02c49e4..a4d62eece24 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/ApiClient.mustache @@ -9,6 +9,10 @@ import java.util.Map; import org.apache.oltu.oauth2.client.request.OAuthClientRequest.AuthenticationRequestBuilder; import org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuilder; +import org.joda.time.DateTime; +import org.joda.time.LocalDate; +import org.joda.time.format.DateTimeFormatter; +import org.joda.time.format.ISODateTimeFormat; import retrofit2.Converter; import retrofit2.Retrofit; @@ -19,6 +23,9 @@ import retrofit2.converter.scalars.ScalarsConverterFactory; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; import okhttp3.Interceptor; import okhttp3.OkHttpClient; import okhttp3.RequestBody; @@ -108,6 +115,8 @@ public class ApiClient { public void createDefaultAdapter() { Gson gson = new GsonBuilder() .setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ") + .registerTypeAdapter(DateTime.class, new DateTimeTypeAdapter()) + .registerTypeAdapter(LocalDate.class, new LocalDateTypeAdapter()) .create(); okClient = new OkHttpClient(); @@ -346,3 +355,58 @@ class GsonCustomConverterFactory extends Converter.Factory } } + +/** + * Gson TypeAdapter for Joda DateTime type + */ +class DateTimeTypeAdapter extends TypeAdapter { + + private final DateTimeFormatter formatter = ISODateTimeFormat.dateTime(); + + @Override + public void write(JsonWriter out, DateTime date) throws IOException { + if (date == null) { + out.nullValue(); + } else { + out.value(formatter.print(date)); + } + } + + @Override + public DateTime read(JsonReader in) throws IOException { + switch (in.peek()) { + case NULL: + in.nextNull(); + return null; + default: + String date = in.nextString(); + return formatter.parseDateTime(date); + } + } +} + +class LocalDateTypeAdapter extends TypeAdapter { + + private final DateTimeFormatter formatter = ISODateTimeFormat.date(); + + @Override + public void write(JsonWriter out, LocalDate date) throws IOException { + if (date == null) { + out.nullValue(); + } else { + out.value(formatter.print(date)); + } + } + + @Override + public LocalDate read(JsonReader in) throws IOException { + switch (in.peek()) { + case NULL: + in.nextNull(); + return null; + default: + String date = in.nextString(); + return formatter.parseLocalDate(date); + } + } +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/build.gradle.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/build.gradle.mustache index e56e682cfcd..fd2e94b582e 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/build.gradle.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/build.gradle.mustache @@ -97,25 +97,20 @@ ext { oltu_version = "1.0.1" retrofit_version = "2.0.2" swagger_annotations_version = "1.5.8" - junit_version = "4.12" -{{#useRxJava}} - rx_java_version = "1.1.3" -{{/useRxJava}} -{{^useRxJava}}{{/useRxJava}} + junit_version = "4.12"{{#useRxJava}} + rx_java_version = "1.1.3"{{/useRxJava}} + jodatime_version = "2.9.3" } dependencies { compile "com.squareup.retrofit2:retrofit:$retrofit_version" compile "com.squareup.retrofit2:converter-scalars:$retrofit_version" - compile "com.squareup.retrofit2:converter-gson:$retrofit_version" -{{#useRxJava}} + compile "com.squareup.retrofit2:converter-gson:$retrofit_version"{{#useRxJava}} compile "com.squareup.retrofit2:adapter-rxjava:$retrofit_version" - compile "io.reactivex:rxjava:$rx_java_version" -{{/useRxJava}} -{{^useRxJava}}{{/useRxJava}} - + compile "io.reactivex:rxjava:$rx_java_version"{{/useRxJava}} compile "io.swagger:swagger-annotations:$swagger_annotations_version" compile "org.apache.oltu.oauth2:org.apache.oltu.oauth2.client:$oltu_version" + compile "joda-time:joda-time:$jodatime_version" testCompile "junit:junit:$junit_version" } diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/build.sbt.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/build.sbt.mustache new file mode 100644 index 00000000000..ff564803b44 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/build.sbt.mustache @@ -0,0 +1,23 @@ +lazy val root = (project in file(".")). + settings( + organization := "{{groupId}}", + name := "{{artifactId}}", + version := "{{artifactVersion}}", + scalaVersion := "2.11.4", + scalacOptions ++= Seq("-feature"), + javacOptions in compile ++= Seq("-Xlint:deprecation"), + publishArtifact in (Compile, packageDoc) := false, + resolvers += Resolver.mavenLocal, + libraryDependencies ++= Seq( + "com.squareup.retrofit2" % "retrofit" % "2.0.2" % "compile", + "com.squareup.retrofit2" % "converter-scalars" % "2.0.2" % "compile", + "com.squareup.retrofit2" % "converter-gson" % "2.0.2" % "compile",{{#useRxJava}} + "com.squareup.retrofit2" % "adapter-rxjava" % "2.0.2" % "compile", + "io.reactivex" % "rxjava" % "1.1.3" % "compile",{{/useRxJava}} + "io.swagger" % "swagger-annotations" % "1.5.8" % "compile", + "org.apache.oltu.oauth2" % "org.apache.oltu.oauth2.client" % "1.0.1" % "compile", + "joda-time" % "joda-time" % "2.9.3" % "compile", + "junit" % "junit" % "4.12" % "test", + "com.novocode" % "junit-interface" % "0.10" % "test" + ) + ) diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/pom.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/pom.mustache index 30f6a71d285..2cc806ebbd3 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/pom.mustache @@ -131,6 +131,11 @@ org.apache.oltu.oauth2 org.apache.oltu.oauth2.client ${oltu-version} + + + joda-time + joda-time + ${jodatime-version} {{#useRxJava}} io.reactivex @@ -153,9 +158,9 @@ 1.5.8 - 2.0.2 - {{#useRxJava}}1.1.3{{/useRxJava}} - 3.2.0 + 2.0.2{{#useRxJava}} + 1.1.3{{/useRxJava}} + 2.9.3 1.0.1 1.0.0 4.12 diff --git a/modules/swagger-codegen/src/main/resources/Java/licenseInfo.mustache b/modules/swagger-codegen/src/main/resources/Java/licenseInfo.mustache new file mode 100644 index 00000000000..861d97234cf --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/licenseInfo.mustache @@ -0,0 +1,23 @@ +/** + * {{{appName}}} + * {{{appDescription}}} + * + * {{#version}}OpenAPI spec version: {{{version}}}{{/version}} + * {{#infoEmail}}Contact: {{{infoEmail}}}{{/infoEmail}} + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ diff --git a/modules/swagger-codegen/src/main/resources/JavaSpringBoot/README.mustache b/modules/swagger-codegen/src/main/resources/JavaSpringBoot/README.mustache index 8f9855eedf9..02d932b8aca 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpringBoot/README.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpringBoot/README.mustache @@ -1,4 +1,4 @@ -# Swagger generated server +{{^interfaceOnly}}# Swagger generated server Spring Boot Server @@ -15,4 +15,31 @@ 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 +Change default port value in application.properties{{/interfaceOnly}}{{#interfaceOnly}} +# Swagger generated API stub + +Spring Framework stub + + +## Overview +This code was generated by the [swagger-codegen](https://github.com/swagger-api/swagger-codegen) project. +By using the [OpenAPI-Spec](https://github.com/swagger-api/swagger-core), you can easily generate an API stub. +This is an example of building API stub interfaces in Java using the Spring framework. + +The stubs generated can be used in your existing Spring-MVC or Spring-Boot application to create controller endpoints +by adding ```@Controller``` classes that implement the interface. Eg: +```java +@Controller +public class PetController implements PetApi { +// implement all PetApi methods +} +``` + +You can also use the interface to create [Spring-Cloud Feign clients](http://projects.spring.io/spring-cloud/spring-cloud.html#spring-cloud-feign-inheritance).Eg: +```java +@FeignClient(name="pet", url="http://petstore.swagger.io/v2") +public interface PetClient extends PetApi { + +} +``` +{{/interfaceOnly}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaSpringBoot/api.mustache b/modules/swagger-codegen/src/main/resources/JavaSpringBoot/api.mustache index b214f376110..bd0d7180529 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpringBoot/api.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpringBoot/api.mustache @@ -7,9 +7,7 @@ import {{modelPackage}}.*; 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; @@ -23,12 +21,10 @@ 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") +@Api(value = "{{{baseName}}}", description = "the {{{baseName}}} API") {{>generatedAnnotation}} {{#operations}} -public class {{classname}} { +public interface {{classname}} { {{#operation}} @ApiOperation(value = "{{{summary}}}", notes = "{{{notes}}}", response = {{{returnType}}}.class{{#returnContainer}}, responseContainer = "{{{returnContainer}}}"{{/returnContainer}}{{#hasAuthMethods}}, authorizations = { @@ -40,16 +36,14 @@ public class {{classname}} { }{{/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}} + @RequestMapping(value = "{{{path}}}",{{#singleContentTypes}} + produces = "{{{vendorExtensions.x-accepts}}}", + consumes = "{{{vendorExtensions.x-contentType}}}",{{/singleContentTypes}}{{^singleContentTypes}}{{#hasProduces}} + produces = { {{#produces}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }, {{/hasProduces}}{{#hasConsumes}} + consumes = { {{#consumes}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} },{{/hasConsumes}}{{/singleContentTypes}} 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); - } + ResponseEntity<{{>returnTypes}}> {{operationId}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}}, + {{/hasMore}}{{/allParams}}); {{/operation}} } diff --git a/modules/swagger-codegen/src/main/resources/JavaSpringBoot/apiController.mustache b/modules/swagger-codegen/src/main/resources/JavaSpringBoot/apiController.mustache new file mode 100644 index 00000000000..0cde913d660 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaSpringBoot/apiController.mustache @@ -0,0 +1,35 @@ +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.RequestParam; +import org.springframework.web.bind.annotation.RequestPart; +import org.springframework.web.multipart.MultipartFile; + +import java.util.List; + +@Controller +{{>generatedAnnotation}} +{{#operations}} +public class {{classname}}Controller implements {{classname}} { + {{#operation}} + public ResponseEntity<{{>returnTypes}}> {{operationId}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}}, + {{/hasMore}}{{/allParams}}) { + // do some magic! + return new ResponseEntity<{{>returnTypes}}>(HttpStatus.OK); + } + + {{/operation}} +} +{{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/JavaSpringBoot/formParams.mustache b/modules/swagger-codegen/src/main/resources/JavaSpringBoot/formParams.mustache index 65e84817a23..d84de0c3376 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpringBoot/formParams.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpringBoot/formParams.mustache @@ -1,2 +1 @@ -{{#isFormParam}}{{#notFile}} -@ApiParam(value = "{{{description}}}"{{#required}}, required=true{{/required}} {{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}) @RequestPart(value="{{paramName}}"{{#required}}, required=true{{/required}}{{^required}}, required=false{{/required}}) {{{dataType}}} {{paramName}}{{/notFile}}{{#isFile}}@ApiParam(value = "file detail") @RequestPart("file") MultipartFile {{baseName}}{{/isFile}}{{/isFormParam}} +{{#isFormParam}}{{#notFile}}@ApiParam(value = "{{{description}}}"{{#required}}, required=true{{/required}} {{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}) @RequestPart(value="{{paramName}}"{{#required}}, required=true{{/required}}{{^required}}, required=false{{/required}}) {{{dataType}}} {{paramName}}{{/notFile}}{{#isFile}}@ApiParam(value = "file detail") @RequestPart("file") MultipartFile {{baseName}}{{/isFile}}{{/isFormParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaSpringBoot/generatedAnnotation.mustache b/modules/swagger-codegen/src/main/resources/JavaSpringBoot/generatedAnnotation.mustache index 49110fc1ad9..a47b6faa85b 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpringBoot/generatedAnnotation.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpringBoot/generatedAnnotation.mustache @@ -1 +1 @@ -@javax.annotation.Generated(value = "{{generatorClass}}", date = "{{generatedDate}}") \ No newline at end of file +{{^hideGenerationTimestamp}}@javax.annotation.Generated(value = "{{generatorClass}}", date = "{{generatedDate}}"){{/hideGenerationTimestamp}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaSpringBoot/headerParams.mustache b/modules/swagger-codegen/src/main/resources/JavaSpringBoot/headerParams.mustache index 297d5131d92..7c9e7356a0b 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpringBoot/headerParams.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpringBoot/headerParams.mustache @@ -1 +1 @@ -{{#isHeaderParam}}@ApiParam(value = "{{{description}}}" {{#required}},required=true{{/required}} {{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}) @RequestHeader(value="{{baseName}}", required={{#required}}true{{/required}}{{^required}}false{{/required}}) {{{dataType}}} {{paramName}}{{/isHeaderParam}} +{{#isHeaderParam}}@ApiParam(value = "{{{description}}}" {{#required}},required=true{{/required}} {{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}) @RequestHeader(value="{{baseName}}", required={{#required}}true{{/required}}{{^required}}false{{/required}}) {{{dataType}}} {{paramName}}{{/isHeaderParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaSpringBoot/pom.mustache b/modules/swagger-codegen/src/main/resources/JavaSpringBoot/pom.mustache index f6cc38793e7..53c3652cb45 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpringBoot/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpringBoot/pom.mustache @@ -14,7 +14,7 @@ 1.3.3.RELEASE - src/main/java + src/main/java{{^interfaceOnly}} org.springframework.boot @@ -27,7 +27,7 @@ - + {{/interfaceOnly}} @@ -50,5 +50,14 @@ springfox-swagger-ui ${springfox-version} + + + com.fasterxml.jackson.datatype + jackson-datatype-joda + + + joda-time + joda-time + \ 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 index 3bb2afcb6cd..d935fb11fd3 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpringBoot/queryParams.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpringBoot/queryParams.mustache @@ -1 +1 @@ -{{#isQueryParam}}@ApiParam(value = "{{{description}}}"{{#required}}, required = true{{/required}}{{#allowableValues}}, allowableValues = "{{{allowableValues}}}"{{/allowableValues}}{{#defaultValue}}, defaultValue = "{{{defaultValue}}}"{{/defaultValue}}) @RequestParam(value = "{{paramName}}"{{#required}}, required = true{{/required}}{{^required}}, required = false{{/required}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}) {{{dataType}}} {{paramName}}{{/isQueryParam}} +{{#isQueryParam}}@ApiParam(value = "{{{description}}}"{{#required}}, required = true{{/required}}{{#allowableValues}}, allowableValues = "{{{allowableValues}}}"{{/allowableValues}}{{#defaultValue}}, defaultValue = "{{{defaultValue}}}"{{/defaultValue}}) @RequestParam(value = "{{paramName}}"{{#required}}, required = true{{/required}}{{^required}}, required = false{{/required}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}) {{{dataType}}} {{paramName}}{{/isQueryParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaSpringBoot/swaggerDocumentationConfig.mustache b/modules/swagger-codegen/src/main/resources/JavaSpringBoot/swaggerDocumentationConfig.mustache index 1af646a6908..970739e1b97 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpringBoot/swaggerDocumentationConfig.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpringBoot/swaggerDocumentationConfig.mustache @@ -34,6 +34,8 @@ public class SwaggerDocumentationConfig { .select() .apis(RequestHandlerSelectors.basePackage("{{apiPackage}}")) .build() + .directModelSubstitute(org.joda.time.LocalDate.class, java.sql.Date.class) + .directModelSubstitute(org.joda.time.DateTime.class, java.util.Date.class) .apiInfo(apiInfo()); } diff --git a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/apiController.mustache b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/apiController.mustache new file mode 100644 index 00000000000..7fe7c5acf60 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/apiController.mustache @@ -0,0 +1,61 @@ +package {{apiPackage}}; + +import {{modelPackage}}.*; + +{{#imports}}import {{import}}; +{{/imports}} + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import io.swagger.annotations.ApiResponses; +import io.swagger.annotations.Authorization; +import io.swagger.annotations.AuthorizationScope; + +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}}) + @io.swagger.annotations.ApiResponses(value = { {{#responses}} + @io.swagger.annotations.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/csharp/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/csharp/ApiClient.mustache index 1d34ff21eae..6ab34216b9f 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/ApiClient.mustache @@ -17,15 +17,28 @@ using RestSharp; namespace {{packageName}}.Client { /// - /// API client is mainly responible for making the HTTP call to the API backend. + /// API client is mainly responsible for making the HTTP call to the API backend. /// - public class ApiClient + public partial class ApiClient { private JsonSerializerSettings serializerSettings = new JsonSerializerSettings { ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor }; + /// + /// Allows for extending request processing for generated code. + /// + /// The RestSharp request object + partial void InterceptRequest(IRestRequest request); + + /// + /// Allows for extending response processing for generated code. + /// + /// The RestSharp request object + /// The RestSharp response object + partial void InterceptResponse(IRestRequest request, IRestResponse response); + /// /// Initializes a new instance of the class /// with default configuration and base path ({{basePath}}). @@ -165,6 +178,7 @@ namespace {{packageName}}.Client // set user agent RestClient.UserAgent = Configuration.UserAgent; + InterceptRequest(request); {{^supportsUWP}} var response = RestClient.Execute(request); {{/supportsUWP}} @@ -172,6 +186,8 @@ namespace {{packageName}}.Client // Using async method to perform sync call (uwp-only) var response = RestClient.ExecuteTaskAsync(request).Result; {{/supportsUWP}} + InterceptResponse(request, response); + return (Object) response; } {{#supportsAsync}} @@ -197,7 +213,9 @@ namespace {{packageName}}.Client var request = PrepareRequest( path, method, queryParams, postBody, headerParams, formParams, fileParams, pathParams, contentType); + InterceptRequest(request); var response = await RestClient.ExecuteTaskAsync(request); + InterceptResponse(request, response); return (Object)response; }{{/supportsAsync}} diff --git a/modules/swagger-codegen/src/main/resources/csharp/Configuration.mustache b/modules/swagger-codegen/src/main/resources/csharp/Configuration.mustache index eddb9d0de1f..48b2886f6c9 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/Configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/Configuration.mustache @@ -80,6 +80,17 @@ namespace {{packageName}}.Client /// Configuration. public static Configuration Default = new Configuration(); + /// + /// Default creation of exceptions for a given method name and response object + /// + public static readonly ExceptionFactory DefaultExceptionFactory = (methodName, response) => + { + int status = (int) response.StatusCode; + if (status >= 400) return new ApiException(status, String.Format("Error calling {0}: {1}", methodName, response.Content), response.Content); + if (status == 0) return new ApiException(status, String.Format("Error calling {0}: {1}", methodName, response.ErrorMessage), response.ErrorMessage); + return null; + }; + /// /// Gets or sets the HTTP timeout (milliseconds) of ApiClient. Default to 100000 milliseconds. /// diff --git a/modules/swagger-codegen/src/main/resources/csharp/ExceptionFactory.mustache b/modules/swagger-codegen/src/main/resources/csharp/ExceptionFactory.mustache new file mode 100644 index 00000000000..c25b88ee614 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/csharp/ExceptionFactory.mustache @@ -0,0 +1,15 @@ +{{>partial_header}} + +using System; +using RestSharp; + +namespace {{packageName}}.Client +{ + /// + /// A delegate to ExceptionFactory method + /// + /// Method name + /// Response + /// Exceptions + public delegate Exception ExceptionFactory(string methodName, IRestResponse response); +} diff --git a/modules/swagger-codegen/src/main/resources/csharp/IApiAccessor.mustache b/modules/swagger-codegen/src/main/resources/csharp/IApiAccessor.mustache index 22db465efaa..df236b8f8c8 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/IApiAccessor.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/IApiAccessor.mustache @@ -24,5 +24,10 @@ namespace {{packageName}}.Client /// /// The base path String GetBasePath(); + + /// + /// Provides a factory method hook for the creation of exceptions. + /// + ExceptionFactory ExceptionFactory { get; set; } } } diff --git a/modules/swagger-codegen/src/main/resources/csharp/Project.mustache b/modules/swagger-codegen/src/main/resources/csharp/Project.mustache index a8e18ea91ac..7a4c741ca4a 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/Project.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/Project.mustache @@ -71,10 +71,10 @@ limitations under the License. - $(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\Newtonsoft.Json.8.0.3\lib\{{targetFrameworkNuget}}\Newtonsoft.Json.dll + ..\packages\Newtonsoft.Json.8.0.3\lib\{{targetFrameworkNuget}}\Newtonsoft.Json.dll + ..\..\packages\Newtonsoft.Json.8.0.3\lib\{{targetFrameworkNuget}}\Newtonsoft.Json.dll + {{binRelativePath}}\Newtonsoft.Json.8.0.3\lib\{{targetFrameworkNuget}}\Newtonsoft.Json.dll $(SolutionDir)\packages\RestSharp.105.1.0\lib\{{targetFrameworkNuget}}\RestSharp.dll diff --git a/modules/swagger-codegen/src/main/resources/csharp/TestProject.mustache b/modules/swagger-codegen/src/main/resources/csharp/TestProject.mustache index 2866dcb0601..f01a7e25dbb 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/TestProject.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/TestProject.mustache @@ -71,10 +71,10 @@ limitations under the License. - $(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\Newtonsoft.Json.8.0.3\lib\{{targetFrameworkNuget}}\Newtonsoft.Json.dll + ..\packages\Newtonsoft.Json.8.0.3\lib\{{targetFrameworkNuget}}\Newtonsoft.Json.dll + ..\..\packages\Newtonsoft.Json.8.0.3\lib\{{targetFrameworkNuget}}\Newtonsoft.Json.dll + {{binRelativePath}}\Newtonsoft.Json.8.0.3\lib\{{targetFrameworkNuget}}\Newtonsoft.Json.dll $(SolutionDir)\packages\RestSharp.105.1.0\lib\{{targetFrameworkNuget}}\RestSharp.dll @@ -83,10 +83,10 @@ limitations under the License. {{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 + $(SolutionDir)\packages\NUnit.3.2.1\lib\nunit.framework.dll + ..\packages\NUnit.3.2.1\lib\nunit.framework.dll + ..\..\packages\NUnit.3.2.1\lib\nunit.framework.dll + {{binRelativePath}}\NUnit.3.2.1\lib\nunit.framework.dll diff --git a/modules/swagger-codegen/src/main/resources/csharp/api.mustache b/modules/swagger-codegen/src/main/resources/csharp/api.mustache index 1145421d22d..807155e4a45 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/api.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/api.mustache @@ -75,6 +75,8 @@ namespace {{packageName}}.Api /// public partial class {{classname}} : I{{classname}} { + private {{packageName}}.Client.ExceptionFactory _exceptionFactory = (name, response) => null; + /// /// Initializes a new instance of the class. /// @@ -83,6 +85,8 @@ namespace {{packageName}}.Api { this.Configuration = new Configuration(new ApiClient(basePath)); + ExceptionFactory = {{packageName}}.Client.Configuration.DefaultExceptionFactory; + // ensure API client has configuration ready if (Configuration.ApiClient.Configuration == null) { @@ -103,6 +107,8 @@ namespace {{packageName}}.Api else this.Configuration = configuration; + ExceptionFactory = {{packageName}}.Client.Configuration.DefaultExceptionFactory; + // ensure API client has configuration ready if (Configuration.ApiClient.Configuration == null) { @@ -135,6 +141,22 @@ namespace {{packageName}}.Api /// An instance of the Configuration public Configuration Configuration {get; set;} + /// + /// Provides a factory method hook for the creation of exceptions. + /// + public {{packageName}}.Client.ExceptionFactory ExceptionFactory + { + get + { + if (_exceptionFactory != null && _exceptionFactory.GetInvocationList().Length > 1) + { + throw new InvalidOperationException("Multicast delegate for ExceptionFactory is unsupported."); + } + return _exceptionFactory; + } + set { _exceptionFactory = value; } + } + /// /// Gets the default header. /// @@ -276,10 +298,11 @@ namespace {{packageName}}.Api int localVarStatusCode = (int) localVarResponse.StatusCode; - if (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling {{operationId}}: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling {{operationId}}: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + if (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("{{operationId}}", localVarResponse); + if (exception != null) throw exception; + } {{#returnType}}return new ApiResponse<{{{returnType}}}>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), @@ -410,10 +433,11 @@ namespace {{packageName}}.Api int localVarStatusCode = (int) localVarResponse.StatusCode; - if (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling {{operationId}}: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling {{operationId}}: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + if (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("{{operationId}}", localVarResponse); + if (exception != null) throw exception; + } {{#returnType}}return new ApiResponse<{{{returnType}}}>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), diff --git a/modules/swagger-codegen/src/main/resources/csharp/api_test.mustache b/modules/swagger-codegen/src/main/resources/csharp/api_test.mustache index cc487fb681e..f3f1caeaf0a 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/api_test.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/api_test.mustache @@ -51,7 +51,8 @@ namespace {{packageName}}.Test [Test] public void {{operationId}}InstanceTest() { - Assert.IsInstanceOf<{{classname}}> (instance, "instance is a {{classname}}"); + // test 'IsInstanceOfType' {{classname}} + Assert.IsInstanceOfType(typeof({{classname}}), instance, "instance is a {{classname}}"); } {{#operations}}{{#operation}} @@ -61,12 +62,12 @@ namespace {{packageName}}.Test [Test] public void {{operationId}}Test() { - // TODO: add unit test for the method '{{operationId}}' + // TODO uncomment below to test the method and replace null with proper value {{#allParams}} - {{{dataType}}} {{paramName}} = null; // TODO: replace null with proper value + //{{{dataType}}} {{paramName}} = null; {{/allParams}} - {{#returnType}}var response = {{/returnType}}instance.{{operationId}}({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); - {{#returnType}}Assert.IsInstanceOf<{{{returnType}}}> (response, "response is {{{returnType}}}");{{/returnType}} + //{{#returnType}}var response = {{/returnType}}instance.{{operationId}}({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); + {{#returnType}}//Assert.IsInstanceOf<{{{returnType}}}> (response, "response is {{{returnType}}}");{{/returnType}} } {{/operation}}{{/operations}} } 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 f93437eb0c8..7aab3657090 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 @@ -1,15 +1,35 @@ #!/usr/bin/env bash +# +# Generated by: https://github.com/swagger-api/swagger-codegen.git +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + frameworkVersion={{targetFrameworkNuget}} netfx=${frameworkVersion#net} +echo "[INFO] Target framework: ${frameworkVersion}" + +echo "[INFO] Download nuget and packages" wget -nc https://nuget.org/nuget.exe; mozroots --import --sync mono nuget.exe install src/{{packageName}}/packages.config -o packages; -mkdir -p bin; -cp packages/Newtonsoft.Json.8.0.2/lib/{{targetFrameworkNuget}}/Newtonsoft.Json.dll bin/Newtonsoft.Json.dll; +echo "[INFO] Copy DLLs to the 'bin' folder" +mkdir -p bin; +cp packages/Newtonsoft.Json.8.0.3/lib/{{targetFrameworkNuget}}/Newtonsoft.Json.dll bin/Newtonsoft.Json.dll; cp packages/RestSharp.105.1.0/lib/{{targetFrameworkNuget}}/RestSharp.dll bin/RestSharp.dll; +echo "[INFO] Run 'mcs' to build bin/{{{packageName}}}.dll" mcs -sdk:${netfx} -r:bin/Newtonsoft.Json.dll,\ bin/RestSharp.dll,\ System.Runtime.Serialization.dll \ @@ -18,3 +38,11 @@ System.Runtime.Serialization.dll \ -recurse:'src/{{packageName}}/*.cs' \ -doc:bin/{{packageName}}.xml \ -platform:anycpu + +if [ $? -ne 0 ] +then + echo "[ERROR] Compilation failed with exit code $?" + exit 1 +else + echo "[INFO] bin/{{{packageName}}}.dll was created successfully" +fi diff --git a/modules/swagger-codegen/src/main/resources/csharp/compile.mustache b/modules/swagger-codegen/src/main/resources/csharp/compile.mustache index 7f6dcfe0713..5da333f4e72 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/compile.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/compile.mustache @@ -1,3 +1,17 @@ +:: Generated by: https://github.com/swagger-api/swagger-codegen.git +:: +:: Licensed under the Apache License, Version 2.0 (the "License"); +:: you may not use this file except in compliance with the License. +:: You may obtain a copy of the License at +:: +:: http://www.apache.org/licenses/LICENSE-2.0 +:: +:: Unless required by applicable law or agreed to in writing, software +:: distributed under the License is distributed on an "AS IS" BASIS, +:: WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +:: See the License for the specific language governing permissions and +:: limitations under the License. + @echo off {{#supportsAsync}}SET CSCPATH=%SYSTEMROOT%\Microsoft.NET\Framework\v4.0.30319{{/supportsAsync}} @@ -8,7 +22,7 @@ if not exist ".\nuget.exe" powershell -Command "(new-object System.Net.WebClient if not exist ".\bin" mkdir bin -copy packages\Newtonsoft.Json.8.0.2\lib\{{targetFrameworkNuget}}\Newtonsoft.Json.dll bin\Newtonsoft.Json.dll +copy packages\Newtonsoft.Json.8.0.3\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\{{packageName}}\*.cs /doc:bin\{{packageName}}.xml diff --git a/modules/swagger-codegen/src/main/resources/csharp/model_test.mustache b/modules/swagger-codegen/src/main/resources/csharp/model_test.mustache index f9dd3c08efc..233534a3348 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/model_test.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/model_test.mustache @@ -25,7 +25,8 @@ namespace {{packageName}}.Test [TestFixture] public class {{classname}}Tests { - private {{classname}} instance; + // TODO uncomment below to declare an instance variable for {{classname}} + //private {{classname}} instance; /// /// Setup before each test @@ -33,7 +34,8 @@ namespace {{packageName}}.Test [SetUp] public void Init() { - instance = new {{classname}}(); + // TODO uncomment below to create an instance of {{classname}} + //instance = new {{classname}}(); } /// @@ -51,7 +53,8 @@ namespace {{packageName}}.Test [Test] public void {{classname}}InstanceTest() { - Assert.IsInstanceOf<{{classname}}> (instance, "instance is a {{classname}}"); + // TODO uncomment below to test "IsInstanceOfType" {{classname}} + //Assert.IsInstanceOfType<{{classname}}> (instance, "variable 'instance' is a {{classname}}"); } {{#vars}} @@ -61,7 +64,7 @@ namespace {{packageName}}.Test [Test] public void {{name}}Test() { - // TODO: unit test for the property '{{name}}' + // TODO unit test for the property '{{name}}' } {{/vars}} diff --git a/modules/swagger-codegen/src/main/resources/csharp/mono_nunit_test.mustache b/modules/swagger-codegen/src/main/resources/csharp/mono_nunit_test.mustache new file mode 100644 index 00000000000..b4d1cd74ca6 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/csharp/mono_nunit_test.mustache @@ -0,0 +1,33 @@ +#!/usr/bin/env bash +# +# Generated by: https://github.com/swagger-api/swagger-codegen.git +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +wget -nc https://nuget.org/nuget.exe +mozroots --import --sync + +echo "[INFO] remove bin/Debug/SwaggerClientTest.dll" +rm src/IO.Swagger.Test/bin/Debug/{{{packageName}}}.Test.dll 2> /dev/null + +echo "[INFO] install NUnit runners via NuGet" +wget -nc https://nuget.org/nuget.exe +mozroots --import --sync +mono nuget.exe install src/{{{packageName}}}.Test/packages.config -o packages + +echo "[INFO] Install NUnit runners via NuGet" +mono nuget.exe install NUnit.Runners -Version 3.2.1 -OutputDirectory packages + +echo "[INFO] Build the solution and run the unit test" +xbuild {{{packageName}}}.sln && \ + mono ./packages/NUnit.ConsoleRunner.3.2.1/tools/nunit3-console.exe src/{{{packageName}}}.Test/bin/Debug/{{{packageName}}}.Test.dll diff --git a/modules/swagger-codegen/src/main/resources/csharp/packages.config.mustache b/modules/swagger-codegen/src/main/resources/csharp/packages.config.mustache index bd4428e687e..d9e5dea7d9f 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/packages.config.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/packages.config.mustache @@ -1,5 +1,5 @@ - + diff --git a/modules/swagger-codegen/src/main/resources/csharp/packages_test.config.mustache b/modules/swagger-codegen/src/main/resources/csharp/packages_test.config.mustache index 5464714bcef..95192a480bf 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/packages_test.config.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/packages_test.config.mustache @@ -1,6 +1,6 @@ - + - + diff --git a/modules/swagger-codegen/src/main/resources/csharp/travis.mustache b/modules/swagger-codegen/src/main/resources/csharp/travis.mustache new file mode 100644 index 00000000000..983f06b7156 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/csharp/travis.mustache @@ -0,0 +1,21 @@ +# +# Generated by: https://github.com/swagger-api/swagger-codegen.git +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +language: csharp +mono: + - latest +solution: {{{packageName}}}.sln +script: + - /bin/sh ./mono_nunit_test.sh 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 3e7e70a81fb..10cb6528d86 100644 --- a/modules/swagger-codegen/src/main/resources/objc/ApiClient-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/ApiClient-body.mustache @@ -265,6 +265,7 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response) self.requestSerializer = [AFHTTPRequestSerializer serializer]; } else { + self.requestSerializer = [AFHTTPRequestSerializer serializer]; NSAssert(NO, @"Unsupported request type %@", requestContentType); } @@ -280,7 +281,9 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response) queryParams = [self.sanitizer sanitizeForSerialization:queryParams]; headerParams = [self.sanitizer sanitizeForSerialization:headerParams]; formParams = [self.sanitizer sanitizeForSerialization:formParams]; - body = [self.sanitizer sanitizeForSerialization:body]; + if(![body isKindOfClass:[NSData class]]) { + body = [self.sanitizer sanitizeForSerialization:body]; + } // auth setting [self updateHeaderParams:&headerParams queryParams:&queryParams WithAuthSettings:authSettings]; diff --git a/modules/swagger-codegen/src/main/resources/objc/JSONRequestSerializer-body.mustache b/modules/swagger-codegen/src/main/resources/objc/JSONRequestSerializer-body.mustache index 78b1409b6b9..63513335d9a 100644 --- a/modules/swagger-codegen/src/main/resources/objc/JSONRequestSerializer-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/JSONRequestSerializer-body.mustache @@ -17,19 +17,21 @@ withParameters:(id)parameters error:(NSError *__autoreleasing *)error { + if (!parameters) { + return request; + } // If the body data which will be serialized isn't NSArray or NSDictionary // then put the data in the http request body directly. if ([parameters isKindOfClass:[NSArray class]] || [parameters isKindOfClass:[NSDictionary class]]) { return [super requestBySerializingRequest:request withParameters:parameters error:error]; - } else { - NSMutableURLRequest *mutableRequest = [request mutableCopy]; - - if (parameters) { - [mutableRequest setHTTPBody:[parameters dataUsingEncoding:self.stringEncoding]]; - } - - return mutableRequest; } + NSMutableURLRequest *mutableRequest = [request mutableCopy]; + if([parameters isKindOfClass:[NSData class]]) { + [mutableRequest setHTTPBody:parameters]; + } else { + [mutableRequest setHTTPBody:[parameters dataUsingEncoding:self.stringEncoding]]; + } + return mutableRequest; } @end diff --git a/modules/swagger-codegen/src/main/resources/perl/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/perl/ApiClient.mustache index 401a33eddad..4da9f8fb41e 100644 --- a/modules/swagger-codegen/src/main/resources/perl/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/perl/ApiClient.mustache @@ -1,3 +1,9 @@ +{{>partial_license}} +# +# NOTE: This class is auto generated by the swagger code generator program. +# Do not edit the class manually. +# Ref: https://github.com/swagger-api/swagger-codegen +# package {{moduleName}}::ApiClient; use strict; diff --git a/modules/swagger-codegen/src/main/resources/perl/ApiFactory.mustache b/modules/swagger-codegen/src/main/resources/perl/ApiFactory.mustache index ef5f322a014..cbda8660c20 100644 --- a/modules/swagger-codegen/src/main/resources/perl/ApiFactory.mustache +++ b/modules/swagger-codegen/src/main/resources/perl/ApiFactory.mustache @@ -1,3 +1,9 @@ +{{>partial_license}} +# +# NOTE: This class is auto generated by the swagger code generator program. +# Do not edit the class manually. +# Ref: https://github.com/swagger-api/swagger-codegen +# package {{moduleName}}::ApiFactory; use strict; diff --git a/modules/swagger-codegen/src/main/resources/perl/AutoDoc.mustache b/modules/swagger-codegen/src/main/resources/perl/AutoDoc.mustache index 3c10c2450fe..2d5eb5208cf 100644 --- a/modules/swagger-codegen/src/main/resources/perl/AutoDoc.mustache +++ b/modules/swagger-codegen/src/main/resources/perl/AutoDoc.mustache @@ -1,3 +1,9 @@ +{{>partial_license}} +# +# NOTE: This class is auto generated by the swagger code generator program. +# Do not edit the class manually. +# Ref: https://github.com/swagger-api/swagger-codegen +# package {{moduleName}}::Role::AutoDoc; use List::MoreUtils qw(uniq); diff --git a/modules/swagger-codegen/src/main/resources/perl/BaseObject.mustache b/modules/swagger-codegen/src/main/resources/perl/BaseObject.mustache index 9f262543acd..80ecda42a4d 100644 --- a/modules/swagger-codegen/src/main/resources/perl/BaseObject.mustache +++ b/modules/swagger-codegen/src/main/resources/perl/BaseObject.mustache @@ -1,3 +1,9 @@ +{{>partial_license}} +# +# NOTE: This class is auto generated by the swagger code generator program. +# Do not edit the class manually. +# Ref: https://github.com/swagger-api/swagger-codegen +# __PACKAGE__->mk_classdata('attribute_map' => {}); __PACKAGE__->mk_classdata('swagger_types' => {}); __PACKAGE__->mk_classdata('method_documentation' => {}); diff --git a/modules/swagger-codegen/src/main/resources/perl/Configuration.mustache b/modules/swagger-codegen/src/main/resources/perl/Configuration.mustache index e0ed9bf3295..500d816b178 100644 --- a/modules/swagger-codegen/src/main/resources/perl/Configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/perl/Configuration.mustache @@ -1,3 +1,9 @@ +{{>partial_license}} +# +# NOTE: This class is auto generated by the swagger code generator program. +# Do not edit the class manually. +# Ref: https://github.com/swagger-api/swagger-codegen +# package {{moduleName}}::Configuration; use strict; diff --git a/modules/swagger-codegen/src/main/resources/perl/Role.mustache b/modules/swagger-codegen/src/main/resources/perl/Role.mustache index fb343ccb890..0c8c1a0375b 100644 --- a/modules/swagger-codegen/src/main/resources/perl/Role.mustache +++ b/modules/swagger-codegen/src/main/resources/perl/Role.mustache @@ -1,3 +1,9 @@ +{{>partial_license}} +# +# NOTE: This class is auto generated by the swagger code generator program. +# Do not edit the class manually. +# Ref: https://github.com/swagger-api/swagger-codegen +# package {{moduleName}}::Role; use utf8; diff --git a/modules/swagger-codegen/src/main/resources/perl/api.mustache b/modules/swagger-codegen/src/main/resources/perl/api.mustache index d7ece2d1e65..3ac7f435908 100644 --- a/modules/swagger-codegen/src/main/resources/perl/api.mustache +++ b/modules/swagger-codegen/src/main/resources/perl/api.mustache @@ -1,21 +1,8 @@ -# -# Copyright 2016 SmartBear Software -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# +{{>partial_license}} # # NOTE: This class is auto generated by the swagger code generator program. # Do not edit the class manually. +# Ref: https://github.com/swagger-api/swagger-codegen # package {{moduleName}}::{{classname}}; diff --git a/modules/swagger-codegen/src/main/resources/perl/api_test.mustache b/modules/swagger-codegen/src/main/resources/perl/api_test.mustache index 98d1e9cce99..6ae0a8b286a 100644 --- a/modules/swagger-codegen/src/main/resources/perl/api_test.mustache +++ b/modules/swagger-codegen/src/main/resources/perl/api_test.mustache @@ -1,21 +1,8 @@ -# -# Copyright 2016 SmartBear Software -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# +{{>partial_license}} # # NOTE: This class is auto generated by Swagger Codegen -# Please update the test case below to test the API endpoints. +# Please update the test cases below to test the API endpoints. +# Ref: https://github.com/swagger-api/swagger-codegen # use Test::More tests => 1; #TODO update number of test cases use Test::Exception; diff --git a/modules/swagger-codegen/src/main/resources/perl/object.mustache b/modules/swagger-codegen/src/main/resources/perl/object.mustache index 126c6409c7f..bb19479c61d 100644 --- a/modules/swagger-codegen/src/main/resources/perl/object.mustache +++ b/modules/swagger-codegen/src/main/resources/perl/object.mustache @@ -1,3 +1,9 @@ +{{>partial_license}} +# +# NOTE: This class is auto generated by the swagger code generator program. +# Do not edit the class manually. +# Ref: https://github.com/swagger-api/swagger-codegen +# {{#models}} {{#model}} package {{moduleName}}::Object::{{classname}}; @@ -19,7 +25,8 @@ use base ("Class::Accessor", "Class::Data::Inheritable"); # #{{description}} # -#NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. +# NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. +# REF: https://github.com/swagger-api/swagger-codegen # {{>BaseObject}} diff --git a/modules/swagger-codegen/src/main/resources/perl/object_test.mustache b/modules/swagger-codegen/src/main/resources/perl/object_test.mustache index dd76f9ac2d7..08ea9200a0a 100644 --- a/modules/swagger-codegen/src/main/resources/perl/object_test.mustache +++ b/modules/swagger-codegen/src/main/resources/perl/object_test.mustache @@ -1,6 +1,9 @@ +{{>partial_license}} +# # NOTE: This class is auto generated by the Swagger Codegen -# Please update the test case below to test the model. - +# Please update the test cases below to test the model. +# Ref: https://github.com/swagger-api/swagger-codegen +# use Test::More tests => 2; use Test::Exception; diff --git a/modules/swagger-codegen/src/main/resources/python/api.mustache b/modules/swagger-codegen/src/main/resources/python/api.mustache index 43962c7f525..050278b2b5d 100644 --- a/modules/swagger-codegen/src/main/resources/python/api.mustache +++ b/modules/swagger-codegen/src/main/resources/python/api.mustache @@ -73,7 +73,6 @@ class {{classname}}(object): ) params[key] = val del params['kwargs'] - {{#allParams}} {{#required}} # verify the required parameter '{{paramName}}' is set @@ -85,28 +84,27 @@ class {{classname}}(object): {{#allParams}} {{#hasValidation}} {{#maxLength}} - if '{{paramName}}' in params and len(params['{{paramName}}']) > {{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}}: + 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}}: + 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}}: + 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}}): + 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') path_params = {} {{#pathParams}} diff --git a/modules/swagger-codegen/src/main/resources/python/api_client.mustache b/modules/swagger-codegen/src/main/resources/python/api_client.mustache index 07b9419e08f..2a4732f5afd 100644 --- a/modules/swagger-codegen/src/main/resources/python/api_client.mustache +++ b/modules/swagger-codegen/src/main/resources/python/api_client.mustache @@ -191,7 +191,7 @@ class ApiClient(object): :return: The serialized form of data. """ types = (str, int, float, bool, tuple) - if sys.version_info < (3,0): + if sys.version_info < (3, 0): types = types + (unicode,) if isinstance(obj, type(None)): return None diff --git a/modules/swagger-codegen/src/main/resources/python/api_test.mustache b/modules/swagger-codegen/src/main/resources/python/api_test.mustache index 4906d0e0371..f0f07f7189e 100644 --- a/modules/swagger-codegen/src/main/resources/python/api_test.mustache +++ b/modules/swagger-codegen/src/main/resources/python/api_test.mustache @@ -8,16 +8,16 @@ import os import sys import unittest -import swagger_client -from swagger_client.rest import ApiException -from swagger_client.apis.{{classVarName}} import {{classname}} +import {{packageName}} +from {{packageName}}.rest import ApiException +from {{packageName}}.apis.{{classVarName}} import {{classname}} class {{#operations}}Test{{classname}}(unittest.TestCase): """ {{classname}} unit test stubs """ def setUp(self): - self.api = swagger_client.apis.{{classVarName}}.{{classname}}() + self.api = {{packageName}}.apis.{{classVarName}}.{{classname}}() def tearDown(self): pass @@ -35,4 +35,4 @@ class {{#operations}}Test{{classname}}(unittest.TestCase): {{/operations}} if __name__ == '__main__': - unittest.main() \ No newline at end of file + unittest.main() diff --git a/modules/swagger-codegen/src/main/resources/python/configuration.mustache b/modules/swagger-codegen/src/main/resources/python/configuration.mustache index 9ea2ab4a7b5..3d2e8db228b 100644 --- a/modules/swagger-codegen/src/main/resources/python/configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/python/configuration.mustache @@ -17,6 +17,7 @@ import logging from six import iteritems + def singleton(cls, *args, **kw): instances = {} @@ -59,7 +60,6 @@ class Configuration(object): # access token for OAuth self.access_token = "" {{/isOAuth}}{{/authMethods}} - # Logging Settings self.logger = {} self.logger["package_logger"] = logging.getLogger("{{packageName}}") @@ -219,7 +219,7 @@ class Configuration(object): 'key': 'Authorization', 'value': self.get_basic_auth_token() }, -{{/isBasic}}{{#isOauth}} +{{/isBasic}}{{#isOAuth}} '{{name}}': { 'type': 'oauth2', @@ -227,7 +227,7 @@ class Configuration(object): 'key': 'Authorization', 'value': 'Bearer ' + self.access_token }, -{{/isOauth}}{{/authMethods}} +{{/isOAuth}}{{/authMethods}} } def to_debug_report(self): diff --git a/modules/swagger-codegen/src/main/resources/python/gitignore.mustache b/modules/swagger-codegen/src/main/resources/python/gitignore.mustache index 1dbc687de01..a655050c263 100644 --- a/modules/swagger-codegen/src/main/resources/python/gitignore.mustache +++ b/modules/swagger-codegen/src/main/resources/python/gitignore.mustache @@ -44,6 +44,8 @@ nosetests.xml coverage.xml *,cover .hypothesis/ +venv/ +.python-version # Translations *.mo diff --git a/modules/swagger-codegen/src/main/resources/python/model.mustache b/modules/swagger-codegen/src/main/resources/python/model.mustache index 781bb37e4e5..a08595db88a 100644 --- a/modules/swagger-codegen/src/main/resources/python/model.mustache +++ b/modules/swagger-codegen/src/main/resources/python/model.mustache @@ -14,7 +14,7 @@ class {{classname}}(object): NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ - def __init__(self): + def __init__(self{{#readWriteVars}}, {{name}}={{#defaultValue}}{{{defaultValue}}}{{/defaultValue}}{{^defaultValue}}None{{/defaultValue}}{{/readWriteVars}}): """ {{classname}} - a model defined in Swagger @@ -33,11 +33,14 @@ class {{classname}}(object): {{/hasMore}}{{/vars}} } -{{#vars}} +{{#readOnlyVars}} self._{{name}} = {{#defaultValue}}{{{defaultValue}}}{{/defaultValue}}{{^defaultValue}}None{{/defaultValue}} -{{/vars}} - -{{#vars}} +{{/readOnlyVars}} +{{#readWriteVars}} + self._{{name}} = {{name}} +{{/readWriteVars}} +{{#vars}}{{#-first}} +{{/-first}} @property def {{name}}(self): """ @@ -49,6 +52,7 @@ class {{classname}}(object): """ return self._{{name}} +{{^isReadOnly}} @{{name}}.setter def {{name}}(self, {{name}}): """ @@ -58,7 +62,8 @@ class {{classname}}(object): :param {{name}}: The {{name}} of this {{classname}}. :type: {{datatype}} """ - {{#isEnum}}allowed_values = [{{#allowableValues}}{{#values}}"{{{this}}}"{{^-last}}, {{/-last}}{{/values}}{{/allowableValues}}] +{{#isEnum}} + allowed_values = [{{#allowableValues}}{{#values}}"{{{this}}}"{{^-last}}, {{/-last}}{{/values}}{{/allowableValues}}] if {{name}} not in allowed_values: raise ValueError( "Invalid value for `{{name}}`, must be one of {0}" @@ -71,23 +76,23 @@ class {{classname}}(object): if not {{name}}: raise ValueError("Invalid value for `{{name}}`, must not be `None`") {{#maxLength}} - if len({{name}}) > {{maxLength}}: + if len({{name}}) > {{maxLength}}: raise ValueError("Invalid value for `{{name}}`, length must be less than `{{maxLength}}`") {{/maxLength}} {{#minLength}} - if len({{name}}) < {{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}}: + if {{name}} > {{maximum}}: raise ValueError("Invalid value for `{{name}}`, must be a value less than or equal to `{{maximum}}`") {{/maximum}} {{#minimum}} - if {{name}} < {{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}}): + 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}} @@ -95,6 +100,7 @@ class {{classname}}(object): self._{{name}} = {{name}} +{{/isReadOnly}} {{/vars}} def to_dict(self): """ @@ -145,6 +151,5 @@ class {{classname}}(object): Returns true if both objects are not equal """ return not self == other - {{/model}} -{{/models}} +{{/models}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/python/model_test.mustache b/modules/swagger-codegen/src/main/resources/python/model_test.mustache index ffd38a52b49..9e1b72b14a0 100644 --- a/modules/swagger-codegen/src/main/resources/python/model_test.mustache +++ b/modules/swagger-codegen/src/main/resources/python/model_test.mustache @@ -10,9 +10,9 @@ import unittest {{#models}} {{#model}} -import swagger_client -from swagger_client.rest import ApiException -from swagger_client.models.{{classFilename}} import {{classname}} +import {{packageName}} +from {{packageName}}.rest import ApiException +from {{packageName}}.models.{{classFilename}} import {{classname}} class Test{{classname}}(unittest.TestCase): @@ -28,10 +28,10 @@ class Test{{classname}}(unittest.TestCase): """ Test {{classname}} """ - model = swagger_client.models.{{classFilename}}.{{classname}}() + model = {{packageName}}.models.{{classFilename}}.{{classname}}() {{/model}} {{/models}} if __name__ == '__main__': - unittest.main() \ No newline at end of file + unittest.main() diff --git a/modules/swagger-codegen/src/main/resources/python/partial_header.mustache b/modules/swagger-codegen/src/main/resources/python/partial_header.mustache index ea97064963c..004460091dd 100644 --- a/modules/swagger-codegen/src/main/resources/python/partial_header.mustache +++ b/modules/swagger-codegen/src/main/resources/python/partial_header.mustache @@ -10,13 +10,13 @@ {{#version}}OpenAPI spec version: {{{version}}}{{/version}} {{#infoEmail}}Contact: {{{infoEmail}}}{{/infoEmail}} Generated by: https://github.com/swagger-api/swagger-codegen.git - + Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at - + http://www.apache.org/licenses/LICENSE-2.0 - + Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. diff --git a/modules/swagger-codegen/src/main/resources/python/setup.mustache b/modules/swagger-codegen/src/main/resources/python/setup.mustache index c825911f91a..f46265995fa 100644 --- a/modules/swagger-codegen/src/main/resources/python/setup.mustache +++ b/modules/swagger-codegen/src/main/resources/python/setup.mustache @@ -7,9 +7,7 @@ from setuptools import setup, find_packages NAME = "{{packageName}}" VERSION = "{{packageVersion}}" - {{#apiInfo}}{{#apis}}{{^hasMore}} - # To install the library, run the following # # python setup.py install @@ -33,5 +31,4 @@ setup( {{appDescription}} """ ) - -{{/hasMore}}{{/apis}}{{/apiInfo}} +{{/hasMore}}{{/apis}}{{/apiInfo}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/rails5/README.md b/modules/swagger-codegen/src/main/resources/rails5/README.md index c5cb90075a6..841b82ad656 100644 --- a/modules/swagger-codegen/src/main/resources/rails5/README.md +++ b/modules/swagger-codegen/src/main/resources/rails5/README.md @@ -14,7 +14,7 @@ bundle install This sample was generated with the [swagger-codegen](https://github.com/swagger-api/swagger-codegen) project. ``` -bin/rake db:create +bin/rake db:create db:migrate bin/rails s ``` diff --git a/modules/swagger-codegen/src/main/resources/rails5/migrate.mustache b/modules/swagger-codegen/src/main/resources/rails5/migrate.mustache new file mode 100644 index 00000000000..508b0ce7ede --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/migrate.mustache @@ -0,0 +1,15 @@ +=begin +{{> info}} +=end + +class InitTables < ActiveRecord::Migration + def change{{#models}}{{#model}} + create_table :{{classFilename}}, id: false do |t|{{#vars}}{{#isContainer}} + t.string :{{name}}{{/isContainer}}{{^isContainer}} + t.{{datatype}} :{{{name}}}{{/isContainer}}{{/vars}} + + t.timestamps + end +{{/model}}{{/models}} + end +end diff --git a/modules/swagger-codegen/src/main/resources/rails5/model.mustache b/modules/swagger-codegen/src/main/resources/rails5/model.mustache new file mode 100644 index 00000000000..edfe9fac56c --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/model.mustache @@ -0,0 +1,12 @@ +=begin +{{> info}} +=end + +{{#models}}{{#model}} +class {{classname}} < ApplicationRecord +{{#requiredVars}} + validate_presence_of :{{name}} +{{/requiredVars}}{{#vars}}{{#isListContainer}} + serialize :{{name}}, Array{{/isListContainer}}{{#isMapContainer}} + serialize :{{name}}, Hash{{/isMapContainer}}{{/vars}} +end{{/model}}{{/models}} diff --git a/modules/swagger-codegen/src/main/resources/scala/build.gradle.mustache b/modules/swagger-codegen/src/main/resources/scala/build.gradle.mustache new file mode 100644 index 00000000000..88faa3610b2 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/scala/build.gradle.mustache @@ -0,0 +1,120 @@ +apply plugin: 'idea' +apply plugin: 'eclipse' + +group = '{{groupId}}' +version = '{{artifactVersion}}' + +buildscript { + repositories { + jcenter() + } + dependencies { + classpath 'com.android.tools.build:gradle:1.5.+' + classpath 'com.github.dcendents:android-maven-gradle-plugin:1.3' + } +} + +repositories { + jcenter() +} + + +if(hasProperty('target') && target == 'android') { + + apply plugin: 'com.android.library' + apply plugin: 'com.github.dcendents.android-maven' + + android { + compileSdkVersion 23 + buildToolsVersion '23.0.2' + defaultConfig { + minSdkVersion 14 + targetSdkVersion 23 + } + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_7 + targetCompatibility JavaVersion.VERSION_1_7 + } + + // Rename the aar correctly + libraryVariants.all { variant -> + variant.outputs.each { output -> + def outputFile = output.outputFile + if (outputFile != null && outputFile.name.endsWith('.aar')) { + def fileName = "${project.name}-${variant.baseName}-${version}.aar" + output.outputFile = new File(outputFile.parent, fileName) + } + } + } + + dependencies { + provided 'javax.annotation:jsr250-api:1.0' + } + } + + afterEvaluate { + android.libraryVariants.all { variant -> + def task = project.tasks.create "jar${variant.name.capitalize()}", Jar + task.description = "Create jar artifact for ${variant.name}" + task.dependsOn variant.javaCompile + task.from variant.javaCompile.destinationDir + task.destinationDir = project.file("${project.buildDir}/outputs/jar") + task.archiveName = "${project.name}-${variant.baseName}-${version}.jar" + artifacts.add('archives', task); + } + } + + task sourcesJar(type: Jar) { + from android.sourceSets.main.java.srcDirs + classifier = 'sources' + } + + artifacts { + archives sourcesJar + } + +} else { + + apply plugin: 'scala' + apply plugin: 'java' + apply plugin: 'maven' + + sourceCompatibility = JavaVersion.VERSION_1_7 + targetCompatibility = JavaVersion.VERSION_1_7 + + install { + repositories.mavenInstaller { + pom.artifactId = '{{artifactId}}' + } + } + + task execute(type:JavaExec) { + main = System.getProperty('mainClass') + classpath = sourceSets.main.runtimeClasspath + } +} + +ext { + scala_version = "2.10.4" + joda_version = "1.2" + jodatime_version = "2.2" + jersey_version = "1.19" + swagger_core_version = "1.5.8" + jersey_async_version = "1.0.5" + jackson_version = "2.4.2" + junit_version = "4.8.1" + scala_test_version = "2.2.4" +} + +dependencies { + compile "com.fasterxml.jackson.module:jackson-module-scala_2.10:$jackson_version" + compile "com.sun.jersey:jersey-client:$jersey_version" + compile "com.sun.jersey.contribs:jersey-multipart:$jersey_version" + compile "org.jfarcand:jersey-ahc-client:$jersey_async_version" + compile "org.scala-lang:scala-library:$scala_version" + compile "io.swagger:swagger-core:$swagger_core_version" + testCompile "org.scalatest:scalatest_2.10:$scala_test_version" + testCompile "junit:junit:$junit_version" + compile "joda-time:joda-time:$jodatime_version" + compile "org.joda:joda-convert:$joda_version" +} diff --git a/modules/swagger-codegen/src/main/resources/scala/gradle-wrapper.jar b/modules/swagger-codegen/src/main/resources/scala/gradle-wrapper.jar new file mode 100644 index 00000000000..2c6137b8789 Binary files /dev/null and b/modules/swagger-codegen/src/main/resources/scala/gradle-wrapper.jar differ diff --git a/modules/swagger-codegen/src/main/resources/scala/gradle-wrapper.properties.mustache b/modules/swagger-codegen/src/main/resources/scala/gradle-wrapper.properties.mustache new file mode 100644 index 00000000000..b7a36473955 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/scala/gradle-wrapper.properties.mustache @@ -0,0 +1,6 @@ +#Tue May 17 23:08:05 CST 2016 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-2.6-bin.zip diff --git a/modules/swagger-codegen/src/main/resources/scala/gradle.properties.mustache b/modules/swagger-codegen/src/main/resources/scala/gradle.properties.mustache new file mode 100644 index 00000000000..05644f0754a --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/scala/gradle.properties.mustache @@ -0,0 +1,2 @@ +# Uncomment to build for Android +#target = android \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/scala/gradlew.bat.mustache b/modules/swagger-codegen/src/main/resources/scala/gradlew.bat.mustache new file mode 100644 index 00000000000..72d362dafd8 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/scala/gradlew.bat.mustache @@ -0,0 +1,90 @@ +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args +if "%@eval[2+2]" == "4" goto 4NT_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* +goto execute + +:4NT_args +@rem Get arguments from the 4NT Shell from JP Software +set CMD_LINE_ARGS=%$ + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/modules/swagger-codegen/src/main/resources/scala/gradlew.mustache b/modules/swagger-codegen/src/main/resources/scala/gradlew.mustache new file mode 100755 index 00000000000..9d82f789151 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/scala/gradlew.mustache @@ -0,0 +1,160 @@ +#!/usr/bin/env bash + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS="" + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn ( ) { + echo "$*" +} + +die ( ) { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; +esac + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin, switch paths to Windows format before running java +if $cygwin ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules +function splitJvmOpts() { + JVM_OPTS=("$@") +} +eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS +JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" + +exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" diff --git a/modules/swagger-codegen/src/main/resources/scala/settings.gradle.mustache b/modules/swagger-codegen/src/main/resources/scala/settings.gradle.mustache new file mode 100644 index 00000000000..b8fd6c4c41f --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/scala/settings.gradle.mustache @@ -0,0 +1 @@ +rootProject.name = "{{artifactId}}" \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/swift/APIHelper.mustache b/modules/swagger-codegen/src/main/resources/swift/APIHelper.mustache index 7041709f365..23e727b6b54 100644 --- a/modules/swagger-codegen/src/main/resources/swift/APIHelper.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/APIHelper.mustache @@ -19,18 +19,19 @@ class APIHelper { return destination } - static func convertBoolToString(source: [String: AnyObject]?) -> [String:AnyObject] { + static func convertBoolToString(source: [String: AnyObject]?) -> [String:AnyObject]? { + guard let source = source else { + return nil + } var destination = [String:AnyObject]() let theTrue = NSNumber(bool: true) let theFalse = NSNumber(bool: false) - if (source != nil) { - for (key, value) in source! { - switch value { - case let x where x === theTrue || x === theFalse: - destination[key] = "\(value as! Bool)" - default: - destination[key] = value - } + for (key, value) in source { + switch value { + case let x where x === theTrue || x === theFalse: + destination[key] = "\(value as! Bool)" + default: + destination[key] = value } } return destination diff --git a/modules/swagger-codegen/src/main/resources/swift/Models.mustache b/modules/swagger-codegen/src/main/resources/swift/Models.mustache index 49798250e72..17b9c2cd276 100644 --- a/modules/swagger-codegen/src/main/resources/swift/Models.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/Models.mustache @@ -34,17 +34,17 @@ public class Response { private var once = dispatch_once_t() class Decoders { static private var decoders = Dictionary AnyObject)>() - + static func addDecoder(clazz clazz: T.Type, decoder: ((AnyObject) -> T)) { let key = "\(T.self)" decoders[key] = { decoder($0) as! AnyObject } } - + static func decode(clazz clazz: [T].Type, source: AnyObject) -> [T] { let array = source as! [AnyObject] return array.map { Decoders.decode(clazz: T.self, source: $0) } } - + static func decode(clazz clazz: [Key:T].Type, source: AnyObject) -> [Key:T] { let sourceDictionary = source as! [Key: AnyObject] var dictionary = [Key:T]() @@ -53,7 +53,7 @@ class Decoders { } return dictionary } - + static func decode(clazz clazz: T.Type, source: AnyObject) -> T { initialize() if T.self is Int32.Type && source is NSNumber { @@ -65,7 +65,7 @@ class Decoders { if source is T { return source as! T } - + let key = "\(T.self)" if let decoder = decoders[key] { return decoder(source) as! T @@ -100,14 +100,15 @@ class Decoders { Decoders.decode(clazz: clazz, source: someSource) } } - + static private func initialize() { dispatch_once(&once) { let formatters = [ "yyyy-MM-dd", "yyyy-MM-dd'T'HH:mm:ssZZZZZ", "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ", - "yyyy-MM-dd'T'HH:mm:ss'Z'" + "yyyy-MM-dd'T'HH:mm:ss'Z'", + "yyyy-MM-dd'T'HH:mm:ss.SSS" ].map { (format: String) -> NSDateFormatter in let formatter = NSDateFormatter() formatter.dateFormat = format @@ -121,7 +122,7 @@ class Decoders { return date } } - + } if let sourceInt = source as? Int { // treat as a java date diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/ignore/CodegenIgnoreProcessorTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/ignore/CodegenIgnoreProcessorTest.java index 784fcfe8480..ef30ca48331 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/ignore/CodegenIgnoreProcessorTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/ignore/CodegenIgnoreProcessorTest.java @@ -1,6 +1,7 @@ package io.swagger.codegen.ignore; import org.apache.commons.io.FileUtils; +import org.apache.commons.lang3.SystemUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.annotations.*; @@ -17,6 +18,7 @@ public class CodegenIgnoreProcessorTest { private static final Logger LOGGER = LoggerFactory.getLogger(CodegenIgnoreProcessorTest.class); private Boolean allowed; + private Boolean skip = false; private final String filename; private final String ignoreDefinition; private final String description; @@ -35,6 +37,11 @@ public class CodegenIgnoreProcessorTest { return this; } + CodegenIgnoreProcessorTest skipOnCondition(Boolean condition) { + this.skip = Boolean.TRUE.equals(condition); + return this; + } + CodegenIgnoreProcessorTest ignored() { this.allowed = false; return this; @@ -73,6 +80,10 @@ public class CodegenIgnoreProcessorTest { @Test public void evaluate() { + if(this.skip) { + return; + } + // Arrange try { // Lazily setup files to avoid conflicts and creation when these tests may not even run. @@ -97,7 +108,7 @@ public class CodegenIgnoreProcessorTest { // Matching filenames new CodegenIgnoreProcessorTest("build.sh", "build.sh", "A file when matching should ignore.").ignored(), new CodegenIgnoreProcessorTest("src/build.sh", "**/build.sh", "A file when matching nested files should ignore.").ignored(), - new CodegenIgnoreProcessorTest("Build.sh", "build.sh", "A file when non-matching should allow.").allowed(), + new CodegenIgnoreProcessorTest("Build.sh", "build.sh", "A file when non-matching should allow.").allowed().skipOnCondition(SystemUtils.IS_OS_WINDOWS), new CodegenIgnoreProcessorTest("build.sh", "/build.sh", "A rooted file when matching should ignore.").ignored(), new CodegenIgnoreProcessorTest("nested/build.sh", "/build.sh", "A rooted file definition when non-matching should allow.").allowed(), new CodegenIgnoreProcessorTest("src/IO.Swagger.Test/Model/AnimalFarmTests.cs", "src/IO.Swagger.Test/Model/AnimalFarmTests.cs", "A file when matching exactly should ignore.").ignored(), 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 84fb38d1dd3..f3948b00781 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 @@ -1,21 +1,9 @@ package io.swagger.codegen.objc; -import io.swagger.codegen.CodegenModel; -import io.swagger.codegen.CodegenOperation; -import io.swagger.codegen.CodegenProperty; -import io.swagger.codegen.DefaultCodegen; +import io.swagger.codegen.*; import io.swagger.codegen.languages.ObjcClientCodegen; -import io.swagger.models.ArrayModel; -import io.swagger.models.Model; -import io.swagger.models.ModelImpl; -import io.swagger.models.Path; -import io.swagger.models.Swagger; -import io.swagger.models.properties.ArrayProperty; -import io.swagger.models.properties.DateTimeProperty; -import io.swagger.models.properties.LongProperty; -import io.swagger.models.properties.MapProperty; -import io.swagger.models.properties.RefProperty; -import io.swagger.models.properties.StringProperty; +import io.swagger.models.*; +import io.swagger.models.properties.*; import io.swagger.parser.SwaggerParser; import com.google.common.collect.Sets; @@ -279,6 +267,20 @@ public class ObjcModelTest { Assert.assertEquals(Sets.intersection(cm.imports, Sets.newHashSet("SWGChildren")).size(), 1); } + @Test(description = "test binary data") + public void binaryDataModelTest() { + final Swagger model = new SwaggerParser().read("src/test/resources/2_0/binaryDataTest.json"); + final DefaultCodegen codegen = new ObjcClientCodegen(); + final String path = "/tests/binaryResponse"; + final Operation p = model.getPaths().get(path).getPost(); + final CodegenOperation op = codegen.fromOperation(path, "post", p, model.getDefinitions()); + + Assert.assertEquals(op.returnType, "NSData*"); + Assert.assertEquals(op.bodyParam.dataType, "NSData*"); + Assert.assertTrue(op.bodyParam.isBinary); + Assert.assertTrue(op.responses.get(0).isBinary); + } + @Test(description = "create proper imports per #316") public void issue316Test() { final Swagger model = new SwaggerParser().read("src/test/resources/2_0/postBodyTest.json"); 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 index af70fc1834a..c4b1281c1dc 100644 --- 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 @@ -10,6 +10,8 @@ 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 + public static final String INTERFACE_ONLY = "true"; + public static final String SINGLE_CONTENT_TYPES = "true"; @Override public String getLanguage() { @@ -22,6 +24,9 @@ public class SpringBootServerOptionsProvider extends JavaOptionsProvider { options.put(SpringBootServerCodegen.CONFIG_PACKAGE, CONFIG_PACKAGE_VALUE); options.put(SpringBootServerCodegen.BASE_PACKAGE, BASE_PACKAGE_VALUE); options.put(CodegenConstants.LIBRARY, LIBRARY_VALUE); + options.put(SpringBootServerCodegen.INTERFACE_ONLY, INTERFACE_ONLY); + options.put(SpringBootServerCodegen.SINGLE_CONTENT_TYPES, SINGLE_CONTENT_TYPES); + return options; } 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 index 7228f119711..c60ac3a582d 100644 --- 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 @@ -54,6 +54,10 @@ public class SpringBootServerOptionsTest extends JavaClientOptionsTest { times = 1; clientCodegen.setBasePackage(SpringBootServerOptionsProvider.BASE_PACKAGE_VALUE); times = 1; + clientCodegen.setInterfaceOnly(Boolean.valueOf(SpringBootServerOptionsProvider.INTERFACE_ONLY)); + times = 1; + clientCodegen.setSingleContentTypes(Boolean.valueOf(SpringBootServerOptionsProvider.SINGLE_CONTENT_TYPES)); + times = 1; }}; } diff --git a/pom.xml b/pom.xml index af8c8544e81..40ebc9bb85f 100644 --- a/pom.xml +++ b/pom.xml @@ -522,6 +522,18 @@ samples/client/petstore/typescript-node/npm + + python-client + + + env + java + + + + samples/client/petstore/python + + ruby-client @@ -557,6 +569,7 @@ + samples/client/petstore/python samples/client/petstore/ruby samples/client/petstore/typescript-fetch/tests/default samples/client/petstore/typescript-fetch/builds/default diff --git a/samples/client/petstore/csharp/SwaggerClient/.swagger-codegen-ignore b/samples/client/petstore/csharp/SwaggerClient/.swagger-codegen-ignore index 19d3377182e..61ed08d3455 100644 --- a/samples/client/petstore/csharp/SwaggerClient/.swagger-codegen-ignore +++ b/samples/client/petstore/csharp/SwaggerClient/.swagger-codegen-ignore @@ -21,3 +21,4 @@ #docs/*.md # Then explicitly reverse the ignore rule for a single file: #!docs/README.md +src/IO.Swagger.Test/IO.Swagger.Test.csproj diff --git a/samples/client/petstore/csharp/SwaggerClient/.travis.yml b/samples/client/petstore/csharp/SwaggerClient/.travis.yml new file mode 100644 index 00000000000..4096e0b50d4 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClient/.travis.yml @@ -0,0 +1,21 @@ +# +# Generated by: https://github.com/swagger-api/swagger-codegen.git +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +language: csharp +mono: + - latest +solution: IO.Swagger.sln +script: + - /bin/sh ./mono_nunit_test.sh diff --git a/samples/client/petstore/csharp/SwaggerClient/IO.Swagger.sln b/samples/client/petstore/csharp/SwaggerClient/IO.Swagger.sln index c0a42faae52..143ffeb1629 100644 --- a/samples/client/petstore/csharp/SwaggerClient/IO.Swagger.sln +++ b/samples/client/petstore/csharp/SwaggerClient/IO.Swagger.sln @@ -2,7 +2,7 @@ Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 2012 VisualStudioVersion = 12.0.0.0 MinimumVisualStudioVersion = 10.0.0.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IO.Swagger", "src\IO.Swagger\IO.Swagger.csproj", "{C81D6286-7BA5-4920-8591-F59169CCE4A4}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IO.Swagger", "src\IO.Swagger\IO.Swagger.csproj", "{BF42B49D-37A0-49C4-A405-24CD946ADAA7}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IO.Swagger.Test", "src\IO.Swagger.Test\IO.Swagger.Test.csproj", "{19F1DEBC-DE5E-4517-8062-F000CD499087}" EndProject @@ -12,10 +12,10 @@ Debug|Any CPU = Debug|Any CPU Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution -{C81D6286-7BA5-4920-8591-F59169CCE4A4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU -{C81D6286-7BA5-4920-8591-F59169CCE4A4}.Debug|Any CPU.Build.0 = Debug|Any CPU -{C81D6286-7BA5-4920-8591-F59169CCE4A4}.Release|Any CPU.ActiveCfg = Release|Any CPU -{C81D6286-7BA5-4920-8591-F59169CCE4A4}.Release|Any CPU.Build.0 = Release|Any CPU +{BF42B49D-37A0-49C4-A405-24CD946ADAA7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{BF42B49D-37A0-49C4-A405-24CD946ADAA7}.Debug|Any CPU.Build.0 = Debug|Any CPU +{BF42B49D-37A0-49C4-A405-24CD946ADAA7}.Release|Any CPU.ActiveCfg = Release|Any CPU +{BF42B49D-37A0-49C4-A405-24CD946ADAA7}.Release|Any CPU.Build.0 = Release|Any CPU {19F1DEBC-DE5E-4517-8062-F000CD499087}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {19F1DEBC-DE5E-4517-8062-F000CD499087}.Debug|Any CPU.Build.0 = Debug|Any CPU {19F1DEBC-DE5E-4517-8062-F000CD499087}.Release|Any CPU.ActiveCfg = Release|Any CPU diff --git a/samples/client/petstore/csharp/SwaggerClient/README.md b/samples/client/petstore/csharp/SwaggerClient/README.md index d9dcb59b2da..c5a53af127d 100644 --- a/samples/client/petstore/csharp/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-05-29T17:27:36.037+08:00 +- Build date: 2016-06-12T16:29:47.553+08:00 - Build package: class io.swagger.codegen.languages.CSharpClientCodegen ## Frameworks supported @@ -54,7 +54,7 @@ namespace Example { var apiInstance = new FakeApi(); - var number = 3.4; // double? | None + var number = 3.4; // decimal? | None var _double = 1.2; // double? | None var _string = _string_example; // string | None var _byte = B; // byte[] | None diff --git a/samples/client/petstore/csharp/SwaggerClient/build.bat b/samples/client/petstore/csharp/SwaggerClient/build.bat index 80a13e48231..ae94b120d7b 100644 --- a/samples/client/petstore/csharp/SwaggerClient/build.bat +++ b/samples/client/petstore/csharp/SwaggerClient/build.bat @@ -1,3 +1,17 @@ +:: Generated by: https://github.com/swagger-api/swagger-codegen.git +:: +:: Licensed under the Apache License, Version 2.0 (the "License"); +:: you may not use this file except in compliance with the License. +:: You may obtain a copy of the License at +:: +:: http://www.apache.org/licenses/LICENSE-2.0 +:: +:: Unless required by applicable law or agreed to in writing, software +:: distributed under the License is distributed on an "AS IS" BASIS, +:: WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +:: See the License for the specific language governing permissions and +:: limitations under the License. + @echo off SET CSCPATH=%SYSTEMROOT%\Microsoft.NET\Framework\v4.0.30319 @@ -8,7 +22,7 @@ if not exist ".\nuget.exe" powershell -Command "(new-object System.Net.WebClient if not exist ".\bin" mkdir bin -copy packages\Newtonsoft.Json.8.0.2\lib\net45\Newtonsoft.Json.dll bin\Newtonsoft.Json.dll +copy packages\Newtonsoft.Json.8.0.3\lib\net45\Newtonsoft.Json.dll bin\Newtonsoft.Json.dll copy packages\RestSharp.105.1.0\lib\net45\RestSharp.dll bin\RestSharp.dll %CSCPATH%\csc /reference:bin\Newtonsoft.Json.dll;bin\RestSharp.dll /target:library /out:bin\IO.Swagger.dll /recurse:src\IO.Swagger\*.cs /doc:bin\IO.Swagger.xml diff --git a/samples/client/petstore/csharp/SwaggerClient/build.sh b/samples/client/petstore/csharp/SwaggerClient/build.sh index 159673fd60c..25228f3cc36 100644 --- a/samples/client/petstore/csharp/SwaggerClient/build.sh +++ b/samples/client/petstore/csharp/SwaggerClient/build.sh @@ -1,15 +1,35 @@ #!/usr/bin/env bash +# +# Generated by: https://github.com/swagger-api/swagger-codegen.git +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + frameworkVersion=net45 netfx=${frameworkVersion#net} +echo "[INFO] Target framework: ${frameworkVersion}" + +echo "[INFO] Download nuget and packages" wget -nc https://nuget.org/nuget.exe; mozroots --import --sync mono nuget.exe install src/IO.Swagger/packages.config -o packages; -mkdir -p bin; -cp packages/Newtonsoft.Json.8.0.2/lib/net45/Newtonsoft.Json.dll bin/Newtonsoft.Json.dll; +echo "[INFO] Copy DLLs to the 'bin' folder" +mkdir -p bin; +cp packages/Newtonsoft.Json.8.0.3/lib/net45/Newtonsoft.Json.dll bin/Newtonsoft.Json.dll; cp packages/RestSharp.105.1.0/lib/net45/RestSharp.dll bin/RestSharp.dll; +echo "[INFO] Run 'mcs' to build bin/IO.Swagger.dll" mcs -sdk:${netfx} -r:bin/Newtonsoft.Json.dll,\ bin/RestSharp.dll,\ System.Runtime.Serialization.dll \ @@ -18,3 +38,11 @@ System.Runtime.Serialization.dll \ -recurse:'src/IO.Swagger/*.cs' \ -doc:bin/IO.Swagger.xml \ -platform:anycpu + +if [ $? -ne 0 ] +then + echo "[ERROR] Compilation failed with exit code $?" + exit 1 +else + echo "[INFO] bin/IO.Swagger.dll was created successfully" +fi diff --git a/samples/client/petstore/csharp/SwaggerClient/docs/FakeApi.md b/samples/client/petstore/csharp/SwaggerClient/docs/FakeApi.md index e4325274999..cc24d4dfa07 100644 --- a/samples/client/petstore/csharp/SwaggerClient/docs/FakeApi.md +++ b/samples/client/petstore/csharp/SwaggerClient/docs/FakeApi.md @@ -8,7 +8,7 @@ Method | HTTP request | Description # **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) +> void TestEndpointParameters (decimal? number, double? _double, string _string, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, byte[] binary = null, DateTime? date = null, DateTime? dateTime = null, string password = null) Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 @@ -30,7 +30,7 @@ namespace Example { var apiInstance = new FakeApi(); - var number = 3.4; // double? | None + var number = 3.4; // decimal? | None var _double = 1.2; // double? | None var _string = _string_example; // string | None var _byte = B; // byte[] | None @@ -61,7 +61,7 @@ namespace Example Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **number** | **double?**| None | + **number** | **decimal?**| None | **_double** | **double?**| None | **_string** | **string**| None | **_byte** | **byte[]**| None | diff --git a/samples/client/petstore/csharp/SwaggerClient/docs/FormatTest.md b/samples/client/petstore/csharp/SwaggerClient/docs/FormatTest.md index 7ddfad04d05..1d366bd7cab 100644 --- a/samples/client/petstore/csharp/SwaggerClient/docs/FormatTest.md +++ b/samples/client/petstore/csharp/SwaggerClient/docs/FormatTest.md @@ -6,7 +6,7 @@ Name | Type | Description | Notes **Integer** | **int?** | | [optional] **Int32** | **int?** | | [optional] **Int64** | **long?** | | [optional] -**Number** | **double?** | | +**Number** | **decimal?** | | **_Float** | **float?** | | [optional] **_Double** | **double?** | | [optional] **_String** | **string** | | [optional] diff --git a/samples/client/petstore/csharp/SwaggerClient/mono_nunit_test.sh b/samples/client/petstore/csharp/SwaggerClient/mono_nunit_test.sh new file mode 100644 index 00000000000..e7032942787 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClient/mono_nunit_test.sh @@ -0,0 +1,33 @@ +#!/usr/bin/env bash +# +# Generated by: https://github.com/swagger-api/swagger-codegen.git +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +wget -nc https://nuget.org/nuget.exe +mozroots --import --sync + +echo "[INFO] remove bin/Debug/SwaggerClientTest.dll" +rm src/IO.Swagger.Test/bin/Debug/IO.Swagger.Test.dll 2> /dev/null + +echo "[INFO] install NUnit runners via NuGet" +wget -nc https://nuget.org/nuget.exe +mozroots --import --sync +mono nuget.exe install src/IO.Swagger.Test/packages.config -o packages + +echo "[INFO] Install NUnit runners via NuGet" +mono nuget.exe install NUnit.Runners -Version 3.2.1 -OutputDirectory packages + +echo "[INFO] Build the solution and run the unit test" +xbuild IO.Swagger.sln && \ + mono ./packages/NUnit.ConsoleRunner.3.2.1/tools/nunit3-console.exe src/IO.Swagger.Test/bin/Debug/IO.Swagger.Test.dll 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 index 71a4063af4e..7f537b16558 100644 --- 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 @@ -48,7 +48,7 @@ namespace IO.Swagger.Test [Test] public void InstanceTest() { - Assert.IsInstanceOf (instance, "instance is a FakeApi"); + Assert.IsInstanceOfType(typeof(FakeApi), instance, "instance is a FakeApi"); } diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Api/PetApiTests.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Api/PetApiTests.cs index b9dae814b68..0d517af68b5 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Api/PetApiTests.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Api/PetApiTests.cs @@ -97,7 +97,7 @@ namespace IO.Swagger.Test [Test] public void InstanceTest() { - Assert.IsInstanceOf (instance, "instance is a PetApi"); + Assert.IsInstanceOfType(typeof(PetApi), instance, "instance is a PetApi"); } @@ -134,7 +134,7 @@ namespace IO.Swagger.Test List listPet = petApi.FindPetsByTags (tagsList); foreach (Pet pet in listPet) // Loop through List with foreach. { - Assert.IsInstanceOf (pet, "Response is a Pet"); + Assert.IsInstanceOfType(typeof(Pet), pet, "Response is a Pet"); Assert.AreEqual ("csharp sample tag name1", pet.Tags[0]); } } @@ -147,7 +147,7 @@ namespace IO.Swagger.Test { List tags = new List(new String[] {"pet"}); var response = instance.FindPetsByTags(tags); - Assert.IsInstanceOf> (response, "response is List"); + Assert.IsInstanceOfType(typeof(List), response, "response is List"); } /// @@ -161,19 +161,19 @@ namespace IO.Swagger.Test PetApi petApi = new PetApi (c1); Pet response = petApi.GetPetById (petId); - Assert.IsInstanceOf (response, "Response is a Pet"); + Assert.IsInstanceOfType(typeof(Pet), response, "Response is a Pet"); Assert.AreEqual ("Csharp test", response.Name); Assert.AreEqual (Pet.StatusEnum.Available, response.Status); - Assert.IsInstanceOf> (response.Tags, "Response.Tags is a Array"); + Assert.IsInstanceOfType(typeof(List), response.Tags, "Response.Tags is a Array"); Assert.AreEqual (petId, response.Tags [0].Id); Assert.AreEqual ("csharp sample tag name1", response.Tags [0].Name); - Assert.IsInstanceOf> (response.PhotoUrls, "Response.PhotoUrls is a Array"); + Assert.IsInstanceOfType(typeof(List), response.PhotoUrls, "Response.PhotoUrls is a Array"); Assert.AreEqual ("sample photoUrls", response.PhotoUrls [0]); - Assert.IsInstanceOf (response.Category, "Response.Category is a Category"); + Assert.IsInstanceOfType(typeof(Category), response.Category, "Response.Category is a Category"); Assert.AreEqual (56, response.Category.Id); Assert.AreEqual ("sample category name2", response.Category.Name); } @@ -187,19 +187,19 @@ namespace IO.Swagger.Test PetApi petApi = new PetApi (); var task = petApi.GetPetByIdAsync (petId); Pet response = task.Result; - Assert.IsInstanceOf (response, "Response is a Pet"); + Assert.IsInstanceOfType(typeof(Pet), response, "Response is a Pet"); Assert.AreEqual ("Csharp test", response.Name); Assert.AreEqual (Pet.StatusEnum.Available, response.Status); - Assert.IsInstanceOf> (response.Tags, "Response.Tags is a Array"); + Assert.IsInstanceOfType(typeof(List), response.Tags, "Response.Tags is a Array"); Assert.AreEqual (petId, response.Tags [0].Id); Assert.AreEqual ("csharp sample tag name1", response.Tags [0].Name); - Assert.IsInstanceOf> (response.PhotoUrls, "Response.PhotoUrls is a Array"); + Assert.IsInstanceOfType(typeof(List), response.PhotoUrls, "Response.PhotoUrls is a Array"); Assert.AreEqual ("sample photoUrls", response.PhotoUrls [0]); - Assert.IsInstanceOf (response.Category, "Response.Category is a Category"); + Assert.IsInstanceOfType(typeof(Category), response.Category, "Response.Category is a Category"); Assert.AreEqual (56, response.Category.Id); Assert.AreEqual ("sample category name2", response.Category.Name); @@ -219,19 +219,19 @@ namespace IO.Swagger.Test Assert.AreEqual (task.Result.Headers["Content-Type"], "application/json"); Pet response = task.Result.Data; - Assert.IsInstanceOf (response, "Response is a Pet"); + Assert.IsInstanceOfType(typeof(Pet), response, "Response is a Pet"); Assert.AreEqual ("Csharp test", response.Name); Assert.AreEqual (Pet.StatusEnum.Available, response.Status); - Assert.IsInstanceOf> (response.Tags, "Response.Tags is a Array"); + Assert.IsInstanceOfType(typeof(List), response.Tags, "Response.Tags is a Array"); Assert.AreEqual (petId, response.Tags [0].Id); Assert.AreEqual ("csharp sample tag name1", response.Tags [0].Name); - Assert.IsInstanceOf> (response.PhotoUrls, "Response.PhotoUrls is a Array"); + Assert.IsInstanceOfType(typeof(List), response.PhotoUrls, "Response.PhotoUrls is a Array"); Assert.AreEqual ("sample photoUrls", response.PhotoUrls [0]); - Assert.IsInstanceOf (response.Category, "Response.Category is a Category"); + Assert.IsInstanceOfType(typeof(Category), response.Category, "Response.Category is a Category"); Assert.AreEqual (56, response.Category.Id); Assert.AreEqual ("sample category name2", response.Category.Name); @@ -258,9 +258,9 @@ namespace IO.Swagger.Test petApi.UpdatePetWithForm (petId, "new form name", "pending"); Pet response = petApi.GetPetById (petId); - Assert.IsInstanceOf (response, "Response is a Pet"); - Assert.IsInstanceOf (response.Category, "Response.Category is a Category"); - Assert.IsInstanceOf> (response.Tags, "Response.Tags is a Array"); + Assert.IsInstanceOfType(typeof(Pet), response, "Response is a Pet"); + Assert.IsInstanceOfType(typeof(Category), response.Category, "Response.Category is a Category"); + Assert.IsInstanceOfType(typeof(List), response.Tags, "Response.Tags is a Array"); Assert.AreEqual ("new form name", response.Name); Assert.AreEqual (Pet.StatusEnum.Pending, response.Status); diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Api/StoreApiTests.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Api/StoreApiTests.cs index e1237b51c0b..2ca3b35f30d 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Api/StoreApiTests.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Api/StoreApiTests.cs @@ -50,7 +50,7 @@ namespace IO.Swagger.Test [Test] public void InstanceTest() { - Assert.IsInstanceOf (instance, "instance is a StoreApi"); + Assert.IsInstanceOfType(typeof(StoreApi), instance, "instance is a StoreApi"); } @@ -84,7 +84,7 @@ namespace IO.Swagger.Test foreach(KeyValuePair entry in response) { - Assert.IsInstanceOf (typeof(int?), entry.Value); + Assert.IsInstanceOfType(typeof(int?), entry.Value); } } diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Api/UserApiTests.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Api/UserApiTests.cs index 77f6bd5ec99..31edf492923 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Api/UserApiTests.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Api/UserApiTests.cs @@ -49,7 +49,7 @@ namespace IO.Swagger.Test [Test] public void InstanceTest() { - Assert.IsInstanceOf (instance, "instance is a UserApi"); + Assert.IsInstanceOfType(typeof(UserApi), instance, "instance is a UserApi"); } diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/IO.Swagger.Test.csproj b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/IO.Swagger.Test.csproj index 4e4b161e255..5660f132a37 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/IO.Swagger.Test.csproj +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/IO.Swagger.Test.csproj @@ -20,7 +20,7 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> - + Debug AnyCPU @@ -59,36 +59,38 @@ limitations under the License. - $(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\Newtonsoft.Json.8.0.3\lib\net45\Newtonsoft.Json.dll + ..\packages\Newtonsoft.Json.8.0.3\lib\net45\Newtonsoft.Json.dll + ..\..\packages\Newtonsoft.Json.8.0.3\lib\net45\Newtonsoft.Json.dll + ..\..\vendor\Newtonsoft.Json.8.0.3\lib\net45\Newtonsoft.Json.dll - $(SolutionDir)\packages\RestSharp.105.1.0\lib\net45\RestSharp.dll - ..\packages\RestSharp.105.1.0\lib\net45\RestSharp.dll - ..\..\packages\RestSharp.105.1.0\lib\net45\RestSharp.dll - ..\..\vendor\RestSharp.105.1.0\lib\net45\RestSharp.dll + $(SolutionDir)\packages\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 + $(SolutionDir)\packages\NUnit.3.2.1\lib\nunit.framework.dll + ..\packages\NUnit.3.2.1\lib\nunit.framework.dll + ..\..\packages\NUnit.3.2.1\lib\nunit.framework.dll + ..\..\vendor\NUnit.3.2.1\lib\nunit.framework.dll - + - + - - {C81D6286-7BA5-4920-8591-F59169CCE4A4} - IO.Swagger - + + {85AE8212-9819-4224-A9E5-B93419EC927B} + IO.Swagger + + + + - diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/AdditionalPropertiesClassTests.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/AdditionalPropertiesClassTests.cs index fca6d20d0dc..b4680801e4c 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/AdditionalPropertiesClassTests.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/AdditionalPropertiesClassTests.cs @@ -47,7 +47,7 @@ namespace IO.Swagger.Test [Test] public void AdditionalPropertiesClassInstanceTest() { - Assert.IsInstanceOf (instance, "instance is a AdditionalPropertiesClass"); + Assert.IsInstanceOfType(typeof(AdditionalPropertiesClass), instance, "instance is a AdditionalPropertiesClass"); } 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 index 5baa4d93485..6e824fbfd84 100644 --- 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 @@ -47,7 +47,7 @@ namespace IO.Swagger.Test [Test] public void AnimalFarmInstanceTest() { - Assert.IsInstanceOf (instance, "instance is a AnimalFarm"); + Assert.IsInstanceOfType(typeof(AnimalFarm), instance, "instance is a AnimalFarm"); } diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/AnimalTests.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/AnimalTests.cs index e7356e3750d..59cd4d76d68 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/AnimalTests.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/AnimalTests.cs @@ -47,7 +47,7 @@ namespace IO.Swagger.Test [Test] public void AnimalInstanceTest() { - Assert.IsInstanceOf (instance, "instance is a Animal"); + Assert.IsInstanceOfType(typeof(Animal), instance, "instance is a Animal"); } /// diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/ApiResponseTests.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/ApiResponseTests.cs index c2535cdadb3..13d4310916b 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/ApiResponseTests.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/ApiResponseTests.cs @@ -47,7 +47,7 @@ namespace IO.Swagger.Test [Test] public void ApiResponseInstanceTest() { - Assert.IsInstanceOf (instance, "instance is a ApiResponse"); + Assert.IsInstanceOfType(typeof(ApiResponse), instance, "instance is a ApiResponse"); } /// diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/ArrayTestTests.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/ArrayTestTests.cs index fd6b6f31d86..c063340171f 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/ArrayTestTests.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/ArrayTestTests.cs @@ -47,7 +47,7 @@ namespace IO.Swagger.Test [Test] public void ArrayTestInstanceTest() { - Assert.IsInstanceOf (instance, "instance is a ArrayTest"); + Assert.IsInstanceOfType(typeof(ArrayTest), instance, "instance is a ArrayTest"); } diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/CatTests.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/CatTests.cs index 72e65f60bf0..8a6abb12f62 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/CatTests.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/CatTests.cs @@ -47,7 +47,7 @@ namespace IO.Swagger.Test [Test] public void CatInstanceTest() { - Assert.IsInstanceOf (instance, "instance is a Cat"); + Assert.IsInstanceOfType(typeof(Cat), instance, "instance is a Cat"); } /// diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/CategoryTests.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/CategoryTests.cs index 96e5d946c0b..3c7ba0499aa 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/CategoryTests.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/CategoryTests.cs @@ -47,7 +47,7 @@ namespace IO.Swagger.Test [Test] public void CategoryInstanceTest() { - Assert.IsInstanceOf (instance, "instance is a Category"); + Assert.IsInstanceOfType(typeof(Category), instance, "instance is a Category"); } /// diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/DogTests.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/DogTests.cs index 624c16d479d..5d3b6fef175 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/DogTests.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/DogTests.cs @@ -47,7 +47,7 @@ namespace IO.Swagger.Test [Test] public void DogInstanceTest() { - Assert.IsInstanceOf (instance, "instance is a Dog"); + Assert.IsInstanceOfType(typeof(Dog), instance, "instance is a Dog"); } /// 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 index d2a3fc86c78..154e3c7b57a 100644 --- 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 @@ -47,7 +47,7 @@ namespace IO.Swagger.Test [Test] public void EnumClassInstanceTest() { - Assert.IsInstanceOf (instance, "instance is a EnumClass"); + Assert.IsInstanceOfType(typeof(EnumClass), 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 index 2679b085233..9ea929a0cd6 100644 --- 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 @@ -47,7 +47,7 @@ namespace IO.Swagger.Test [Test] public void EnumTestInstanceTest() { - Assert.IsInstanceOf (instance, "instance is a EnumTest"); + Assert.IsInstanceOfType(typeof(EnumTest), instance, "instance is a EnumTest"); } /// diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/FormatTestTests.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/FormatTestTests.cs index e1d59bcc174..1d2d334a45e 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/FormatTestTests.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/FormatTestTests.cs @@ -47,7 +47,7 @@ namespace IO.Swagger.Test [Test] public void FormatTestInstanceTest() { - Assert.IsInstanceOf (instance, "instance is a FormatTest"); + Assert.IsInstanceOfType(typeof(FormatTest), instance, "instance is a FormatTest"); } /// diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/MixedPropertiesAndAdditionalPropertiesClassTests.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/MixedPropertiesAndAdditionalPropertiesClassTests.cs index e21779241db..2157758ec1f 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/MixedPropertiesAndAdditionalPropertiesClassTests.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/MixedPropertiesAndAdditionalPropertiesClassTests.cs @@ -47,7 +47,7 @@ namespace IO.Swagger.Test [Test] public void MixedPropertiesAndAdditionalPropertiesClassInstanceTest() { - Assert.IsInstanceOf (instance, "instance is a MixedPropertiesAndAdditionalPropertiesClass"); + Assert.IsInstanceOfType(typeof(MixedPropertiesAndAdditionalPropertiesClass), instance, "instance is a MixedPropertiesAndAdditionalPropertiesClass"); } /// diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/Model200ResponseTests.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/Model200ResponseTests.cs index eb55902a998..13bbc1b1c7d 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/Model200ResponseTests.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/Model200ResponseTests.cs @@ -47,7 +47,7 @@ namespace IO.Swagger.Test [Test] public void Model200ResponseInstanceTest() { - Assert.IsInstanceOf (instance, "instance is a Model200Response"); + Assert.IsInstanceOfType(typeof(Model200Response), instance, "instance is a Model200Response"); } /// diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/ModelReturnTests.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/ModelReturnTests.cs index 1c620b73241..53e62fc51a3 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/ModelReturnTests.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/ModelReturnTests.cs @@ -47,7 +47,7 @@ namespace IO.Swagger.Test [Test] public void ModelReturnInstanceTest() { - Assert.IsInstanceOf (instance, "instance is a ModelReturn"); + Assert.IsInstanceOfType(typeof(ModelReturn), instance, "instance is a ModelReturn"); } /// diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/NameTests.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/NameTests.cs index d8fbafe238c..d1e0deec41f 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/NameTests.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/NameTests.cs @@ -47,7 +47,7 @@ namespace IO.Swagger.Test [Test] public void NameInstanceTest() { - Assert.IsInstanceOf (instance, "instance is a Name"); + Assert.IsInstanceOfType(typeof(Name), instance, "instance is a Name"); } /// diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/OrderTests.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/OrderTests.cs index 2d55d2300f9..799b6ef43f8 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/OrderTests.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/OrderTests.cs @@ -57,7 +57,7 @@ namespace IO.Swagger.Test [Test] public void OrderInstanceTest() { - Assert.IsInstanceOf (instance, "instance is a Order"); + Assert.IsInstanceOfType(typeof(Order), instance, "instance is a Order"); } /// diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/PetTests.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/PetTests.cs index 24be033f6c5..7029264ee06 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/PetTests.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/PetTests.cs @@ -49,7 +49,7 @@ namespace IO.Swagger.Test [Test] public void PetInstanceTest() { - Assert.IsInstanceOf (instance, "instance is a Pet"); + Assert.IsInstanceOfType(typeof(Pet), instance, "instance is a Pet"); } /// diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/ReadOnlyFirstTests.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/ReadOnlyFirstTests.cs index 9aa3cec42b2..e0c4029546b 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/ReadOnlyFirstTests.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/ReadOnlyFirstTests.cs @@ -47,7 +47,7 @@ namespace IO.Swagger.Test [Test] public void ReadOnlyFirstInstanceTest() { - Assert.IsInstanceOf (instance, "instance is a ReadOnlyFirst"); + Assert.IsInstanceOfType(typeof(ReadOnlyFirst), instance, "instance is a ReadOnlyFirst"); } /// diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/SpecialModelNameTests.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/SpecialModelNameTests.cs index 21051e71f54..eec6e837449 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/SpecialModelNameTests.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/SpecialModelNameTests.cs @@ -47,7 +47,7 @@ namespace IO.Swagger.Test [Test] public void SpecialModelNameInstanceTest() { - Assert.IsInstanceOf (instance, "instance is a SpecialModelName"); + Assert.IsInstanceOfType(typeof(SpecialModelName), instance, "instance is a SpecialModelName"); } /// diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/TagTests.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/TagTests.cs index 4fff0e4c12d..2b78594eb6f 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/TagTests.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/TagTests.cs @@ -47,7 +47,7 @@ namespace IO.Swagger.Test [Test] public void TagInstanceTest() { - Assert.IsInstanceOf (instance, "instance is a Tag"); + Assert.IsInstanceOfType(typeof(Tag), instance, "instance is a Tag"); } /// diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/UserTests.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/UserTests.cs index 38f2667c403..59451079ebf 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/UserTests.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/UserTests.cs @@ -47,7 +47,7 @@ namespace IO.Swagger.Test [Test] public void UserInstanceTest() { - Assert.IsInstanceOf (instance, "instance is a User"); + Assert.IsInstanceOfType(typeof(User), instance, "instance is a User"); } /// 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 index a8a3491f63d..317248179b6 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/packages.config +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/packages.config @@ -1,6 +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 index 00ce83ef910..973771809a2 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Api/FakeApi.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Api/FakeApi.cs @@ -55,7 +55,7 @@ namespace IO.Swagger.Api /// 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); + void TestEndpointParameters (decimal? number, double? _double, string _string, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, byte[] binary = null, DateTime? date = null, DateTime? dateTime = null, string password = null); /// /// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 @@ -77,7 +77,7 @@ namespace IO.Swagger.Api /// 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); + ApiResponse TestEndpointParametersWithHttpInfo (decimal? number, double? _double, string _string, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, byte[] binary = null, DateTime? date = null, DateTime? dateTime = null, string password = null); #endregion Synchronous Operations #region Asynchronous Operations /// @@ -100,7 +100,7 @@ namespace IO.Swagger.Api /// 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); + System.Threading.Tasks.Task TestEndpointParametersAsync (decimal? number, double? _double, string _string, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, byte[] binary = null, DateTime? date = null, DateTime? dateTime = null, string password = null); /// /// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 @@ -122,7 +122,7 @@ namespace IO.Swagger.Api /// 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); + System.Threading.Tasks.Task> TestEndpointParametersAsyncWithHttpInfo (decimal? number, double? _double, string _string, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, byte[] binary = null, DateTime? date = null, DateTime? dateTime = null, string password = null); #endregion Asynchronous Operations } @@ -131,6 +131,8 @@ namespace IO.Swagger.Api /// public partial class FakeApi : IFakeApi { + private IO.Swagger.Client.ExceptionFactory _exceptionFactory = (name, response) => null; + /// /// Initializes a new instance of the class. /// @@ -139,6 +141,8 @@ namespace IO.Swagger.Api { this.Configuration = new Configuration(new ApiClient(basePath)); + ExceptionFactory = IO.Swagger.Client.Configuration.DefaultExceptionFactory; + // ensure API client has configuration ready if (Configuration.ApiClient.Configuration == null) { @@ -159,6 +163,8 @@ namespace IO.Swagger.Api else this.Configuration = configuration; + ExceptionFactory = IO.Swagger.Client.Configuration.DefaultExceptionFactory; + // ensure API client has configuration ready if (Configuration.ApiClient.Configuration == null) { @@ -191,6 +197,22 @@ namespace IO.Swagger.Api /// An instance of the Configuration public Configuration Configuration {get; set;} + /// + /// Provides a factory method hook for the creation of exceptions. + /// + public IO.Swagger.Client.ExceptionFactory ExceptionFactory + { + get + { + if (_exceptionFactory != null && _exceptionFactory.GetInvocationList().Length > 1) + { + throw new InvalidOperationException("Multicast delegate for ExceptionFactory is unsupported."); + } + return _exceptionFactory; + } + set { _exceptionFactory = value; } + } + /// /// Gets the default header. /// @@ -230,7 +252,7 @@ namespace IO.Swagger.Api /// 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) + public void TestEndpointParameters (decimal? number, double? _double, string _string, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, byte[] binary = null, DateTime? date = null, DateTime? dateTime = null, string password = null) { TestEndpointParametersWithHttpInfo(number, _double, _string, _byte, integer, int32, int64, _float, binary, date, dateTime, password); } @@ -252,7 +274,7 @@ namespace IO.Swagger.Api /// 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) + public ApiResponse TestEndpointParametersWithHttpInfo (decimal? number, double? _double, string _string, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, byte[] binary = null, DateTime? date = null, DateTime? dateTime = null, string password = null) { // verify the required parameter 'number' is set if (number == null) @@ -315,10 +337,11 @@ namespace IO.Swagger.Api 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); + if (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("TestEndpointParameters", localVarResponse); + if (exception != null) throw exception; + } return new ApiResponse(localVarStatusCode, @@ -343,7 +366,7 @@ namespace IO.Swagger.Api /// 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) + public async System.Threading.Tasks.Task TestEndpointParametersAsync (decimal? number, double? _double, string _string, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, byte[] binary = null, DateTime? date = null, DateTime? dateTime = null, string password = null) { await TestEndpointParametersAsyncWithHttpInfo(number, _double, _string, _byte, integer, int32, int64, _float, binary, date, dateTime, password); @@ -366,7 +389,7 @@ namespace IO.Swagger.Api /// 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) + public async System.Threading.Tasks.Task> TestEndpointParametersAsyncWithHttpInfo (decimal? number, double? _double, string _string, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, byte[] binary = null, DateTime? date = null, DateTime? dateTime = null, string password = null) { // verify the required parameter 'number' is set if (number == null) @@ -429,10 +452,11 @@ namespace IO.Swagger.Api 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); + if (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("TestEndpointParameters", localVarResponse); + if (exception != null) throw exception; + } return new ApiResponse(localVarStatusCode, diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Api/PetApi.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Api/PetApi.cs index e147d33cceb..abf5a0595b2 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Api/PetApi.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Api/PetApi.cs @@ -402,6 +402,8 @@ namespace IO.Swagger.Api /// public partial class PetApi : IPetApi { + private IO.Swagger.Client.ExceptionFactory _exceptionFactory = (name, response) => null; + /// /// Initializes a new instance of the class. /// @@ -410,6 +412,8 @@ namespace IO.Swagger.Api { this.Configuration = new Configuration(new ApiClient(basePath)); + ExceptionFactory = IO.Swagger.Client.Configuration.DefaultExceptionFactory; + // ensure API client has configuration ready if (Configuration.ApiClient.Configuration == null) { @@ -430,6 +434,8 @@ namespace IO.Swagger.Api else this.Configuration = configuration; + ExceptionFactory = IO.Swagger.Client.Configuration.DefaultExceptionFactory; + // ensure API client has configuration ready if (Configuration.ApiClient.Configuration == null) { @@ -462,6 +468,22 @@ namespace IO.Swagger.Api /// An instance of the Configuration public Configuration Configuration {get; set;} + /// + /// Provides a factory method hook for the creation of exceptions. + /// + public IO.Swagger.Client.ExceptionFactory ExceptionFactory + { + get + { + if (_exceptionFactory != null && _exceptionFactory.GetInvocationList().Length > 1) + { + throw new InvalidOperationException("Multicast delegate for ExceptionFactory is unsupported."); + } + return _exceptionFactory; + } + set { _exceptionFactory = value; } + } + /// /// Gets the default header. /// @@ -557,10 +579,11 @@ namespace IO.Swagger.Api int localVarStatusCode = (int) localVarResponse.StatusCode; - if (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling AddPet: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling AddPet: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + if (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("AddPet", localVarResponse); + if (exception != null) throw exception; + } return new ApiResponse(localVarStatusCode, @@ -642,10 +665,11 @@ namespace IO.Swagger.Api int localVarStatusCode = (int) localVarResponse.StatusCode; - if (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling AddPet: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling AddPet: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + if (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("AddPet", localVarResponse); + if (exception != null) throw exception; + } return new ApiResponse(localVarStatusCode, @@ -720,10 +744,11 @@ namespace IO.Swagger.Api int localVarStatusCode = (int) localVarResponse.StatusCode; - if (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling DeletePet: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling DeletePet: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + if (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("DeletePet", localVarResponse); + if (exception != null) throw exception; + } return new ApiResponse(localVarStatusCode, @@ -799,10 +824,11 @@ namespace IO.Swagger.Api int localVarStatusCode = (int) localVarResponse.StatusCode; - if (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling DeletePet: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling DeletePet: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + if (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("DeletePet", localVarResponse); + if (exception != null) throw exception; + } return new ApiResponse(localVarStatusCode, @@ -875,10 +901,11 @@ namespace IO.Swagger.Api int localVarStatusCode = (int) localVarResponse.StatusCode; - if (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling FindPetsByStatus: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling FindPetsByStatus: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + if (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("FindPetsByStatus", localVarResponse); + if (exception != null) throw exception; + } return new ApiResponse>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), @@ -952,10 +979,11 @@ namespace IO.Swagger.Api int localVarStatusCode = (int) localVarResponse.StatusCode; - if (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling FindPetsByStatus: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling FindPetsByStatus: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + if (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("FindPetsByStatus", localVarResponse); + if (exception != null) throw exception; + } return new ApiResponse>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), @@ -1028,10 +1056,11 @@ namespace IO.Swagger.Api int localVarStatusCode = (int) localVarResponse.StatusCode; - if (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling FindPetsByTags: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling FindPetsByTags: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + if (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("FindPetsByTags", localVarResponse); + if (exception != null) throw exception; + } return new ApiResponse>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), @@ -1105,10 +1134,11 @@ namespace IO.Swagger.Api int localVarStatusCode = (int) localVarResponse.StatusCode; - if (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling FindPetsByTags: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling FindPetsByTags: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + if (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("FindPetsByTags", localVarResponse); + if (exception != null) throw exception; + } return new ApiResponse>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), @@ -1181,10 +1211,11 @@ namespace IO.Swagger.Api int localVarStatusCode = (int) localVarResponse.StatusCode; - if (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling GetPetById: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling GetPetById: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + if (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("GetPetById", localVarResponse); + if (exception != null) throw exception; + } return new ApiResponse(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), @@ -1257,10 +1288,11 @@ namespace IO.Swagger.Api int localVarStatusCode = (int) localVarResponse.StatusCode; - if (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling GetPetById: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling GetPetById: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + if (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("GetPetById", localVarResponse); + if (exception != null) throw exception; + } return new ApiResponse(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), @@ -1341,10 +1373,11 @@ namespace IO.Swagger.Api int localVarStatusCode = (int) localVarResponse.StatusCode; - if (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling UpdatePet: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling UpdatePet: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + if (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("UpdatePet", localVarResponse); + if (exception != null) throw exception; + } return new ApiResponse(localVarStatusCode, @@ -1426,10 +1459,11 @@ namespace IO.Swagger.Api int localVarStatusCode = (int) localVarResponse.StatusCode; - if (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling UpdatePet: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling UpdatePet: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + if (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("UpdatePet", localVarResponse); + if (exception != null) throw exception; + } return new ApiResponse(localVarStatusCode, @@ -1508,10 +1542,11 @@ namespace IO.Swagger.Api int localVarStatusCode = (int) localVarResponse.StatusCode; - if (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling UpdatePetWithForm: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling UpdatePetWithForm: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + if (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("UpdatePetWithForm", localVarResponse); + if (exception != null) throw exception; + } return new ApiResponse(localVarStatusCode, @@ -1591,10 +1626,11 @@ namespace IO.Swagger.Api int localVarStatusCode = (int) localVarResponse.StatusCode; - if (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling UpdatePetWithForm: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling UpdatePetWithForm: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + if (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("UpdatePetWithForm", localVarResponse); + if (exception != null) throw exception; + } return new ApiResponse(localVarStatusCode, @@ -1673,10 +1709,11 @@ namespace IO.Swagger.Api int localVarStatusCode = (int) localVarResponse.StatusCode; - if (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling UploadFile: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling UploadFile: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + if (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("UploadFile", localVarResponse); + if (exception != null) throw exception; + } return new ApiResponse(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), @@ -1756,10 +1793,11 @@ namespace IO.Swagger.Api int localVarStatusCode = (int) localVarResponse.StatusCode; - if (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling UploadFile: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling UploadFile: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + if (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("UploadFile", localVarResponse); + if (exception != null) throw exception; + } return new ApiResponse(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Api/StoreApi.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Api/StoreApi.cs index ed5dd54ec40..3fbbe71b8ca 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Api/StoreApi.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Api/StoreApi.cs @@ -210,6 +210,8 @@ namespace IO.Swagger.Api /// public partial class StoreApi : IStoreApi { + private IO.Swagger.Client.ExceptionFactory _exceptionFactory = (name, response) => null; + /// /// Initializes a new instance of the class. /// @@ -218,6 +220,8 @@ namespace IO.Swagger.Api { this.Configuration = new Configuration(new ApiClient(basePath)); + ExceptionFactory = IO.Swagger.Client.Configuration.DefaultExceptionFactory; + // ensure API client has configuration ready if (Configuration.ApiClient.Configuration == null) { @@ -238,6 +242,8 @@ namespace IO.Swagger.Api else this.Configuration = configuration; + ExceptionFactory = IO.Swagger.Client.Configuration.DefaultExceptionFactory; + // ensure API client has configuration ready if (Configuration.ApiClient.Configuration == null) { @@ -270,6 +276,22 @@ namespace IO.Swagger.Api /// An instance of the Configuration public Configuration Configuration {get; set;} + /// + /// Provides a factory method hook for the creation of exceptions. + /// + public IO.Swagger.Client.ExceptionFactory ExceptionFactory + { + get + { + if (_exceptionFactory != null && _exceptionFactory.GetInvocationList().Length > 1) + { + throw new InvalidOperationException("Multicast delegate for ExceptionFactory is unsupported."); + } + return _exceptionFactory; + } + set { _exceptionFactory = value; } + } + /// /// Gets the default header. /// @@ -350,10 +372,11 @@ namespace IO.Swagger.Api int localVarStatusCode = (int) localVarResponse.StatusCode; - if (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling DeleteOrder: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling DeleteOrder: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + if (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("DeleteOrder", localVarResponse); + if (exception != null) throw exception; + } return new ApiResponse(localVarStatusCode, @@ -420,10 +443,11 @@ namespace IO.Swagger.Api int localVarStatusCode = (int) localVarResponse.StatusCode; - if (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling DeleteOrder: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling DeleteOrder: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + if (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("DeleteOrder", localVarResponse); + if (exception != null) throw exception; + } return new ApiResponse(localVarStatusCode, @@ -489,10 +513,11 @@ namespace IO.Swagger.Api int localVarStatusCode = (int) localVarResponse.StatusCode; - if (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling GetInventory: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling GetInventory: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + if (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("GetInventory", localVarResponse); + if (exception != null) throw exception; + } return new ApiResponse>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), @@ -558,10 +583,11 @@ namespace IO.Swagger.Api int localVarStatusCode = (int) localVarResponse.StatusCode; - if (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling GetInventory: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling GetInventory: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + if (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("GetInventory", localVarResponse); + if (exception != null) throw exception; + } return new ApiResponse>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), @@ -628,10 +654,11 @@ namespace IO.Swagger.Api int localVarStatusCode = (int) localVarResponse.StatusCode; - if (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling GetOrderById: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling GetOrderById: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + if (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("GetOrderById", localVarResponse); + if (exception != null) throw exception; + } return new ApiResponse(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), @@ -699,10 +726,11 @@ namespace IO.Swagger.Api int localVarStatusCode = (int) localVarResponse.StatusCode; - if (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling GetOrderById: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling GetOrderById: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + if (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("GetOrderById", localVarResponse); + if (exception != null) throw exception; + } return new ApiResponse(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), @@ -776,10 +804,11 @@ namespace IO.Swagger.Api int localVarStatusCode = (int) localVarResponse.StatusCode; - if (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling PlaceOrder: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling PlaceOrder: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + if (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("PlaceOrder", localVarResponse); + if (exception != null) throw exception; + } return new ApiResponse(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), @@ -854,10 +883,11 @@ namespace IO.Swagger.Api int localVarStatusCode = (int) localVarResponse.StatusCode; - if (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling PlaceOrder: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling PlaceOrder: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + if (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("PlaceOrder", localVarResponse); + if (exception != null) throw exception; + } return new ApiResponse(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Api/UserApi.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Api/UserApi.cs index 6cb5bee041c..6fb6244264e 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Api/UserApi.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Api/UserApi.cs @@ -386,6 +386,8 @@ namespace IO.Swagger.Api /// public partial class UserApi : IUserApi { + private IO.Swagger.Client.ExceptionFactory _exceptionFactory = (name, response) => null; + /// /// Initializes a new instance of the class. /// @@ -394,6 +396,8 @@ namespace IO.Swagger.Api { this.Configuration = new Configuration(new ApiClient(basePath)); + ExceptionFactory = IO.Swagger.Client.Configuration.DefaultExceptionFactory; + // ensure API client has configuration ready if (Configuration.ApiClient.Configuration == null) { @@ -414,6 +418,8 @@ namespace IO.Swagger.Api else this.Configuration = configuration; + ExceptionFactory = IO.Swagger.Client.Configuration.DefaultExceptionFactory; + // ensure API client has configuration ready if (Configuration.ApiClient.Configuration == null) { @@ -446,6 +452,22 @@ namespace IO.Swagger.Api /// An instance of the Configuration public Configuration Configuration {get; set;} + /// + /// Provides a factory method hook for the creation of exceptions. + /// + public IO.Swagger.Client.ExceptionFactory ExceptionFactory + { + get + { + if (_exceptionFactory != null && _exceptionFactory.GetInvocationList().Length > 1) + { + throw new InvalidOperationException("Multicast delegate for ExceptionFactory is unsupported."); + } + return _exceptionFactory; + } + set { _exceptionFactory = value; } + } + /// /// Gets the default header. /// @@ -533,10 +555,11 @@ namespace IO.Swagger.Api int localVarStatusCode = (int) localVarResponse.StatusCode; - if (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling CreateUser: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling CreateUser: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + if (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("CreateUser", localVarResponse); + if (exception != null) throw exception; + } return new ApiResponse(localVarStatusCode, @@ -610,10 +633,11 @@ namespace IO.Swagger.Api int localVarStatusCode = (int) localVarResponse.StatusCode; - if (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling CreateUser: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling CreateUser: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + if (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("CreateUser", localVarResponse); + if (exception != null) throw exception; + } return new ApiResponse(localVarStatusCode, @@ -686,10 +710,11 @@ namespace IO.Swagger.Api int localVarStatusCode = (int) localVarResponse.StatusCode; - if (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling CreateUsersWithArrayInput: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling CreateUsersWithArrayInput: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + if (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("CreateUsersWithArrayInput", localVarResponse); + if (exception != null) throw exception; + } return new ApiResponse(localVarStatusCode, @@ -763,10 +788,11 @@ namespace IO.Swagger.Api int localVarStatusCode = (int) localVarResponse.StatusCode; - if (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling CreateUsersWithArrayInput: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling CreateUsersWithArrayInput: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + if (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("CreateUsersWithArrayInput", localVarResponse); + if (exception != null) throw exception; + } return new ApiResponse(localVarStatusCode, @@ -839,10 +865,11 @@ namespace IO.Swagger.Api int localVarStatusCode = (int) localVarResponse.StatusCode; - if (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling CreateUsersWithListInput: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling CreateUsersWithListInput: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + if (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("CreateUsersWithListInput", localVarResponse); + if (exception != null) throw exception; + } return new ApiResponse(localVarStatusCode, @@ -916,10 +943,11 @@ namespace IO.Swagger.Api int localVarStatusCode = (int) localVarResponse.StatusCode; - if (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling CreateUsersWithListInput: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling CreateUsersWithListInput: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + if (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("CreateUsersWithListInput", localVarResponse); + if (exception != null) throw exception; + } return new ApiResponse(localVarStatusCode, @@ -985,10 +1013,11 @@ namespace IO.Swagger.Api int localVarStatusCode = (int) localVarResponse.StatusCode; - if (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling DeleteUser: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling DeleteUser: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + if (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("DeleteUser", localVarResponse); + if (exception != null) throw exception; + } return new ApiResponse(localVarStatusCode, @@ -1055,10 +1084,11 @@ namespace IO.Swagger.Api int localVarStatusCode = (int) localVarResponse.StatusCode; - if (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling DeleteUser: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling DeleteUser: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + if (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("DeleteUser", localVarResponse); + if (exception != null) throw exception; + } return new ApiResponse(localVarStatusCode, @@ -1125,10 +1155,11 @@ namespace IO.Swagger.Api int localVarStatusCode = (int) localVarResponse.StatusCode; - if (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling GetUserByName: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling GetUserByName: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + if (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("GetUserByName", localVarResponse); + if (exception != null) throw exception; + } return new ApiResponse(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), @@ -1196,10 +1227,11 @@ namespace IO.Swagger.Api int localVarStatusCode = (int) localVarResponse.StatusCode; - if (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling GetUserByName: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling GetUserByName: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + if (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("GetUserByName", localVarResponse); + if (exception != null) throw exception; + } return new ApiResponse(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), @@ -1272,10 +1304,11 @@ namespace IO.Swagger.Api int localVarStatusCode = (int) localVarResponse.StatusCode; - if (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling LoginUser: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling LoginUser: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + if (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("LoginUser", localVarResponse); + if (exception != null) throw exception; + } return new ApiResponse(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), @@ -1349,10 +1382,11 @@ namespace IO.Swagger.Api int localVarStatusCode = (int) localVarResponse.StatusCode; - if (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling LoginUser: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling LoginUser: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + if (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("LoginUser", localVarResponse); + if (exception != null) throw exception; + } return new ApiResponse(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), @@ -1412,10 +1446,11 @@ namespace IO.Swagger.Api int localVarStatusCode = (int) localVarResponse.StatusCode; - if (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling LogoutUser: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling LogoutUser: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + if (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("LogoutUser", localVarResponse); + if (exception != null) throw exception; + } return new ApiResponse(localVarStatusCode, @@ -1476,10 +1511,11 @@ namespace IO.Swagger.Api int localVarStatusCode = (int) localVarResponse.StatusCode; - if (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling LogoutUser: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling LogoutUser: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + if (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("LogoutUser", localVarResponse); + if (exception != null) throw exception; + } return new ApiResponse(localVarStatusCode, @@ -1558,10 +1594,11 @@ namespace IO.Swagger.Api int localVarStatusCode = (int) localVarResponse.StatusCode; - if (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling UpdateUser: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling UpdateUser: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + if (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("UpdateUser", localVarResponse); + if (exception != null) throw exception; + } return new ApiResponse(localVarStatusCode, @@ -1641,10 +1678,11 @@ namespace IO.Swagger.Api int localVarStatusCode = (int) localVarResponse.StatusCode; - if (localVarStatusCode >= 400) - throw new ApiException (localVarStatusCode, "Error calling UpdateUser: " + localVarResponse.Content, localVarResponse.Content); - else if (localVarStatusCode == 0) - throw new ApiException (localVarStatusCode, "Error calling UpdateUser: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); + if (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("UpdateUser", localVarResponse); + if (exception != null) throw exception; + } return new ApiResponse(localVarStatusCode, diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Client/ApiClient.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Client/ApiClient.cs index 4331456ceaa..c5a2de83da1 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Client/ApiClient.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Client/ApiClient.cs @@ -36,15 +36,28 @@ using RestSharp; namespace IO.Swagger.Client { /// - /// API client is mainly responible for making the HTTP call to the API backend. + /// API client is mainly responsible for making the HTTP call to the API backend. /// - public class ApiClient + public partial class ApiClient { private JsonSerializerSettings serializerSettings = new JsonSerializerSettings { ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor }; + /// + /// Allows for extending request processing for generated code. + /// + /// The RestSharp request object + partial void InterceptRequest(IRestRequest request); + + /// + /// Allows for extending response processing for generated code. + /// + /// The RestSharp request object + /// The RestSharp response object + partial void InterceptResponse(IRestRequest request, IRestResponse response); + /// /// Initializes a new instance of the class /// with default configuration and base path (http://petstore.swagger.io/v2). @@ -177,7 +190,10 @@ namespace IO.Swagger.Client // set user agent RestClient.UserAgent = Configuration.UserAgent; + InterceptRequest(request); var response = RestClient.Execute(request); + InterceptResponse(request, response); + return (Object) response; } /// @@ -202,7 +218,9 @@ namespace IO.Swagger.Client var request = PrepareRequest( path, method, queryParams, postBody, headerParams, formParams, fileParams, pathParams, contentType); + InterceptRequest(request); var response = await RestClient.ExecuteTaskAsync(request); + InterceptResponse(request, response); return (Object)response; } diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Client/Configuration.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Client/Configuration.cs index 451f6d61354..533b994dab2 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Client/Configuration.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Client/Configuration.cs @@ -101,6 +101,17 @@ namespace IO.Swagger.Client /// Configuration. public static Configuration Default = new Configuration(); + /// + /// Default creation of exceptions for a given method name and response object + /// + public static readonly ExceptionFactory DefaultExceptionFactory = (methodName, response) => + { + int status = (int) response.StatusCode; + if (status >= 400) return new ApiException(status, String.Format("Error calling {0}: {1}", methodName, response.Content), response.Content); + if (status == 0) return new ApiException(status, String.Format("Error calling {0}: {1}", methodName, response.ErrorMessage), response.ErrorMessage); + return null; + }; + /// /// Gets or sets the HTTP timeout (milliseconds) of ApiClient. Default to 100000 milliseconds. /// diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Client/ExceptionFactory.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Client/ExceptionFactory.cs new file mode 100644 index 00000000000..579cb8618c2 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Client/ExceptionFactory.cs @@ -0,0 +1,36 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +using System; +using RestSharp; + +namespace IO.Swagger.Client +{ + /// + /// A delegate to ExceptionFactory method + /// + /// Method name + /// Response + /// Exceptions + public delegate Exception ExceptionFactory(string methodName, IRestResponse response); +} diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Client/IApiAccessor.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Client/IApiAccessor.cs index 1c91ef50003..65ff8bef73b 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Client/IApiAccessor.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Client/IApiAccessor.cs @@ -45,5 +45,10 @@ namespace IO.Swagger.Client /// /// The base path String GetBasePath(); + + /// + /// Provides a factory method hook for the creation of exceptions. + /// + ExceptionFactory ExceptionFactory { get; set; } } } diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/IO.Swagger.csproj b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/IO.Swagger.csproj index 20fdb3385e1..7a78c9e7e69 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/IO.Swagger.csproj +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/IO.Swagger.csproj @@ -24,7 +24,7 @@ limitations under the License. Debug AnyCPU - {C81D6286-7BA5-4920-8591-F59169CCE4A4} + {BF42B49D-37A0-49C4-A405-24CD946ADAA7} Library Properties Swagger Library @@ -59,10 +59,10 @@ limitations under the License. - $(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\Newtonsoft.Json.8.0.3\lib\net45\Newtonsoft.Json.dll + ..\packages\Newtonsoft.Json.8.0.3\lib\net45\Newtonsoft.Json.dll + ..\..\packages\Newtonsoft.Json.8.0.3\lib\net45\Newtonsoft.Json.dll + ..\..\vendor\Newtonsoft.Json.8.0.3\lib\net45\Newtonsoft.Json.dll $(SolutionDir)\packages\RestSharp.105.1.0\lib\net45\RestSharp.dll diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/FormatTest.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/FormatTest.cs index eb1a6a8924b..5e50732ee0b 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/FormatTest.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/FormatTest.cs @@ -60,7 +60,7 @@ namespace IO.Swagger.Model /// 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, Guid? Uuid = null, string Password = null) + public FormatTest(int? Integer = null, int? Int32 = null, long? Int64 = null, decimal? Number = null, float? _Float = null, double? _Double = null, string _String = null, byte[] _Byte = null, byte[] Binary = null, DateTime? Date = null, DateTime? DateTime = null, Guid? Uuid = null, string Password = null) { // to ensure "Number" is required (not null) if (Number == null) @@ -128,7 +128,7 @@ namespace IO.Swagger.Model /// Gets or Sets Number /// [DataMember(Name="number", EmitDefaultValue=false)] - public double? Number { get; set; } + public decimal? Number { get; set; } /// /// Gets or Sets _Float /// diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/packages.config b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/packages.config index 91f17cd0819..80f617d6d9f 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/packages.config +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/packages.config @@ -1,5 +1,5 @@ - + diff --git a/samples/client/petstore/java/default/.swagger-codegen-ignore b/samples/client/petstore/java/default/.swagger-codegen-ignore new file mode 100644 index 00000000000..19d3377182e --- /dev/null +++ b/samples/client/petstore/java/default/.swagger-codegen-ignore @@ -0,0 +1,23 @@ +# Swagger Codegen Ignore +# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell Swagger Codgen to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# Thsi matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/client/petstore/java/default/LICENSE b/samples/client/petstore/java/default/LICENSE new file mode 100644 index 00000000000..8dada3edaf5 --- /dev/null +++ b/samples/client/petstore/java/default/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/samples/client/petstore/java/default/docs/AdditionalPropertiesClass.md b/samples/client/petstore/java/default/docs/AdditionalPropertiesClass.md new file mode 100644 index 00000000000..0437c4dd8cc --- /dev/null +++ b/samples/client/petstore/java/default/docs/AdditionalPropertiesClass.md @@ -0,0 +1,11 @@ + +# AdditionalPropertiesClass + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**mapProperty** | **Map<String, String>** | | [optional] +**mapOfMapProperty** | [**Map<String, Map<String, String>>**](Map.md) | | [optional] + + + diff --git a/samples/client/petstore/java/default/docs/Animal.md b/samples/client/petstore/java/default/docs/Animal.md index 3ecb7f991f3..b3f325c3524 100644 --- a/samples/client/petstore/java/default/docs/Animal.md +++ b/samples/client/petstore/java/default/docs/Animal.md @@ -5,6 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **className** | **String** | | +**color** | **String** | | [optional] diff --git a/samples/client/petstore/java/default/docs/ArrayTest.md b/samples/client/petstore/java/default/docs/ArrayTest.md new file mode 100644 index 00000000000..9feee16427f --- /dev/null +++ b/samples/client/petstore/java/default/docs/ArrayTest.md @@ -0,0 +1,12 @@ + +# ArrayTest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**arrayOfString** | **List<String>** | | [optional] +**arrayArrayOfInteger** | [**List<List<Long>>**](List.md) | | [optional] +**arrayArrayOfModel** | [**List<List<ReadOnlyFirst>>**](List.md) | | [optional] + + + diff --git a/samples/client/petstore/java/default/docs/Cat.md b/samples/client/petstore/java/default/docs/Cat.md index 373af540c41..be6e56fa8ce 100644 --- a/samples/client/petstore/java/default/docs/Cat.md +++ b/samples/client/petstore/java/default/docs/Cat.md @@ -5,6 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **className** | **String** | | +**color** | **String** | | [optional] **declawed** | **Boolean** | | [optional] diff --git a/samples/client/petstore/java/default/docs/Dog.md b/samples/client/petstore/java/default/docs/Dog.md index a1d638d3bad..71a7dbe809e 100644 --- a/samples/client/petstore/java/default/docs/Dog.md +++ b/samples/client/petstore/java/default/docs/Dog.md @@ -5,6 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **className** | **String** | | +**color** | **String** | | [optional] **breed** | **String** | | [optional] diff --git a/samples/client/petstore/java/default/docs/FakeApi.md b/samples/client/petstore/java/default/docs/FakeApi.md index b4e5f34974a..0c1f55a0902 100644 --- a/samples/client/petstore/java/default/docs/FakeApi.md +++ b/samples/client/petstore/java/default/docs/FakeApi.md @@ -32,8 +32,8 @@ 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 +LocalDate date = new LocalDate(); // LocalDate | None +DateTime dateTime = new DateTime(); // DateTime | None String password = "password_example"; // String | None try { apiInstance.testEndpointParameters(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password); @@ -56,8 +56,8 @@ Name | Type | Description | Notes **int64** | **Long**| None | [optional] **_float** | **Float**| None | [optional] **binary** | **byte[]**| None | [optional] - **date** | **Date**| None | [optional] - **dateTime** | **Date**| None | [optional] + **date** | **LocalDate**| None | [optional] + **dateTime** | **DateTime**| None | [optional] **password** | **String**| None | [optional] ### Return type @@ -70,6 +70,6 @@ No authorization required ### HTTP request headers - - **Content-Type**: Not defined - - **Accept**: application/xml, application/json + - **Content-Type**: application/xml; charset=utf-8, application/json; charset=utf-8 + - **Accept**: application/xml; charset=utf-8, application/json; charset=utf-8 diff --git a/samples/client/petstore/java/default/docs/FormatTest.md b/samples/client/petstore/java/default/docs/FormatTest.md index dc2b559dad2..44de7d9511a 100644 --- a/samples/client/petstore/java/default/docs/FormatTest.md +++ b/samples/client/petstore/java/default/docs/FormatTest.md @@ -13,8 +13,8 @@ Name | Type | Description | Notes **string** | **String** | | [optional] **_byte** | **byte[]** | | **binary** | **byte[]** | | [optional] -**date** | [**Date**](Date.md) | | -**dateTime** | [**Date**](Date.md) | | [optional] +**date** | [**LocalDate**](LocalDate.md) | | +**dateTime** | [**DateTime**](DateTime.md) | | [optional] **uuid** | **String** | | [optional] **password** | **String** | | diff --git a/samples/client/petstore/java/default/docs/MixedPropertiesAndAdditionalPropertiesClass.md b/samples/client/petstore/java/default/docs/MixedPropertiesAndAdditionalPropertiesClass.md new file mode 100644 index 00000000000..e3487bcc501 --- /dev/null +++ b/samples/client/petstore/java/default/docs/MixedPropertiesAndAdditionalPropertiesClass.md @@ -0,0 +1,12 @@ + +# MixedPropertiesAndAdditionalPropertiesClass + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**uuid** | **String** | | [optional] +**dateTime** | [**DateTime**](DateTime.md) | | [optional] +**map** | [**Map<String, Animal>**](Animal.md) | | [optional] + + + diff --git a/samples/client/petstore/java/default/docs/Name.md b/samples/client/petstore/java/default/docs/Name.md index 5390a15e9cd..ce2fb4dee50 100644 --- a/samples/client/petstore/java/default/docs/Name.md +++ b/samples/client/petstore/java/default/docs/Name.md @@ -7,6 +7,7 @@ Name | Type | Description | Notes **name** | **Integer** | | **snakeCase** | **Integer** | | [optional] **property** | **String** | | [optional] +**_123Number** | **Integer** | | [optional] diff --git a/samples/client/petstore/java/default/docs/Order.md b/samples/client/petstore/java/default/docs/Order.md index 29ca3ddbc6b..a1089f5384e 100644 --- a/samples/client/petstore/java/default/docs/Order.md +++ b/samples/client/petstore/java/default/docs/Order.md @@ -7,7 +7,7 @@ Name | Type | Description | Notes **id** | **Long** | | [optional] **petId** | **Long** | | [optional] **quantity** | **Integer** | | [optional] -**shipDate** | [**Date**](Date.md) | | [optional] +**shipDate** | [**DateTime**](DateTime.md) | | [optional] **status** | [**StatusEnum**](#StatusEnum) | Order Status | [optional] **complete** | **Boolean** | | [optional] diff --git a/samples/client/petstore/java/default/docs/ReadOnlyFirst.md b/samples/client/petstore/java/default/docs/ReadOnlyFirst.md new file mode 100644 index 00000000000..426b7cde95a --- /dev/null +++ b/samples/client/petstore/java/default/docs/ReadOnlyFirst.md @@ -0,0 +1,11 @@ + +# ReadOnlyFirst + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**bar** | **String** | | [optional] +**baz** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/default/gradlew b/samples/client/petstore/java/default/gradlew old mode 100755 new mode 100644 diff --git a/samples/client/petstore/java/default/petstore_profiling.output b/samples/client/petstore/java/default/petstore_profiling.output deleted file mode 100644 index 21562548765..00000000000 --- a/samples/client/petstore/java/default/petstore_profiling.output +++ /dev/null @@ -1,23 +0,0 @@ -# To run the profiling: -# mvn compile test-compile exec:java -Dexec.classpathScope=test -Dexec.mainClass="io.swagger.PetstoreProfiling" - -0: ADD PET => 0.987609128 -0: GET PET => 0.450873167 -0: UPDATE PET => 0.447611998 -0: DELETE PET => 0.397707664 -1: ADD PET => 0.395333121 -1: GET PET => 0.381760136 -1: UPDATE PET => 0.395245221 -1: DELETE PET => 0.384854324 -2: ADD PET => 0.400336227 -2: GET PET => 0.378959921 -2: UPDATE PET => 0.397619284 -2: DELETE PET => 0.383307393 -3: ADD PET => 0.385764805 -3: GET PET => 0.40218304 -3: UPDATE PET => 0.387887511 -3: DELETE PET => 0.398063489 -4: ADD PET => 0.384757488 -4: GET PET => 0.398719713 -4: UPDATE PET => 0.383319052 -4: DELETE PET => 0.408516644 diff --git a/samples/client/petstore/java/default/pom.xml b/samples/client/petstore/java/default/pom.xml index 2ea4060bc3a..0b24e120100 100644 --- a/samples/client/petstore/java/default/pom.xml +++ b/samples/client/petstore/java/default/pom.xml @@ -97,8 +97,8 @@ maven-compiler-plugin 2.3.2 - 1.6 - 1.6 + 1.7 + 1.7 diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/ApiClient.java index 50c0e8db641..0d7898329d0 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/ApiClient.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/ApiClient.java @@ -41,7 +41,7 @@ import io.swagger.client.auth.HttpBasicAuth; import io.swagger.client.auth.ApiKeyAuth; import io.swagger.client.auth.OAuth; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-03-17T15:55:38.841+08:00") + public class ApiClient { private Map defaultHeaderMap = new HashMap(); private String basePath = "http://petstore.swagger.io/v2"; @@ -75,13 +75,8 @@ public class ApiClient { // Setup authentications (key: authentication name, value: authentication). authentications = new HashMap(); - authentications.put("petstore_auth", new OAuth()); - authentications.put("test_api_client_id", new ApiKeyAuth("header", "x-test_api_client_id")); - authentications.put("test_api_client_secret", new ApiKeyAuth("header", "x-test_api_client_secret")); authentications.put("api_key", new ApiKeyAuth("header", "api_key")); - authentications.put("test_http_basic", new HttpBasicAuth()); - authentications.put("test_api_key_query", new ApiKeyAuth("query", "test_api_key_query")); - authentications.put("test_api_key_header", new ApiKeyAuth("header", "test_api_key_header")); + authentications.put("petstore_auth", new OAuth()); // Prevent the authentications from being modified. authentications = Collections.unmodifiableMap(authentications); diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/ApiException.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/ApiException.java index 27395e86ba9..600bb507f09 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/ApiException.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/ApiException.java @@ -1,3 +1,28 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client; import java.util.Map; @@ -5,65 +30,74 @@ import java.util.List; public class ApiException extends Exception { - private int code = 0; - private Map> responseHeaders = null; - private String responseBody = null; + private int code = 0; + private Map> responseHeaders = null; + private String responseBody = null; - public ApiException() {} + public ApiException() {} - public ApiException(Throwable throwable) { - super(throwable); - } + public ApiException(Throwable throwable) { + super(throwable); + } - public ApiException(String message) { - super(message); - } + public ApiException(String message) { + super(message); + } - public ApiException(String message, Throwable throwable, int code, Map> responseHeaders, String responseBody) { - super(message, throwable); - this.code = code; - this.responseHeaders = responseHeaders; - this.responseBody = responseBody; - } + public ApiException(String message, Throwable throwable, int code, Map> responseHeaders, String responseBody) { + super(message, throwable); + this.code = code; + this.responseHeaders = responseHeaders; + this.responseBody = responseBody; + } - public ApiException(String message, int code, Map> responseHeaders, String responseBody) { - this(message, (Throwable) null, code, responseHeaders, responseBody); - } + public ApiException(String message, int code, Map> responseHeaders, String responseBody) { + this(message, (Throwable) null, code, responseHeaders, responseBody); + } - public ApiException(String message, Throwable throwable, int code, Map> responseHeaders) { - this(message, throwable, code, responseHeaders, null); - } + public ApiException(String message, Throwable throwable, int code, Map> responseHeaders) { + this(message, throwable, code, responseHeaders, null); + } - public ApiException(int code, Map> responseHeaders, String responseBody) { - this((String) null, (Throwable) null, code, responseHeaders, responseBody); - } + public ApiException(int code, Map> responseHeaders, String responseBody) { + this((String) null, (Throwable) null, code, responseHeaders, responseBody); + } - public ApiException(int code, String message) { - super(message); - this.code = code; - } + public ApiException(int code, String message) { + super(message); + this.code = code; + } - public ApiException(int code, String message, Map> responseHeaders, String responseBody) { - this(code, message); - this.responseHeaders = responseHeaders; - this.responseBody = responseBody; - } + public ApiException(int code, String message, Map> responseHeaders, String responseBody) { + this(code, message); + this.responseHeaders = responseHeaders; + this.responseBody = responseBody; + } - public int getCode() { - return code; - } + /** + * Get the HTTP status code. + * + * @return HTTP status code + */ + public int getCode() { + return code; + } - /** - * Get the HTTP response headers. - */ - public Map> getResponseHeaders() { - return responseHeaders; - } + /** + * Get the HTTP response headers. + * + * @return A map of list of string + */ + public Map> getResponseHeaders() { + return responseHeaders; + } - /** - * Get the HTTP response body. - */ - public String getResponseBody() { - return responseBody; - } + /** + * Get the HTTP response body. + * + * @return Response body in the form of string + */ + public String getResponseBody() { + return responseBody; + } } diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/Configuration.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/Configuration.java index 19b0ebeae4e..cbdadd6262d 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/Configuration.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/Configuration.java @@ -1,22 +1,51 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client; public class Configuration { - private static ApiClient defaultApiClient = new ApiClient(); + private static ApiClient defaultApiClient = new ApiClient(); - /** - * Get the default API client, which would be used when creating API - * instances without providing an API client. - */ - public static ApiClient getDefaultApiClient() { - return defaultApiClient; - } + /** + * Get the default API client, which would be used when creating API + * instances without providing an API client. + * + * @return Default API client + */ + public static ApiClient getDefaultApiClient() { + return defaultApiClient; + } - /** - * Set the default API client, which would be used when creating API - * instances without providing an API client. - */ - public static void setDefaultApiClient(ApiClient apiClient) { - defaultApiClient = apiClient; - } + /** + * Set the default API client, which would be used when creating API + * instances without providing an API client. + * + * @param apiClient API client + */ + public static void setDefaultApiClient(ApiClient apiClient) { + defaultApiClient = apiClient; + } } diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/Pair.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/Pair.java index d8d32210b10..4b44c415812 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/Pair.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/Pair.java @@ -1,3 +1,28 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client; diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/StringUtil.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/StringUtil.java index 1383dd0decb..03c6c81e434 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/StringUtil.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/StringUtil.java @@ -1,3 +1,28 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client; 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 40ee5e2774f..18ec9428c16 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 @@ -8,7 +8,8 @@ import io.swagger.client.Configuration; import io.swagger.client.model.*; import io.swagger.client.Pair; -import java.util.Date; +import org.joda.time.LocalDate; +import org.joda.time.DateTime; import java.math.BigDecimal; @@ -54,7 +55,7 @@ public class FakeApi { * @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 { + public void testEndpointParameters(BigDecimal number, Double _double, String string, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, byte[] binary, LocalDate date, DateTime dateTime, String password) throws ApiException { Object localVarPostBody = null; // verify the required parameter 'number' is set @@ -113,12 +114,12 @@ if (password != null) localVarFormParams.put("password", password); final String[] localVarAccepts = { - "application/xml", "application/json" + "application/xml; charset=utf-8", "application/json; charset=utf-8" }; final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] localVarContentTypes = { - + "application/xml; charset=utf-8", "application/json; charset=utf-8" }; final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/ApiKeyAuth.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/ApiKeyAuth.java index 6882dbc41c0..6ba15566b60 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/ApiKeyAuth.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/ApiKeyAuth.java @@ -1,3 +1,28 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.auth; import io.swagger.client.Pair; diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/Authentication.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/Authentication.java index 98b1a6900b9..a063a6998b5 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/Authentication.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/Authentication.java @@ -1,3 +1,28 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.auth; import io.swagger.client.Pair; @@ -6,6 +31,11 @@ import java.util.Map; import java.util.List; public interface Authentication { - /** Apply authentication settings to header and query params. */ - void applyToParams(List queryParams, Map headerParams); + /** + * Apply authentication settings to header and query params. + * + * @param queryParams List of query parameters + * @param headerParams Map of header parameters + */ + void applyToParams(List queryParams, Map headerParams); } diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/HttpBasicAuth.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/HttpBasicAuth.java index 64f2c887377..5895370e4d4 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/HttpBasicAuth.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/HttpBasicAuth.java @@ -1,3 +1,28 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.auth; import io.swagger.client.Pair; diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/OAuth.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/OAuth.java index 76d2917f24e..8802ebc92c8 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/OAuth.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/OAuth.java @@ -1,3 +1,28 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.auth; import io.swagger.client.Pair; diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/OAuthFlow.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/OAuthFlow.java index 597ec99b48b..ec1f942b0f2 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/OAuthFlow.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/OAuthFlow.java @@ -1,5 +1,30 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.auth; public enum OAuthFlow { accessCode, implicit, password, application -} \ No newline at end of file +} diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java new file mode 100644 index 00000000000..ccaba7709c4 --- /dev/null +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java @@ -0,0 +1,97 @@ +package io.swagger.client.model; + +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + + +/** + * AdditionalPropertiesClass + */ + +public class AdditionalPropertiesClass { + + private Map mapProperty = new HashMap(); + private Map> mapOfMapProperty = new HashMap>(); + + + /** + **/ + public AdditionalPropertiesClass mapProperty(Map mapProperty) { + this.mapProperty = mapProperty; + return this; + } + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("map_property") + public Map getMapProperty() { + return mapProperty; + } + public void setMapProperty(Map mapProperty) { + this.mapProperty = mapProperty; + } + + + /** + **/ + public AdditionalPropertiesClass mapOfMapProperty(Map> mapOfMapProperty) { + this.mapOfMapProperty = mapOfMapProperty; + return this; + } + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("map_of_map_property") + public Map> getMapOfMapProperty() { + return mapOfMapProperty; + } + public void setMapOfMapProperty(Map> mapOfMapProperty) { + this.mapOfMapProperty = mapOfMapProperty; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + AdditionalPropertiesClass additionalPropertiesClass = (AdditionalPropertiesClass) o; + return Objects.equals(this.mapProperty, additionalPropertiesClass.mapProperty) && + Objects.equals(this.mapOfMapProperty, additionalPropertiesClass.mapOfMapProperty); + } + + @Override + public int hashCode() { + return Objects.hash(mapProperty, mapOfMapProperty); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class AdditionalPropertiesClass {\n"); + + sb.append(" mapProperty: ").append(toIndentedString(mapProperty)).append("\n"); + sb.append(" mapOfMapProperty: ").append(toIndentedString(mapOfMapProperty)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Animal.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Animal.java index 365f0110b78..25c7d3e421c 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 @@ -14,6 +14,7 @@ import io.swagger.annotations.ApiModelProperty; public class Animal { private String className = null; + private String color = "red"; /** @@ -33,6 +34,23 @@ public class Animal { } + /** + **/ + public Animal color(String color) { + this.color = color; + return this; + } + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("color") + public String getColor() { + return color; + } + public void setColor(String color) { + this.color = color; + } + + @Override public boolean equals(java.lang.Object o) { if (this == o) { @@ -42,12 +60,13 @@ public class Animal { return false; } Animal animal = (Animal) o; - return Objects.equals(this.className, animal.className); + return Objects.equals(this.className, animal.className) && + Objects.equals(this.color, animal.color); } @Override public int hashCode() { - return Objects.hash(className); + return Objects.hash(className, color); } @Override @@ -56,6 +75,7 @@ public class Animal { sb.append("class Animal {\n"); sb.append(" className: ").append(toIndentedString(className)).append("\n"); + sb.append(" color: ").append(toIndentedString(color)).append("\n"); sb.append("}"); return sb.toString(); } diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/ArrayTest.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/ArrayTest.java new file mode 100644 index 00000000000..6c1eb23d8d0 --- /dev/null +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/ArrayTest.java @@ -0,0 +1,116 @@ +package io.swagger.client.model; + +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.util.ArrayList; +import java.util.List; + + +/** + * ArrayTest + */ + +public class ArrayTest { + + private List arrayOfString = new ArrayList(); + private List> arrayArrayOfInteger = new ArrayList>(); + private List> arrayArrayOfModel = new ArrayList>(); + + + /** + **/ + public ArrayTest arrayOfString(List arrayOfString) { + this.arrayOfString = arrayOfString; + return this; + } + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("array_of_string") + public List getArrayOfString() { + return arrayOfString; + } + public void setArrayOfString(List arrayOfString) { + this.arrayOfString = arrayOfString; + } + + + /** + **/ + public ArrayTest arrayArrayOfInteger(List> arrayArrayOfInteger) { + this.arrayArrayOfInteger = arrayArrayOfInteger; + return this; + } + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("array_array_of_integer") + public List> getArrayArrayOfInteger() { + return arrayArrayOfInteger; + } + public void setArrayArrayOfInteger(List> arrayArrayOfInteger) { + this.arrayArrayOfInteger = arrayArrayOfInteger; + } + + + /** + **/ + public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { + this.arrayArrayOfModel = arrayArrayOfModel; + return this; + } + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("array_array_of_model") + public List> getArrayArrayOfModel() { + return arrayArrayOfModel; + } + public void setArrayArrayOfModel(List> arrayArrayOfModel) { + this.arrayArrayOfModel = arrayArrayOfModel; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ArrayTest arrayTest = (ArrayTest) o; + return Objects.equals(this.arrayOfString, arrayTest.arrayOfString) && + Objects.equals(this.arrayArrayOfInteger, arrayTest.arrayArrayOfInteger) && + Objects.equals(this.arrayArrayOfModel, arrayTest.arrayArrayOfModel); + } + + @Override + public int hashCode() { + return Objects.hash(arrayOfString, arrayArrayOfInteger, arrayArrayOfModel); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ArrayTest {\n"); + + sb.append(" arrayOfString: ").append(toIndentedString(arrayOfString)).append("\n"); + sb.append(" arrayArrayOfInteger: ").append(toIndentedString(arrayArrayOfInteger)).append("\n"); + sb.append(" arrayArrayOfModel: ").append(toIndentedString(arrayArrayOfModel)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Cat.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Cat.java index 21c54aff204..5ef9e23bd96 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 @@ -15,6 +15,7 @@ import io.swagger.client.model.Animal; public class Cat extends Animal { private String className = null; + private String color = "red"; private Boolean declawed = null; @@ -35,6 +36,23 @@ public class Cat extends Animal { } + /** + **/ + public Cat color(String color) { + this.color = color; + return this; + } + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("color") + public String getColor() { + return color; + } + public void setColor(String color) { + this.color = color; + } + + /** **/ public Cat declawed(Boolean declawed) { @@ -62,13 +80,14 @@ public class Cat extends Animal { } Cat cat = (Cat) o; return Objects.equals(this.className, cat.className) && + Objects.equals(this.color, cat.color) && Objects.equals(this.declawed, cat.declawed) && super.equals(o); } @Override public int hashCode() { - return Objects.hash(className, declawed, super.hashCode()); + return Objects.hash(className, color, declawed, super.hashCode()); } @Override @@ -77,6 +96,7 @@ public class Cat extends Animal { sb.append("class Cat {\n"); sb.append(" ").append(toIndentedString(super.toString())).append("\n"); sb.append(" className: ").append(toIndentedString(className)).append("\n"); + sb.append(" color: ").append(toIndentedString(color)).append("\n"); sb.append(" declawed: ").append(toIndentedString(declawed)).append("\n"); sb.append("}"); return sb.toString(); diff --git a/samples/client/petstore/java/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 ed5581058c6..4b3cc947cc5 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 @@ -15,6 +15,7 @@ import io.swagger.client.model.Animal; public class Dog extends Animal { private String className = null; + private String color = "red"; private String breed = null; @@ -35,6 +36,23 @@ public class Dog extends Animal { } + /** + **/ + public Dog color(String color) { + this.color = color; + return this; + } + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("color") + public String getColor() { + return color; + } + public void setColor(String color) { + this.color = color; + } + + /** **/ public Dog breed(String breed) { @@ -62,13 +80,14 @@ public class Dog extends Animal { } Dog dog = (Dog) o; return Objects.equals(this.className, dog.className) && + Objects.equals(this.color, dog.color) && Objects.equals(this.breed, dog.breed) && super.equals(o); } @Override public int hashCode() { - return Objects.hash(className, breed, super.hashCode()); + return Objects.hash(className, color, breed, super.hashCode()); } @Override @@ -77,6 +96,7 @@ public class Dog extends Animal { sb.append("class Dog {\n"); sb.append(" ").append(toIndentedString(super.toString())).append("\n"); sb.append(" className: ").append(toIndentedString(className)).append("\n"); + sb.append(" color: ").append(toIndentedString(color)).append("\n"); sb.append(" breed: ").append(toIndentedString(breed)).append("\n"); sb.append("}"); return sb.toString(); diff --git a/samples/client/petstore/java/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 c01974880ae..79376150017 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 @@ -6,7 +6,8 @@ import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.math.BigDecimal; -import java.util.Date; +import org.joda.time.DateTime; +import org.joda.time.LocalDate; /** @@ -24,8 +25,8 @@ public class FormatTest { private String string = null; private byte[] _byte = null; private byte[] binary = null; - private Date date = null; - private Date dateTime = null; + private LocalDate date = null; + private DateTime dateTime = null; private String uuid = null; private String password = null; @@ -195,34 +196,34 @@ public class FormatTest { /** **/ - public FormatTest date(Date date) { + public FormatTest date(LocalDate date) { this.date = date; return this; } @ApiModelProperty(example = "null", required = true, value = "") @JsonProperty("date") - public Date getDate() { + public LocalDate getDate() { return date; } - public void setDate(Date date) { + public void setDate(LocalDate date) { this.date = date; } /** **/ - public FormatTest dateTime(Date dateTime) { + public FormatTest dateTime(DateTime dateTime) { this.dateTime = dateTime; return this; } @ApiModelProperty(example = "null", value = "") @JsonProperty("dateTime") - public Date getDateTime() { + public DateTime getDateTime() { return dateTime; } - public void setDateTime(Date dateTime) { + public void setDateTime(DateTime dateTime) { this.dateTime = dateTime; } diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java new file mode 100644 index 00000000000..2f0972bf41e --- /dev/null +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -0,0 +1,119 @@ +package io.swagger.client.model; + +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.client.model.Animal; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.joda.time.DateTime; + + +/** + * MixedPropertiesAndAdditionalPropertiesClass + */ + +public class MixedPropertiesAndAdditionalPropertiesClass { + + private String uuid = null; + private DateTime dateTime = null; + private Map map = new HashMap(); + + + /** + **/ + public MixedPropertiesAndAdditionalPropertiesClass uuid(String uuid) { + this.uuid = uuid; + return this; + } + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("uuid") + public String getUuid() { + return uuid; + } + public void setUuid(String uuid) { + this.uuid = uuid; + } + + + /** + **/ + public MixedPropertiesAndAdditionalPropertiesClass dateTime(DateTime dateTime) { + this.dateTime = dateTime; + return this; + } + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("dateTime") + public DateTime getDateTime() { + return dateTime; + } + public void setDateTime(DateTime dateTime) { + this.dateTime = dateTime; + } + + + /** + **/ + public MixedPropertiesAndAdditionalPropertiesClass map(Map map) { + this.map = map; + return this; + } + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("map") + public Map getMap() { + return map; + } + public void setMap(Map map) { + this.map = map; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + MixedPropertiesAndAdditionalPropertiesClass mixedPropertiesAndAdditionalPropertiesClass = (MixedPropertiesAndAdditionalPropertiesClass) o; + return Objects.equals(this.uuid, mixedPropertiesAndAdditionalPropertiesClass.uuid) && + Objects.equals(this.dateTime, mixedPropertiesAndAdditionalPropertiesClass.dateTime) && + Objects.equals(this.map, mixedPropertiesAndAdditionalPropertiesClass.map); + } + + @Override + public int hashCode() { + return Objects.hash(uuid, dateTime, map); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class MixedPropertiesAndAdditionalPropertiesClass {\n"); + + sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); + sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); + sb.append(" map: ").append(toIndentedString(map)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Name.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Name.java index 60b26b55658..1ba2cc5e4a3 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 @@ -17,6 +17,7 @@ public class Name { private Integer name = null; private Integer snakeCase = null; private String property = null; + private Integer _123Number = null; /** @@ -60,6 +61,13 @@ public class Name { } + @ApiModelProperty(example = "null", value = "") + @JsonProperty("123Number") + public Integer get123Number() { + return _123Number; + } + + @Override public boolean equals(java.lang.Object o) { if (this == o) { @@ -71,12 +79,13 @@ public class Name { Name name = (Name) o; return Objects.equals(this.name, name.name) && Objects.equals(this.snakeCase, name.snakeCase) && - Objects.equals(this.property, name.property); + Objects.equals(this.property, name.property) && + Objects.equals(this._123Number, name._123Number); } @Override public int hashCode() { - return Objects.hash(name, snakeCase, property); + return Objects.hash(name, snakeCase, property, _123Number); } @Override @@ -87,6 +96,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(" _123Number: ").append(toIndentedString(_123Number)).append("\n"); sb.append("}"); return sb.toString(); } 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 ed5739592a3..cec651e73a6 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 @@ -6,7 +6,7 @@ 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 org.joda.time.DateTime; /** @@ -18,7 +18,7 @@ public class Order { private Long id = null; private Long petId = null; private Integer quantity = null; - private Date shipDate = null; + private DateTime shipDate = null; /** * Order Status @@ -98,17 +98,17 @@ public class Order { /** **/ - public Order shipDate(Date shipDate) { + public Order shipDate(DateTime shipDate) { this.shipDate = shipDate; return this; } @ApiModelProperty(example = "null", value = "") @JsonProperty("shipDate") - public Date getShipDate() { + public DateTime getShipDate() { return shipDate; } - public void setShipDate(Date shipDate) { + public void setShipDate(DateTime shipDate) { this.shipDate = shipDate; } diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/ReadOnlyFirst.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/ReadOnlyFirst.java new file mode 100644 index 00000000000..fdc3587df0e --- /dev/null +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/ReadOnlyFirst.java @@ -0,0 +1,84 @@ +package io.swagger.client.model; + +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + + +/** + * ReadOnlyFirst + */ + +public class ReadOnlyFirst { + + private String bar = null; + private String baz = null; + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("bar") + public String getBar() { + return bar; + } + + + /** + **/ + public ReadOnlyFirst baz(String baz) { + this.baz = baz; + return this; + } + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("baz") + public String getBaz() { + return baz; + } + public void setBaz(String baz) { + this.baz = baz; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ReadOnlyFirst readOnlyFirst = (ReadOnlyFirst) o; + return Objects.equals(this.bar, readOnlyFirst.bar) && + Objects.equals(this.baz, readOnlyFirst.baz); + } + + @Override + public int hashCode() { + return Objects.hash(bar, baz); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ReadOnlyFirst {\n"); + + sb.append(" bar: ").append(toIndentedString(bar)).append("\n"); + sb.append(" baz: ").append(toIndentedString(baz)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java/default/src/test/java/io/swagger/client/ApiClientTest.java b/samples/client/petstore/java/default/src/test/java/io/swagger/client/ApiClientTest.java index 47f004c283b..19b55257d0c 100644 --- a/samples/client/petstore/java/default/src/test/java/io/swagger/client/ApiClientTest.java +++ b/samples/client/petstore/java/default/src/test/java/io/swagger/client/ApiClientTest.java @@ -111,6 +111,7 @@ public class ApiClientTest { } } + @Ignore("There is no more basic auth in petstore security definitions") @Test public void testSetUsernameAndPassword() { HttpBasicAuth auth = null; diff --git a/samples/client/petstore/java/default/src/test/java/io/swagger/client/api/PetApiTest.java b/samples/client/petstore/java/default/src/test/java/io/swagger/client/api/PetApiTest.java index c25e0d8bfa2..e75a9c7e7da 100644 --- a/samples/client/petstore/java/default/src/test/java/io/swagger/client/api/PetApiTest.java +++ b/samples/client/petstore/java/default/src/test/java/io/swagger/client/api/PetApiTest.java @@ -1,155 +1,306 @@ package io.swagger.client.api; -import io.swagger.client.ApiException; -import io.swagger.client.model.Pet; -import io.swagger.client.model.ModelApiResponse; -import java.io.File; -import org.junit.Test; +import com.fasterxml.jackson.annotation.*; +import com.fasterxml.jackson.databind.*; +import com.fasterxml.jackson.datatype.joda.*; +import io.swagger.TestUtils; + +import io.swagger.client.*; +import io.swagger.client.api.*; +import io.swagger.client.auth.*; +import io.swagger.client.model.*; + +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileWriter; import java.util.ArrayList; -import java.util.HashMap; +import java.util.Arrays; import java.util.List; import java.util.Map; -/** - * API tests for PetApi - */ +import org.junit.*; +import static org.junit.Assert.*; + public class PetApiTest { + private PetApi api; + private ObjectMapper mapper; - private final PetApi api = new PetApi(); - - - /** - * Add a new pet to the store - * - * - * - * @throws ApiException - * if the Api call fails - */ - @Test - public void addPetTest() throws ApiException { - Pet body = null; - // api.addPet(body); - - // TODO: test validations + @Before + public void setup() { + api = new PetApi(); + // setup authentication + ApiKeyAuth apiKeyAuth = (ApiKeyAuth) api.getApiClient().getAuthentication("api_key"); + apiKeyAuth.setApiKey("special-key"); } - - /** - * Deletes a pet - * - * - * - * @throws ApiException - * if the Api call fails - */ - @Test - public void deletePetTest() throws ApiException { - Long petId = null; - String apiKey = null; - // api.deletePet(petId, apiKey); - // TODO: test validations - } - - /** - * Finds Pets by status - * - * Multiple status values can be provided with comma separated strings - * - * @throws ApiException - * if the Api call fails - */ @Test - public void findPetsByStatusTest() throws ApiException { - List status = null; - // List response = api.findPetsByStatus(status); + public void testApiClient() { + // the default api client is used + assertEquals(Configuration.getDefaultApiClient(), api.getApiClient()); + assertNotNull(api.getApiClient()); + assertEquals("http://petstore.swagger.io/v2", api.getApiClient().getBasePath()); + assertFalse(api.getApiClient().isDebugging()); - // TODO: test validations + ApiClient oldClient = api.getApiClient(); + + ApiClient newClient = new ApiClient(); + newClient.setBasePath("http://example.com"); + newClient.setDebugging(true); + + // set api client via constructor + api = new PetApi(newClient); + assertNotNull(api.getApiClient()); + assertEquals("http://example.com", api.getApiClient().getBasePath()); + assertTrue(api.getApiClient().isDebugging()); + + // set api client via setter method + api.setApiClient(oldClient); + assertNotNull(api.getApiClient()); + assertEquals("http://petstore.swagger.io/v2", api.getApiClient().getBasePath()); + assertFalse(api.getApiClient().isDebugging()); } - - /** - * Finds Pets by tags - * - * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. - * - * @throws ApiException - * if the Api call fails - */ + @Test - public void findPetsByTagsTest() throws ApiException { - List tags = null; - // List response = api.findPetsByTags(tags); + public void testCreateAndGetPet() throws Exception { + Pet pet = createRandomPet(); + api.addPet(pet); - // TODO: test validations + Pet fetched = api.getPetById(pet.getId()); + assertNotNull(fetched); + assertEquals(pet.getId(), fetched.getId()); + assertNotNull(fetched.getCategory()); + assertEquals(fetched.getCategory().getName(), pet.getCategory().getName()); } - - /** - * Find pet by ID - * - * Returns a single pet - * - * @throws ApiException - * if the Api call fails - */ + + /* @Test - public void getPetByIdTest() throws ApiException { - Long petId = null; - // Pet response = api.getPetById(petId); + public void testCreateAndGetPetWithByteArray() throws Exception { + Pet pet = createRandomPet(); + byte[] bytes = serializeJson(pet).getBytes(); + api.addPetUsingByteArray(bytes); - // TODO: test validations + byte[] fetchedBytes = api.petPetIdtestingByteArraytrueGet(pet.getId()); + Pet fetched = deserializeJson(new String(fetchedBytes), Pet.class); + assertNotNull(fetched); + assertEquals(pet.getId(), fetched.getId()); + assertNotNull(fetched.getCategory()); + assertEquals(fetched.getCategory().getName(), pet.getCategory().getName()); } - - /** - * Update an existing pet - * - * - * - * @throws ApiException - * if the Api call fails - */ + @Test - public void updatePetTest() throws ApiException { - Pet body = null; - // api.updatePet(body); + public void testGetPetByIdInObject() throws Exception { + Pet pet = new Pet(); + pet.setId(TestUtils.nextId()); + pet.setName("pet " + pet.getId()); - // TODO: test validations + Category category = new Category(); + category.setId(TestUtils.nextId()); + category.setName("category " + category.getId()); + pet.setCategory(category); + + pet.setStatus(Pet.StatusEnum.PENDING); + List photos = Arrays.asList(new String[]{"http://foo.bar.com/1"}); + pet.setPhotoUrls(photos); + + api.addPet(pet); + + InlineResponse200 fetched = api.getPetByIdInObject(pet.getId()); + assertEquals(pet.getId(), fetched.getId()); + assertEquals(pet.getName(), fetched.getName()); + + Object categoryObj = fetched.getCategory(); + assertNotNull(categoryObj); + assertTrue(categoryObj instanceof Map); + + Map categoryMap = (Map) categoryObj; + Object categoryIdObj = categoryMap.get("id"); + assertTrue(categoryIdObj instanceof Integer); + Integer categoryIdInt = (Integer) categoryIdObj; + assertEquals(category.getId(), Long.valueOf(categoryIdInt)); + assertEquals(category.getName(), categoryMap.get("name")); } - - /** - * Updates a pet in the store with form data - * - * - * - * @throws ApiException - * if the Api call fails - */ + */ + @Test - public void updatePetWithFormTest() throws ApiException { - Long petId = null; - String name = null; - String status = null; - // api.updatePetWithForm(petId, name, status); + public void testUpdatePet() throws Exception { + Pet pet = createRandomPet(); + pet.setName("programmer"); - // TODO: test validations + api.updatePet(pet); + + Pet fetched = api.getPetById(pet.getId()); + assertNotNull(fetched); + assertEquals(pet.getId(), fetched.getId()); + assertNotNull(fetched.getCategory()); + assertEquals(fetched.getCategory().getName(), pet.getCategory().getName()); } - - /** - * uploads an image - * - * - * - * @throws ApiException - * if the Api call fails - */ + @Test - public void uploadFileTest() throws ApiException { - Long petId = null; - String additionalMetadata = null; - File file = null; - // ModelApiResponse response = api.uploadFile(petId, additionalMetadata, file); + public void testFindPetsByStatus() throws Exception { + Pet pet = createRandomPet(); + pet.setName("programmer"); + pet.setStatus(Pet.StatusEnum.AVAILABLE); - // TODO: test validations + api.updatePet(pet); + + List pets = api.findPetsByStatus(Arrays.asList(new String[]{"available"})); + assertNotNull(pets); + + boolean found = false; + for (Pet fetched : pets) { + if (fetched.getId().equals(pet.getId())) { + found = true; + break; + } + } + + assertTrue(found); + } + + @Test + public void testFindPetsByTags() throws Exception { + Pet pet = createRandomPet(); + pet.setName("monster"); + pet.setStatus(Pet.StatusEnum.AVAILABLE); + + List tags = new ArrayList(); + Tag tag1 = new Tag(); + tag1.setName("friendly"); + tags.add(tag1); + pet.setTags(tags); + + api.updatePet(pet); + + List pets = api.findPetsByTags(Arrays.asList(new String[]{"friendly"})); + assertNotNull(pets); + + boolean found = false; + for (Pet fetched : pets) { + if (fetched.getId().equals(pet.getId())) { + found = true; + break; + } + } + assertTrue(found); + } + + @Test + public void testUpdatePetWithForm() throws Exception { + Pet pet = createRandomPet(); + pet.setName("frank"); + api.addPet(pet); + + Pet fetched = api.getPetById(pet.getId()); + + api.updatePetWithForm(fetched.getId(), "furt", null); + Pet updated = api.getPetById(fetched.getId()); + + assertEquals(updated.getName(), "furt"); + } + + @Test + public void testDeletePet() throws Exception { + Pet pet = createRandomPet(); + api.addPet(pet); + + Pet fetched = api.getPetById(pet.getId()); + api.deletePet(fetched.getId(), null); + + try { + fetched = api.getPetById(fetched.getId()); + fail("expected an error"); + } catch (ApiException e) { + assertEquals(404, e.getCode()); + } + } + + @Test + public void testUploadFile() throws Exception { + Pet pet = createRandomPet(); + api.addPet(pet); + + File file = new File("hello.txt"); + BufferedWriter writer = new BufferedWriter(new FileWriter(file)); + writer.write("Hello world!"); + writer.close(); + + api.uploadFile(pet.getId(), "a test file", new File(file.getAbsolutePath())); + } + + @Test + public void testEqualsAndHashCode() { + Pet pet1 = new Pet(); + Pet pet2 = new Pet(); + assertTrue(pet1.equals(pet2)); + assertTrue(pet2.equals(pet1)); + assertTrue(pet1.hashCode() == pet2.hashCode()); + assertTrue(pet1.equals(pet1)); + assertTrue(pet1.hashCode() == pet1.hashCode()); + + pet2.setName("really-happy"); + pet2.setPhotoUrls(Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"})); + assertFalse(pet1.equals(pet2)); + assertFalse(pet2.equals(pet1)); + assertFalse(pet1.hashCode() == (pet2.hashCode())); + assertTrue(pet2.equals(pet2)); + assertTrue(pet2.hashCode() == pet2.hashCode()); + + pet1.setName("really-happy"); + pet1.setPhotoUrls(Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"})); + assertTrue(pet1.equals(pet2)); + assertTrue(pet2.equals(pet1)); + assertTrue(pet1.hashCode() == pet2.hashCode()); + assertTrue(pet1.equals(pet1)); + assertTrue(pet1.hashCode() == pet1.hashCode()); + } + + private Pet createRandomPet() { + Pet pet = new Pet(); + pet.setId(TestUtils.nextId()); + pet.setName("gorilla"); + + Category category = new Category(); + category.setName("really-happy"); + + pet.setCategory(category); + pet.setStatus(Pet.StatusEnum.AVAILABLE); + List photos = Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"}); + pet.setPhotoUrls(photos); + + return pet; + } + + private String serializeJson(Object o) { + if (mapper == null) { + mapper = createObjectMapper(); + } + try { + return mapper.writeValueAsString(o); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + private T deserializeJson(String json, Class klass) { + if (mapper == null) { + mapper = createObjectMapper(); + } + try { + return mapper.readValue(json, klass); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + private ObjectMapper createObjectMapper() { + ObjectMapper mapper = new ObjectMapper(); + mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); + mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING); + mapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING); + mapper.registerModule(new JodaModule()); + return mapper; } - } diff --git a/samples/client/petstore/java/default/src/test/java/io/swagger/client/api/StoreApiTest.java b/samples/client/petstore/java/default/src/test/java/io/swagger/client/api/StoreApiTest.java index 31abbbeae4e..51779f265f0 100644 --- a/samples/client/petstore/java/default/src/test/java/io/swagger/client/api/StoreApiTest.java +++ b/samples/client/petstore/java/default/src/test/java/io/swagger/client/api/StoreApiTest.java @@ -1,83 +1,103 @@ package io.swagger.client.api; +import io.swagger.TestUtils; + import io.swagger.client.ApiException; -import io.swagger.client.model.Order; -import org.junit.Test; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; +import io.swagger.client.*; +import io.swagger.client.api.*; +import io.swagger.client.auth.*; +import io.swagger.client.model.*; + +import java.lang.reflect.Field; import java.util.Map; +import java.text.SimpleDateFormat; + +import org.joda.time.DateTime; +import org.joda.time.DateTimeZone; +import org.junit.*; +import static org.junit.Assert.*; -/** - * API tests for StoreApi - */ public class StoreApiTest { + StoreApi api = null; - private final StoreApi api = new StoreApi(); - - - /** - * Delete purchase order by ID - * - * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors - * - * @throws ApiException - * if the Api call fails - */ - @Test - public void deleteOrderTest() throws ApiException { - String orderId = null; - // api.deleteOrder(orderId); - - // TODO: test validations + @Before + public void setup() { + api = new StoreApi(); + // setup authentication + ApiKeyAuth apiKeyAuth = (ApiKeyAuth) api.getApiClient().getAuthentication("api_key"); + apiKeyAuth.setApiKey("special-key"); + // set custom date format that is used by the petstore server + api.getApiClient().setDateFormat(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ")); } - - /** - * Returns pet inventories by status - * - * Returns a map of status codes to quantities - * - * @throws ApiException - * if the Api call fails - */ - @Test - public void getInventoryTest() throws ApiException { - // Map response = api.getInventory(); - // TODO: test validations - } - - /** - * Find purchase order by ID - * - * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - * - * @throws ApiException - * if the Api call fails - */ @Test - public void getOrderByIdTest() throws ApiException { - Long orderId = null; - // Order response = api.getOrderById(orderId); - - // TODO: test validations + public void testGetInventory() throws Exception { + Map inventory = api.getInventory(); + assertTrue(inventory.keySet().size() > 0); } - - /** - * Place an order for a pet - * - * - * - * @throws ApiException - * if the Api call fails - */ + + /* @Test - public void placeOrderTest() throws ApiException { - Order body = null; - // Order response = api.placeOrder(body); + public void testGetInventoryInObject() throws Exception { + Object inventoryObj = api.getInventoryInObject(); + assertTrue(inventoryObj instanceof Map); - // TODO: test validations + Map inventoryMap = (Map) inventoryObj; + assertTrue(inventoryMap.keySet().size() > 0); + + Map.Entry firstEntry = (Map.Entry) inventoryMap.entrySet().iterator().next(); + assertTrue(firstEntry.getKey() instanceof String); + assertTrue(firstEntry.getValue() instanceof Integer); + } + */ + + @Test + public void testPlaceOrder() throws Exception { + Order order = createOrder(); + api.placeOrder(order); + + Order fetched = api.getOrderById(order.getId()); + assertEquals(order.getId(), fetched.getId()); + assertEquals(order.getPetId(), fetched.getPetId()); + assertEquals(order.getQuantity(), fetched.getQuantity()); + assertEquals(order.getShipDate().withZone(DateTimeZone.UTC), fetched.getShipDate().withZone(DateTimeZone.UTC)); + } + + @Test + public void testDeleteOrder() throws Exception { + Order order = createOrder(); + api.placeOrder(order); + + Order fetched = api.getOrderById(order.getId()); + assertEquals(fetched.getId(), order.getId()); + + api.deleteOrder(String.valueOf(order.getId())); + + try { + api.getOrderById(order.getId()); + // fail("expected an error"); + } catch (ApiException e) { + // ok + } + } + + private Order createOrder() { + Order order = new Order(); + order.setPetId(new Long(200)); + order.setQuantity(new Integer(13)); + order.setShipDate(DateTime.now()); + order.setStatus(Order.StatusEnum.PLACED); + order.setComplete(true); + + try { + Field idField = Order.class.getDeclaredField("id"); + idField.setAccessible(true); + idField.set(order, TestUtils.nextId()); + } catch (Exception e) { + throw new RuntimeException(e); + } + + return order; } - } diff --git a/samples/client/petstore/java/default/src/test/java/io/swagger/client/api/UserApiTest.java b/samples/client/petstore/java/default/src/test/java/io/swagger/client/api/UserApiTest.java index 7e96762ff4e..c7fb92d2552 100644 --- a/samples/client/petstore/java/default/src/test/java/io/swagger/client/api/UserApiTest.java +++ b/samples/client/petstore/java/default/src/test/java/io/swagger/client/api/UserApiTest.java @@ -1,149 +1,88 @@ package io.swagger.client.api; -import io.swagger.client.ApiException; -import io.swagger.client.model.User; -import org.junit.Test; +import io.swagger.TestUtils; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; +import io.swagger.client.api.*; +import io.swagger.client.auth.*; +import io.swagger.client.model.*; + +import java.util.Arrays; + +import org.junit.*; +import static org.junit.Assert.*; -/** - * API tests for UserApi - */ public class UserApiTest { + UserApi api = null; - private final UserApi api = new UserApi(); - - - /** - * Create user - * - * This can only be done by the logged in user. - * - * @throws ApiException - * if the Api call fails - */ - @Test - public void createUserTest() throws ApiException { - User body = null; - // api.createUser(body); - - // TODO: test validations + @Before + public void setup() { + api = new UserApi(); + // setup authentication + ApiKeyAuth apiKeyAuth = (ApiKeyAuth) api.getApiClient().getAuthentication("api_key"); + apiKeyAuth.setApiKey("special-key"); } - - /** - * Creates list of users with given input array - * - * - * - * @throws ApiException - * if the Api call fails - */ - @Test - public void createUsersWithArrayInputTest() throws ApiException { - List body = null; - // api.createUsersWithArrayInput(body); - // TODO: test validations - } - - /** - * Creates list of users with given input array - * - * - * - * @throws ApiException - * if the Api call fails - */ @Test - public void createUsersWithListInputTest() throws ApiException { - List body = null; - // api.createUsersWithListInput(body); + public void testCreateUser() throws Exception { + User user = createUser(); - // TODO: test validations + api.createUser(user); + + User fetched = api.getUserByName(user.getUsername()); + assertEquals(user.getId(), fetched.getId()); } - - /** - * Delete user - * - * This can only be done by the logged in user. - * - * @throws ApiException - * if the Api call fails - */ + @Test - public void deleteUserTest() throws ApiException { - String username = null; - // api.deleteUser(username); + public void testCreateUsersWithArray() throws Exception { + User user1 = createUser(); + user1.setUsername("user" + user1.getId()); + User user2 = createUser(); + user2.setUsername("user" + user2.getId()); - // TODO: test validations + api.createUsersWithArrayInput(Arrays.asList(new User[]{user1, user2})); + + User fetched = api.getUserByName(user1.getUsername()); + assertEquals(user1.getId(), fetched.getId()); } - - /** - * Get user by user name - * - * - * - * @throws ApiException - * if the Api call fails - */ + @Test - public void getUserByNameTest() throws ApiException { - String username = null; - // User response = api.getUserByName(username); + public void testCreateUsersWithList() throws Exception { + User user1 = createUser(); + user1.setUsername("user" + user1.getId()); + User user2 = createUser(); + user2.setUsername("user" + user2.getId()); - // TODO: test validations + api.createUsersWithListInput(Arrays.asList(new User[]{user1, user2})); + + User fetched = api.getUserByName(user1.getUsername()); + assertEquals(user1.getId(), fetched.getId()); } - - /** - * Logs user into the system - * - * - * - * @throws ApiException - * if the Api call fails - */ + @Test - public void loginUserTest() throws ApiException { - String username = null; - String password = null; - // String response = api.loginUser(username, password); + public void testLoginUser() throws Exception { + User user = createUser(); + api.createUser(user); - // TODO: test validations + String token = api.loginUser(user.getUsername(), user.getPassword()); + assertTrue(token.startsWith("logged in user session:")); } - - /** - * Logs out current logged in user session - * - * - * - * @throws ApiException - * if the Api call fails - */ + @Test - public void logoutUserTest() throws ApiException { - // api.logoutUser(); - - // TODO: test validations + public void logoutUser() throws Exception { + api.logoutUser(); } - - /** - * Updated user - * - * This can only be done by the logged in user. - * - * @throws ApiException - * if the Api call fails - */ - @Test - public void updateUserTest() throws ApiException { - String username = null; - User body = null; - // api.updateUser(username, body); - // TODO: test validations + private User createUser() { + User user = new User(); + user.setId(TestUtils.nextId()); + user.setUsername("fred" + user.getId()); + user.setFirstName("Fred"); + user.setLastName("Meyer"); + user.setEmail("fred@fredmeyer.com"); + user.setPassword("xxXXxx"); + user.setPhone("408-867-5309"); + user.setUserStatus(123); + + return user; } - } diff --git a/samples/client/petstore/java/default/src/test/java/io/swagger/petstore/test/PetApiTest.java b/samples/client/petstore/java/default/src/test/java/io/swagger/petstore/test/PetApiTest.java deleted file mode 100644 index 9e927a69ba2..00000000000 --- a/samples/client/petstore/java/default/src/test/java/io/swagger/petstore/test/PetApiTest.java +++ /dev/null @@ -1,306 +0,0 @@ -package io.swagger.petstore.test; - -import com.fasterxml.jackson.annotation.*; -import com.fasterxml.jackson.databind.*; -import com.fasterxml.jackson.datatype.joda.*; - -import io.swagger.TestUtils; - -import io.swagger.client.*; -import io.swagger.client.api.*; -import io.swagger.client.auth.*; -import io.swagger.client.model.*; - -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileWriter; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Map; - -import org.junit.*; -import static org.junit.Assert.*; - -public class PetApiTest { - private PetApi api; - private ObjectMapper mapper; - - @Before - public void setup() { - api = new PetApi(); - // setup authentication - ApiKeyAuth apiKeyAuth = (ApiKeyAuth) api.getApiClient().getAuthentication("api_key"); - apiKeyAuth.setApiKey("special-key"); - } - - @Test - public void testApiClient() { - // the default api client is used - assertEquals(Configuration.getDefaultApiClient(), api.getApiClient()); - assertNotNull(api.getApiClient()); - assertEquals("http://petstore.swagger.io/v2", api.getApiClient().getBasePath()); - assertFalse(api.getApiClient().isDebugging()); - - ApiClient oldClient = api.getApiClient(); - - ApiClient newClient = new ApiClient(); - newClient.setBasePath("http://example.com"); - newClient.setDebugging(true); - - // set api client via constructor - api = new PetApi(newClient); - assertNotNull(api.getApiClient()); - assertEquals("http://example.com", api.getApiClient().getBasePath()); - assertTrue(api.getApiClient().isDebugging()); - - // set api client via setter method - api.setApiClient(oldClient); - assertNotNull(api.getApiClient()); - assertEquals("http://petstore.swagger.io/v2", api.getApiClient().getBasePath()); - assertFalse(api.getApiClient().isDebugging()); - } - - @Test - public void testCreateAndGetPet() throws Exception { - Pet pet = createRandomPet(); - api.addPet(pet); - - Pet fetched = api.getPetById(pet.getId()); - assertNotNull(fetched); - assertEquals(pet.getId(), fetched.getId()); - assertNotNull(fetched.getCategory()); - assertEquals(fetched.getCategory().getName(), pet.getCategory().getName()); - } - - /* - @Test - public void testCreateAndGetPetWithByteArray() throws Exception { - Pet pet = createRandomPet(); - byte[] bytes = serializeJson(pet).getBytes(); - api.addPetUsingByteArray(bytes); - - byte[] fetchedBytes = api.petPetIdtestingByteArraytrueGet(pet.getId()); - Pet fetched = deserializeJson(new String(fetchedBytes), Pet.class); - assertNotNull(fetched); - assertEquals(pet.getId(), fetched.getId()); - assertNotNull(fetched.getCategory()); - assertEquals(fetched.getCategory().getName(), pet.getCategory().getName()); - } - - @Test - public void testGetPetByIdInObject() throws Exception { - Pet pet = new Pet(); - pet.setId(TestUtils.nextId()); - pet.setName("pet " + pet.getId()); - - Category category = new Category(); - category.setId(TestUtils.nextId()); - category.setName("category " + category.getId()); - pet.setCategory(category); - - pet.setStatus(Pet.StatusEnum.PENDING); - List photos = Arrays.asList(new String[]{"http://foo.bar.com/1"}); - pet.setPhotoUrls(photos); - - api.addPet(pet); - - InlineResponse200 fetched = api.getPetByIdInObject(pet.getId()); - assertEquals(pet.getId(), fetched.getId()); - assertEquals(pet.getName(), fetched.getName()); - - Object categoryObj = fetched.getCategory(); - assertNotNull(categoryObj); - assertTrue(categoryObj instanceof Map); - - Map categoryMap = (Map) categoryObj; - Object categoryIdObj = categoryMap.get("id"); - assertTrue(categoryIdObj instanceof Integer); - Integer categoryIdInt = (Integer) categoryIdObj; - assertEquals(category.getId(), Long.valueOf(categoryIdInt)); - assertEquals(category.getName(), categoryMap.get("name")); - } - */ - - @Test - public void testUpdatePet() throws Exception { - Pet pet = createRandomPet(); - pet.setName("programmer"); - - api.updatePet(pet); - - Pet fetched = api.getPetById(pet.getId()); - assertNotNull(fetched); - assertEquals(pet.getId(), fetched.getId()); - assertNotNull(fetched.getCategory()); - assertEquals(fetched.getCategory().getName(), pet.getCategory().getName()); - } - - @Test - public void testFindPetsByStatus() throws Exception { - Pet pet = createRandomPet(); - pet.setName("programmer"); - pet.setStatus(Pet.StatusEnum.AVAILABLE); - - api.updatePet(pet); - - List pets = api.findPetsByStatus(Arrays.asList(new String[]{"available"})); - assertNotNull(pets); - - boolean found = false; - for (Pet fetched : pets) { - if (fetched.getId().equals(pet.getId())) { - found = true; - break; - } - } - - assertTrue(found); - } - - @Test - public void testFindPetsByTags() throws Exception { - Pet pet = createRandomPet(); - pet.setName("monster"); - pet.setStatus(Pet.StatusEnum.AVAILABLE); - - List tags = new ArrayList(); - Tag tag1 = new Tag(); - tag1.setName("friendly"); - tags.add(tag1); - pet.setTags(tags); - - api.updatePet(pet); - - List pets = api.findPetsByTags(Arrays.asList(new String[]{"friendly"})); - assertNotNull(pets); - - boolean found = false; - for (Pet fetched : pets) { - if (fetched.getId().equals(pet.getId())) { - found = true; - break; - } - } - assertTrue(found); - } - - @Test - public void testUpdatePetWithForm() throws Exception { - Pet pet = createRandomPet(); - pet.setName("frank"); - api.addPet(pet); - - Pet fetched = api.getPetById(pet.getId()); - - api.updatePetWithForm(fetched.getId(), "furt", null); - Pet updated = api.getPetById(fetched.getId()); - - assertEquals(updated.getName(), "furt"); - } - - @Test - public void testDeletePet() throws Exception { - Pet pet = createRandomPet(); - api.addPet(pet); - - Pet fetched = api.getPetById(pet.getId()); - api.deletePet(fetched.getId(), null); - - try { - fetched = api.getPetById(fetched.getId()); - fail("expected an error"); - } catch (ApiException e) { - assertEquals(404, e.getCode()); - } - } - - @Test - public void testUploadFile() throws Exception { - Pet pet = createRandomPet(); - api.addPet(pet); - - File file = new File("hello.txt"); - BufferedWriter writer = new BufferedWriter(new FileWriter(file)); - writer.write("Hello world!"); - writer.close(); - - api.uploadFile(pet.getId(), "a test file", new File(file.getAbsolutePath())); - } - - @Test - public void testEqualsAndHashCode() { - Pet pet1 = new Pet(); - Pet pet2 = new Pet(); - assertTrue(pet1.equals(pet2)); - assertTrue(pet2.equals(pet1)); - assertTrue(pet1.hashCode() == pet2.hashCode()); - assertTrue(pet1.equals(pet1)); - assertTrue(pet1.hashCode() == pet1.hashCode()); - - pet2.setName("really-happy"); - pet2.setPhotoUrls(Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"})); - assertFalse(pet1.equals(pet2)); - assertFalse(pet2.equals(pet1)); - assertFalse(pet1.hashCode() == (pet2.hashCode())); - assertTrue(pet2.equals(pet2)); - assertTrue(pet2.hashCode() == pet2.hashCode()); - - pet1.setName("really-happy"); - pet1.setPhotoUrls(Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"})); - assertTrue(pet1.equals(pet2)); - assertTrue(pet2.equals(pet1)); - assertTrue(pet1.hashCode() == pet2.hashCode()); - assertTrue(pet1.equals(pet1)); - assertTrue(pet1.hashCode() == pet1.hashCode()); - } - - private Pet createRandomPet() { - Pet pet = new Pet(); - pet.setId(TestUtils.nextId()); - pet.setName("gorilla"); - - Category category = new Category(); - category.setName("really-happy"); - - pet.setCategory(category); - pet.setStatus(Pet.StatusEnum.AVAILABLE); - List photos = Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"}); - pet.setPhotoUrls(photos); - - return pet; - } - - private String serializeJson(Object o) { - if (mapper == null) { - mapper = createObjectMapper(); - } - try { - return mapper.writeValueAsString(o); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - - private T deserializeJson(String json, Class klass) { - if (mapper == null) { - mapper = createObjectMapper(); - } - try { - return mapper.readValue(json, klass); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - - private ObjectMapper createObjectMapper() { - ObjectMapper mapper = new ObjectMapper(); - mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); - mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING); - mapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING); - mapper.registerModule(new JodaModule()); - return mapper; - } -} diff --git a/samples/client/petstore/java/default/src/test/java/io/swagger/petstore/test/StoreApiTest.java b/samples/client/petstore/java/default/src/test/java/io/swagger/petstore/test/StoreApiTest.java deleted file mode 100644 index 4b33d380f14..00000000000 --- a/samples/client/petstore/java/default/src/test/java/io/swagger/petstore/test/StoreApiTest.java +++ /dev/null @@ -1,100 +0,0 @@ -package io.swagger.petstore.test; - -import io.swagger.TestUtils; - -import io.swagger.client.ApiException; - -import io.swagger.client.*; -import io.swagger.client.api.*; -import io.swagger.client.auth.*; -import io.swagger.client.model.*; - -import java.lang.reflect.Field; -import java.util.Map; -import java.text.SimpleDateFormat; - -import org.junit.*; -import static org.junit.Assert.*; - -public class StoreApiTest { - StoreApi api = null; - - @Before - public void setup() { - api = new StoreApi(); - // setup authentication - ApiKeyAuth apiKeyAuth = (ApiKeyAuth) api.getApiClient().getAuthentication("api_key"); - apiKeyAuth.setApiKey("special-key"); - // set custom date format that is used by the petstore server - api.getApiClient().setDateFormat(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ")); - } - - @Test - public void testGetInventory() throws Exception { - Map inventory = api.getInventory(); - assertTrue(inventory.keySet().size() > 0); - } - - /* - @Test - public void testGetInventoryInObject() throws Exception { - Object inventoryObj = api.getInventoryInObject(); - assertTrue(inventoryObj instanceof Map); - - Map inventoryMap = (Map) inventoryObj; - assertTrue(inventoryMap.keySet().size() > 0); - - Map.Entry firstEntry = (Map.Entry) inventoryMap.entrySet().iterator().next(); - assertTrue(firstEntry.getKey() instanceof String); - assertTrue(firstEntry.getValue() instanceof Integer); - } - */ - - @Test - public void testPlaceOrder() throws Exception { - Order order = createOrder(); - api.placeOrder(order); - - Order fetched = api.getOrderById(order.getId()); - assertEquals(order.getId(), fetched.getId()); - assertEquals(order.getPetId(), fetched.getPetId()); - assertEquals(order.getQuantity(), fetched.getQuantity()); - } - - @Test - public void testDeleteOrder() throws Exception { - Order order = createOrder(); - api.placeOrder(order); - - Order fetched = api.getOrderById(order.getId()); - assertEquals(fetched.getId(), order.getId()); - - api.deleteOrder(String.valueOf(order.getId())); - - try { - api.getOrderById(order.getId()); - // fail("expected an error"); - } catch (ApiException e) { - // ok - } - } - - private Order createOrder() { - Order order = new Order(); - order.setPetId(new Long(200)); - order.setQuantity(new Integer(13)); - order.setShipDate(new java.util.Date()); - order.setStatus(Order.StatusEnum.PLACED); - order.setComplete(true); - - try { - Field idField = Order.class.getDeclaredField("id"); - idField.setAccessible(true); - idField.set(order, TestUtils.nextId()); - } catch (Exception e) { - throw new RuntimeException(e); - } - - return order; - } -} diff --git a/samples/client/petstore/java/default/src/test/java/io/swagger/petstore/test/UserApiTest.java b/samples/client/petstore/java/default/src/test/java/io/swagger/petstore/test/UserApiTest.java deleted file mode 100644 index 195e5c1e861..00000000000 --- a/samples/client/petstore/java/default/src/test/java/io/swagger/petstore/test/UserApiTest.java +++ /dev/null @@ -1,88 +0,0 @@ -package io.swagger.petstore.test; - -import io.swagger.TestUtils; - -import io.swagger.client.api.*; -import io.swagger.client.auth.*; -import io.swagger.client.model.*; - -import java.util.Arrays; - -import org.junit.*; -import static org.junit.Assert.*; - -public class UserApiTest { - UserApi api = null; - - @Before - public void setup() { - api = new UserApi(); - // setup authentication - ApiKeyAuth apiKeyAuth = (ApiKeyAuth) api.getApiClient().getAuthentication("api_key"); - apiKeyAuth.setApiKey("special-key"); - } - - @Test - public void testCreateUser() throws Exception { - User user = createUser(); - - api.createUser(user); - - User fetched = api.getUserByName(user.getUsername()); - assertEquals(user.getId(), fetched.getId()); - } - - @Test - public void testCreateUsersWithArray() throws Exception { - User user1 = createUser(); - user1.setUsername("user" + user1.getId()); - User user2 = createUser(); - user2.setUsername("user" + user2.getId()); - - api.createUsersWithArrayInput(Arrays.asList(new User[]{user1, user2})); - - User fetched = api.getUserByName(user1.getUsername()); - assertEquals(user1.getId(), fetched.getId()); - } - - @Test - public void testCreateUsersWithList() throws Exception { - User user1 = createUser(); - user1.setUsername("user" + user1.getId()); - User user2 = createUser(); - user2.setUsername("user" + user2.getId()); - - api.createUsersWithListInput(Arrays.asList(new User[]{user1, user2})); - - User fetched = api.getUserByName(user1.getUsername()); - assertEquals(user1.getId(), fetched.getId()); - } - - @Test - public void testLoginUser() throws Exception { - User user = createUser(); - api.createUser(user); - - String token = api.loginUser(user.getUsername(), user.getPassword()); - assertTrue(token.startsWith("logged in user session:")); - } - - @Test - public void logoutUser() throws Exception { - api.logoutUser(); - } - - private User createUser() { - User user = new User(); - user.setId(TestUtils.nextId()); - user.setUsername("fred" + user.getId()); - user.setFirstName("Fred"); - user.setLastName("Meyer"); - user.setEmail("fred@fredmeyer.com"); - user.setPassword("xxXXxx"); - user.setPhone("408-867-5309"); - user.setUserStatus(123); - - return user; - } -} diff --git a/samples/client/petstore/java/feign/build.sbt b/samples/client/petstore/java/feign/build.sbt new file mode 100644 index 00000000000..344d5538317 --- /dev/null +++ b/samples/client/petstore/java/feign/build.sbt @@ -0,0 +1,26 @@ +lazy val root = (project in file(".")). + settings( + organization := "io.swagger", + name := "swagger-petstore-feign", + version := "1.0.0", + scalaVersion := "2.11.4", + scalacOptions ++= Seq("-feature"), + javacOptions in compile ++= Seq("-Xlint:deprecation"), + publishArtifact in (Compile, packageDoc) := false, + resolvers += Resolver.mavenLocal, + libraryDependencies ++= Seq( + "io.swagger" % "swagger-annotations" % "1.5.8" % "compile", + "com.netflix.feign" % "feign-core" % "8.16.0" % "compile", + "com.netflix.feign" % "feign-jackson" % "8.16.0" % "compile", + "com.netflix.feign" % "feign-slf4j" % "8.16.0" % "compile", + "com.fasterxml.jackson.core" % "jackson-core" % "2.7.0" % "compile", + "com.fasterxml.jackson.core" % "jackson-annotations" % "2.7.0" % "compile", + "com.fasterxml.jackson.core" % "jackson-databind" % "2.7.0" % "compile", + "com.fasterxml.jackson.datatype" % "jackson-datatype-joda" % "2.1.5" % "compile", + "joda-time" % "joda-time" % "2.9.3" % "compile", + "org.apache.oltu.oauth2" % "org.apache.oltu.oauth2.client" % "1.0.1" % "compile", + "com.brsanthu" % "migbase64" % "2.2" % "compile", + "junit" % "junit" % "4.12" % "test", + "com.novocode" % "junit-interface" % "0.10" % "test" + ) + ) diff --git a/samples/client/petstore/java/feign/pom.xml b/samples/client/petstore/java/feign/pom.xml index 164399be4a6..6d055959b5e 100644 --- a/samples/client/petstore/java/feign/pom.xml +++ b/samples/client/petstore/java/feign/pom.xml @@ -100,8 +100,8 @@ maven-compiler-plugin 2.3.2 - 1.6 - 1.6 + 1.7 + 1.7 @@ -149,19 +149,7 @@ com.fasterxml.jackson.datatype jackson-datatype-joda - 2.1.5 - - - joda-time - joda-time - ${jodatime-version} - - - - - com.brsanthu - migbase64 - 2.2 + ${jackson-version} diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/ApiClient.java index 303927d064e..75b3a96f2c7 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/ApiClient.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/ApiClient.java @@ -9,6 +9,7 @@ import org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuil import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; +import com.fasterxml.jackson.datatype.joda.JodaModule; import feign.Feign; import feign.RequestInterceptor; @@ -18,11 +19,11 @@ import feign.slf4j.Slf4jLogger; import io.swagger.client.auth.*; import io.swagger.client.auth.OAuth.AccessTokenListener; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-02-17T17:16:23.375+08:00") + public class ApiClient { public interface Api {} - private ObjectMapper objectMapper; + protected ObjectMapper objectMapper; private String basePath = "http://petstore.swagger.io/v2"; private Map apiAuthorizations; private Feign.Builder feignBuilder; @@ -42,16 +43,8 @@ public class ApiClient { RequestInterceptor auth; if (authName == "petstore_auth") { auth = new OAuth(OAuthFlow.implicit, "http://petstore.swagger.io/api/oauth/dialog", "", "write:pets, read:pets"); - } else if (authName == "test_api_client_id") { - auth = new ApiKeyAuth("header", "x-test_api_client_id"); - } else if (authName == "test_api_client_secret") { - auth = new ApiKeyAuth("header", "x-test_api_client_secret"); } else if (authName == "api_key") { auth = new ApiKeyAuth("header", "api_key"); - } else if (authName == "test_api_key_query") { - auth = new ApiKeyAuth("query", "test_api_key_query"); - } else if (authName == "test_api_key_header") { - auth = new ApiKeyAuth("header", "test_api_key_header"); } else { throw new RuntimeException("auth name \"" + authName + "\" not found in available auth names"); } @@ -135,6 +128,13 @@ public class ApiClient { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING); objectMapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING); + objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); + objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); + objectMapper.registerModule(new JodaModule()); + return objectMapper; + } + + public ObjectMapper getObjectMapper(){ return objectMapper; } diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/FormAwareEncoder.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/FormAwareEncoder.java index 0ed60ea489a..179a2834da9 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/FormAwareEncoder.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/FormAwareEncoder.java @@ -14,7 +14,7 @@ import feign.codec.EncodeException; import feign.codec.Encoder; import feign.RequestTemplate; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-31T18:50:49.249+02:00") + public class FormAwareEncoder implements Encoder { public static final String UTF_8 = "utf-8"; private static final String LINE_FEED = "\r\n"; diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/StringUtil.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/StringUtil.java index 6c316df3516..1383dd0decb 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/StringUtil.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/StringUtil.java @@ -1,6 +1,6 @@ package io.swagger.client; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-31T18:50:49.249+02:00") + public class StringUtil { /** * Check if the given array contains the given value (with case-insensitive comparison). diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/FakeApi.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/FakeApi.java index 4874476628b..dbabdc64995 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,8 +2,9 @@ package io.swagger.client.api; import io.swagger.client.ApiClient; +import org.joda.time.LocalDate; import java.math.BigDecimal; -import java.util.Date; +import org.joda.time.DateTime; import java.util.ArrayList; import java.util.HashMap; @@ -11,7 +12,7 @@ import java.util.List; import java.util.Map; import feign.*; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-31T18:50:49.249+02:00") + public interface FakeApi extends ApiClient.Api { @@ -37,5 +38,5 @@ public interface FakeApi extends ApiClient.Api { "Content-type: application/xml; charset=utf-8", "Accept: application/xml; charset=utf-8,application/json; charset=utf-8", }) - void testEndpointParameters(@Param("number") BigDecimal number, @Param("_double") Double _double, @Param("string") String string, @Param("_byte") byte[] _byte, @Param("integer") Integer integer, @Param("int32") Integer int32, @Param("int64") Long int64, @Param("_float") Float _float, @Param("binary") byte[] binary, @Param("date") 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") LocalDate date, @Param("dateTime") DateTime dateTime, @Param("password") String password); } diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/PetApi.java index 330838eb0a0..e486495c5a9 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/PetApi.java @@ -12,7 +12,7 @@ import java.util.List; import java.util.Map; import feign.*; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-31T18:50:49.249+02:00") + public interface PetApi extends ApiClient.Api { diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/StoreApi.java index 2ff088ba096..ee80acba0b4 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/StoreApi.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/StoreApi.java @@ -10,7 +10,7 @@ import java.util.List; import java.util.Map; import feign.*; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-31T18:50:49.249+02:00") + public interface StoreApi extends ApiClient.Api { diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/UserApi.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/UserApi.java index c2e63a1a48c..6a2c8a6afb1 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/UserApi.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/UserApi.java @@ -10,7 +10,7 @@ import java.util.List; import java.util.Map; import feign.*; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-31T18:50:49.249+02:00") + public interface UserApi extends ApiClient.Api { diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java index 4a7155f2b6a..ccaba7709c4 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java @@ -13,7 +13,7 @@ import java.util.Map; /** * AdditionalPropertiesClass */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-31T18:50:49.249+02:00") + public class AdditionalPropertiesClass { private Map mapProperty = new HashMap(); diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Animal.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Animal.java index 1b350d588c9..25c7d3e421c 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Animal.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Animal.java @@ -10,7 +10,7 @@ import io.swagger.annotations.ApiModelProperty; /** * Animal */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-31T18:50:49.249+02:00") + public class Animal { private String className = null; diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/AnimalFarm.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/AnimalFarm.java index e1ded299373..647e3a893e1 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/AnimalFarm.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/AnimalFarm.java @@ -10,7 +10,7 @@ import java.util.List; /** * AnimalFarm */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-31T18:50:49.249+02:00") + public class AnimalFarm extends ArrayList { diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ArrayTest.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ArrayTest.java index 79b7694b6d3..6c1eb23d8d0 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ArrayTest.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ArrayTest.java @@ -12,7 +12,7 @@ import java.util.List; /** * ArrayTest */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-31T18:50:49.249+02:00") + public class ArrayTest { private List arrayOfString = new ArrayList(); diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Cat.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Cat.java index 4302c3b25ea..5ef9e23bd96 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Cat.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Cat.java @@ -11,7 +11,7 @@ import io.swagger.client.model.Animal; /** * Cat */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-31T18:50:49.249+02:00") + public class Cat extends Animal { private String className = null; diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Category.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Category.java index f87abb520f4..c6cb703a89e 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Category.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Category.java @@ -10,7 +10,7 @@ import io.swagger.annotations.ApiModelProperty; /** * Category */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-31T18:50:49.249+02:00") + public class Category { private Long id = null; diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Dog.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Dog.java index 84f5e702797..4b3cc947cc5 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Dog.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Dog.java @@ -11,7 +11,7 @@ import io.swagger.client.model.Animal; /** * Dog */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-31T18:50:49.249+02:00") + public class Dog extends Animal { private String className = null; diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/EnumTest.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/EnumTest.java index 8d11a05968f..1c8657fd3ec 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/EnumTest.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/EnumTest.java @@ -11,7 +11,7 @@ import io.swagger.annotations.ApiModelProperty; /** * EnumTest */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-31T18:50:49.249+02:00") + public class EnumTest { 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 c4d9d9d3279..79376150017 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 @@ -6,13 +6,14 @@ import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.math.BigDecimal; -import java.util.Date; +import org.joda.time.DateTime; +import org.joda.time.LocalDate; /** * FormatTest */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-31T18:50:49.249+02:00") + public class FormatTest { private Integer integer = null; @@ -24,8 +25,8 @@ public class FormatTest { private String string = null; private byte[] _byte = null; private byte[] binary = null; - private Date date = null; - private Date dateTime = null; + private LocalDate date = null; + private DateTime dateTime = null; private String uuid = null; private String password = null; @@ -195,34 +196,34 @@ public class FormatTest { /** **/ - public FormatTest date(Date date) { + public FormatTest date(LocalDate date) { this.date = date; return this; } @ApiModelProperty(example = "null", required = true, value = "") @JsonProperty("date") - public Date getDate() { + public LocalDate getDate() { return date; } - public void setDate(Date date) { + public void setDate(LocalDate date) { this.date = date; } /** **/ - public FormatTest dateTime(Date dateTime) { + public FormatTest dateTime(DateTime dateTime) { this.dateTime = dateTime; return this; } @ApiModelProperty(example = "null", value = "") @JsonProperty("dateTime") - public Date getDateTime() { + public DateTime getDateTime() { return dateTime; } - public void setDateTime(Date dateTime) { + public void setDateTime(DateTime dateTime) { this.dateTime = dateTime; } diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java index 598ed2ccce3..2f0972bf41e 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -6,20 +6,20 @@ import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import io.swagger.client.model.Animal; -import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; +import org.joda.time.DateTime; /** * MixedPropertiesAndAdditionalPropertiesClass */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-31T18:50:49.249+02:00") + public class MixedPropertiesAndAdditionalPropertiesClass { private String uuid = null; - private Date dateTime = null; + private DateTime dateTime = null; private Map map = new HashMap(); @@ -42,17 +42,17 @@ public class MixedPropertiesAndAdditionalPropertiesClass { /** **/ - public MixedPropertiesAndAdditionalPropertiesClass dateTime(Date dateTime) { + public MixedPropertiesAndAdditionalPropertiesClass dateTime(DateTime dateTime) { this.dateTime = dateTime; return this; } @ApiModelProperty(example = "null", value = "") @JsonProperty("dateTime") - public Date getDateTime() { + public DateTime getDateTime() { return dateTime; } - public void setDateTime(Date dateTime) { + public void setDateTime(DateTime dateTime) { this.dateTime = dateTime; } diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Model200Response.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Model200Response.java index 59aa3011fb9..b2809525c7f 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Model200Response.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Model200Response.java @@ -11,7 +11,7 @@ import io.swagger.annotations.ApiModelProperty; * Model for testing model name starting with number */ @ApiModel(description = "Model for testing model name starting with number") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-31T18:50:49.249+02:00") + public class Model200Response { private Integer name = null; diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ModelApiResponse.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ModelApiResponse.java index 1927555c00b..32fb86dd323 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ModelApiResponse.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ModelApiResponse.java @@ -10,7 +10,7 @@ import io.swagger.annotations.ApiModelProperty; /** * ModelApiResponse */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-31T18:50:49.249+02:00") + public class ModelApiResponse { private Integer code = null; diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ModelReturn.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ModelReturn.java index 843c2262bd2..a076d16f964 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ModelReturn.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ModelReturn.java @@ -11,7 +11,7 @@ import io.swagger.annotations.ApiModelProperty; * Model for testing reserved words */ @ApiModel(description = "Model for testing reserved words") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-31T18:50:49.249+02:00") + public class ModelReturn { private Integer _return = null; diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Name.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Name.java index 2d5b16efdb5..1ba2cc5e4a3 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Name.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Name.java @@ -11,7 +11,7 @@ import io.swagger.annotations.ApiModelProperty; * Model for testing model name same as property name */ @ApiModel(description = "Model for testing model name same as property name") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-31T18:50:49.249+02:00") + public class Name { private Integer name = null; diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Order.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Order.java index 9715dc583ca..cec651e73a6 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Order.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Order.java @@ -6,19 +6,19 @@ 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 org.joda.time.DateTime; /** * Order */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-31T18:50:49.249+02:00") + public class Order { private Long id = null; private Long petId = null; private Integer quantity = null; - private Date shipDate = null; + private DateTime shipDate = null; /** * Order Status @@ -98,17 +98,17 @@ public class Order { /** **/ - public Order shipDate(Date shipDate) { + public Order shipDate(DateTime shipDate) { this.shipDate = shipDate; return this; } @ApiModelProperty(example = "null", value = "") @JsonProperty("shipDate") - public Date getShipDate() { + public DateTime getShipDate() { return shipDate; } - public void setShipDate(Date shipDate) { + public void setShipDate(DateTime shipDate) { this.shipDate = shipDate; } diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Pet.java index b6062e49c37..da8b76ad024 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Pet.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Pet.java @@ -15,7 +15,7 @@ import java.util.List; /** * Pet */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-31T18:50:49.249+02:00") + public class Pet { private Long id = null; diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ReadOnlyFirst.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ReadOnlyFirst.java index 8afaf45f4a2..fdc3587df0e 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ReadOnlyFirst.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ReadOnlyFirst.java @@ -10,7 +10,7 @@ import io.swagger.annotations.ApiModelProperty; /** * ReadOnlyFirst */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-31T18:50:49.249+02:00") + public class ReadOnlyFirst { private String bar = null; diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/SpecialModelName.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/SpecialModelName.java index b29b9777a82..24e57756cb2 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/SpecialModelName.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/SpecialModelName.java @@ -10,7 +10,7 @@ import io.swagger.annotations.ApiModelProperty; /** * SpecialModelName */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-31T18:50:49.249+02:00") + public class SpecialModelName { private Long specialPropertyName = null; diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Tag.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Tag.java index d661146dd86..9d3bdd8cb9e 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Tag.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Tag.java @@ -10,7 +10,7 @@ import io.swagger.annotations.ApiModelProperty; /** * Tag */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-31T18:50:49.249+02:00") + public class Tag { private Long id = null; diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/User.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/User.java index 695c4053ff6..f23553660de 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/User.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/User.java @@ -10,7 +10,7 @@ import io.swagger.annotations.ApiModelProperty; /** * User */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-31T18:50:49.249+02:00") + public class User { private Long id = null; diff --git a/samples/client/petstore/java/feign/src/test/java/io/swagger/client/api/FakeApiTest.java b/samples/client/petstore/java/feign/src/test/java/io/swagger/client/api/FakeApiTest.java index 5a5df9a3ee6..504e027829f 100644 --- a/samples/client/petstore/java/feign/src/test/java/io/swagger/client/api/FakeApiTest.java +++ b/samples/client/petstore/java/feign/src/test/java/io/swagger/client/api/FakeApiTest.java @@ -1,8 +1,9 @@ package io.swagger.client.api; import io.swagger.client.ApiClient; +import org.joda.time.LocalDate; import java.math.BigDecimal; -import java.util.Date; +import org.joda.time.DateTime; import org.junit.Before; import org.junit.Test; @@ -40,8 +41,8 @@ public class FakeApiTest { Long int64 = null; Float _float = null; byte[] binary = null; - Date date = null; - Date dateTime = null; + LocalDate date = null; + DateTime dateTime = null; String password = null; // api.testEndpointParameters(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password); diff --git a/samples/client/petstore/java/feign/src/test/java/io/swagger/petstore/test/StoreApiTest.java b/samples/client/petstore/java/feign/src/test/java/io/swagger/petstore/test/StoreApiTest.java index ca14be28a80..92a3a951eb5 100644 --- a/samples/client/petstore/java/feign/src/test/java/io/swagger/petstore/test/StoreApiTest.java +++ b/samples/client/petstore/java/feign/src/test/java/io/swagger/petstore/test/StoreApiTest.java @@ -4,13 +4,14 @@ import feign.FeignException; import io.swagger.TestUtils; -import io.swagger.client.*; +import io.swagger.client.ApiClient; import io.swagger.client.api.*; import io.swagger.client.model.*; import java.lang.reflect.Field; import java.util.Map; +import org.joda.time.DateTimeZone; import org.junit.*; import static org.junit.Assert.*; @@ -39,6 +40,7 @@ public class StoreApiTest { assertEquals(order.getId(), fetched.getId()); assertEquals(order.getPetId(), fetched.getPetId()); assertEquals(order.getQuantity(), fetched.getQuantity()); + assertEquals(order.getShipDate().withZone(DateTimeZone.UTC), fetched.getShipDate().withZone(DateTimeZone.UTC)); } @Test @@ -63,7 +65,7 @@ public class StoreApiTest { Order order = new Order(); order.setPetId(new Long(200)); order.setQuantity(new Integer(13)); - order.setShipDate(new java.util.Date()); + order.setShipDate(org.joda.time.DateTime.now()); order.setStatus(Order.StatusEnum.PLACED); order.setComplete(true); diff --git a/samples/client/petstore/java/jersey2/build.gradle b/samples/client/petstore/java/jersey2/build.gradle index 9c98d11c4cd..6574f746d05 100644 --- a/samples/client/petstore/java/jersey2/build.gradle +++ b/samples/client/petstore/java/jersey2/build.gradle @@ -94,7 +94,7 @@ if(hasProperty('target') && target == 'android') { } ext { - swagger_annotations_version = "1.5.0" + swagger_annotations_version = "1.5.8" jackson_version = "2.7.0" jersey_version = "2.22.2" jodatime_version = "2.9.3" diff --git a/samples/client/petstore/java/jersey2/docs/FakeApi.md b/samples/client/petstore/java/jersey2/docs/FakeApi.md index 8e15d4d1f69..0c1f55a0902 100644 --- a/samples/client/petstore/java/jersey2/docs/FakeApi.md +++ b/samples/client/petstore/java/jersey2/docs/FakeApi.md @@ -32,8 +32,8 @@ 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 +LocalDate date = new LocalDate(); // LocalDate | None +DateTime dateTime = new DateTime(); // DateTime | None String password = "password_example"; // String | None try { apiInstance.testEndpointParameters(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password); @@ -56,8 +56,8 @@ Name | Type | Description | Notes **int64** | **Long**| None | [optional] **_float** | **Float**| None | [optional] **binary** | **byte[]**| None | [optional] - **date** | **Date**| None | [optional] - **dateTime** | **Date**| None | [optional] + **date** | **LocalDate**| None | [optional] + **dateTime** | **DateTime**| None | [optional] **password** | **String**| None | [optional] ### Return type diff --git a/samples/client/petstore/java/jersey2/docs/FormatTest.md b/samples/client/petstore/java/jersey2/docs/FormatTest.md index dc2b559dad2..44de7d9511a 100644 --- a/samples/client/petstore/java/jersey2/docs/FormatTest.md +++ b/samples/client/petstore/java/jersey2/docs/FormatTest.md @@ -13,8 +13,8 @@ Name | Type | Description | Notes **string** | **String** | | [optional] **_byte** | **byte[]** | | **binary** | **byte[]** | | [optional] -**date** | [**Date**](Date.md) | | -**dateTime** | [**Date**](Date.md) | | [optional] +**date** | [**LocalDate**](LocalDate.md) | | +**dateTime** | [**DateTime**](DateTime.md) | | [optional] **uuid** | **String** | | [optional] **password** | **String** | | diff --git a/samples/client/petstore/java/jersey2/docs/MixedPropertiesAndAdditionalPropertiesClass.md b/samples/client/petstore/java/jersey2/docs/MixedPropertiesAndAdditionalPropertiesClass.md index 00cc10ca9b3..e3487bcc501 100644 --- a/samples/client/petstore/java/jersey2/docs/MixedPropertiesAndAdditionalPropertiesClass.md +++ b/samples/client/petstore/java/jersey2/docs/MixedPropertiesAndAdditionalPropertiesClass.md @@ -5,7 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **uuid** | **String** | | [optional] -**dateTime** | [**Date**](Date.md) | | [optional] +**dateTime** | [**DateTime**](DateTime.md) | | [optional] **map** | [**Map<String, Animal>**](Animal.md) | | [optional] diff --git a/samples/client/petstore/java/jersey2/docs/Order.md b/samples/client/petstore/java/jersey2/docs/Order.md index 29ca3ddbc6b..a1089f5384e 100644 --- a/samples/client/petstore/java/jersey2/docs/Order.md +++ b/samples/client/petstore/java/jersey2/docs/Order.md @@ -7,7 +7,7 @@ Name | Type | Description | Notes **id** | **Long** | | [optional] **petId** | **Long** | | [optional] **quantity** | **Integer** | | [optional] -**shipDate** | [**Date**](Date.md) | | [optional] +**shipDate** | [**DateTime**](DateTime.md) | | [optional] **status** | [**StatusEnum**](#StatusEnum) | Order Status | [optional] **complete** | **Boolean** | | [optional] diff --git a/samples/client/petstore/java/jersey2/gradlew b/samples/client/petstore/java/jersey2/gradlew old mode 100755 new mode 100644 diff --git a/samples/client/petstore/java/jersey2/hello.txt b/samples/client/petstore/java/jersey2/hello.txt deleted file mode 100644 index 6769dd60bdf..00000000000 --- a/samples/client/petstore/java/jersey2/hello.txt +++ /dev/null @@ -1 +0,0 @@ -Hello world! \ No newline at end of file diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiClient.java index bc43cfe670e..a2607bfd516 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiClient.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiClient.java @@ -48,7 +48,7 @@ import io.swagger.client.auth.HttpBasicAuth; import io.swagger.client.auth.ApiKeyAuth; import io.swagger.client.auth.OAuth; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-03-17T17:22:31.147+08:00") + public class ApiClient { private Map defaultHeaderMap = new HashMap(); private String basePath = "http://petstore.swagger.io/v2"; @@ -84,13 +84,8 @@ public class ApiClient { // Setup authentications (key: authentication name, value: authentication). authentications = new HashMap(); - authentications.put("petstore_auth", new OAuth()); - authentications.put("test_api_client_id", new ApiKeyAuth("header", "x-test_api_client_id")); - authentications.put("test_api_client_secret", new ApiKeyAuth("header", "x-test_api_client_secret")); authentications.put("api_key", new ApiKeyAuth("header", "api_key")); - authentications.put("test_http_basic", new HttpBasicAuth()); - authentications.put("test_api_key_query", new ApiKeyAuth("query", "test_api_key_query")); - authentications.put("test_api_key_header", new ApiKeyAuth("header", "test_api_key_header")); + authentications.put("petstore_auth", new OAuth()); // Prevent the authentications from being modified. authentications = Collections.unmodifiableMap(authentications); } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiException.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiException.java index 00a3321d474..600bb507f09 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiException.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiException.java @@ -1,69 +1,103 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client; import java.util.Map; import java.util.List; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-06-03T00:41:43.242+08:00") + public class ApiException extends Exception { - private int code = 0; - private Map> responseHeaders = null; - private String responseBody = null; + private int code = 0; + private Map> responseHeaders = null; + private String responseBody = null; - public ApiException() {} + public ApiException() {} - public ApiException(Throwable throwable) { - super(throwable); - } + public ApiException(Throwable throwable) { + super(throwable); + } - public ApiException(String message) { - super(message); - } + public ApiException(String message) { + super(message); + } - public ApiException(String message, Throwable throwable, int code, Map> responseHeaders, String responseBody) { - super(message, throwable); - this.code = code; - this.responseHeaders = responseHeaders; - this.responseBody = responseBody; - } + public ApiException(String message, Throwable throwable, int code, Map> responseHeaders, String responseBody) { + super(message, throwable); + this.code = code; + this.responseHeaders = responseHeaders; + this.responseBody = responseBody; + } - public ApiException(String message, int code, Map> responseHeaders, String responseBody) { - this(message, (Throwable) null, code, responseHeaders, responseBody); - } + public ApiException(String message, int code, Map> responseHeaders, String responseBody) { + this(message, (Throwable) null, code, responseHeaders, responseBody); + } - public ApiException(String message, Throwable throwable, int code, Map> responseHeaders) { - this(message, throwable, code, responseHeaders, null); - } + public ApiException(String message, Throwable throwable, int code, Map> responseHeaders) { + this(message, throwable, code, responseHeaders, null); + } - public ApiException(int code, Map> responseHeaders, String responseBody) { - this((String) null, (Throwable) null, code, responseHeaders, responseBody); - } + public ApiException(int code, Map> responseHeaders, String responseBody) { + this((String) null, (Throwable) null, code, responseHeaders, responseBody); + } - public ApiException(int code, String message) { - super(message); - this.code = code; - } + public ApiException(int code, String message) { + super(message); + this.code = code; + } - public ApiException(int code, String message, Map> responseHeaders, String responseBody) { - this(code, message); - this.responseHeaders = responseHeaders; - this.responseBody = responseBody; - } + public ApiException(int code, String message, Map> responseHeaders, String responseBody) { + this(code, message); + this.responseHeaders = responseHeaders; + this.responseBody = responseBody; + } - public int getCode() { - return code; - } + /** + * Get the HTTP status code. + * + * @return HTTP status code + */ + public int getCode() { + return code; + } - /** - * Get the HTTP response headers. - */ - public Map> getResponseHeaders() { - return responseHeaders; - } + /** + * Get the HTTP response headers. + * + * @return A map of list of string + */ + public Map> getResponseHeaders() { + return responseHeaders; + } - /** - * Get the HTTP response body. - */ - public String getResponseBody() { - return responseBody; - } + /** + * Get the HTTP response body. + * + * @return Response body in the form of string + */ + public String getResponseBody() { + return responseBody; + } } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/Configuration.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/Configuration.java index bbfa1a1c4ee..cbdadd6262d 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/Configuration.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/Configuration.java @@ -1,22 +1,51 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-06-03T00:41:43.242+08:00") + public class Configuration { - private static ApiClient defaultApiClient = new ApiClient(); + private static ApiClient defaultApiClient = new ApiClient(); - /** - * Get the default API client, which would be used when creating API - * instances without providing an API client. - */ - public static ApiClient getDefaultApiClient() { - return defaultApiClient; - } + /** + * Get the default API client, which would be used when creating API + * instances without providing an API client. + * + * @return Default API client + */ + public static ApiClient getDefaultApiClient() { + return defaultApiClient; + } - /** - * Set the default API client, which would be used when creating API - * instances without providing an API client. - */ - public static void setDefaultApiClient(ApiClient apiClient) { - defaultApiClient = apiClient; - } + /** + * Set the default API client, which would be used when creating API + * instances without providing an API client. + * + * @param apiClient API client + */ + public static void setDefaultApiClient(ApiClient apiClient) { + defaultApiClient = apiClient; + } } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/JSON.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/JSON.java index f38b16d55ad..d6f725b2caa 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/JSON.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/JSON.java @@ -8,7 +8,7 @@ import java.text.DateFormat; import javax.ws.rs.ext.ContextResolver; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-06-03T00:41:43.242+08:00") + public class JSON implements ContextResolver { private ObjectMapper mapper; diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/Pair.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/Pair.java index 863136c9ef6..4b44c415812 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/Pair.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/Pair.java @@ -1,6 +1,31 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-06-03T00:41:43.242+08:00") + public class Pair { private String name = ""; private String value = ""; diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/StringUtil.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/StringUtil.java index 9bd7767e8a2..03c6c81e434 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/StringUtil.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/StringUtil.java @@ -1,6 +1,31 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-06-03T00:41:43.242+08:00") + public class StringUtil { /** * Check if the given array contains the given value (with case-insensitive comparison). diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/FakeApi.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/FakeApi.java index e120b12d42c..b8b499c4dee 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/FakeApi.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/FakeApi.java @@ -7,15 +7,16 @@ import io.swagger.client.Pair; import javax.ws.rs.core.GenericType; +import org.joda.time.LocalDate; +import org.joda.time.DateTime; 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-06-03T00:41:43.242+08:00") + public class FakeApi { private ApiClient apiClient; @@ -52,7 +53,7 @@ public class FakeApi { * @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 { + public void testEndpointParameters(BigDecimal number, Double _double, String string, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, byte[] binary, LocalDate date, DateTime dateTime, String password) throws ApiException { Object localVarPostBody = null; // verify the required parameter 'number' is set diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/PetApi.java index f09defffe3c..ab85c4ac394 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/PetApi.java @@ -8,15 +8,15 @@ import io.swagger.client.Pair; import javax.ws.rs.core.GenericType; import io.swagger.client.model.Pet; -import io.swagger.client.model.ModelApiResponse; import java.io.File; +import io.swagger.client.model.ModelApiResponse; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-06-03T00:41:43.242+08:00") + public class PetApi { private ApiClient apiClient; diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/StoreApi.java index 36336fe8c0b..c0c9a166ad7 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/StoreApi.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/StoreApi.java @@ -14,7 +14,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-06-03T00:41:43.242+08:00") + public class StoreApi { private ApiClient apiClient; diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/UserApi.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/UserApi.java index 42e08132830..7602f4e2ba9 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/UserApi.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/UserApi.java @@ -14,7 +14,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-06-03T00:41:43.242+08:00") + public class UserApi { private ApiClient apiClient; diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/ApiKeyAuth.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/ApiKeyAuth.java index 6d5c20361ef..6ba15566b60 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/ApiKeyAuth.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/ApiKeyAuth.java @@ -1,3 +1,28 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.auth; import io.swagger.client.Pair; @@ -5,7 +30,7 @@ import io.swagger.client.Pair; import java.util.Map; import java.util.List; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-06-03T00:41:43.242+08:00") + public class ApiKeyAuth implements Authentication { private final String location; private final String paramName; diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/Authentication.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/Authentication.java index 98b1a6900b9..a063a6998b5 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/Authentication.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/Authentication.java @@ -1,3 +1,28 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.auth; import io.swagger.client.Pair; @@ -6,6 +31,11 @@ import java.util.Map; import java.util.List; public interface Authentication { - /** Apply authentication settings to header and query params. */ - void applyToParams(List queryParams, Map headerParams); + /** + * Apply authentication settings to header and query params. + * + * @param queryParams List of query parameters + * @param headerParams Map of header parameters + */ + void applyToParams(List queryParams, Map headerParams); } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/HttpBasicAuth.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/HttpBasicAuth.java index 8bc5686d3c1..5895370e4d4 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/HttpBasicAuth.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/HttpBasicAuth.java @@ -1,3 +1,28 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.auth; import io.swagger.client.Pair; @@ -9,7 +34,7 @@ import java.util.List; import java.io.UnsupportedEncodingException; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-06-03T00:41:43.242+08:00") + public class HttpBasicAuth implements Authentication { private String username; private String password; diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/OAuth.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/OAuth.java index 140ee3d63c9..8802ebc92c8 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/OAuth.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/OAuth.java @@ -1,3 +1,28 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.auth; import io.swagger.client.Pair; @@ -5,7 +30,7 @@ import io.swagger.client.Pair; import java.util.Map; import java.util.List; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-06-03T00:41:43.242+08:00") + public class OAuth implements Authentication { private String accessToken; diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/OAuthFlow.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/OAuthFlow.java index 597ec99b48b..ec1f942b0f2 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/OAuthFlow.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/OAuthFlow.java @@ -1,5 +1,30 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.auth; public enum OAuthFlow { accessCode, implicit, password, application -} \ No newline at end of file +} diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java index 4c9d7b51a02..ccaba7709c4 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java @@ -13,7 +13,7 @@ import java.util.Map; /** * AdditionalPropertiesClass */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-06-03T00:41:43.242+08:00") + public class AdditionalPropertiesClass { private Map mapProperty = new HashMap(); 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 3506eb25298..25c7d3e421c 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 @@ -10,7 +10,7 @@ import io.swagger.annotations.ApiModelProperty; /** * Animal */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-06-03T00:41:43.242+08:00") + public class Animal { private String className = null; diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/AnimalFarm.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/AnimalFarm.java index e035fb41d85..647e3a893e1 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/AnimalFarm.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/AnimalFarm.java @@ -10,7 +10,7 @@ import java.util.List; /** * AnimalFarm */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-06-03T00:41:43.242+08:00") + public class AnimalFarm extends ArrayList { diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ArrayTest.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ArrayTest.java index 7b4d2bb3cc3..6c1eb23d8d0 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ArrayTest.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ArrayTest.java @@ -12,7 +12,7 @@ import java.util.List; /** * ArrayTest */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-06-03T00:41:43.242+08:00") + public class ArrayTest { private List arrayOfString = new ArrayList(); 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 19d57357959..5ef9e23bd96 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 @@ -11,7 +11,7 @@ import io.swagger.client.model.Animal; /** * Cat */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-06-03T00:41:43.242+08:00") + public class Cat extends Animal { private String className = null; 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 5f8edb7f80f..c6cb703a89e 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 @@ -10,7 +10,7 @@ import io.swagger.annotations.ApiModelProperty; /** * Category */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-06-03T00:41:43.242+08:00") + public class Category { private Long id = null; 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 2c01fa4f1a1..4b3cc947cc5 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 @@ -11,7 +11,7 @@ import io.swagger.client.model.Animal; /** * Dog */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-06-03T00:41:43.242+08:00") + public class Dog extends Animal { private String className = null; diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/EnumTest.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/EnumTest.java index 08d5c3d617a..1c8657fd3ec 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 @@ -11,7 +11,7 @@ import io.swagger.annotations.ApiModelProperty; /** * EnumTest */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-06-03T00:41:43.242+08:00") + public class EnumTest { 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 2f80a5dc972..79376150017 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 @@ -6,13 +6,14 @@ import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.math.BigDecimal; -import java.util.Date; +import org.joda.time.DateTime; +import org.joda.time.LocalDate; /** * FormatTest */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-06-03T00:41:43.242+08:00") + public class FormatTest { private Integer integer = null; @@ -24,8 +25,8 @@ public class FormatTest { private String string = null; private byte[] _byte = null; private byte[] binary = null; - private Date date = null; - private Date dateTime = null; + private LocalDate date = null; + private DateTime dateTime = null; private String uuid = null; private String password = null; @@ -195,34 +196,34 @@ public class FormatTest { /** **/ - public FormatTest date(Date date) { + public FormatTest date(LocalDate date) { this.date = date; return this; } @ApiModelProperty(example = "null", required = true, value = "") @JsonProperty("date") - public Date getDate() { + public LocalDate getDate() { return date; } - public void setDate(Date date) { + public void setDate(LocalDate date) { this.date = date; } /** **/ - public FormatTest dateTime(Date dateTime) { + public FormatTest dateTime(DateTime dateTime) { this.dateTime = dateTime; return this; } @ApiModelProperty(example = "null", value = "") @JsonProperty("dateTime") - public Date getDateTime() { + public DateTime getDateTime() { return dateTime; } - public void setDateTime(Date dateTime) { + public void setDateTime(DateTime dateTime) { this.dateTime = dateTime; } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java index c55c44aa4c7..2f0972bf41e 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -6,20 +6,20 @@ import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import io.swagger.client.model.Animal; -import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; +import org.joda.time.DateTime; /** * MixedPropertiesAndAdditionalPropertiesClass */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-06-03T00:41:43.242+08:00") + public class MixedPropertiesAndAdditionalPropertiesClass { private String uuid = null; - private Date dateTime = null; + private DateTime dateTime = null; private Map map = new HashMap(); @@ -42,17 +42,17 @@ public class MixedPropertiesAndAdditionalPropertiesClass { /** **/ - public MixedPropertiesAndAdditionalPropertiesClass dateTime(Date dateTime) { + public MixedPropertiesAndAdditionalPropertiesClass dateTime(DateTime dateTime) { this.dateTime = dateTime; return this; } @ApiModelProperty(example = "null", value = "") @JsonProperty("dateTime") - public Date getDateTime() { + public DateTime getDateTime() { return dateTime; } - public void setDateTime(Date dateTime) { + public void setDateTime(DateTime dateTime) { this.dateTime = dateTime; } 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 3a3014b87c0..b2809525c7f 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 @@ -11,7 +11,7 @@ import io.swagger.annotations.ApiModelProperty; * Model for testing model name starting with number */ @ApiModel(description = "Model for testing model name starting with number") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-06-03T00:41:43.242+08:00") + public class Model200Response { private Integer name = null; 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 b8e916043e5..32fb86dd323 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 @@ -10,7 +10,7 @@ import io.swagger.annotations.ApiModelProperty; /** * ModelApiResponse */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-06-03T00:41:43.242+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 28df30b73f0..a076d16f964 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 @@ -11,7 +11,7 @@ import io.swagger.annotations.ApiModelProperty; * Model for testing reserved words */ @ApiModel(description = "Model for testing reserved words") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-06-03T00:41:43.242+08:00") + public class ModelReturn { private Integer _return = null; 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 091e716d948..1ba2cc5e4a3 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 @@ -11,7 +11,7 @@ import io.swagger.annotations.ApiModelProperty; * Model for testing model name same as property name */ @ApiModel(description = "Model for testing model name same as property name") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-06-03T00:41:43.242+08:00") + public class Name { private Integer name = null; 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 40c54de3071..cec651e73a6 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 @@ -6,19 +6,19 @@ 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 org.joda.time.DateTime; /** * Order */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-06-03T00:41:43.242+08:00") + public class Order { private Long id = null; private Long petId = null; private Integer quantity = null; - private Date shipDate = null; + private DateTime shipDate = null; /** * Order Status @@ -98,17 +98,17 @@ public class Order { /** **/ - public Order shipDate(Date shipDate) { + public Order shipDate(DateTime shipDate) { this.shipDate = shipDate; return this; } @ApiModelProperty(example = "null", value = "") @JsonProperty("shipDate") - public Date getShipDate() { + public DateTime getShipDate() { return shipDate; } - public void setShipDate(Date shipDate) { + public void setShipDate(DateTime shipDate) { this.shipDate = shipDate; } 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 2ec54dd8d8f..da8b76ad024 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 @@ -15,7 +15,7 @@ import java.util.List; /** * Pet */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-06-03T00:41:43.242+08:00") + public class Pet { private Long id = null; diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ReadOnlyFirst.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ReadOnlyFirst.java index 268c6adc65e..fdc3587df0e 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ReadOnlyFirst.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ReadOnlyFirst.java @@ -10,7 +10,7 @@ import io.swagger.annotations.ApiModelProperty; /** * ReadOnlyFirst */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-06-03T00:41:43.242+08:00") + public class ReadOnlyFirst { private String bar = null; diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/SpecialModelName.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/SpecialModelName.java index 3b2003b6e47..24e57756cb2 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 @@ -10,7 +10,7 @@ import io.swagger.annotations.ApiModelProperty; /** * SpecialModelName */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-06-03T00:41:43.242+08:00") + public class SpecialModelName { private Long specialPropertyName = null; 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 277e48fa0b2..9d3bdd8cb9e 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 @@ -10,7 +10,7 @@ import io.swagger.annotations.ApiModelProperty; /** * Tag */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-06-03T00:41:43.242+08:00") + public class Tag { private Long id = null; diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/User.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/User.java index d1f924eb2a8..f23553660de 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 @@ -10,7 +10,7 @@ import io.swagger.annotations.ApiModelProperty; /** * User */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-06-03T00:41:43.242+08:00") + public class User { private Long id = null; diff --git a/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/ApiClientTest.java b/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/ApiClientTest.java index 47f004c283b..19b55257d0c 100644 --- a/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/ApiClientTest.java +++ b/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/ApiClientTest.java @@ -111,6 +111,7 @@ public class ApiClientTest { } } + @Ignore("There is no more basic auth in petstore security definitions") @Test public void testSetUsernameAndPassword() { HttpBasicAuth auth = null; diff --git a/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/JSONTest.java b/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/JSONTest.java index f10909ab9e7..9386b3d5236 100644 --- a/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/JSONTest.java +++ b/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/JSONTest.java @@ -3,10 +3,10 @@ package io.swagger.client; import io.swagger.client.model.Order; import java.lang.Exception; -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.TimeZone; +import org.joda.time.DateTimeZone; +import org.joda.time.format.DateTimeFormatter; +import org.joda.time.format.ISODateTimeFormat; import org.junit.*; import static org.junit.Assert.*; @@ -23,26 +23,23 @@ public class JSONTest { @Test public void testDefaultDate() throws Exception { - final DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); - dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); + final DateTimeFormatter dateFormat = ISODateTimeFormat.dateTime(); final String dateStr = "2015-11-07T14:11:05.267Z"; - order.setShipDate(dateFormat.parse(dateStr)); + order.setShipDate(dateFormat.parseDateTime(dateStr)); String str = json.getContext(null).writeValueAsString(order); Order o = json.getContext(null).readValue(str, Order.class); - assertEquals(dateStr, dateFormat.format(o.getShipDate())); + assertEquals(dateStr, dateFormat.print(o.getShipDate())); } @Test public void testCustomDate() throws Exception { - final DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX"); - dateFormat.setTimeZone(TimeZone.getTimeZone("GMT-2")); + final DateTimeFormatter dateFormat = ISODateTimeFormat.dateTimeNoMillis().withZone(DateTimeZone.forID("Etc/GMT+2")); final String dateStr = "2015-11-07T14:11:05-02:00"; - order.setShipDate(dateFormat.parse(dateStr)); + order.setShipDate(dateFormat.parseDateTime(dateStr)); - json.setDateFormat(dateFormat); String str = json.getContext(null).writeValueAsString(order); Order o = json.getContext(null).readValue(str, Order.class); - assertEquals(dateStr, dateFormat.format(o.getShipDate())); + assertEquals(dateStr, dateFormat.print(o.getShipDate())); } } \ No newline at end of file diff --git a/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/api/PetApiTest.java b/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/api/PetApiTest.java index c25e0d8bfa2..7f4d27c8b77 100644 --- a/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/api/PetApiTest.java +++ b/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/api/PetApiTest.java @@ -1,155 +1,288 @@ package io.swagger.client.api; -import io.swagger.client.ApiException; -import io.swagger.client.model.Pet; -import io.swagger.client.model.ModelApiResponse; -import java.io.File; -import org.junit.Test; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.swagger.TestUtils; + +import io.swagger.client.*; +import io.swagger.client.api.*; +import io.swagger.client.auth.*; +import io.swagger.client.model.*; + +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileWriter; import java.util.ArrayList; -import java.util.HashMap; +import java.util.Arrays; import java.util.List; import java.util.Map; -/** - * API tests for PetApi - */ +import org.junit.*; +import static org.junit.Assert.*; + public class PetApiTest { + PetApi api = null; - private final PetApi api = new PetApi(); - - - /** - * Add a new pet to the store - * - * - * - * @throws ApiException - * if the Api call fails - */ - @Test - public void addPetTest() throws ApiException { - Pet body = null; - // api.addPet(body); - - // TODO: test validations + @Before + public void setup() { + api = new PetApi(); + // setup authentication + ApiKeyAuth apiKeyAuth = (ApiKeyAuth) api.getApiClient().getAuthentication("api_key"); + apiKeyAuth.setApiKey("special-key"); } - - /** - * Deletes a pet - * - * - * - * @throws ApiException - * if the Api call fails - */ - @Test - public void deletePetTest() throws ApiException { - Long petId = null; - String apiKey = null; - // api.deletePet(petId, apiKey); - // TODO: test validations - } - - /** - * Finds Pets by status - * - * Multiple status values can be provided with comma separated strings - * - * @throws ApiException - * if the Api call fails - */ @Test - public void findPetsByStatusTest() throws ApiException { - List status = null; - // List response = api.findPetsByStatus(status); + public void testApiClient() { + // the default api client is used + assertEquals(Configuration.getDefaultApiClient(), api.getApiClient()); + assertNotNull(api.getApiClient()); + assertEquals("http://petstore.swagger.io/v2", api.getApiClient().getBasePath()); + assertFalse(api.getApiClient().isDebugging()); - // TODO: test validations + ApiClient oldClient = api.getApiClient(); + + ApiClient newClient = new ApiClient(); + newClient.setBasePath("http://example.com"); + newClient.setDebugging(true); + + // set api client via constructor + api = new PetApi(newClient); + assertNotNull(api.getApiClient()); + assertEquals("http://example.com", api.getApiClient().getBasePath()); + assertTrue(api.getApiClient().isDebugging()); + + // set api client via setter method + api.setApiClient(oldClient); + assertNotNull(api.getApiClient()); + assertEquals("http://petstore.swagger.io/v2", api.getApiClient().getBasePath()); + assertFalse(api.getApiClient().isDebugging()); } - - /** - * Finds Pets by tags - * - * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. - * - * @throws ApiException - * if the Api call fails - */ + @Test - public void findPetsByTagsTest() throws ApiException { - List tags = null; - // List response = api.findPetsByTags(tags); + public void testCreateAndGetPet() throws Exception { + Pet pet = createRandomPet(); + api.addPet(pet); - // TODO: test validations + Pet fetched = api.getPetById(pet.getId()); + assertNotNull(fetched); + assertEquals(pet.getId(), fetched.getId()); + assertNotNull(fetched.getCategory()); + assertEquals(fetched.getCategory().getName(), pet.getCategory().getName()); } - - /** - * Find pet by ID - * - * Returns a single pet - * - * @throws ApiException - * if the Api call fails - */ + + /* @Test - public void getPetByIdTest() throws ApiException { - Long petId = null; - // Pet response = api.getPetById(petId); + public void testCreateAndGetPetWithByteArray() throws Exception { + Pet pet = createRandomPet(); + byte[] bytes = serializeJson(pet, api.getApiClient()).getBytes(); + api.addPetUsingByteArray(bytes); - // TODO: test validations + byte[] fetchedBytes = api.petPetIdtestingByteArraytrueGet(pet.getId()); + Pet fetched = deserializeJson(new String(fetchedBytes), Pet.class, api.getApiClient()); + assertNotNull(fetched); + assertEquals(pet.getId(), fetched.getId()); + assertNotNull(fetched.getCategory()); + assertEquals(fetched.getCategory().getName(), pet.getCategory().getName()); } - - /** - * Update an existing pet - * - * - * - * @throws ApiException - * if the Api call fails - */ + @Test - public void updatePetTest() throws ApiException { - Pet body = null; - // api.updatePet(body); + public void testGetPetByIdInObject() throws Exception { + Pet pet = new Pet(); + pet.setId(TestUtils.nextId()); + pet.setName("pet " + pet.getId()); - // TODO: test validations + Category category = new Category(); + category.setId(TestUtils.nextId()); + category.setName("category " + category.getId()); + pet.setCategory(category); + + pet.setStatus(Pet.StatusEnum.PENDING); + List photos = Arrays.asList(new String[]{"http://foo.bar.com/1"}); + pet.setPhotoUrls(photos); + + api.addPet(pet); + + InlineResponse200 fetched = api.getPetByIdInObject(pet.getId()); + assertEquals(pet.getId(), fetched.getId()); + assertEquals(pet.getName(), fetched.getName()); + + Object categoryObj = fetched.getCategory(); + assertNotNull(categoryObj); + assertTrue(categoryObj instanceof Map); + + Map categoryMap = (Map) categoryObj; + Object categoryIdObj = categoryMap.get("id"); + assertTrue(categoryIdObj instanceof Integer); + Integer categoryIdInt = (Integer) categoryIdObj; + assertEquals(category.getId(), Long.valueOf(categoryIdInt)); + assertEquals(category.getName(), categoryMap.get("name")); } - - /** - * Updates a pet in the store with form data - * - * - * - * @throws ApiException - * if the Api call fails - */ + */ + @Test - public void updatePetWithFormTest() throws ApiException { - Long petId = null; - String name = null; - String status = null; - // api.updatePetWithForm(petId, name, status); + public void testUpdatePet() throws Exception { + Pet pet = createRandomPet(); + pet.setName("programmer"); - // TODO: test validations + api.updatePet(pet); + + Pet fetched = api.getPetById(pet.getId()); + assertNotNull(fetched); + assertEquals(pet.getId(), fetched.getId()); + assertNotNull(fetched.getCategory()); + assertEquals(fetched.getCategory().getName(), pet.getCategory().getName()); } - - /** - * uploads an image - * - * - * - * @throws ApiException - * if the Api call fails - */ + @Test - public void uploadFileTest() throws ApiException { - Long petId = null; - String additionalMetadata = null; - File file = null; - // ModelApiResponse response = api.uploadFile(petId, additionalMetadata, file); + public void testFindPetsByStatus() throws Exception { + Pet pet = createRandomPet(); + pet.setName("programmer"); + pet.setStatus(Pet.StatusEnum.AVAILABLE); - // TODO: test validations + api.updatePet(pet); + + List pets = api.findPetsByStatus(Arrays.asList(new String[]{"available"})); + assertNotNull(pets); + + boolean found = false; + for (Pet fetched : pets) { + if (fetched.getId().equals(pet.getId())) { + found = true; + break; + } + } + + assertTrue(found); + } + + @Test + public void testFindPetsByTags() throws Exception { + Pet pet = createRandomPet(); + pet.setName("monster"); + pet.setStatus(Pet.StatusEnum.AVAILABLE); + + List tags = new ArrayList(); + Tag tag1 = new Tag(); + tag1.setName("friendly"); + tags.add(tag1); + pet.setTags(tags); + + api.updatePet(pet); + + List pets = api.findPetsByTags(Arrays.asList(new String[]{"friendly"})); + assertNotNull(pets); + + boolean found = false; + for (Pet fetched : pets) { + if (fetched.getId().equals(pet.getId())) { + found = true; + break; + } + } + assertTrue(found); + } + + @Test + public void testUpdatePetWithForm() throws Exception { + Pet pet = createRandomPet(); + pet.setName("frank"); + api.addPet(pet); + + Pet fetched = api.getPetById(pet.getId()); + + api.updatePetWithForm(fetched.getId(), "furt", null); + Pet updated = api.getPetById(fetched.getId()); + + assertEquals(updated.getName(), "furt"); + } + + @Test + public void testDeletePet() throws Exception { + Pet pet = createRandomPet(); + api.addPet(pet); + + Pet fetched = api.getPetById(pet.getId()); + api.deletePet(fetched.getId(), null); + + try { + fetched = api.getPetById(fetched.getId()); + fail("expected an error"); + } catch (ApiException e) { + assertEquals(404, e.getCode()); + } + } + + @Test + public void testUploadFile() throws Exception { + Pet pet = createRandomPet(); + api.addPet(pet); + + File file = new File("hello.txt"); + BufferedWriter writer = new BufferedWriter(new FileWriter(file)); + writer.write("Hello world!"); + writer.close(); + + api.uploadFile(pet.getId(), "a test file", new File(file.getAbsolutePath())); + } + + @Test + public void testEqualsAndHashCode() { + Pet pet1 = new Pet(); + Pet pet2 = new Pet(); + assertTrue(pet1.equals(pet2)); + assertTrue(pet2.equals(pet1)); + assertTrue(pet1.hashCode() == pet2.hashCode()); + assertTrue(pet1.equals(pet1)); + assertTrue(pet1.hashCode() == pet1.hashCode()); + + pet2.setName("really-happy"); + pet2.setPhotoUrls(Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"})); + assertFalse(pet1.equals(pet2)); + assertFalse(pet2.equals(pet1)); + assertFalse(pet1.hashCode() == (pet2.hashCode())); + assertTrue(pet2.equals(pet2)); + assertTrue(pet2.hashCode() == pet2.hashCode()); + + pet1.setName("really-happy"); + pet1.setPhotoUrls(Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"})); + assertTrue(pet1.equals(pet2)); + assertTrue(pet2.equals(pet1)); + assertTrue(pet1.hashCode() == pet2.hashCode()); + assertTrue(pet1.equals(pet1)); + assertTrue(pet1.hashCode() == pet1.hashCode()); + } + + private Pet createRandomPet() { + Pet pet = new Pet(); + pet.setId(TestUtils.nextId()); + pet.setName("gorilla"); + + Category category = new Category(); + category.setName("really-happy"); + + pet.setCategory(category); + pet.setStatus(Pet.StatusEnum.AVAILABLE); + List photos = Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"}); + pet.setPhotoUrls(photos); + + return pet; + } + + private String serializeJson(Object o, ApiClient apiClient) { + ObjectMapper mapper = apiClient.getJSON().getContext(null); + try { + return mapper.writeValueAsString(o); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + private T deserializeJson(String json, Class klass, ApiClient apiClient) { + ObjectMapper mapper = apiClient.getJSON().getContext(null); + try { + return mapper.readValue(json, klass); + } catch (Exception e) { + throw new RuntimeException(e); + } } - } diff --git a/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/api/StoreApiTest.java b/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/api/StoreApiTest.java index 31abbbeae4e..3cc2442c64d 100644 --- a/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/api/StoreApiTest.java +++ b/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/api/StoreApiTest.java @@ -1,83 +1,100 @@ package io.swagger.client.api; -import io.swagger.client.ApiException; -import io.swagger.client.model.Order; -import org.junit.Test; +import io.swagger.TestUtils; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; +import io.swagger.client.*; +import io.swagger.client.auth.*; +import io.swagger.client.model.*; + +import java.lang.reflect.Field; import java.util.Map; +import java.text.SimpleDateFormat; + +import org.joda.time.DateTime; +import org.joda.time.DateTimeZone; +import org.junit.*; +import static org.junit.Assert.*; -/** - * API tests for StoreApi - */ public class StoreApiTest { + StoreApi api = null; - private final StoreApi api = new StoreApi(); - - - /** - * Delete purchase order by ID - * - * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors - * - * @throws ApiException - * if the Api call fails - */ - @Test - public void deleteOrderTest() throws ApiException { - String orderId = null; - // api.deleteOrder(orderId); - - // TODO: test validations + @Before + public void setup() { + api = new StoreApi(); + // setup authentication + ApiKeyAuth apiKeyAuth = (ApiKeyAuth) api.getApiClient().getAuthentication("api_key"); + apiKeyAuth.setApiKey("special-key"); + // set custom date format that is used by the petstore server + api.getApiClient().setDateFormat(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ")); } - - /** - * Returns pet inventories by status - * - * Returns a map of status codes to quantities - * - * @throws ApiException - * if the Api call fails - */ - @Test - public void getInventoryTest() throws ApiException { - // Map response = api.getInventory(); - // TODO: test validations - } - - /** - * Find purchase order by ID - * - * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - * - * @throws ApiException - * if the Api call fails - */ @Test - public void getOrderByIdTest() throws ApiException { - Long orderId = null; - // Order response = api.getOrderById(orderId); - - // TODO: test validations + public void testGetInventory() throws Exception { + Map inventory = api.getInventory(); + assertTrue(inventory.keySet().size() > 0); } - - /** - * Place an order for a pet - * - * - * - * @throws ApiException - * if the Api call fails - */ + + /* @Test - public void placeOrderTest() throws ApiException { - Order body = null; - // Order response = api.placeOrder(body); + public void testGetInventoryInObject() throws Exception { + Object inventoryObj = api.getInventoryInObject(); + assertTrue(inventoryObj instanceof Map); - // TODO: test validations + Map inventoryMap = (Map) inventoryObj; + assertTrue(inventoryMap.keySet().size() > 0); + + Map.Entry firstEntry = (Map.Entry) inventoryMap.entrySet().iterator().next(); + assertTrue(firstEntry.getKey() instanceof String); + assertTrue(firstEntry.getValue() instanceof Integer); + } + */ + + @Test + public void testPlaceOrder() throws Exception { + Order order = createOrder(); + api.placeOrder(order); + + Order fetched = api.getOrderById(order.getId()); + assertEquals(order.getId(), fetched.getId()); + assertEquals(order.getPetId(), fetched.getPetId()); + assertEquals(order.getQuantity(), fetched.getQuantity()); + assertEquals(order.getShipDate().withZone(DateTimeZone.UTC), fetched.getShipDate().withZone(DateTimeZone.UTC)); + } + + @Test + public void testDeleteOrder() throws Exception { + Order order = createOrder(); + api.placeOrder(order); + + Order fetched = api.getOrderById(order.getId()); + assertEquals(fetched.getId(), order.getId()); + + api.deleteOrder(String.valueOf(order.getId())); + + try { + api.getOrderById(order.getId()); + // fail("expected an error"); + } catch (ApiException e) { + // ok + } + } + + private Order createOrder() { + Order order = new Order(); + order.setPetId(new Long(200)); + order.setQuantity(new Integer(13)); + order.setShipDate(DateTime.now()); + order.setStatus(Order.StatusEnum.PLACED); + order.setComplete(true); + + try { + Field idField = Order.class.getDeclaredField("id"); + idField.setAccessible(true); + idField.set(order, TestUtils.nextId()); + } catch (Exception e) { + throw new RuntimeException(e); + } + + return order; } - } diff --git a/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/api/UserApiTest.java b/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/api/UserApiTest.java index 7e96762ff4e..c7fb92d2552 100644 --- a/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/api/UserApiTest.java +++ b/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/api/UserApiTest.java @@ -1,149 +1,88 @@ package io.swagger.client.api; -import io.swagger.client.ApiException; -import io.swagger.client.model.User; -import org.junit.Test; +import io.swagger.TestUtils; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; +import io.swagger.client.api.*; +import io.swagger.client.auth.*; +import io.swagger.client.model.*; + +import java.util.Arrays; + +import org.junit.*; +import static org.junit.Assert.*; -/** - * API tests for UserApi - */ public class UserApiTest { + UserApi api = null; - private final UserApi api = new UserApi(); - - - /** - * Create user - * - * This can only be done by the logged in user. - * - * @throws ApiException - * if the Api call fails - */ - @Test - public void createUserTest() throws ApiException { - User body = null; - // api.createUser(body); - - // TODO: test validations + @Before + public void setup() { + api = new UserApi(); + // setup authentication + ApiKeyAuth apiKeyAuth = (ApiKeyAuth) api.getApiClient().getAuthentication("api_key"); + apiKeyAuth.setApiKey("special-key"); } - - /** - * Creates list of users with given input array - * - * - * - * @throws ApiException - * if the Api call fails - */ - @Test - public void createUsersWithArrayInputTest() throws ApiException { - List body = null; - // api.createUsersWithArrayInput(body); - // TODO: test validations - } - - /** - * Creates list of users with given input array - * - * - * - * @throws ApiException - * if the Api call fails - */ @Test - public void createUsersWithListInputTest() throws ApiException { - List body = null; - // api.createUsersWithListInput(body); + public void testCreateUser() throws Exception { + User user = createUser(); - // TODO: test validations + api.createUser(user); + + User fetched = api.getUserByName(user.getUsername()); + assertEquals(user.getId(), fetched.getId()); } - - /** - * Delete user - * - * This can only be done by the logged in user. - * - * @throws ApiException - * if the Api call fails - */ + @Test - public void deleteUserTest() throws ApiException { - String username = null; - // api.deleteUser(username); + public void testCreateUsersWithArray() throws Exception { + User user1 = createUser(); + user1.setUsername("user" + user1.getId()); + User user2 = createUser(); + user2.setUsername("user" + user2.getId()); - // TODO: test validations + api.createUsersWithArrayInput(Arrays.asList(new User[]{user1, user2})); + + User fetched = api.getUserByName(user1.getUsername()); + assertEquals(user1.getId(), fetched.getId()); } - - /** - * Get user by user name - * - * - * - * @throws ApiException - * if the Api call fails - */ + @Test - public void getUserByNameTest() throws ApiException { - String username = null; - // User response = api.getUserByName(username); + public void testCreateUsersWithList() throws Exception { + User user1 = createUser(); + user1.setUsername("user" + user1.getId()); + User user2 = createUser(); + user2.setUsername("user" + user2.getId()); - // TODO: test validations + api.createUsersWithListInput(Arrays.asList(new User[]{user1, user2})); + + User fetched = api.getUserByName(user1.getUsername()); + assertEquals(user1.getId(), fetched.getId()); } - - /** - * Logs user into the system - * - * - * - * @throws ApiException - * if the Api call fails - */ + @Test - public void loginUserTest() throws ApiException { - String username = null; - String password = null; - // String response = api.loginUser(username, password); + public void testLoginUser() throws Exception { + User user = createUser(); + api.createUser(user); - // TODO: test validations + String token = api.loginUser(user.getUsername(), user.getPassword()); + assertTrue(token.startsWith("logged in user session:")); } - - /** - * Logs out current logged in user session - * - * - * - * @throws ApiException - * if the Api call fails - */ + @Test - public void logoutUserTest() throws ApiException { - // api.logoutUser(); - - // TODO: test validations + public void logoutUser() throws Exception { + api.logoutUser(); } - - /** - * Updated user - * - * This can only be done by the logged in user. - * - * @throws ApiException - * if the Api call fails - */ - @Test - public void updateUserTest() throws ApiException { - String username = null; - User body = null; - // api.updateUser(username, body); - // TODO: test validations + private User createUser() { + User user = new User(); + user.setId(TestUtils.nextId()); + user.setUsername("fred" + user.getId()); + user.setFirstName("Fred"); + user.setLastName("Meyer"); + user.setEmail("fred@fredmeyer.com"); + user.setPassword("xxXXxx"); + user.setPhone("408-867-5309"); + user.setUserStatus(123); + + return user; } - } diff --git a/samples/client/petstore/java/jersey2/src/test/java/io/swagger/petstore/test/PetApiTest.java b/samples/client/petstore/java/jersey2/src/test/java/io/swagger/petstore/test/PetApiTest.java deleted file mode 100644 index 51583853257..00000000000 --- a/samples/client/petstore/java/jersey2/src/test/java/io/swagger/petstore/test/PetApiTest.java +++ /dev/null @@ -1,288 +0,0 @@ -package io.swagger.petstore.test; - -import com.fasterxml.jackson.databind.ObjectMapper; - -import io.swagger.TestUtils; - -import io.swagger.client.*; -import io.swagger.client.api.*; -import io.swagger.client.auth.*; -import io.swagger.client.model.*; - -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileWriter; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Map; - -import org.junit.*; -import static org.junit.Assert.*; - -public class PetApiTest { - PetApi api = null; - - @Before - public void setup() { - api = new PetApi(); - // setup authentication - ApiKeyAuth apiKeyAuth = (ApiKeyAuth) api.getApiClient().getAuthentication("api_key"); - apiKeyAuth.setApiKey("special-key"); - } - - @Test - public void testApiClient() { - // the default api client is used - assertEquals(Configuration.getDefaultApiClient(), api.getApiClient()); - assertNotNull(api.getApiClient()); - assertEquals("http://petstore.swagger.io/v2", api.getApiClient().getBasePath()); - assertFalse(api.getApiClient().isDebugging()); - - ApiClient oldClient = api.getApiClient(); - - ApiClient newClient = new ApiClient(); - newClient.setBasePath("http://example.com"); - newClient.setDebugging(true); - - // set api client via constructor - api = new PetApi(newClient); - assertNotNull(api.getApiClient()); - assertEquals("http://example.com", api.getApiClient().getBasePath()); - assertTrue(api.getApiClient().isDebugging()); - - // set api client via setter method - api.setApiClient(oldClient); - assertNotNull(api.getApiClient()); - assertEquals("http://petstore.swagger.io/v2", api.getApiClient().getBasePath()); - assertFalse(api.getApiClient().isDebugging()); - } - - @Test - public void testCreateAndGetPet() throws Exception { - Pet pet = createRandomPet(); - api.addPet(pet); - - Pet fetched = api.getPetById(pet.getId()); - assertNotNull(fetched); - assertEquals(pet.getId(), fetched.getId()); - assertNotNull(fetched.getCategory()); - assertEquals(fetched.getCategory().getName(), pet.getCategory().getName()); - } - - /* - @Test - public void testCreateAndGetPetWithByteArray() throws Exception { - Pet pet = createRandomPet(); - byte[] bytes = serializeJson(pet, api.getApiClient()).getBytes(); - api.addPetUsingByteArray(bytes); - - byte[] fetchedBytes = api.petPetIdtestingByteArraytrueGet(pet.getId()); - Pet fetched = deserializeJson(new String(fetchedBytes), Pet.class, api.getApiClient()); - assertNotNull(fetched); - assertEquals(pet.getId(), fetched.getId()); - assertNotNull(fetched.getCategory()); - assertEquals(fetched.getCategory().getName(), pet.getCategory().getName()); - } - - @Test - public void testGetPetByIdInObject() throws Exception { - Pet pet = new Pet(); - pet.setId(TestUtils.nextId()); - pet.setName("pet " + pet.getId()); - - Category category = new Category(); - category.setId(TestUtils.nextId()); - category.setName("category " + category.getId()); - pet.setCategory(category); - - pet.setStatus(Pet.StatusEnum.PENDING); - List photos = Arrays.asList(new String[]{"http://foo.bar.com/1"}); - pet.setPhotoUrls(photos); - - api.addPet(pet); - - InlineResponse200 fetched = api.getPetByIdInObject(pet.getId()); - assertEquals(pet.getId(), fetched.getId()); - assertEquals(pet.getName(), fetched.getName()); - - Object categoryObj = fetched.getCategory(); - assertNotNull(categoryObj); - assertTrue(categoryObj instanceof Map); - - Map categoryMap = (Map) categoryObj; - Object categoryIdObj = categoryMap.get("id"); - assertTrue(categoryIdObj instanceof Integer); - Integer categoryIdInt = (Integer) categoryIdObj; - assertEquals(category.getId(), Long.valueOf(categoryIdInt)); - assertEquals(category.getName(), categoryMap.get("name")); - } - */ - - @Test - public void testUpdatePet() throws Exception { - Pet pet = createRandomPet(); - pet.setName("programmer"); - - api.updatePet(pet); - - Pet fetched = api.getPetById(pet.getId()); - assertNotNull(fetched); - assertEquals(pet.getId(), fetched.getId()); - assertNotNull(fetched.getCategory()); - assertEquals(fetched.getCategory().getName(), pet.getCategory().getName()); - } - - @Test - public void testFindPetsByStatus() throws Exception { - Pet pet = createRandomPet(); - pet.setName("programmer"); - pet.setStatus(Pet.StatusEnum.AVAILABLE); - - api.updatePet(pet); - - List pets = api.findPetsByStatus(Arrays.asList(new String[]{"available"})); - assertNotNull(pets); - - boolean found = false; - for (Pet fetched : pets) { - if (fetched.getId().equals(pet.getId())) { - found = true; - break; - } - } - - assertTrue(found); - } - - @Test - public void testFindPetsByTags() throws Exception { - Pet pet = createRandomPet(); - pet.setName("monster"); - pet.setStatus(Pet.StatusEnum.AVAILABLE); - - List tags = new ArrayList(); - Tag tag1 = new Tag(); - tag1.setName("friendly"); - tags.add(tag1); - pet.setTags(tags); - - api.updatePet(pet); - - List pets = api.findPetsByTags(Arrays.asList(new String[]{"friendly"})); - assertNotNull(pets); - - boolean found = false; - for (Pet fetched : pets) { - if (fetched.getId().equals(pet.getId())) { - found = true; - break; - } - } - assertTrue(found); - } - - @Test - public void testUpdatePetWithForm() throws Exception { - Pet pet = createRandomPet(); - pet.setName("frank"); - api.addPet(pet); - - Pet fetched = api.getPetById(pet.getId()); - - api.updatePetWithForm(fetched.getId(), "furt", null); - Pet updated = api.getPetById(fetched.getId()); - - assertEquals(updated.getName(), "furt"); - } - - @Test - public void testDeletePet() throws Exception { - Pet pet = createRandomPet(); - api.addPet(pet); - - Pet fetched = api.getPetById(pet.getId()); - api.deletePet(fetched.getId(), null); - - try { - fetched = api.getPetById(fetched.getId()); - fail("expected an error"); - } catch (ApiException e) { - assertEquals(404, e.getCode()); - } - } - - @Test - public void testUploadFile() throws Exception { - Pet pet = createRandomPet(); - api.addPet(pet); - - File file = new File("hello.txt"); - BufferedWriter writer = new BufferedWriter(new FileWriter(file)); - writer.write("Hello world!"); - writer.close(); - - api.uploadFile(pet.getId(), "a test file", new File(file.getAbsolutePath())); - } - - @Test - public void testEqualsAndHashCode() { - Pet pet1 = new Pet(); - Pet pet2 = new Pet(); - assertTrue(pet1.equals(pet2)); - assertTrue(pet2.equals(pet1)); - assertTrue(pet1.hashCode() == pet2.hashCode()); - assertTrue(pet1.equals(pet1)); - assertTrue(pet1.hashCode() == pet1.hashCode()); - - pet2.setName("really-happy"); - pet2.setPhotoUrls(Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"})); - assertFalse(pet1.equals(pet2)); - assertFalse(pet2.equals(pet1)); - assertFalse(pet1.hashCode() == (pet2.hashCode())); - assertTrue(pet2.equals(pet2)); - assertTrue(pet2.hashCode() == pet2.hashCode()); - - pet1.setName("really-happy"); - pet1.setPhotoUrls(Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"})); - assertTrue(pet1.equals(pet2)); - assertTrue(pet2.equals(pet1)); - assertTrue(pet1.hashCode() == pet2.hashCode()); - assertTrue(pet1.equals(pet1)); - assertTrue(pet1.hashCode() == pet1.hashCode()); - } - - private Pet createRandomPet() { - Pet pet = new Pet(); - pet.setId(TestUtils.nextId()); - pet.setName("gorilla"); - - Category category = new Category(); - category.setName("really-happy"); - - pet.setCategory(category); - pet.setStatus(Pet.StatusEnum.AVAILABLE); - List photos = Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"}); - pet.setPhotoUrls(photos); - - return pet; - } - - private String serializeJson(Object o, ApiClient apiClient) { - ObjectMapper mapper = apiClient.getJSON().getContext(null); - try { - return mapper.writeValueAsString(o); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - - private T deserializeJson(String json, Class klass, ApiClient apiClient) { - ObjectMapper mapper = apiClient.getJSON().getContext(null); - try { - return mapper.readValue(json, klass); - } catch (Exception e) { - throw new RuntimeException(e); - } - } -} diff --git a/samples/client/petstore/java/jersey2/src/test/java/io/swagger/petstore/test/StoreApiTest.java b/samples/client/petstore/java/jersey2/src/test/java/io/swagger/petstore/test/StoreApiTest.java deleted file mode 100644 index 7ccbdf3f32b..00000000000 --- a/samples/client/petstore/java/jersey2/src/test/java/io/swagger/petstore/test/StoreApiTest.java +++ /dev/null @@ -1,98 +0,0 @@ -package io.swagger.petstore.test; - -import io.swagger.TestUtils; - -import io.swagger.client.*; -import io.swagger.client.api.*; -import io.swagger.client.auth.*; -import io.swagger.client.model.*; - -import java.lang.reflect.Field; -import java.util.Map; -import java.text.SimpleDateFormat; - -import org.junit.*; -import static org.junit.Assert.*; - -public class StoreApiTest { - StoreApi api = null; - - @Before - public void setup() { - api = new StoreApi(); - // setup authentication - ApiKeyAuth apiKeyAuth = (ApiKeyAuth) api.getApiClient().getAuthentication("api_key"); - apiKeyAuth.setApiKey("special-key"); - // set custom date format that is used by the petstore server - api.getApiClient().setDateFormat(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ")); - } - - @Test - public void testGetInventory() throws Exception { - Map inventory = api.getInventory(); - assertTrue(inventory.keySet().size() > 0); - } - - /* - @Test - public void testGetInventoryInObject() throws Exception { - Object inventoryObj = api.getInventoryInObject(); - assertTrue(inventoryObj instanceof Map); - - Map inventoryMap = (Map) inventoryObj; - assertTrue(inventoryMap.keySet().size() > 0); - - Map.Entry firstEntry = (Map.Entry) inventoryMap.entrySet().iterator().next(); - assertTrue(firstEntry.getKey() instanceof String); - assertTrue(firstEntry.getValue() instanceof Integer); - } - */ - - @Test - public void testPlaceOrder() throws Exception { - Order order = createOrder(); - api.placeOrder(order); - - Order fetched = api.getOrderById(order.getId()); - assertEquals(order.getId(), fetched.getId()); - assertEquals(order.getPetId(), fetched.getPetId()); - assertEquals(order.getQuantity(), fetched.getQuantity()); - } - - @Test - public void testDeleteOrder() throws Exception { - Order order = createOrder(); - api.placeOrder(order); - - Order fetched = api.getOrderById(order.getId()); - assertEquals(fetched.getId(), order.getId()); - - api.deleteOrder(String.valueOf(order.getId())); - - try { - api.getOrderById(order.getId()); - // fail("expected an error"); - } catch (ApiException e) { - // ok - } - } - - private Order createOrder() { - Order order = new Order(); - order.setPetId(new Long(200)); - order.setQuantity(new Integer(13)); - order.setShipDate(new java.util.Date()); - order.setStatus(Order.StatusEnum.PLACED); - order.setComplete(true); - - try { - Field idField = Order.class.getDeclaredField("id"); - idField.setAccessible(true); - idField.set(order, TestUtils.nextId()); - } catch (Exception e) { - throw new RuntimeException(e); - } - - return order; - } -} diff --git a/samples/client/petstore/java/jersey2/src/test/java/io/swagger/petstore/test/UserApiTest.java b/samples/client/petstore/java/jersey2/src/test/java/io/swagger/petstore/test/UserApiTest.java deleted file mode 100644 index 195e5c1e861..00000000000 --- a/samples/client/petstore/java/jersey2/src/test/java/io/swagger/petstore/test/UserApiTest.java +++ /dev/null @@ -1,88 +0,0 @@ -package io.swagger.petstore.test; - -import io.swagger.TestUtils; - -import io.swagger.client.api.*; -import io.swagger.client.auth.*; -import io.swagger.client.model.*; - -import java.util.Arrays; - -import org.junit.*; -import static org.junit.Assert.*; - -public class UserApiTest { - UserApi api = null; - - @Before - public void setup() { - api = new UserApi(); - // setup authentication - ApiKeyAuth apiKeyAuth = (ApiKeyAuth) api.getApiClient().getAuthentication("api_key"); - apiKeyAuth.setApiKey("special-key"); - } - - @Test - public void testCreateUser() throws Exception { - User user = createUser(); - - api.createUser(user); - - User fetched = api.getUserByName(user.getUsername()); - assertEquals(user.getId(), fetched.getId()); - } - - @Test - public void testCreateUsersWithArray() throws Exception { - User user1 = createUser(); - user1.setUsername("user" + user1.getId()); - User user2 = createUser(); - user2.setUsername("user" + user2.getId()); - - api.createUsersWithArrayInput(Arrays.asList(new User[]{user1, user2})); - - User fetched = api.getUserByName(user1.getUsername()); - assertEquals(user1.getId(), fetched.getId()); - } - - @Test - public void testCreateUsersWithList() throws Exception { - User user1 = createUser(); - user1.setUsername("user" + user1.getId()); - User user2 = createUser(); - user2.setUsername("user" + user2.getId()); - - api.createUsersWithListInput(Arrays.asList(new User[]{user1, user2})); - - User fetched = api.getUserByName(user1.getUsername()); - assertEquals(user1.getId(), fetched.getId()); - } - - @Test - public void testLoginUser() throws Exception { - User user = createUser(); - api.createUser(user); - - String token = api.loginUser(user.getUsername(), user.getPassword()); - assertTrue(token.startsWith("logged in user session:")); - } - - @Test - public void logoutUser() throws Exception { - api.logoutUser(); - } - - private User createUser() { - User user = new User(); - user.setId(TestUtils.nextId()); - user.setUsername("fred" + user.getId()); - user.setFirstName("Fred"); - user.setLastName("Meyer"); - user.setEmail("fred@fredmeyer.com"); - user.setPassword("xxXXxx"); - user.setPhone("408-867-5309"); - user.setUserStatus(123); - - return user; - } -} diff --git a/samples/client/petstore/java/okhttp-gson/build.gradle b/samples/client/petstore/java/okhttp-gson/build.gradle index 57812871f64..d7c6b63ea75 100644 --- a/samples/client/petstore/java/okhttp-gson/build.gradle +++ b/samples/client/petstore/java/okhttp-gson/build.gradle @@ -98,5 +98,6 @@ dependencies { compile 'com.squareup.okhttp:okhttp:2.7.5' compile 'com.squareup.okhttp:logging-interceptor:2.7.5' compile 'com.google.code.gson:gson:2.6.2' + compile 'joda-time:joda-time:2.9.3' testCompile 'junit:junit:4.12' } diff --git a/samples/client/petstore/java/okhttp-gson/build.sbt b/samples/client/petstore/java/okhttp-gson/build.sbt index bbfd5c01bab..01a1095f8a4 100644 --- a/samples/client/petstore/java/okhttp-gson/build.sbt +++ b/samples/client/petstore/java/okhttp-gson/build.sbt @@ -13,6 +13,7 @@ lazy val root = (project in file(".")). "com.squareup.okhttp" % "okhttp" % "2.7.5", "com.squareup.okhttp" % "logging-interceptor" % "2.7.5", "com.google.code.gson" % "gson" % "2.6.2", + "joda-time" % "joda-time" % "2.9.3" % "compile", "junit" % "junit" % "4.12" % "test", "com.novocode" % "junit-interface" % "0.10" % "test" ) diff --git a/samples/client/petstore/java/okhttp-gson/docs/FakeApi.md b/samples/client/petstore/java/okhttp-gson/docs/FakeApi.md index 8e15d4d1f69..0c1f55a0902 100644 --- a/samples/client/petstore/java/okhttp-gson/docs/FakeApi.md +++ b/samples/client/petstore/java/okhttp-gson/docs/FakeApi.md @@ -32,8 +32,8 @@ 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 +LocalDate date = new LocalDate(); // LocalDate | None +DateTime dateTime = new DateTime(); // DateTime | None String password = "password_example"; // String | None try { apiInstance.testEndpointParameters(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password); @@ -56,8 +56,8 @@ Name | Type | Description | Notes **int64** | **Long**| None | [optional] **_float** | **Float**| None | [optional] **binary** | **byte[]**| None | [optional] - **date** | **Date**| None | [optional] - **dateTime** | **Date**| None | [optional] + **date** | **LocalDate**| None | [optional] + **dateTime** | **DateTime**| None | [optional] **password** | **String**| None | [optional] ### Return type diff --git a/samples/client/petstore/java/okhttp-gson/docs/FormatTest.md b/samples/client/petstore/java/okhttp-gson/docs/FormatTest.md index dc2b559dad2..44de7d9511a 100644 --- a/samples/client/petstore/java/okhttp-gson/docs/FormatTest.md +++ b/samples/client/petstore/java/okhttp-gson/docs/FormatTest.md @@ -13,8 +13,8 @@ Name | Type | Description | Notes **string** | **String** | | [optional] **_byte** | **byte[]** | | **binary** | **byte[]** | | [optional] -**date** | [**Date**](Date.md) | | -**dateTime** | [**Date**](Date.md) | | [optional] +**date** | [**LocalDate**](LocalDate.md) | | +**dateTime** | [**DateTime**](DateTime.md) | | [optional] **uuid** | **String** | | [optional] **password** | **String** | | diff --git a/samples/client/petstore/java/okhttp-gson/docs/MixedPropertiesAndAdditionalPropertiesClass.md b/samples/client/petstore/java/okhttp-gson/docs/MixedPropertiesAndAdditionalPropertiesClass.md index 00cc10ca9b3..e3487bcc501 100644 --- a/samples/client/petstore/java/okhttp-gson/docs/MixedPropertiesAndAdditionalPropertiesClass.md +++ b/samples/client/petstore/java/okhttp-gson/docs/MixedPropertiesAndAdditionalPropertiesClass.md @@ -5,7 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **uuid** | **String** | | [optional] -**dateTime** | [**Date**](Date.md) | | [optional] +**dateTime** | [**DateTime**](DateTime.md) | | [optional] **map** | [**Map<String, Animal>**](Animal.md) | | [optional] diff --git a/samples/client/petstore/java/okhttp-gson/docs/Order.md b/samples/client/petstore/java/okhttp-gson/docs/Order.md index 29ca3ddbc6b..a1089f5384e 100644 --- a/samples/client/petstore/java/okhttp-gson/docs/Order.md +++ b/samples/client/petstore/java/okhttp-gson/docs/Order.md @@ -7,7 +7,7 @@ Name | Type | Description | Notes **id** | **Long** | | [optional] **petId** | **Long** | | [optional] **quantity** | **Integer** | | [optional] -**shipDate** | [**Date**](Date.md) | | [optional] +**shipDate** | [**DateTime**](DateTime.md) | | [optional] **status** | [**StatusEnum**](#StatusEnum) | Order Status | [optional] **complete** | **Boolean** | | [optional] diff --git a/samples/client/petstore/java/okhttp-gson/gradlew b/samples/client/petstore/java/okhttp-gson/gradlew old mode 100755 new mode 100644 diff --git a/samples/client/petstore/java/okhttp-gson/hello.txt b/samples/client/petstore/java/okhttp-gson/hello.txt deleted file mode 100644 index 6769dd60bdf..00000000000 --- a/samples/client/petstore/java/okhttp-gson/hello.txt +++ /dev/null @@ -1 +0,0 @@ -Hello world! \ No newline at end of file diff --git a/samples/client/petstore/java/okhttp-gson/pom.xml b/samples/client/petstore/java/okhttp-gson/pom.xml index 638e1b9345e..a534184d824 100644 --- a/samples/client/petstore/java/okhttp-gson/pom.xml +++ b/samples/client/petstore/java/okhttp-gson/pom.xml @@ -105,40 +105,6 @@ 1.7 - - - org.codehaus.mojo - exec-maven-plugin - 1.2.1 - - - gradle-test - integration-test - - exec - - - gradle - - check - - - - - sbt-test - integration-test - - exec - - - sbt - - publishLocal - - - - - @@ -162,6 +128,11 @@ gson ${gson-version} + + joda-time + joda-time + ${jodatime-version} + @@ -172,9 +143,10 @@ - 1.5.8 + 1.5.9 2.7.5 2.6.2 + 2.9.3 1.0.0 4.12 UTF-8 diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiCallback.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiCallback.java index fcf2d289fbf..efd0535e654 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiCallback.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiCallback.java @@ -1,3 +1,28 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client; import java.io.IOException; @@ -11,39 +36,39 @@ import java.util.List; * @param The return type */ public interface ApiCallback { - /** - * This is called when the API call fails. - * - * @param e The exception causing the failure - * @param statusCode Status code of the response if available, otherwise it would be 0 - * @param responseHeaders Headers of the response if available, otherwise it would be null - */ - void onFailure(ApiException e, int statusCode, Map> responseHeaders); + /** + * This is called when the API call fails. + * + * @param e The exception causing the failure + * @param statusCode Status code of the response if available, otherwise it would be 0 + * @param responseHeaders Headers of the response if available, otherwise it would be null + */ + void onFailure(ApiException e, int statusCode, Map> responseHeaders); - /** - * This is called when the API call succeeded. - * - * @param result The result deserialized from response - * @param statusCode Status code of the response - * @param responseHeaders Headers of the response - */ - void onSuccess(T result, int statusCode, Map> responseHeaders); + /** + * This is called when the API call succeeded. + * + * @param result The result deserialized from response + * @param statusCode Status code of the response + * @param responseHeaders Headers of the response + */ + void onSuccess(T result, int statusCode, Map> responseHeaders); - /** - * This is called when the API upload processing. - * - * @param bytesWritten bytes Written - * @param contentLength content length of request body - * @param done write end - */ - void onUploadProgress(long bytesWritten, long contentLength, boolean done); + /** + * This is called when the API upload processing. + * + * @param bytesWritten bytes Written + * @param contentLength content length of request body + * @param done write end + */ + void onUploadProgress(long bytesWritten, long contentLength, boolean done); - /** - * This is called when the API downlond processing. - * - * @param bytesRead bytes Read - * @param contentLength content lenngth of the response - * @param done Read end - */ - void onDownloadProgress(long bytesRead, long contentLength, boolean done); + /** + * This is called when the API downlond processing. + * + * @param bytesRead bytes Read + * @param contentLength content lenngth of the response + * @param done Read end + */ + void onDownloadProgress(long bytesRead, long contentLength, boolean done); } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiClient.java index 9328cb74d84..374a185a599 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiClient.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiClient.java @@ -1,3 +1,28 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client; import com.squareup.okhttp.Call; @@ -67,1072 +92,1233 @@ import io.swagger.client.auth.ApiKeyAuth; import io.swagger.client.auth.OAuth; public class ApiClient { - public static final double JAVA_VERSION; - public static final boolean IS_ANDROID; - public static final int ANDROID_SDK_VERSION; + public static final double JAVA_VERSION; + public static final boolean IS_ANDROID; + public static final int ANDROID_SDK_VERSION; - static { - JAVA_VERSION = Double.parseDouble(System.getProperty("java.specification.version")); - boolean isAndroid; - try { - Class.forName("android.app.Activity"); - isAndroid = true; - } catch (ClassNotFoundException e) { - isAndroid = false; - } - IS_ANDROID = isAndroid; - int sdkVersion = 0; - if (IS_ANDROID) { - try { - sdkVersion = Class.forName("android.os.Build$VERSION").getField("SDK_INT").getInt(null); - } catch (Exception e) { + static { + JAVA_VERSION = Double.parseDouble(System.getProperty("java.specification.version")); + boolean isAndroid; try { - sdkVersion = Integer.parseInt((String) Class.forName("android.os.Build$VERSION").getField("SDK").get(null)); - } catch (Exception e2) { } - } + Class.forName("android.app.Activity"); + isAndroid = true; + } catch (ClassNotFoundException e) { + isAndroid = false; + } + IS_ANDROID = isAndroid; + int sdkVersion = 0; + if (IS_ANDROID) { + try { + sdkVersion = Class.forName("android.os.Build$VERSION").getField("SDK_INT").getInt(null); + } catch (Exception e) { + try { + sdkVersion = Integer.parseInt((String) Class.forName("android.os.Build$VERSION").getField("SDK").get(null)); + } catch (Exception e2) { } + } + } + ANDROID_SDK_VERSION = sdkVersion; } - ANDROID_SDK_VERSION = sdkVersion; - } - /** - * The datetime format to be used when lenientDatetimeFormat is enabled. - */ - public static final String LENIENT_DATETIME_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"; + /** + * The datetime format to be used when lenientDatetimeFormat is enabled. + */ + public static final String LENIENT_DATETIME_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"; - private String basePath = "http://petstore.swagger.io/v2"; - private boolean lenientOnJson = false; - private boolean debugging = false; - private Map defaultHeaderMap = new HashMap(); - private String tempFolderPath = null; + private String basePath = "http://petstore.swagger.io/v2"; + private boolean lenientOnJson = false; + private boolean debugging = false; + private Map defaultHeaderMap = new HashMap(); + private String tempFolderPath = null; - private Map authentications; + private Map authentications; - private DateFormat dateFormat; - private DateFormat datetimeFormat; - private boolean lenientDatetimeFormat; - private int dateLength; + private DateFormat dateFormat; + private DateFormat datetimeFormat; + private boolean lenientDatetimeFormat; + private int dateLength; - private InputStream sslCaCert; - private boolean verifyingSsl; + private InputStream sslCaCert; + private boolean verifyingSsl; - private OkHttpClient httpClient; - private JSON json; + private OkHttpClient httpClient; + private JSON json; - private HttpLoggingInterceptor loggingInterceptor; - - public ApiClient() { - httpClient = new OkHttpClient(); - - verifyingSsl = true; - - json = new JSON(this); + private HttpLoggingInterceptor loggingInterceptor; /* - * Use RFC3339 format for date and datetime. - * See http://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14 + * Constructor for ApiClient */ - this.dateFormat = new SimpleDateFormat("yyyy-MM-dd"); - // Always use UTC as the default time zone when dealing with date (without time). - this.dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); - initDatetimeFormat(); + public ApiClient() { + httpClient = new OkHttpClient(); - // Be lenient on datetime formats when parsing datetime from string. - // See parseDatetime. - this.lenientDatetimeFormat = true; + verifyingSsl = true; - // Set default User-Agent. - setUserAgent("Swagger-Codegen/1.0.0/java"); + json = new JSON(this); - // Setup authentications (key: authentication name, value: authentication). - authentications = new HashMap(); - authentications.put("petstore_auth", new OAuth()); - authentications.put("api_key", new ApiKeyAuth("header", "api_key")); - // Prevent the authentications from being modified. - authentications = Collections.unmodifiableMap(authentications); - } + /* + * Use RFC3339 format for date and datetime. + * See http://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14 + */ + this.dateFormat = new SimpleDateFormat("yyyy-MM-dd"); + // Always use UTC as the default time zone when dealing with date (without time). + this.dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); + initDatetimeFormat(); - public String getBasePath() { - return basePath; - } + // Be lenient on datetime formats when parsing datetime from string. + // See parseDatetime. + this.lenientDatetimeFormat = true; - public ApiClient setBasePath(String basePath) { - this.basePath = basePath; - return this; - } + // Set default User-Agent. + setUserAgent("Swagger-Codegen/1.0.0/java"); - public OkHttpClient getHttpClient() { - return httpClient; - } - - public ApiClient setHttpClient(OkHttpClient httpClient) { - this.httpClient = httpClient; - return this; - } - - public JSON getJSON() { - return json; - } - - public ApiClient setJSON(JSON json) { - this.json = json; - return this; - } - - public boolean isVerifyingSsl() { - return verifyingSsl; - } - - /** - * Configure whether to verify certificate and hostname when making https requests. - * Default to true. - * NOTE: Do NOT set to false in production code, otherwise you would face multiple types of cryptographic attacks. - */ - public ApiClient setVerifyingSsl(boolean verifyingSsl) { - this.verifyingSsl = verifyingSsl; - applySslSettings(); - return this; - } - - public InputStream getSslCaCert() { - return sslCaCert; - } - - /** - * Configure the CA certificate to be trusted when making https requests. - * Use null to reset to default. - */ - public ApiClient setSslCaCert(InputStream sslCaCert) { - this.sslCaCert = sslCaCert; - applySslSettings(); - return this; - } - - public DateFormat getDateFormat() { - return dateFormat; - } - - public ApiClient setDateFormat(DateFormat dateFormat) { - this.dateFormat = dateFormat; - this.dateLength = this.dateFormat.format(new Date()).length(); - return this; - } - - public DateFormat getDatetimeFormat() { - return datetimeFormat; - } - - public ApiClient setDatetimeFormat(DateFormat datetimeFormat) { - this.datetimeFormat = datetimeFormat; - return this; - } - - /** - * Whether to allow various ISO 8601 datetime formats when parsing a datetime string. - * @see #parseDatetime(String) - */ - public boolean isLenientDatetimeFormat() { - return lenientDatetimeFormat; - } - - public ApiClient setLenientDatetimeFormat(boolean lenientDatetimeFormat) { - this.lenientDatetimeFormat = lenientDatetimeFormat; - return this; - } - - /** - * Parse the given date string into Date object. - * The default dateFormat supports these ISO 8601 date formats: - * 2015-08-16 - * 2015-8-16 - */ - public Date parseDate(String str) { - if (str == null) - return null; - try { - return dateFormat.parse(str); - } catch (ParseException e) { - throw new RuntimeException(e); - } - } - - /** - * Parse the given datetime string into Date object. - * When lenientDatetimeFormat is enabled, the following ISO 8601 datetime formats are supported: - * 2015-08-16T08:20:05Z - * 2015-8-16T8:20:05Z - * 2015-08-16T08:20:05+00:00 - * 2015-08-16T08:20:05+0000 - * 2015-08-16T08:20:05.376Z - * 2015-08-16T08:20:05.376+00:00 - * 2015-08-16T08:20:05.376+00 - * Note: The 3-digit milli-seconds is optional. Time zone is required and can be in one of - * these formats: - * Z (same with +0000) - * +08:00 (same with +0800) - * -02 (same with -0200) - * -0200 - * @see https://en.wikipedia.org/wiki/ISO_8601 - */ - public Date parseDatetime(String str) { - if (str == null) - return null; - - DateFormat format; - if (lenientDatetimeFormat) { - /* - * When lenientDatetimeFormat is enabled, normalize the date string - * into LENIENT_DATETIME_FORMAT to support various formats - * defined by ISO 8601. - */ - // normalize time zone - // trailing "Z": 2015-08-16T08:20:05Z => 2015-08-16T08:20:05+0000 - str = str.replaceAll("[zZ]\\z", "+0000"); - // remove colon in time zone: 2015-08-16T08:20:05+00:00 => 2015-08-16T08:20:05+0000 - str = str.replaceAll("([+-]\\d{2}):(\\d{2})\\z", "$1$2"); - // expand time zone: 2015-08-16T08:20:05+00 => 2015-08-16T08:20:05+0000 - str = str.replaceAll("([+-]\\d{2})\\z", "$100"); - // add milliseconds when missing - // 2015-08-16T08:20:05+0000 => 2015-08-16T08:20:05.000+0000 - str = str.replaceAll("(:\\d{1,2})([+-]\\d{4})\\z", "$1.000$2"); - format = new SimpleDateFormat(LENIENT_DATETIME_FORMAT); - } else { - format = this.datetimeFormat; + // Setup authentications (key: authentication name, value: authentication). + authentications = new HashMap(); + authentications.put("petstore_auth", new OAuth()); + authentications.put("api_key", new ApiKeyAuth("header", "api_key")); + // Prevent the authentications from being modified. + authentications = Collections.unmodifiableMap(authentications); } - try { - return format.parse(str); - } catch (ParseException e) { - throw new RuntimeException(e); - } - } - - public Date parseDateOrDatetime(String str) { - if (str == null) - return null; - else if (str.length() <= dateLength) - return parseDate(str); - else - return parseDatetime(str); - } - - /** - * Format the given Date object into string. - */ - public String formatDate(Date date) { - return dateFormat.format(date); - } - - /** - * Format the given Date object into string. - */ - public String formatDatetime(Date date) { - return datetimeFormat.format(date); - } - - /** - * Get authentications (key: authentication name, value: authentication). - */ - public Map getAuthentications() { - return authentications; - } - - /** - * Get authentication for the given name. - * - * @param authName The authentication name - * @return The authentication, null if not found - */ - public Authentication getAuthentication(String authName) { - return authentications.get(authName); - } - - /** - * Helper method to set username for the first HTTP basic authentication. - */ - public void setUsername(String username) { - for (Authentication auth : authentications.values()) { - if (auth instanceof HttpBasicAuth) { - ((HttpBasicAuth) auth).setUsername(username); - return; - } - } - throw new RuntimeException("No HTTP basic authentication configured!"); - } - - /** - * Helper method to set password for the first HTTP basic authentication. - */ - public void setPassword(String password) { - for (Authentication auth : authentications.values()) { - if (auth instanceof HttpBasicAuth) { - ((HttpBasicAuth) auth).setPassword(password); - return; - } - } - throw new RuntimeException("No HTTP basic authentication configured!"); - } - - /** - * Helper method to set API key value for the first API key authentication. - */ - public void setApiKey(String apiKey) { - for (Authentication auth : authentications.values()) { - if (auth instanceof ApiKeyAuth) { - ((ApiKeyAuth) auth).setApiKey(apiKey); - return; - } - } - throw new RuntimeException("No API key authentication configured!"); - } - - /** - * Helper method to set API key prefix for the first API key authentication. - */ - public void setApiKeyPrefix(String apiKeyPrefix) { - for (Authentication auth : authentications.values()) { - if (auth instanceof ApiKeyAuth) { - ((ApiKeyAuth) auth).setApiKeyPrefix(apiKeyPrefix); - return; - } - } - throw new RuntimeException("No API key authentication configured!"); - } - - /** - * Helper method to set access token for the first OAuth2 authentication. - */ - public void setAccessToken(String accessToken) { - for (Authentication auth : authentications.values()) { - if (auth instanceof OAuth) { - ((OAuth) auth).setAccessToken(accessToken); - return; - } - } - throw new RuntimeException("No OAuth2 authentication configured!"); - } - - /** - * Set the User-Agent header's value (by adding to the default header map). - */ - public ApiClient setUserAgent(String userAgent) { - addDefaultHeader("User-Agent", userAgent); - return this; - } - - /** - * Add a default header. - * - * @param key The header's key - * @param value The header's value - */ - public ApiClient addDefaultHeader(String key, String value) { - defaultHeaderMap.put(key, value); - return this; - } - - /** - * @see https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/stream/JsonReader.html#setLenient(boolean) - */ - public boolean isLenientOnJson() { - return lenientOnJson; - } - - public ApiClient setLenientOnJson(boolean lenient) { - this.lenientOnJson = lenient; - return this; - } - - /** - * Check that whether debugging is enabled for this API client. - */ - public boolean isDebugging() { - return debugging; - } - - /** - * Enable/disable debugging for this API client. - * - * @param debugging To enable (true) or disable (false) debugging - */ - public ApiClient setDebugging(boolean debugging) { - if (debugging != this.debugging) { - if (debugging) { - loggingInterceptor = new HttpLoggingInterceptor(); - loggingInterceptor.setLevel(Level.BODY); - httpClient.interceptors().add(loggingInterceptor); - } else { - httpClient.interceptors().remove(loggingInterceptor); - loggingInterceptor = null; - } - } - this.debugging = debugging; - return this; - } - - /** - * The path of temporary folder used to store downloaded files from endpoints - * with file response. The default value is null, i.e. using - * the system's default tempopary folder. - * - * @see https://docs.oracle.com/javase/7/docs/api/java/io/File.html#createTempFile(java.lang.String,%20java.lang.String,%20java.io.File) - */ - public String getTempFolderPath() { - return tempFolderPath; - } - - public ApiClient setTempFolderPath(String tempFolderPath) { - this.tempFolderPath = tempFolderPath; - return this; - } - - /** - * Connect timeout (in milliseconds). - */ - public int getConnectTimeout() { - return httpClient.getConnectTimeout(); - } - - /** - * Sets the connect timeout (in milliseconds). - * A value of 0 means no timeout, otherwise values must be between 1 and - * {@link Integer#MAX_VALUE}. - */ - public ApiClient setConnectTimeout(int connectionTimeout) { - httpClient.setConnectTimeout(connectionTimeout, TimeUnit.MILLISECONDS); - return this; - } - - /** - * Format the given parameter object into string. - */ - public String parameterToString(Object param) { - if (param == null) { - return ""; - } else if (param instanceof Date) { - return formatDatetime((Date) param); - } else if (param instanceof Collection) { - StringBuilder b = new StringBuilder(); - for (Object o : (Collection)param) { - if (b.length() > 0) { - b.append(","); - } - b.append(String.valueOf(o)); - } - return b.toString(); - } else { - return String.valueOf(param); - } - } - - /* - Format to {@code Pair} objects. - */ - public List parameterToPairs(String collectionFormat, String name, Object value){ - List params = new ArrayList(); - - // preconditions - if (name == null || name.isEmpty() || value == null) return params; - - Collection valueCollection = null; - if (value instanceof Collection) { - valueCollection = (Collection) value; - } else { - params.add(new Pair(name, parameterToString(value))); - return params; + /** + * Get base path + * + * @return Baes path + */ + public String getBasePath() { + return basePath; } - if (valueCollection.isEmpty()){ - return params; + /** + * Set base path + * + * @param basePath Base path of the URL (e.g http://petstore.swagger.io/v2) + * @return An instance of OkHttpClient + */ + public ApiClient setBasePath(String basePath) { + this.basePath = basePath; + return this; } - // get the collection format - collectionFormat = (collectionFormat == null || collectionFormat.isEmpty() ? "csv" : collectionFormat); // default: csv - - // create the params based on the collection format - if (collectionFormat.equals("multi")) { - for (Object item : valueCollection) { - params.add(new Pair(name, parameterToString(item))); - } - - return params; + /** + * Get HTTP client + * + * @return An instance of OkHttpClient + */ + public OkHttpClient getHttpClient() { + return httpClient; } - String delimiter = ","; - - if (collectionFormat.equals("csv")) { - delimiter = ","; - } else if (collectionFormat.equals("ssv")) { - delimiter = " "; - } else if (collectionFormat.equals("tsv")) { - delimiter = "\t"; - } else if (collectionFormat.equals("pipes")) { - delimiter = "|"; + /** + * Set HTTP client + * + * @param httpClient An instance of OkHttpClient + * @return Api Client + */ + public ApiClient setHttpClient(OkHttpClient httpClient) { + this.httpClient = httpClient; + return this; } - StringBuilder sb = new StringBuilder() ; - for (Object item : valueCollection) { - sb.append(delimiter); - sb.append(parameterToString(item)); + /** + * Get JSON + * + * @return JSON object + */ + public JSON getJSON() { + return json; } - params.add(new Pair(name, sb.substring(1))); - - return params; - } - - /** - * Sanitize filename by removing path. - * e.g. ../../sun.gif becomes sun.gif - * - * @param filename The filename to be sanitized - * @return The sanitized filename - */ - public String sanitizeFilename(String filename) { - return filename.replaceAll(".*[/\\\\]", ""); - } - - /** - * Check if the given MIME is a JSON MIME. - * JSON MIME examples: - * application/json - * application/json; charset=UTF8 - * APPLICATION/JSON - */ - public boolean isJsonMime(String mime) { - return mime != null && mime.matches("(?i)application\\/json(;.*)?"); - } - - /** - * Select the Accept header's value from the given accepts array: - * if JSON exists in the given array, use it; - * otherwise use all of them (joining into a string) - * - * @param accepts The accepts array to select from - * @return The Accept header to use. If the given array is empty, - * null will be returned (not to set the Accept header explicitly). - */ - public String selectHeaderAccept(String[] accepts) { - if (accepts.length == 0) { - return null; - } - for (String accept : accepts) { - if (isJsonMime(accept)) { - return accept; - } - } - return StringUtil.join(accepts, ","); - } - - /** - * Select the Content-Type header's value from the given array: - * if JSON exists in the given array, use it; - * otherwise use the first one of the array. - * - * @param contentTypes The Content-Type array to select from - * @return The Content-Type header to use. If the given array is empty, - * JSON will be used. - */ - public String selectHeaderContentType(String[] contentTypes) { - if (contentTypes.length == 0) { - return "application/json"; - } - for (String contentType : contentTypes) { - if (isJsonMime(contentType)) { - return contentType; - } - } - return contentTypes[0]; - } - - /** - * Escape the given string to be used as URL query value. - */ - public String escapeString(String str) { - try { - return URLEncoder.encode(str, "utf8").replaceAll("\\+", "%20"); - } catch (UnsupportedEncodingException e) { - return str; - } - } - - /** - * Deserialize response body to Java object, according to the return type and - * the Content-Type response header. - * - * @param response HTTP response - * @param returnType The type of the Java object - * @return The deserialized Java object - * @throws ApiException If fail to deserialize response body, i.e. cannot read response body - * or the Content-Type of the response is not supported. - */ - public T deserialize(Response response, Type returnType) throws ApiException { - if (response == null || returnType == null) { - return null; + /** + * Set JSON + * + * @param json JSON object + * @return Api client + */ + public ApiClient setJSON(JSON json) { + this.json = json; + return this; } - if ("byte[]".equals(returnType.toString())) { - // Handle binary response (byte array). - try { - return (T) response.body().bytes(); - } catch (IOException e) { - throw new ApiException(e); - } - } else if (returnType.equals(File.class)) { - // Handle file downloading. - return (T) downloadFileFromResponse(response); + /** + * True if isVerifyingSsl flag is on + * + * @return True if isVerifySsl flag is on + */ + public boolean isVerifyingSsl() { + return verifyingSsl; } - String respBody; - try { - if (response.body() != null) - respBody = response.body().string(); - else - respBody = null; - } catch (IOException e) { - throw new ApiException(e); + /** + * Configure whether to verify certificate and hostname when making https requests. + * Default to true. + * NOTE: Do NOT set to false in production code, otherwise you would face multiple types of cryptographic attacks. + * + * @param verifyingSsl True to verify TLS/SSL connection + * @return ApiClient + */ + public ApiClient setVerifyingSsl(boolean verifyingSsl) { + this.verifyingSsl = verifyingSsl; + applySslSettings(); + return this; } - if (respBody == null || "".equals(respBody)) { - return null; + /** + * Get SSL CA cert. + * + * @return Input stream to the SSL CA cert + */ + public InputStream getSslCaCert() { + return sslCaCert; } - String contentType = response.headers().get("Content-Type"); - if (contentType == null) { - // ensuring a default content type - contentType = "application/json"; - } - if (isJsonMime(contentType)) { - return json.deserialize(respBody, returnType); - } else if (returnType.equals(String.class)) { - // Expecting string, return the raw response body. - return (T) respBody; - } else { - throw new ApiException( - "Content type \"" + contentType + "\" is not supported for type: " + returnType, - response.code(), - response.headers().toMultimap(), - respBody); - } - } - - /** - * Serialize the given Java object into request body according to the object's - * class and the request Content-Type. - * - * @param obj The Java object - * @param contentType The request Content-Type - * @return The serialized request body - * @throws ApiException If fail to serialize the given object - */ - public RequestBody serialize(Object obj, String contentType) throws ApiException { - if (obj instanceof byte[]) { - // Binary (byte array) body parameter support. - return RequestBody.create(MediaType.parse(contentType), (byte[]) obj); - } else if (obj instanceof File) { - // File body parameter support. - return RequestBody.create(MediaType.parse(contentType), (File) obj); - } else if (isJsonMime(contentType)) { - String content; - if (obj != null) { - content = json.serialize(obj); - } else { - content = null; - } - return RequestBody.create(MediaType.parse(contentType), content); - } else { - throw new ApiException("Content type \"" + contentType + "\" is not supported"); - } - } - - /** - * Download file from the given response. - * @throws ApiException If fail to read file content from response and write to disk - */ - public File downloadFileFromResponse(Response response) throws ApiException { - try { - File file = prepareDownloadFile(response); - BufferedSink sink = Okio.buffer(Okio.sink(file)); - sink.writeAll(response.body().source()); - sink.close(); - return file; - } catch (IOException e) { - throw new ApiException(e); - } - } - - public File prepareDownloadFile(Response response) throws IOException { - String filename = null; - String contentDisposition = response.header("Content-Disposition"); - if (contentDisposition != null && !"".equals(contentDisposition)) { - // Get filename from the Content-Disposition header. - Pattern pattern = Pattern.compile("filename=['\"]?([^'\"\\s]+)['\"]?"); - Matcher matcher = pattern.matcher(contentDisposition); - if (matcher.find()) { - filename = sanitizeFilename(matcher.group(1)); - } + /** + * Configure the CA certificate to be trusted when making https requests. + * Use null to reset to default. + * + * @param sslCaCert input stream for SSL CA cert + * @return ApiClient + */ + public ApiClient setSslCaCert(InputStream sslCaCert) { + this.sslCaCert = sslCaCert; + applySslSettings(); + return this; } - String prefix = null; - String suffix = null; - if (filename == null) { - prefix = "download-"; - suffix = ""; - } else { - int pos = filename.lastIndexOf("."); - if (pos == -1) { - prefix = filename + "-"; - } else { - prefix = filename.substring(0, pos) + "-"; - suffix = filename.substring(pos); - } - // File.createTempFile requires the prefix to be at least three characters long - if (prefix.length() < 3) - prefix = "download-"; + public DateFormat getDateFormat() { + return dateFormat; } - if (tempFolderPath == null) - return File.createTempFile(prefix, suffix); - else - return File.createTempFile(prefix, suffix, new File(tempFolderPath)); - } - - /** - * @see #execute(Call, Type) - */ - public ApiResponse execute(Call call) throws ApiException { - return execute(call, null); - } - - /** - * Execute HTTP call and deserialize the HTTP response body into the given return type. - * - * @param returnType The return type used to deserialize HTTP response body - * @param The return type corresponding to (same with) returnType - * @return ApiResponse object containing response status, headers and - * data, which is a Java object deserialized from response body and would be null - * when returnType is null. - * @throws ApiException If fail to execute the call - */ - public ApiResponse execute(Call call, Type returnType) throws ApiException { - try { - Response response = call.execute(); - T data = handleResponse(response, returnType); - return new ApiResponse(response.code(), response.headers().toMultimap(), data); - } catch (IOException e) { - throw new ApiException(e); + public ApiClient setDateFormat(DateFormat dateFormat) { + this.dateFormat = dateFormat; + this.dateLength = this.dateFormat.format(new Date()).length(); + return this; } - } - /** - * #see executeAsync(Call, Type, ApiCallback) - */ - public void executeAsync(Call call, ApiCallback callback) { - executeAsync(call, null, callback); - } + public DateFormat getDatetimeFormat() { + return datetimeFormat; + } - /** - * Execute HTTP call asynchronously. - * - * @see #execute(Call, Type) - * @param The callback to be executed when the API call finishes - */ - public void executeAsync(Call call, final Type returnType, final ApiCallback callback) { - call.enqueue(new Callback() { - @Override - public void onFailure(Request request, IOException e) { - callback.onFailure(new ApiException(e), 0, null); - } + public ApiClient setDatetimeFormat(DateFormat datetimeFormat) { + this.datetimeFormat = datetimeFormat; + return this; + } - @Override - public void onResponse(Response response) throws IOException { - T result; + /** + * Whether to allow various ISO 8601 datetime formats when parsing a datetime string. + * @see #parseDatetime(String) + * @return True if lenientDatetimeFormat flag is set to true + */ + public boolean isLenientDatetimeFormat() { + return lenientDatetimeFormat; + } + + public ApiClient setLenientDatetimeFormat(boolean lenientDatetimeFormat) { + this.lenientDatetimeFormat = lenientDatetimeFormat; + return this; + } + + /** + * Parse the given date string into Date object. + * The default dateFormat supports these ISO 8601 date formats: + * 2015-08-16 + * 2015-8-16 + * @param str String to be parsed + * @return Date + */ + public Date parseDate(String str) { + if (str == null) + return null; try { - result = (T) handleResponse(response, returnType); - } catch (ApiException e) { - callback.onFailure(e, response.code(), response.headers().toMultimap()); - return; + return dateFormat.parse(str); + } catch (ParseException e) { + throw new RuntimeException(e); + } + } + + /** + * Parse the given datetime string into Date object. + * When lenientDatetimeFormat is enabled, the following ISO 8601 datetime formats are supported: + * 2015-08-16T08:20:05Z + * 2015-8-16T8:20:05Z + * 2015-08-16T08:20:05+00:00 + * 2015-08-16T08:20:05+0000 + * 2015-08-16T08:20:05.376Z + * 2015-08-16T08:20:05.376+00:00 + * 2015-08-16T08:20:05.376+00 + * Note: The 3-digit milli-seconds is optional. Time zone is required and can be in one of + * these formats: + * Z (same with +0000) + * +08:00 (same with +0800) + * -02 (same with -0200) + * -0200 + * @see ISO 8601 + * @param str Date time string to be parsed + * @return Date representation of the string + */ + public Date parseDatetime(String str) { + if (str == null) + return null; + + DateFormat format; + if (lenientDatetimeFormat) { + /* + * When lenientDatetimeFormat is enabled, normalize the date string + * into LENIENT_DATETIME_FORMAT to support various formats + * defined by ISO 8601. + */ + // normalize time zone + // trailing "Z": 2015-08-16T08:20:05Z => 2015-08-16T08:20:05+0000 + str = str.replaceAll("[zZ]\\z", "+0000"); + // remove colon in time zone: 2015-08-16T08:20:05+00:00 => 2015-08-16T08:20:05+0000 + str = str.replaceAll("([+-]\\d{2}):(\\d{2})\\z", "$1$2"); + // expand time zone: 2015-08-16T08:20:05+00 => 2015-08-16T08:20:05+0000 + str = str.replaceAll("([+-]\\d{2})\\z", "$100"); + // add milliseconds when missing + // 2015-08-16T08:20:05+0000 => 2015-08-16T08:20:05.000+0000 + str = str.replaceAll("(:\\d{1,2})([+-]\\d{4})\\z", "$1.000$2"); + format = new SimpleDateFormat(LENIENT_DATETIME_FORMAT); + } else { + format = this.datetimeFormat; } - callback.onSuccess(result, response.code(), response.headers().toMultimap()); - } - }); - } - /** - * Handle the given response, return the deserialized object when the response is successful. - * - * @throws ApiException If the response has a unsuccessful status code or - * fail to deserialize the response body - */ - public T handleResponse(Response response, Type returnType) throws ApiException { - if (response.isSuccessful()) { - if (returnType == null || response.code() == 204) { - // returning null if the returnType is not defined, - // or the status code is 204 (No Content) - return null; - } else { - return deserialize(response, returnType); - } - } else { - String respBody = null; - if (response.body() != null) { try { - respBody = response.body().string(); + return format.parse(str); + } catch (ParseException e) { + throw new RuntimeException(e); + } + } + + /* + * Parse date or date time in string format into Date object. + * + * @param str Date time string to be parsed + * @return Date representation of the string + */ + public Date parseDateOrDatetime(String str) { + if (str == null) + return null; + else if (str.length() <= dateLength) + return parseDate(str); + else + return parseDatetime(str); + } + + /** + * Format the given Date object into string (Date format). + * + * @param date Date object + * @return Formatted date in string representation + */ + public String formatDate(Date date) { + return dateFormat.format(date); + } + + /** + * Format the given Date object into string (Datetime format). + * + * @param date Date object + * @return Formatted datetime in string representation + */ + public String formatDatetime(Date date) { + return datetimeFormat.format(date); + } + + /** + * Get authentications (key: authentication name, value: authentication). + * + * @return Map of authentication objects + */ + public Map getAuthentications() { + return authentications; + } + + /** + * Get authentication for the given name. + * + * @param authName The authentication name + * @return The authentication, null if not found + */ + public Authentication getAuthentication(String authName) { + return authentications.get(authName); + } + + /** + * Helper method to set username for the first HTTP basic authentication. + * + * @param username Username + */ + public void setUsername(String username) { + for (Authentication auth : authentications.values()) { + if (auth instanceof HttpBasicAuth) { + ((HttpBasicAuth) auth).setUsername(username); + return; + } + } + throw new RuntimeException("No HTTP basic authentication configured!"); + } + + /** + * Helper method to set password for the first HTTP basic authentication. + * + * @param password Password + */ + public void setPassword(String password) { + for (Authentication auth : authentications.values()) { + if (auth instanceof HttpBasicAuth) { + ((HttpBasicAuth) auth).setPassword(password); + return; + } + } + throw new RuntimeException("No HTTP basic authentication configured!"); + } + + /** + * Helper method to set API key value for the first API key authentication. + * + * @param apiKey API key + */ + public void setApiKey(String apiKey) { + for (Authentication auth : authentications.values()) { + if (auth instanceof ApiKeyAuth) { + ((ApiKeyAuth) auth).setApiKey(apiKey); + return; + } + } + throw new RuntimeException("No API key authentication configured!"); + } + + /** + * Helper method to set API key prefix for the first API key authentication. + * + * @param apiKeyPrefix API key prefix + */ + public void setApiKeyPrefix(String apiKeyPrefix) { + for (Authentication auth : authentications.values()) { + if (auth instanceof ApiKeyAuth) { + ((ApiKeyAuth) auth).setApiKeyPrefix(apiKeyPrefix); + return; + } + } + throw new RuntimeException("No API key authentication configured!"); + } + + /** + * Helper method to set access token for the first OAuth2 authentication. + * + * @param accessToken Access token + */ + public void setAccessToken(String accessToken) { + for (Authentication auth : authentications.values()) { + if (auth instanceof OAuth) { + ((OAuth) auth).setAccessToken(accessToken); + return; + } + } + throw new RuntimeException("No OAuth2 authentication configured!"); + } + + /** + * Set the User-Agent header's value (by adding to the default header map). + * + * @param userAgent HTTP request's user agent + * @return ApiClient + */ + public ApiClient setUserAgent(String userAgent) { + addDefaultHeader("User-Agent", userAgent); + return this; + } + + /** + * Add a default header. + * + * @param key The header's key + * @param value The header's value + * @return ApiClient + */ + public ApiClient addDefaultHeader(String key, String value) { + defaultHeaderMap.put(key, value); + return this; + } + + /** + * @see setLenient + * + * @return True if lenientOnJson is enabled, false otherwise. + */ + public boolean isLenientOnJson() { + return lenientOnJson; + } + + /** + * Set LenientOnJson + * + * @param lenient True to enable lenientOnJson + * @return ApiClient + */ + public ApiClient setLenientOnJson(boolean lenient) { + this.lenientOnJson = lenient; + return this; + } + + /** + * Check that whether debugging is enabled for this API client. + * + * @return True if debugging is enabled, false otherwise. + */ + public boolean isDebugging() { + return debugging; + } + + /** + * Enable/disable debugging for this API client. + * + * @param debugging To enable (true) or disable (false) debugging + * @return ApiClient + */ + public ApiClient setDebugging(boolean debugging) { + if (debugging != this.debugging) { + if (debugging) { + loggingInterceptor = new HttpLoggingInterceptor(); + loggingInterceptor.setLevel(Level.BODY); + httpClient.interceptors().add(loggingInterceptor); + } else { + httpClient.interceptors().remove(loggingInterceptor); + loggingInterceptor = null; + } + } + this.debugging = debugging; + return this; + } + + /** + * The path of temporary folder used to store downloaded files from endpoints + * with file response. The default value is null, i.e. using + * the system's default tempopary folder. + * + * @see createTempFile + * @return Temporary folder path + */ + public String getTempFolderPath() { + return tempFolderPath; + } + + /** + * Set the tempoaray folder path (for downloading files) + * + * @param tempFolderPath Temporary folder path + * @return ApiClient + */ + public ApiClient setTempFolderPath(String tempFolderPath) { + this.tempFolderPath = tempFolderPath; + return this; + } + + /** + * Get connection timeout (in milliseconds). + * + * @return Timeout in milliseconds + */ + public int getConnectTimeout() { + return httpClient.getConnectTimeout(); + } + + /** + * Sets the connect timeout (in milliseconds). + * A value of 0 means no timeout, otherwise values must be between 1 and + * + * @param connectionTimeout connection timeout in milliseconds + * @return Api client + */ + public ApiClient setConnectTimeout(int connectionTimeout) { + httpClient.setConnectTimeout(connectionTimeout, TimeUnit.MILLISECONDS); + return this; + } + + /** + * Format the given parameter object into string. + * + * @param param Parameter + * @return String representation of the parameter + */ + public String parameterToString(Object param) { + if (param == null) { + return ""; + } else if (param instanceof Date) { + return formatDatetime((Date) param); + } else if (param instanceof Collection) { + StringBuilder b = new StringBuilder(); + for (Object o : (Collection)param) { + if (b.length() > 0) { + b.append(","); + } + b.append(String.valueOf(o)); + } + return b.toString(); + } else { + return String.valueOf(param); + } + } + + /** + * Format to {@code Pair} objects. + * + * @param collectionFormat collection format (e.g. csv, tsv) + * @param name Name + * @param value Value + * @return A list of Pair objects + */ + public List parameterToPairs(String collectionFormat, String name, Object value){ + List params = new ArrayList(); + + // preconditions + if (name == null || name.isEmpty() || value == null) return params; + + Collection valueCollection = null; + if (value instanceof Collection) { + valueCollection = (Collection) value; + } else { + params.add(new Pair(name, parameterToString(value))); + return params; + } + + if (valueCollection.isEmpty()){ + return params; + } + + // get the collection format + collectionFormat = (collectionFormat == null || collectionFormat.isEmpty() ? "csv" : collectionFormat); // default: csv + + // create the params based on the collection format + if (collectionFormat.equals("multi")) { + for (Object item : valueCollection) { + params.add(new Pair(name, parameterToString(item))); + } + + return params; + } + + String delimiter = ","; + + if (collectionFormat.equals("csv")) { + delimiter = ","; + } else if (collectionFormat.equals("ssv")) { + delimiter = " "; + } else if (collectionFormat.equals("tsv")) { + delimiter = "\t"; + } else if (collectionFormat.equals("pipes")) { + delimiter = "|"; + } + + StringBuilder sb = new StringBuilder() ; + for (Object item : valueCollection) { + sb.append(delimiter); + sb.append(parameterToString(item)); + } + + params.add(new Pair(name, sb.substring(1))); + + return params; + } + + /** + * Sanitize filename by removing path. + * e.g. ../../sun.gif becomes sun.gif + * + * @param filename The filename to be sanitized + * @return The sanitized filename + */ + public String sanitizeFilename(String filename) { + return filename.replaceAll(".*[/\\\\]", ""); + } + + /** + * Check if the given MIME is a JSON MIME. + * JSON MIME examples: + * application/json + * application/json; charset=UTF8 + * APPLICATION/JSON + * + * @param mime MIME (Multipurpose Internet Mail Extensions) + * @return True if the given MIME is JSON, false otherwise. + */ + public boolean isJsonMime(String mime) { + return mime != null && mime.matches("(?i)application\\/json(;.*)?"); + } + + /** + * Select the Accept header's value from the given accepts array: + * if JSON exists in the given array, use it; + * otherwise use all of them (joining into a string) + * + * @param accepts The accepts array to select from + * @return The Accept header to use. If the given array is empty, + * null will be returned (not to set the Accept header explicitly). + */ + public String selectHeaderAccept(String[] accepts) { + if (accepts.length == 0) { + return null; + } + for (String accept : accepts) { + if (isJsonMime(accept)) { + return accept; + } + } + return StringUtil.join(accepts, ","); + } + + /** + * Select the Content-Type header's value from the given array: + * if JSON exists in the given array, use it; + * otherwise use the first one of the array. + * + * @param contentTypes The Content-Type array to select from + * @return The Content-Type header to use. If the given array is empty, + * JSON will be used. + */ + public String selectHeaderContentType(String[] contentTypes) { + if (contentTypes.length == 0) { + return "application/json"; + } + for (String contentType : contentTypes) { + if (isJsonMime(contentType)) { + return contentType; + } + } + return contentTypes[0]; + } + + /** + * Escape the given string to be used as URL query value. + * + * @param str String to be escaped + * @return Escaped string + */ + public String escapeString(String str) { + try { + return URLEncoder.encode(str, "utf8").replaceAll("\\+", "%20"); + } catch (UnsupportedEncodingException e) { + return str; + } + } + + /** + * Deserialize response body to Java object, according to the return type and + * the Content-Type response header. + * + * @param Type + * @param response HTTP response + * @param returnType The type of the Java object + * @return The deserialized Java object + * @throws ApiException If fail to deserialize response body, i.e. cannot read response body + * or the Content-Type of the response is not supported. + */ + public T deserialize(Response response, Type returnType) throws ApiException { + if (response == null || returnType == null) { + return null; + } + + if ("byte[]".equals(returnType.toString())) { + // Handle binary response (byte array). + try { + return (T) response.body().bytes(); + } catch (IOException e) { + throw new ApiException(e); + } + } else if (returnType.equals(File.class)) { + // Handle file downloading. + return (T) downloadFileFromResponse(response); + } + + String respBody; + try { + if (response.body() != null) + respBody = response.body().string(); + else + respBody = null; } catch (IOException e) { - throw new ApiException(response.message(), e, response.code(), response.headers().toMultimap()); + throw new ApiException(e); } - } - throw new ApiException(response.message(), response.code(), response.headers().toMultimap(), respBody); - } - } - /** - * Build HTTP call with the given options. - * - * @param path The sub-path of the HTTP URL - * @param method The request method, one of "GET", "HEAD", "OPTIONS", "POST", "PUT", "PATCH" and "DELETE" - * @param queryParams The query parameters - * @param body The request body object - * @param headerParams The header parameters - * @param formParams The form parameters - * @param authNames The authentications to apply - * @return The HTTP call - * @throws ApiException If fail to serialize the request body object - */ - public Call buildCall(String path, String method, List queryParams, Object body, Map headerParams, Map formParams, String[] authNames, ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - updateParamsForAuth(authNames, queryParams, headerParams); - - final String url = buildUrl(path, queryParams); - final Request.Builder reqBuilder = new Request.Builder().url(url); - processHeaderParams(headerParams, reqBuilder); - - String contentType = (String) headerParams.get("Content-Type"); - // ensuring a default content type - if (contentType == null) { - contentType = "application/json"; - } - - RequestBody reqBody; - if (!HttpMethod.permitsRequestBody(method)) { - reqBody = null; - } else if ("application/x-www-form-urlencoded".equals(contentType)) { - reqBody = buildRequestBodyFormEncoding(formParams); - } else if ("multipart/form-data".equals(contentType)) { - reqBody = buildRequestBodyMultipart(formParams); - } else if (body == null) { - if ("DELETE".equals(method)) { - // allow calling DELETE without sending a request body - reqBody = null; - } else { - // use an empty request body (for POST, PUT and PATCH) - reqBody = RequestBody.create(MediaType.parse(contentType), ""); - } - } else { - reqBody = serialize(body, contentType); - } - - Request request = null; - - if(progressRequestListener != null && reqBody != null) { - ProgressRequestBody progressRequestBody = new ProgressRequestBody(reqBody, progressRequestListener); - request = reqBuilder.method(method, progressRequestBody).build(); - } else { - request = reqBuilder.method(method, reqBody).build(); - } - - return httpClient.newCall(request); - } - - /** - * Build full URL by concatenating base path, the given sub path and query parameters. - * - * @param path The sub path - * @param queryParams The query parameters - * @return The full URL - */ - public String buildUrl(String path, List queryParams) { - final StringBuilder url = new StringBuilder(); - url.append(basePath).append(path); - - if (queryParams != null && !queryParams.isEmpty()) { - // support (constant) query string in `path`, e.g. "/posts?draft=1" - String prefix = path.contains("?") ? "&" : "?"; - for (Pair param : queryParams) { - if (param.getValue() != null) { - if (prefix != null) { - url.append(prefix); - prefix = null; - } else { - url.append("&"); - } - String value = parameterToString(param.getValue()); - url.append(escapeString(param.getName())).append("=").append(escapeString(value)); + if (respBody == null || "".equals(respBody)) { + return null; } - } - } - return url.toString(); - } - - /** - * Set header parameters to the request builder, including default headers. - */ - public void processHeaderParams(Map headerParams, Request.Builder reqBuilder) { - for (Entry param : headerParams.entrySet()) { - reqBuilder.header(param.getKey(), parameterToString(param.getValue())); - } - for (Entry header : defaultHeaderMap.entrySet()) { - if (!headerParams.containsKey(header.getKey())) { - reqBuilder.header(header.getKey(), parameterToString(header.getValue())); - } - } - } - - /** - * Update query and header parameters based on authentication settings. - * - * @param authNames The authentications to apply - */ - public void updateParamsForAuth(String[] authNames, List queryParams, Map headerParams) { - for (String authName : authNames) { - Authentication auth = authentications.get(authName); - if (auth == null) throw new RuntimeException("Authentication undefined: " + authName); - auth.applyToParams(queryParams, headerParams); - } - } - - /** - * Build a form-encoding request body with the given form parameters. - */ - public RequestBody buildRequestBodyFormEncoding(Map formParams) { - FormEncodingBuilder formBuilder = new FormEncodingBuilder(); - for (Entry param : formParams.entrySet()) { - formBuilder.add(param.getKey(), parameterToString(param.getValue())); - } - return formBuilder.build(); - } - - /** - * Build a multipart (file uploading) request body with the given form parameters, - * which could contain text fields and file fields. - */ - public RequestBody buildRequestBodyMultipart(Map formParams) { - MultipartBuilder mpBuilder = new MultipartBuilder().type(MultipartBuilder.FORM); - for (Entry param : formParams.entrySet()) { - if (param.getValue() instanceof File) { - File file = (File) param.getValue(); - Headers partHeaders = Headers.of("Content-Disposition", "form-data; name=\"" + param.getKey() + "\"; filename=\"" + file.getName() + "\""); - MediaType mediaType = MediaType.parse(guessContentTypeFromFile(file)); - mpBuilder.addPart(partHeaders, RequestBody.create(mediaType, file)); - } else { - Headers partHeaders = Headers.of("Content-Disposition", "form-data; name=\"" + param.getKey() + "\""); - mpBuilder.addPart(partHeaders, RequestBody.create(null, parameterToString(param.getValue()))); - } - } - return mpBuilder.build(); - } - - /** - * Guess Content-Type header from the given file (defaults to "application/octet-stream"). - * - * @param file The given file - * @return The Content-Type guessed - */ - public String guessContentTypeFromFile(File file) { - String contentType = URLConnection.guessContentTypeFromName(file.getName()); - if (contentType == null) { - return "application/octet-stream"; - } else { - return contentType; - } - } - - /** - * Initialize datetime format according to the current environment, e.g. Java 1.7 and Android. - */ - private void initDatetimeFormat() { - String formatWithTimeZone = null; - if (IS_ANDROID) { - if (ANDROID_SDK_VERSION >= 18) { - // The time zone format "ZZZZZ" is available since Android 4.3 (SDK version 18) - formatWithTimeZone = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ"; - } - } else if (JAVA_VERSION >= 1.7) { - // The time zone format "XXX" is available since Java 1.7 - formatWithTimeZone = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX"; - } - if (formatWithTimeZone != null) { - this.datetimeFormat = new SimpleDateFormat(formatWithTimeZone); - // NOTE: Use the system's default time zone (mainly for datetime formatting). - } else { - // Use a common format that works across all systems. - this.datetimeFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); - // Always use the UTC time zone as we are using a constant trailing "Z" here. - this.datetimeFormat.setTimeZone(TimeZone.getTimeZone("UTC")); - } - } - - /** - * Apply SSL related settings to httpClient according to the current values of - * verifyingSsl and sslCaCert. - */ - private void applySslSettings() { - try { - KeyManager[] keyManagers = null; - TrustManager[] trustManagers = null; - HostnameVerifier hostnameVerifier = null; - if (!verifyingSsl) { - TrustManager trustAll = new X509TrustManager() { - @Override - public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {} - @Override - public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {} - @Override - public X509Certificate[] getAcceptedIssuers() { return null; } - }; - SSLContext sslContext = SSLContext.getInstance("TLS"); - trustManagers = new TrustManager[]{ trustAll }; - hostnameVerifier = new HostnameVerifier() { - @Override - public boolean verify(String hostname, SSLSession session) { return true; } - }; - } else if (sslCaCert != null) { - char[] password = null; // Any password will work. - CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); - Collection certificates = certificateFactory.generateCertificates(sslCaCert); - if (certificates.isEmpty()) { - throw new IllegalArgumentException("expected non-empty set of trusted certificates"); + String contentType = response.headers().get("Content-Type"); + if (contentType == null) { + // ensuring a default content type + contentType = "application/json"; } - KeyStore caKeyStore = newEmptyKeyStore(password); - int index = 0; - for (Certificate certificate : certificates) { - String certificateAlias = "ca" + Integer.toString(index++); - caKeyStore.setCertificateEntry(certificateAlias, certificate); + if (isJsonMime(contentType)) { + return json.deserialize(respBody, returnType); + } else if (returnType.equals(String.class)) { + // Expecting string, return the raw response body. + return (T) respBody; + } else { + throw new ApiException( + "Content type \"" + contentType + "\" is not supported for type: " + returnType, + response.code(), + response.headers().toMultimap(), + respBody); } - TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); - trustManagerFactory.init(caKeyStore); - trustManagers = trustManagerFactory.getTrustManagers(); - } - - if (keyManagers != null || trustManagers != null) { - SSLContext sslContext = SSLContext.getInstance("TLS"); - sslContext.init(keyManagers, trustManagers, new SecureRandom()); - httpClient.setSslSocketFactory(sslContext.getSocketFactory()); - } else { - httpClient.setSslSocketFactory(null); - } - httpClient.setHostnameVerifier(hostnameVerifier); - } catch (GeneralSecurityException e) { - throw new RuntimeException(e); } - } - private KeyStore newEmptyKeyStore(char[] password) throws GeneralSecurityException { - try { - KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); - keyStore.load(null, password); - return keyStore; - } catch (IOException e) { - throw new AssertionError(e); + /** + * Serialize the given Java object into request body according to the object's + * class and the request Content-Type. + * + * @param obj The Java object + * @param contentType The request Content-Type + * @return The serialized request body + * @throws ApiException If fail to serialize the given object + */ + public RequestBody serialize(Object obj, String contentType) throws ApiException { + if (obj instanceof byte[]) { + // Binary (byte array) body parameter support. + return RequestBody.create(MediaType.parse(contentType), (byte[]) obj); + } else if (obj instanceof File) { + // File body parameter support. + return RequestBody.create(MediaType.parse(contentType), (File) obj); + } else if (isJsonMime(contentType)) { + String content; + if (obj != null) { + content = json.serialize(obj); + } else { + content = null; + } + return RequestBody.create(MediaType.parse(contentType), content); + } else { + throw new ApiException("Content type \"" + contentType + "\" is not supported"); + } + } + + /** + * Download file from the given response. + * + * @param response An instance of the Response object + * @throws ApiException If fail to read file content from response and write to disk + * @return Downloaded file + */ + public File downloadFileFromResponse(Response response) throws ApiException { + try { + File file = prepareDownloadFile(response); + BufferedSink sink = Okio.buffer(Okio.sink(file)); + sink.writeAll(response.body().source()); + sink.close(); + return file; + } catch (IOException e) { + throw new ApiException(e); + } + } + + /** + * Prepare file for download + * + * @param response An instance of the Response object + * @throws IOException If fail to prepare file for download + * @return Prepared file for the download + */ + public File prepareDownloadFile(Response response) throws IOException { + String filename = null; + String contentDisposition = response.header("Content-Disposition"); + if (contentDisposition != null && !"".equals(contentDisposition)) { + // Get filename from the Content-Disposition header. + Pattern pattern = Pattern.compile("filename=['\"]?([^'\"\\s]+)['\"]?"); + Matcher matcher = pattern.matcher(contentDisposition); + if (matcher.find()) { + filename = sanitizeFilename(matcher.group(1)); + } + } + + String prefix = null; + String suffix = null; + if (filename == null) { + prefix = "download-"; + suffix = ""; + } else { + int pos = filename.lastIndexOf("."); + if (pos == -1) { + prefix = filename + "-"; + } else { + prefix = filename.substring(0, pos) + "-"; + suffix = filename.substring(pos); + } + // File.createTempFile requires the prefix to be at least three characters long + if (prefix.length() < 3) + prefix = "download-"; + } + + if (tempFolderPath == null) + return File.createTempFile(prefix, suffix); + else + return File.createTempFile(prefix, suffix, new File(tempFolderPath)); + } + + /** + * {@link #execute(Call, Type)} + * + * @param Type + * @param call An instance of the Call object + * @throws ApiException If fail to execute the call + * @return ApiResponse<T> + */ + public ApiResponse execute(Call call) throws ApiException { + return execute(call, null); + } + + /** + * Execute HTTP call and deserialize the HTTP response body into the given return type. + * + * @param returnType The return type used to deserialize HTTP response body + * @param The return type corresponding to (same with) returnType + * @param call Call + * @return ApiResponse object containing response status, headers and + * data, which is a Java object deserialized from response body and would be null + * when returnType is null. + * @throws ApiException If fail to execute the call + */ + public ApiResponse execute(Call call, Type returnType) throws ApiException { + try { + Response response = call.execute(); + T data = handleResponse(response, returnType); + return new ApiResponse(response.code(), response.headers().toMultimap(), data); + } catch (IOException e) { + throw new ApiException(e); + } + } + + /** + * {@link #executeAsync(Call, Type, ApiCallback)} + * + * @param Type + * @param call An instance of the Call object + * @param callback ApiCallback<T> + */ + public void executeAsync(Call call, ApiCallback callback) { + executeAsync(call, null, callback); + } + + /** + * Execute HTTP call asynchronously. + * + * @see #execute(Call, Type) + * @param Type + * @param call The callback to be executed when the API call finishes + * @param returnType Return type + * @param callback ApiCallback + */ + public void executeAsync(Call call, final Type returnType, final ApiCallback callback) { + call.enqueue(new Callback() { + @Override + public void onFailure(Request request, IOException e) { + callback.onFailure(new ApiException(e), 0, null); + } + + @Override + public void onResponse(Response response) throws IOException { + T result; + try { + result = (T) handleResponse(response, returnType); + } catch (ApiException e) { + callback.onFailure(e, response.code(), response.headers().toMultimap()); + return; + } + callback.onSuccess(result, response.code(), response.headers().toMultimap()); + } + }); + } + + /** + * Handle the given response, return the deserialized object when the response is successful. + * + * @param Type + * @param response Response + * @param returnType Return type + * @throws ApiException If the response has a unsuccessful status code or + * fail to deserialize the response body + * @return Type + */ + public T handleResponse(Response response, Type returnType) throws ApiException { + if (response.isSuccessful()) { + if (returnType == null || response.code() == 204) { + // returning null if the returnType is not defined, + // or the status code is 204 (No Content) + return null; + } else { + return deserialize(response, returnType); + } + } else { + String respBody = null; + if (response.body() != null) { + try { + respBody = response.body().string(); + } catch (IOException e) { + throw new ApiException(response.message(), e, response.code(), response.headers().toMultimap()); + } + } + throw new ApiException(response.message(), response.code(), response.headers().toMultimap(), respBody); + } + } + + /** + * Build HTTP call with the given options. + * + * @param path The sub-path of the HTTP URL + * @param method The request method, one of "GET", "HEAD", "OPTIONS", "POST", "PUT", "PATCH" and "DELETE" + * @param queryParams The query parameters + * @param body The request body object + * @param headerParams The header parameters + * @param formParams The form parameters + * @param authNames The authentications to apply + * @param progressRequestListener Progress request listener + * @return The HTTP call + * @throws ApiException If fail to serialize the request body object + */ + public Call buildCall(String path, String method, List queryParams, Object body, Map headerParams, Map formParams, String[] authNames, ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + updateParamsForAuth(authNames, queryParams, headerParams); + + final String url = buildUrl(path, queryParams); + final Request.Builder reqBuilder = new Request.Builder().url(url); + processHeaderParams(headerParams, reqBuilder); + + String contentType = (String) headerParams.get("Content-Type"); + // ensuring a default content type + if (contentType == null) { + contentType = "application/json"; + } + + RequestBody reqBody; + if (!HttpMethod.permitsRequestBody(method)) { + reqBody = null; + } else if ("application/x-www-form-urlencoded".equals(contentType)) { + reqBody = buildRequestBodyFormEncoding(formParams); + } else if ("multipart/form-data".equals(contentType)) { + reqBody = buildRequestBodyMultipart(formParams); + } else if (body == null) { + if ("DELETE".equals(method)) { + // allow calling DELETE without sending a request body + reqBody = null; + } else { + // use an empty request body (for POST, PUT and PATCH) + reqBody = RequestBody.create(MediaType.parse(contentType), ""); + } + } else { + reqBody = serialize(body, contentType); + } + + Request request = null; + + if(progressRequestListener != null && reqBody != null) { + ProgressRequestBody progressRequestBody = new ProgressRequestBody(reqBody, progressRequestListener); + request = reqBuilder.method(method, progressRequestBody).build(); + } else { + request = reqBuilder.method(method, reqBody).build(); + } + + return httpClient.newCall(request); + } + + /** + * Build full URL by concatenating base path, the given sub path and query parameters. + * + * @param path The sub path + * @param queryParams The query parameters + * @return The full URL + */ + public String buildUrl(String path, List queryParams) { + final StringBuilder url = new StringBuilder(); + url.append(basePath).append(path); + + if (queryParams != null && !queryParams.isEmpty()) { + // support (constant) query string in `path`, e.g. "/posts?draft=1" + String prefix = path.contains("?") ? "&" : "?"; + for (Pair param : queryParams) { + if (param.getValue() != null) { + if (prefix != null) { + url.append(prefix); + prefix = null; + } else { + url.append("&"); + } + String value = parameterToString(param.getValue()); + url.append(escapeString(param.getName())).append("=").append(escapeString(value)); + } + } + } + + return url.toString(); + } + + /** + * Set header parameters to the request builder, including default headers. + * + * @param headerParams Header parameters in the ofrm of Map + * @param reqBuilder Reqeust.Builder + */ + public void processHeaderParams(Map headerParams, Request.Builder reqBuilder) { + for (Entry param : headerParams.entrySet()) { + reqBuilder.header(param.getKey(), parameterToString(param.getValue())); + } + for (Entry header : defaultHeaderMap.entrySet()) { + if (!headerParams.containsKey(header.getKey())) { + reqBuilder.header(header.getKey(), parameterToString(header.getValue())); + } + } + } + + /** + * Update query and header parameters based on authentication settings. + * + * @param authNames The authentications to apply + * @param queryParams List of query parameters + * @param headerParams Map of header parameters + */ + public void updateParamsForAuth(String[] authNames, List queryParams, Map headerParams) { + for (String authName : authNames) { + Authentication auth = authentications.get(authName); + if (auth == null) throw new RuntimeException("Authentication undefined: " + authName); + auth.applyToParams(queryParams, headerParams); + } + } + + /** + * Build a form-encoding request body with the given form parameters. + * + * @param formParams Form parameters in the form of Map + * @return RequestBody + */ + public RequestBody buildRequestBodyFormEncoding(Map formParams) { + FormEncodingBuilder formBuilder = new FormEncodingBuilder(); + for (Entry param : formParams.entrySet()) { + formBuilder.add(param.getKey(), parameterToString(param.getValue())); + } + return formBuilder.build(); + } + + /** + * Build a multipart (file uploading) request body with the given form parameters, + * which could contain text fields and file fields. + * + * @param formParams Form parameters in the form of Map + * @return RequestBody + */ + public RequestBody buildRequestBodyMultipart(Map formParams) { + MultipartBuilder mpBuilder = new MultipartBuilder().type(MultipartBuilder.FORM); + for (Entry param : formParams.entrySet()) { + if (param.getValue() instanceof File) { + File file = (File) param.getValue(); + Headers partHeaders = Headers.of("Content-Disposition", "form-data; name=\"" + param.getKey() + "\"; filename=\"" + file.getName() + "\""); + MediaType mediaType = MediaType.parse(guessContentTypeFromFile(file)); + mpBuilder.addPart(partHeaders, RequestBody.create(mediaType, file)); + } else { + Headers partHeaders = Headers.of("Content-Disposition", "form-data; name=\"" + param.getKey() + "\""); + mpBuilder.addPart(partHeaders, RequestBody.create(null, parameterToString(param.getValue()))); + } + } + return mpBuilder.build(); + } + + /** + * Guess Content-Type header from the given file (defaults to "application/octet-stream"). + * + * @param file The given file + * @return The guessed Content-Type + */ + public String guessContentTypeFromFile(File file) { + String contentType = URLConnection.guessContentTypeFromName(file.getName()); + if (contentType == null) { + return "application/octet-stream"; + } else { + return contentType; + } + } + + /** + * Initialize datetime format according to the current environment, e.g. Java 1.7 and Android. + */ + private void initDatetimeFormat() { + String formatWithTimeZone = null; + if (IS_ANDROID) { + if (ANDROID_SDK_VERSION >= 18) { + // The time zone format "ZZZZZ" is available since Android 4.3 (SDK version 18) + formatWithTimeZone = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ"; + } + } else if (JAVA_VERSION >= 1.7) { + // The time zone format "XXX" is available since Java 1.7 + formatWithTimeZone = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX"; + } + if (formatWithTimeZone != null) { + this.datetimeFormat = new SimpleDateFormat(formatWithTimeZone); + // NOTE: Use the system's default time zone (mainly for datetime formatting). + } else { + // Use a common format that works across all systems. + this.datetimeFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); + // Always use the UTC time zone as we are using a constant trailing "Z" here. + this.datetimeFormat.setTimeZone(TimeZone.getTimeZone("UTC")); + } + } + + /** + * Apply SSL related settings to httpClient according to the current values of + * verifyingSsl and sslCaCert. + */ + private void applySslSettings() { + try { + KeyManager[] keyManagers = null; + TrustManager[] trustManagers = null; + HostnameVerifier hostnameVerifier = null; + if (!verifyingSsl) { + TrustManager trustAll = new X509TrustManager() { + @Override + public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {} + @Override + public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {} + @Override + public X509Certificate[] getAcceptedIssuers() { return null; } + }; + SSLContext sslContext = SSLContext.getInstance("TLS"); + trustManagers = new TrustManager[]{ trustAll }; + hostnameVerifier = new HostnameVerifier() { + @Override + public boolean verify(String hostname, SSLSession session) { return true; } + }; + } else if (sslCaCert != null) { + char[] password = null; // Any password will work. + CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); + Collection certificates = certificateFactory.generateCertificates(sslCaCert); + if (certificates.isEmpty()) { + throw new IllegalArgumentException("expected non-empty set of trusted certificates"); + } + KeyStore caKeyStore = newEmptyKeyStore(password); + int index = 0; + for (Certificate certificate : certificates) { + String certificateAlias = "ca" + Integer.toString(index++); + caKeyStore.setCertificateEntry(certificateAlias, certificate); + } + TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); + trustManagerFactory.init(caKeyStore); + trustManagers = trustManagerFactory.getTrustManagers(); + } + + if (keyManagers != null || trustManagers != null) { + SSLContext sslContext = SSLContext.getInstance("TLS"); + sslContext.init(keyManagers, trustManagers, new SecureRandom()); + httpClient.setSslSocketFactory(sslContext.getSocketFactory()); + } else { + httpClient.setSslSocketFactory(null); + } + httpClient.setHostnameVerifier(hostnameVerifier); + } catch (GeneralSecurityException e) { + throw new RuntimeException(e); + } + } + + private KeyStore newEmptyKeyStore(char[] password) throws GeneralSecurityException { + try { + KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); + keyStore.load(null, password); + return keyStore; + } catch (IOException e) { + throw new AssertionError(e); + } } - } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiException.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiException.java index 73836815f56..600bb507f09 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiException.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiException.java @@ -1,69 +1,103 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client; import java.util.Map; import java.util.List; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-06-03T00:41:49.229+08:00") + public class ApiException extends Exception { - private int code = 0; - private Map> responseHeaders = null; - private String responseBody = null; + private int code = 0; + private Map> responseHeaders = null; + private String responseBody = null; - public ApiException() {} + public ApiException() {} - public ApiException(Throwable throwable) { - super(throwable); - } + public ApiException(Throwable throwable) { + super(throwable); + } - public ApiException(String message) { - super(message); - } + public ApiException(String message) { + super(message); + } - public ApiException(String message, Throwable throwable, int code, Map> responseHeaders, String responseBody) { - super(message, throwable); - this.code = code; - this.responseHeaders = responseHeaders; - this.responseBody = responseBody; - } + public ApiException(String message, Throwable throwable, int code, Map> responseHeaders, String responseBody) { + super(message, throwable); + this.code = code; + this.responseHeaders = responseHeaders; + this.responseBody = responseBody; + } - public ApiException(String message, int code, Map> responseHeaders, String responseBody) { - this(message, (Throwable) null, code, responseHeaders, responseBody); - } + public ApiException(String message, int code, Map> responseHeaders, String responseBody) { + this(message, (Throwable) null, code, responseHeaders, responseBody); + } - public ApiException(String message, Throwable throwable, int code, Map> responseHeaders) { - this(message, throwable, code, responseHeaders, null); - } + public ApiException(String message, Throwable throwable, int code, Map> responseHeaders) { + this(message, throwable, code, responseHeaders, null); + } - public ApiException(int code, Map> responseHeaders, String responseBody) { - this((String) null, (Throwable) null, code, responseHeaders, responseBody); - } + public ApiException(int code, Map> responseHeaders, String responseBody) { + this((String) null, (Throwable) null, code, responseHeaders, responseBody); + } - public ApiException(int code, String message) { - super(message); - this.code = code; - } + public ApiException(int code, String message) { + super(message); + this.code = code; + } - public ApiException(int code, String message, Map> responseHeaders, String responseBody) { - this(code, message); - this.responseHeaders = responseHeaders; - this.responseBody = responseBody; - } + public ApiException(int code, String message, Map> responseHeaders, String responseBody) { + this(code, message); + this.responseHeaders = responseHeaders; + this.responseBody = responseBody; + } - public int getCode() { - return code; - } + /** + * Get the HTTP status code. + * + * @return HTTP status code + */ + public int getCode() { + return code; + } - /** - * Get the HTTP response headers. - */ - public Map> getResponseHeaders() { - return responseHeaders; - } + /** + * Get the HTTP response headers. + * + * @return A map of list of string + */ + public Map> getResponseHeaders() { + return responseHeaders; + } - /** - * Get the HTTP response body. - */ - public String getResponseBody() { - return responseBody; - } + /** + * Get the HTTP response body. + * + * @return Response body in the form of string + */ + public String getResponseBody() { + return responseBody; + } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiResponse.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiResponse.java index 0a33f09e64e..b112f15f3e3 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiResponse.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiResponse.java @@ -1,3 +1,28 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client; import java.util.List; @@ -9,38 +34,38 @@ import java.util.Map; * @param T The type of data that is deserialized from response body */ public class ApiResponse { - final private int statusCode; - final private Map> headers; - final private T data; + final private int statusCode; + final private Map> headers; + final private T data; - /** - * @param statusCode The status code of HTTP response - * @param headers The headers of HTTP response - */ - public ApiResponse(int statusCode, Map> headers) { - this(statusCode, headers, null); - } + /** + * @param statusCode The status code of HTTP response + * @param headers The headers of HTTP response + */ + public ApiResponse(int statusCode, Map> headers) { + this(statusCode, headers, null); + } - /** - * @param statusCode The status code of HTTP response - * @param headers The headers of HTTP response - * @param data The object deserialized from response bod - */ - public ApiResponse(int statusCode, Map> headers, T data) { - this.statusCode = statusCode; - this.headers = headers; - this.data = data; - } + /** + * @param statusCode The status code of HTTP response + * @param headers The headers of HTTP response + * @param data The object deserialized from response bod + */ + public ApiResponse(int statusCode, Map> headers, T data) { + this.statusCode = statusCode; + this.headers = headers; + this.data = data; + } - public int getStatusCode() { - return statusCode; - } + public int getStatusCode() { + return statusCode; + } - public Map> getHeaders() { - return headers; - } + public Map> getHeaders() { + return headers; + } - public T getData() { - return data; - } + public T getData() { + return data; + } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/Configuration.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/Configuration.java index db5ca8245e1..cbdadd6262d 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/Configuration.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/Configuration.java @@ -1,22 +1,51 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-06-03T00:41:49.229+08:00") + public class Configuration { - private static ApiClient defaultApiClient = new ApiClient(); + private static ApiClient defaultApiClient = new ApiClient(); - /** - * Get the default API client, which would be used when creating API - * instances without providing an API client. - */ - public static ApiClient getDefaultApiClient() { - return defaultApiClient; - } + /** + * Get the default API client, which would be used when creating API + * instances without providing an API client. + * + * @return Default API client + */ + public static ApiClient getDefaultApiClient() { + return defaultApiClient; + } - /** - * Set the default API client, which would be used when creating API - * instances without providing an API client. - */ - public static void setDefaultApiClient(ApiClient apiClient) { - defaultApiClient = apiClient; - } + /** + * Set the default API client, which would be used when creating API + * instances without providing an API client. + * + * @param apiClient API client + */ + public static void setDefaultApiClient(ApiClient apiClient) { + defaultApiClient = apiClient; + } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/JSON.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/JSON.java index d9d0881a153..7e404e47a26 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/JSON.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/JSON.java @@ -1,3 +1,28 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client; import com.google.gson.Gson; @@ -10,76 +35,118 @@ import com.google.gson.JsonParseException; import com.google.gson.JsonPrimitive; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; +import com.google.gson.TypeAdapter; import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; import java.io.StringReader; import java.lang.reflect.Type; import java.util.Date; +import org.joda.time.DateTime; +import org.joda.time.LocalDate; +import org.joda.time.format.DateTimeFormatter; +import org.joda.time.format.ISODateTimeFormat; + public class JSON { - private ApiClient apiClient; - private Gson gson; + private ApiClient apiClient; + private Gson gson; - public JSON(ApiClient apiClient) { - this.apiClient = apiClient; - gson = new GsonBuilder() - .registerTypeAdapter(Date.class, new DateAdapter(apiClient)) - .create(); - } - - public Gson getGson() { - return gson; - } - - public void setGson(Gson gson) { - this.gson = gson; - } - - /** - * Serialize the given Java object into JSON string. - */ - public String serialize(Object obj) { - return gson.toJson(obj); - } - - /** - * Deserialize the given JSON string to Java object. - * - * @param body The JSON string - * @param returnType The type to deserialize inot - * @return The deserialized Java object - */ - public T deserialize(String body, Type returnType) { - try { - if (apiClient.isLenientOnJson()) { - JsonReader jsonReader = new JsonReader(new StringReader(body)); - // see https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/stream/JsonReader.html#setLenient(boolean) - jsonReader.setLenient(true); - return gson.fromJson(jsonReader, returnType); - } else { - return gson.fromJson(body, returnType); - } - } catch (JsonParseException e) { - // Fallback processing when failed to parse JSON form response body: - // return the response body string directly for the String return type; - // parse response body into date or datetime for the Date return type. - if (returnType.equals(String.class)) - return (T) body; - else if (returnType.equals(Date.class)) - return (T) apiClient.parseDateOrDatetime(body); - else throw(e); + /** + * JSON constructor. + * + * @param apiClient An instance of ApiClient + */ + public JSON(ApiClient apiClient) { + this.apiClient = apiClient; + gson = new GsonBuilder() + .registerTypeAdapter(Date.class, new DateAdapter(apiClient)) + .registerTypeAdapter(DateTime.class, new DateTimeTypeAdapter()) + .registerTypeAdapter(LocalDate.class, new LocalDateTypeAdapter()) + .create(); + } + + /** + * Get Gson. + * + * @return Gson + */ + public Gson getGson() { + return gson; + } + + /** + * Set Gson. + * + * @param gson Gson + */ + public void setGson(Gson gson) { + this.gson = gson; + } + + /** + * Serialize the given Java object into JSON string. + * + * @param obj Object + * @return String representation of the JSON + */ + public String serialize(Object obj) { + return gson.toJson(obj); + } + + /** + * Deserialize the given JSON string to Java object. + * + * @param Type + * @param body The JSON string + * @param returnType The type to deserialize inot + * @return The deserialized Java object + */ + public T deserialize(String body, Type returnType) { + try { + if (apiClient.isLenientOnJson()) { + JsonReader jsonReader = new JsonReader(new StringReader(body)); + // see https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/stream/JsonReader.html#setLenient(boolean) + jsonReader.setLenient(true); + return gson.fromJson(jsonReader, returnType); + } else { + return gson.fromJson(body, returnType); + } + } catch (JsonParseException e) { + // Fallback processing when failed to parse JSON form response body: + // return the response body string directly for the String return type; + // parse response body into date or datetime for the Date return type. + if (returnType.equals(String.class)) + return (T) body; + else if (returnType.equals(Date.class)) + return (T) apiClient.parseDateOrDatetime(body); + else throw(e); + } } - } } class DateAdapter implements JsonSerializer, JsonDeserializer { private final ApiClient apiClient; + /** + * Constructor for DateAdapter + * + * @param apiClient Api client + */ public DateAdapter(ApiClient apiClient) { super(); this.apiClient = apiClient; } + /** + * Serialize + * + * @param src Date + * @param typeOfSrc Type + * @param context Json Serialization Context + * @return Json Element + */ @Override public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) { if (src == null) { @@ -89,6 +156,16 @@ class DateAdapter implements JsonSerializer, JsonDeserializer { } } + /** + * Deserialize + * + * @param json Json element + * @param date Type + * @param typeOfSrc Type + * @param context Json Serialization Context + * @return Date + * @throw JsonParseException if fail to parse + */ @Override public Date deserialize(JsonElement json, Type date, JsonDeserializationContext context) throws JsonParseException { String str = json.getAsJsonPrimitive().getAsString(); @@ -99,3 +176,62 @@ class DateAdapter implements JsonSerializer, JsonDeserializer { } } } + +/** + * Gson TypeAdapter for Joda DateTime type + */ +class DateTimeTypeAdapter extends TypeAdapter { + + private final DateTimeFormatter formatter = ISODateTimeFormat.dateTime(); + + @Override + public void write(JsonWriter out, DateTime date) throws IOException { + if (date == null) { + out.nullValue(); + } else { + out.value(formatter.print(date)); + } + } + + @Override + public DateTime read(JsonReader in) throws IOException { + switch (in.peek()) { + case NULL: + in.nextNull(); + return null; + default: + String date = in.nextString(); + return formatter.parseDateTime(date); + } + } +} + +/** + * Gson TypeAdapter for Joda LocalDate type + */ +class LocalDateTypeAdapter extends TypeAdapter { + + private final DateTimeFormatter formatter = ISODateTimeFormat.date(); + + @Override + public void write(JsonWriter out, LocalDate date) throws IOException { + if (date == null) { + out.nullValue(); + } else { + out.value(formatter.print(date)); + } + } + + @Override + public LocalDate read(JsonReader in) throws IOException { + switch (in.peek()) { + case NULL: + in.nextNull(); + return null; + default: + String date = in.nextString(); + return formatter.parseLocalDate(date); + } + } +} + diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/Pair.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/Pair.java index e49c7eb9146..4b44c415812 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/Pair.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/Pair.java @@ -1,6 +1,31 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-06-03T00:41:49.229+08:00") + public class Pair { private String name = ""; private String value = ""; diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ProgressRequestBody.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ProgressRequestBody.java index 71f34ed1140..a29fc9aec70 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ProgressRequestBody.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ProgressRequestBody.java @@ -1,3 +1,28 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client; import com.squareup.okhttp.MediaType; @@ -18,9 +43,9 @@ public class ProgressRequestBody extends RequestBody { } private final RequestBody requestBody; - + private final ProgressRequestListener progressListener; - + private BufferedSink bufferedSink; public ProgressRequestBody(RequestBody requestBody, ProgressRequestListener progressListener) { @@ -43,7 +68,7 @@ public class ProgressRequestBody extends RequestBody { if (bufferedSink == null) { bufferedSink = Okio.buffer(sink(sink)); } - + requestBody.writeTo(bufferedSink); bufferedSink.flush(); @@ -51,7 +76,7 @@ public class ProgressRequestBody extends RequestBody { private Sink sink(Sink sink) { return new ForwardingSink(sink) { - + long bytesWritten = 0L; long contentLength = 0L; diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ProgressResponseBody.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ProgressResponseBody.java index 138da3f2106..c20672cf0c4 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ProgressResponseBody.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ProgressResponseBody.java @@ -1,3 +1,28 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client; import com.squareup.okhttp.MediaType; diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/StringUtil.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/StringUtil.java index b4a8d21f750..03c6c81e434 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/StringUtil.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/StringUtil.java @@ -1,6 +1,31 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-06-03T00:41:49.229+08:00") + public class StringUtil { /** * Check if the given array contains the given value (with case-insensitive comparison). diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/FakeApi.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/FakeApi.java index d4b464235bf..e502060d682 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 @@ -1,3 +1,28 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.api; import io.swagger.client.ApiCallback; @@ -11,14 +36,11 @@ import io.swagger.client.ProgressResponseBody; import com.google.gson.reflect.TypeToken; -import com.squareup.okhttp.Call; -import com.squareup.okhttp.Interceptor; -import com.squareup.okhttp.Response; - import java.io.IOException; +import org.joda.time.LocalDate; import java.math.BigDecimal; -import java.util.Date; +import org.joda.time.DateTime; import java.lang.reflect.Type; import java.util.ArrayList; @@ -27,196 +49,196 @@ import java.util.List; import java.util.Map; public class FakeApi { - private ApiClient apiClient; + private ApiClient apiClient; - public FakeApi() { - this(Configuration.getDefaultApiClient()); - } - - public FakeApi(ApiClient apiClient) { - this.apiClient = apiClient; - } - - public ApiClient getApiClient() { - return apiClient; - } - - public void setApiClient(ApiClient apiClient) { - this.apiClient = apiClient; - } - - /* Build call for testEndpointParameters */ - 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 - if (number == null) { - throw new ApiException("Missing the required parameter 'number' when calling testEndpointParameters(Async)"); + public FakeApi() { + this(Configuration.getDefaultApiClient()); } - - // verify the required parameter '_double' is set - if (_double == null) { - throw new ApiException("Missing the required parameter '_double' when calling testEndpointParameters(Async)"); + + public FakeApi(ApiClient apiClient) { + this.apiClient = apiClient; } - - // verify the required parameter 'string' is set - if (string == null) { - throw new ApiException("Missing the required parameter 'string' when calling testEndpointParameters(Async)"); + + public ApiClient getApiClient() { + return apiClient; } - - // verify the required parameter '_byte' is set - if (_byte == null) { - throw new ApiException("Missing the required parameter '_byte' when calling testEndpointParameters(Async)"); + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; } - - // create path and map variables - String localVarPath = "/fake".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - if (integer != null) - localVarFormParams.put("integer", integer); - if (int32 != null) - localVarFormParams.put("int32", int32); - if (int64 != null) - localVarFormParams.put("int64", int64); - if (number != null) - localVarFormParams.put("number", number); - if (_float != null) - localVarFormParams.put("float", _float); - if (_double != null) - localVarFormParams.put("double", _double); - if (string != null) - localVarFormParams.put("string", string); - if (_byte != null) - localVarFormParams.put("byte", _byte); - if (binary != null) - localVarFormParams.put("binary", binary); - if (date != null) - localVarFormParams.put("date", date); - if (dateTime != null) - localVarFormParams.put("dateTime", dateTime); - if (password != null) - localVarFormParams.put("password", password); - - final String[] localVarAccepts = { - "application/xml; charset=utf-8", "application/json; charset=utf-8" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - "application/xml; charset=utf-8", "application/json; charset=utf-8" - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new Interceptor() { - @Override - public Response intercept(Interceptor.Chain chain) throws IOException { - Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); + /* Build call for testEndpointParameters */ + private com.squareup.okhttp.Call testEndpointParametersCall(BigDecimal number, Double _double, String string, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, byte[] binary, LocalDate date, DateTime dateTime, String password, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'number' is set + if (number == null) { + throw new ApiException("Missing the required parameter 'number' when calling testEndpointParameters(Async)"); } - }); + + // verify the required parameter '_double' is set + if (_double == null) { + throw new ApiException("Missing the required parameter '_double' when calling testEndpointParameters(Async)"); + } + + // verify the required parameter 'string' is set + if (string == null) { + throw new ApiException("Missing the required parameter 'string' when calling testEndpointParameters(Async)"); + } + + // verify the required parameter '_byte' is set + if (_byte == null) { + throw new ApiException("Missing the required parameter '_byte' when calling testEndpointParameters(Async)"); + } + + + // create path and map variables + String localVarPath = "/fake".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + if (integer != null) + localVarFormParams.put("integer", integer); + if (int32 != null) + localVarFormParams.put("int32", int32); + if (int64 != null) + localVarFormParams.put("int64", int64); + if (number != null) + localVarFormParams.put("number", number); + if (_float != null) + localVarFormParams.put("float", _float); + if (_double != null) + localVarFormParams.put("double", _double); + if (string != null) + localVarFormParams.put("string", string); + if (_byte != null) + localVarFormParams.put("byte", _byte); + if (binary != null) + localVarFormParams.put("binary", binary); + if (date != null) + localVarFormParams.put("date", date); + if (dateTime != null) + localVarFormParams.put("dateTime", dateTime); + if (password != null) + localVarFormParams.put("password", password); + + final String[] localVarAccepts = { + "application/xml; charset=utf-8", "application/json; charset=utf-8" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + "application/xml; charset=utf-8", "application/json; charset=utf-8" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - * @param number None (required) - * @param _double None (required) - * @param 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 fail to call the API, e.g. server error or cannot deserialize the response body - */ - 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); - } - - /** - * 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) - * @return ApiResponse - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse testEndpointParametersWithHttpInfo(BigDecimal number, Double _double, String 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); - } - - /** - * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 (asynchronously) - * 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) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public Call 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; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; + /** + * 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 fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void testEndpointParameters(BigDecimal number, Double _double, String string, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, byte[] binary, LocalDate date, DateTime dateTime, String password) throws ApiException { + testEndpointParametersWithHttpInfo(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password); } - Call call = testEndpointParametersCall(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } + /** + * 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) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse testEndpointParametersWithHttpInfo(BigDecimal number, Double _double, String string, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, byte[] binary, LocalDate date, DateTime dateTime, String password) throws ApiException { + com.squareup.okhttp.Call call = testEndpointParametersCall(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password, null, null); + return apiClient.execute(call); + } + + /** + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 (asynchronously) + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * @param number None (required) + * @param _double None (required) + * @param 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) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call testEndpointParametersAsync(BigDecimal number, Double _double, String string, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, byte[] binary, LocalDate date, DateTime dateTime, String password, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = testEndpointParametersCall(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/PetApi.java index ac7ad688c56..d453504215c 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/PetApi.java @@ -1,3 +1,28 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.api; import io.swagger.client.ApiCallback; @@ -11,10 +36,6 @@ import io.swagger.client.ProgressResponseBody; import com.google.gson.reflect.TypeToken; -import com.squareup.okhttp.Call; -import com.squareup.okhttp.Interceptor; -import com.squareup.okhttp.Response; - import java.io.IOException; import io.swagger.client.model.Pet; @@ -28,887 +49,887 @@ import java.util.List; import java.util.Map; public class PetApi { - private ApiClient apiClient; + private ApiClient apiClient; - public PetApi() { - this(Configuration.getDefaultApiClient()); - } - - public PetApi(ApiClient apiClient) { - this.apiClient = apiClient; - } - - public ApiClient getApiClient() { - return apiClient; - } - - public void setApiClient(ApiClient apiClient) { - this.apiClient = apiClient; - } - - /* Build call for addPet */ - private Call addPetCall(Pet body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = body; - - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException("Missing the required parameter 'body' when calling addPet(Async)"); - } - - - // create path and map variables - String localVarPath = "/pet".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - "application/json", "application/xml" - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new Interceptor() { - @Override - public Response intercept(Interceptor.Chain chain) throws IOException { - Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); + public PetApi() { + this(Configuration.getDefaultApiClient()); } - String[] localVarAuthNames = new String[] { "petstore_auth" }; - return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * Add a new pet to the store - * - * @param body Pet object that needs to be added to the store (required) - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void addPet(Pet body) throws ApiException { - addPetWithHttpInfo(body); - } - - /** - * Add a new pet to the store - * - * @param body Pet object that needs to be added to the store (required) - * @return ApiResponse - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse addPetWithHttpInfo(Pet body) throws ApiException { - Call call = addPetCall(body, null, null); - return apiClient.execute(call); - } - - /** - * Add a new pet to the store (asynchronously) - * - * @param body Pet object that needs to be added to the store (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public Call addPetAsync(Pet body, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; + public PetApi(ApiClient apiClient) { + this.apiClient = apiClient; } - Call call = addPetCall(body, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } - /* Build call for deletePet */ - private Call deletePetCall(Long petId, String apiKey, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'petId' is set - if (petId == null) { - throw new ApiException("Missing the required parameter 'petId' when calling deletePet(Async)"); - } - - - // create path and map variables - String localVarPath = "/pet/{petId}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - if (apiKey != null) - localVarHeaderParams.put("api_key", apiClient.parameterToString(apiKey)); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new Interceptor() { - @Override - public Response intercept(Interceptor.Chain chain) throws IOException { - Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); + public ApiClient getApiClient() { + return apiClient; } - String[] localVarAuthNames = new String[] { "petstore_auth" }; - return apiClient.buildCall(localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * Deletes a pet - * - * @param petId Pet id to delete (required) - * @param apiKey (optional) - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void deletePet(Long petId, String apiKey) throws ApiException { - deletePetWithHttpInfo(petId, apiKey); - } - - /** - * Deletes a pet - * - * @param petId Pet id to delete (required) - * @param apiKey (optional) - * @return ApiResponse - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse deletePetWithHttpInfo(Long petId, String apiKey) throws ApiException { - Call call = deletePetCall(petId, apiKey, null, null); - return apiClient.execute(call); - } - - /** - * Deletes a pet (asynchronously) - * - * @param petId Pet id to delete (required) - * @param apiKey (optional) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public Call deletePetAsync(Long petId, String apiKey, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; } - Call call = deletePetCall(petId, apiKey, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } - /* Build call for findPetsByStatus */ - private Call findPetsByStatusCall(List status, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'status' is set - if (status == null) { - throw new ApiException("Missing the required parameter 'status' when calling findPetsByStatus(Async)"); - } - - - // create path and map variables - String localVarPath = "/pet/findByStatus".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - if (status != null) - localVarQueryParams.addAll(apiClient.parameterToPairs("csv", "status", status)); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new Interceptor() { - @Override - public Response intercept(Interceptor.Chain chain) throws IOException { - Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); + /* Build call for addPet */ + private com.squareup.okhttp.Call addPetCall(Pet body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException("Missing the required parameter 'body' when calling addPet(Async)"); } - }); + + + // create path and map variables + String localVarPath = "/pet".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + "application/json", "application/xml" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } - String[] localVarAuthNames = new String[] { "petstore_auth" }; - return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * Finds Pets by status - * Multiple status values can be provided with comma separated strings - * @param status Status values that need to be considered for filter (required) - * @return List - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public List findPetsByStatus(List status) throws ApiException { - ApiResponse> resp = findPetsByStatusWithHttpInfo(status); - return resp.getData(); - } - - /** - * Finds Pets by status - * Multiple status values can be provided with comma separated strings - * @param status Status values that need to be considered for filter (required) - * @return ApiResponse> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse> findPetsByStatusWithHttpInfo(List status) throws ApiException { - Call call = findPetsByStatusCall(status, null, null); - Type localVarReturnType = new TypeToken>(){}.getType(); - return apiClient.execute(call, localVarReturnType); - } - - /** - * Finds Pets by status (asynchronously) - * Multiple status values can be provided with comma separated strings - * @param status Status values that need to be considered for filter (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public Call findPetsByStatusAsync(List status, final ApiCallback> callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; + /** + * Add a new pet to the store + * + * @param body Pet object that needs to be added to the store (required) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void addPet(Pet body) throws ApiException { + addPetWithHttpInfo(body); } - Call call = findPetsByStatusCall(status, progressListener, progressRequestListener); - Type localVarReturnType = new TypeToken>(){}.getType(); - apiClient.executeAsync(call, localVarReturnType, callback); - return call; - } - /* Build call for findPetsByTags */ - private Call findPetsByTagsCall(List tags, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'tags' is set - if (tags == null) { - throw new ApiException("Missing the required parameter 'tags' when calling findPetsByTags(Async)"); - } - - - // create path and map variables - String localVarPath = "/pet/findByTags".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - if (tags != null) - localVarQueryParams.addAll(apiClient.parameterToPairs("csv", "tags", tags)); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new Interceptor() { - @Override - public Response intercept(Interceptor.Chain chain) throws IOException { - Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); + /** + * Add a new pet to the store + * + * @param body Pet object that needs to be added to the store (required) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse addPetWithHttpInfo(Pet body) throws ApiException { + com.squareup.okhttp.Call call = addPetCall(body, null, null); + return apiClient.execute(call); } - String[] localVarAuthNames = new String[] { "petstore_auth" }; - return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } + /** + * Add a new pet to the store (asynchronously) + * + * @param body Pet object that needs to be added to the store (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call addPetAsync(Pet body, final ApiCallback callback) throws ApiException { - /** - * Finds Pets by tags - * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. - * @param tags Tags to filter by (required) - * @return List - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public List findPetsByTags(List tags) throws ApiException { - ApiResponse> resp = findPetsByTagsWithHttpInfo(tags); - return resp.getData(); - } + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - /** - * Finds Pets by tags - * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. - * @param tags Tags to filter by (required) - * @return ApiResponse> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse> findPetsByTagsWithHttpInfo(List tags) throws ApiException { - Call call = findPetsByTagsCall(tags, null, null); - Type localVarReturnType = new TypeToken>(){}.getType(); - return apiClient.execute(call, localVarReturnType); - } + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; - /** - * Finds Pets by tags (asynchronously) - * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. - * @param tags Tags to filter by (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public Call findPetsByTagsAsync(List tags, final ApiCallback> callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; } - }; - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); + com.squareup.okhttp.Call call = addPetCall(body, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for deletePet */ + private com.squareup.okhttp.Call deletePetCall(Long petId, String apiKey, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException("Missing the required parameter 'petId' when calling deletePet(Async)"); } - }; + + + // create path and map variables + String localVarPath = "/pet/{petId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + if (apiKey != null) + localVarHeaderParams.put("api_key", apiClient.parameterToString(apiKey)); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + return apiClient.buildCall(localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } - Call call = findPetsByTagsCall(tags, progressListener, progressRequestListener); - Type localVarReturnType = new TypeToken>(){}.getType(); - apiClient.executeAsync(call, localVarReturnType, callback); - return call; - } - /* Build call for getPetById */ - private Call getPetByIdCall(Long petId, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'petId' is set - if (petId == null) { - throw new ApiException("Missing the required parameter 'petId' when calling getPetById(Async)"); - } - - - // create path and map variables - String localVarPath = "/pet/{petId}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new Interceptor() { - @Override - public Response intercept(Interceptor.Chain chain) throws IOException { - Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); + /** + * Deletes a pet + * + * @param petId Pet id to delete (required) + * @param apiKey (optional) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void deletePet(Long petId, String apiKey) throws ApiException { + deletePetWithHttpInfo(petId, apiKey); } - String[] localVarAuthNames = new String[] { "api_key" }; - return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * Find pet by ID - * Returns a single pet - * @param petId ID of pet to return (required) - * @return Pet - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public Pet getPetById(Long petId) throws ApiException { - ApiResponse resp = getPetByIdWithHttpInfo(petId); - return resp.getData(); - } - - /** - * Find pet by ID - * Returns a single pet - * @param petId ID of pet to return (required) - * @return ApiResponse - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse getPetByIdWithHttpInfo(Long petId) throws ApiException { - Call call = getPetByIdCall(petId, null, null); - Type localVarReturnType = new TypeToken(){}.getType(); - return apiClient.execute(call, localVarReturnType); - } - - /** - * Find pet by ID (asynchronously) - * Returns a single pet - * @param petId ID of pet to return (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public Call getPetByIdAsync(Long petId, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; + /** + * Deletes a pet + * + * @param petId Pet id to delete (required) + * @param apiKey (optional) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse deletePetWithHttpInfo(Long petId, String apiKey) throws ApiException { + com.squareup.okhttp.Call call = deletePetCall(petId, apiKey, null, null); + return apiClient.execute(call); } - Call call = getPetByIdCall(petId, progressListener, progressRequestListener); - Type localVarReturnType = new TypeToken(){}.getType(); - apiClient.executeAsync(call, localVarReturnType, callback); - return call; - } - /* Build call for updatePet */ - private Call updatePetCall(Pet body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = body; - - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException("Missing the required parameter 'body' when calling updatePet(Async)"); - } - + /** + * Deletes a pet (asynchronously) + * + * @param petId Pet id to delete (required) + * @param apiKey (optional) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call deletePetAsync(Long petId, String apiKey, final ApiCallback callback) throws ApiException { - // create path and map variables - String localVarPath = "/pet".replaceAll("\\{format\\}","json"); + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - List localVarQueryParams = new ArrayList(); + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - "application/json", "application/xml" - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new Interceptor() { - @Override - public Response intercept(Interceptor.Chain chain) throws IOException { - Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; } - }); + + com.squareup.okhttp.Call call = deletePetCall(petId, apiKey, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for findPetsByStatus */ + private com.squareup.okhttp.Call findPetsByStatusCall(List status, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'status' is set + if (status == null) { + throw new ApiException("Missing the required parameter 'status' when calling findPetsByStatus(Async)"); + } + + + // create path and map variables + String localVarPath = "/pet/findByStatus".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + if (status != null) + localVarQueryParams.addAll(apiClient.parameterToPairs("csv", "status", status)); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } - String[] localVarAuthNames = new String[] { "petstore_auth" }; - return apiClient.buildCall(localVarPath, "PUT", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * Update an existing pet - * - * @param body Pet object that needs to be added to the store (required) - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void updatePet(Pet body) throws ApiException { - updatePetWithHttpInfo(body); - } - - /** - * Update an existing pet - * - * @param body Pet object that needs to be added to the store (required) - * @return ApiResponse - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse updatePetWithHttpInfo(Pet body) throws ApiException { - Call call = updatePetCall(body, null, null); - return apiClient.execute(call); - } - - /** - * Update an existing pet (asynchronously) - * - * @param body Pet object that needs to be added to the store (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public Call updatePetAsync(Pet body, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; + /** + * Finds Pets by status + * Multiple status values can be provided with comma separated strings + * @param status Status values that need to be considered for filter (required) + * @return List<Pet> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public List findPetsByStatus(List status) throws ApiException { + ApiResponse> resp = findPetsByStatusWithHttpInfo(status); + return resp.getData(); } - Call call = updatePetCall(body, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } - /* Build call for updatePetWithForm */ - private Call updatePetWithFormCall(Long petId, String name, String status, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'petId' is set - if (petId == null) { - throw new ApiException("Missing the required parameter 'petId' when calling updatePetWithForm(Async)"); - } - - - // create path and map variables - String localVarPath = "/pet/{petId}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - if (name != null) - localVarFormParams.put("name", name); - if (status != null) - localVarFormParams.put("status", status); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - "application/x-www-form-urlencoded" - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new Interceptor() { - @Override - public Response intercept(Interceptor.Chain chain) throws IOException { - Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); + /** + * Finds Pets by status + * Multiple status values can be provided with comma separated strings + * @param status Status values that need to be considered for filter (required) + * @return ApiResponse<List<Pet>> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse> findPetsByStatusWithHttpInfo(List status) throws ApiException { + com.squareup.okhttp.Call call = findPetsByStatusCall(status, null, null); + Type localVarReturnType = new TypeToken>(){}.getType(); + return apiClient.execute(call, localVarReturnType); } - String[] localVarAuthNames = new String[] { "petstore_auth" }; - return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } + /** + * Finds Pets by status (asynchronously) + * Multiple status values can be provided with comma separated strings + * @param status Status values that need to be considered for filter (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call findPetsByStatusAsync(List status, final ApiCallback> callback) throws ApiException { - /** - * Updates a pet in the store with form data - * - * @param petId ID of pet that needs to be updated (required) - * @param name Updated name of the pet (optional) - * @param status Updated status of the pet (optional) - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void updatePetWithForm(Long petId, String name, String status) throws ApiException { - updatePetWithFormWithHttpInfo(petId, name, status); - } + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - /** - * Updates a pet in the store with form data - * - * @param petId ID of pet that needs to be updated (required) - * @param name Updated name of the pet (optional) - * @param status Updated status of the pet (optional) - * @return ApiResponse - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse updatePetWithFormWithHttpInfo(Long petId, String name, String status) throws ApiException { - Call call = updatePetWithFormCall(petId, name, status, null, null); - return apiClient.execute(call); - } + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; - /** - * Updates a pet in the store with form data (asynchronously) - * - * @param petId ID of pet that needs to be updated (required) - * @param name Updated name of the pet (optional) - * @param status Updated status of the pet (optional) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public Call updatePetWithFormAsync(Long petId, String name, String status, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; } - }; - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); + com.squareup.okhttp.Call call = findPetsByStatusCall(status, progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken>(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; + } + /* Build call for findPetsByTags */ + private com.squareup.okhttp.Call findPetsByTagsCall(List tags, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'tags' is set + if (tags == null) { + throw new ApiException("Missing the required parameter 'tags' when calling findPetsByTags(Async)"); } - }; + + + // create path and map variables + String localVarPath = "/pet/findByTags".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + if (tags != null) + localVarQueryParams.addAll(apiClient.parameterToPairs("csv", "tags", tags)); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } - Call call = updatePetWithFormCall(petId, name, status, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } - /* Build call for uploadFile */ - private Call uploadFileCall(Long petId, String additionalMetadata, File file, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'petId' is set - if (petId == null) { - throw new ApiException("Missing the required parameter 'petId' when calling uploadFile(Async)"); - } - - - // create path and map variables - String localVarPath = "/pet/{petId}/uploadImage".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - if (additionalMetadata != null) - localVarFormParams.put("additionalMetadata", additionalMetadata); - if (file != null) - localVarFormParams.put("file", file); - - final String[] localVarAccepts = { - "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - "multipart/form-data" - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new Interceptor() { - @Override - public Response intercept(Interceptor.Chain chain) throws IOException { - Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); + /** + * Finds Pets by tags + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * @param tags Tags to filter by (required) + * @return List<Pet> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public List findPetsByTags(List tags) throws ApiException { + ApiResponse> resp = findPetsByTagsWithHttpInfo(tags); + return resp.getData(); } - String[] localVarAuthNames = new String[] { "petstore_auth" }; - return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * uploads an image - * - * @param petId ID of pet to update (required) - * @param additionalMetadata Additional data to pass to server (optional) - * @param file file to upload (optional) - * @return ModelApiResponse - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ModelApiResponse uploadFile(Long petId, String additionalMetadata, File file) throws ApiException { - ApiResponse resp = uploadFileWithHttpInfo(petId, additionalMetadata, file); - return resp.getData(); - } - - /** - * uploads an image - * - * @param petId ID of pet to update (required) - * @param additionalMetadata Additional data to pass to server (optional) - * @param file file to upload (optional) - * @return ApiResponse - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse uploadFileWithHttpInfo(Long petId, String additionalMetadata, File file) throws ApiException { - Call call = uploadFileCall(petId, additionalMetadata, file, null, null); - Type localVarReturnType = new TypeToken(){}.getType(); - return apiClient.execute(call, localVarReturnType); - } - - /** - * uploads an image (asynchronously) - * - * @param petId ID of pet to update (required) - * @param additionalMetadata Additional data to pass to server (optional) - * @param file file to upload (optional) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public Call uploadFileAsync(Long petId, String additionalMetadata, File file, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; + /** + * Finds Pets by tags + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * @param tags Tags to filter by (required) + * @return ApiResponse<List<Pet>> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse> findPetsByTagsWithHttpInfo(List tags) throws ApiException { + com.squareup.okhttp.Call call = findPetsByTagsCall(tags, null, null); + Type localVarReturnType = new TypeToken>(){}.getType(); + return apiClient.execute(call, localVarReturnType); } - Call call = uploadFileCall(petId, additionalMetadata, file, progressListener, progressRequestListener); - Type localVarReturnType = new TypeToken(){}.getType(); - apiClient.executeAsync(call, localVarReturnType, callback); - return call; - } + /** + * Finds Pets by tags (asynchronously) + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * @param tags Tags to filter by (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call findPetsByTagsAsync(List tags, final ApiCallback> callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = findPetsByTagsCall(tags, progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken>(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; + } + /* Build call for getPetById */ + private com.squareup.okhttp.Call getPetByIdCall(Long petId, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException("Missing the required parameter 'petId' when calling getPetById(Async)"); + } + + + // create path and map variables + String localVarPath = "/pet/{petId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "api_key" }; + return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Find pet by ID + * Returns a single pet + * @param petId ID of pet to return (required) + * @return Pet + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public Pet getPetById(Long petId) throws ApiException { + ApiResponse resp = getPetByIdWithHttpInfo(petId); + return resp.getData(); + } + + /** + * Find pet by ID + * Returns a single pet + * @param petId ID of pet to return (required) + * @return ApiResponse<Pet> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse getPetByIdWithHttpInfo(Long petId) throws ApiException { + com.squareup.okhttp.Call call = getPetByIdCall(petId, null, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return apiClient.execute(call, localVarReturnType); + } + + /** + * Find pet by ID (asynchronously) + * Returns a single pet + * @param petId ID of pet to return (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call getPetByIdAsync(Long petId, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = getPetByIdCall(petId, progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; + } + /* Build call for updatePet */ + private com.squareup.okhttp.Call updatePetCall(Pet body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException("Missing the required parameter 'body' when calling updatePet(Async)"); + } + + + // create path and map variables + String localVarPath = "/pet".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + "application/json", "application/xml" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + return apiClient.buildCall(localVarPath, "PUT", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Update an existing pet + * + * @param body Pet object that needs to be added to the store (required) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void updatePet(Pet body) throws ApiException { + updatePetWithHttpInfo(body); + } + + /** + * Update an existing pet + * + * @param body Pet object that needs to be added to the store (required) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse updatePetWithHttpInfo(Pet body) throws ApiException { + com.squareup.okhttp.Call call = updatePetCall(body, null, null); + return apiClient.execute(call); + } + + /** + * Update an existing pet (asynchronously) + * + * @param body Pet object that needs to be added to the store (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call updatePetAsync(Pet body, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = updatePetCall(body, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for updatePetWithForm */ + private com.squareup.okhttp.Call updatePetWithFormCall(Long petId, String name, String status, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException("Missing the required parameter 'petId' when calling updatePetWithForm(Async)"); + } + + + // create path and map variables + String localVarPath = "/pet/{petId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + if (name != null) + localVarFormParams.put("name", name); + if (status != null) + localVarFormParams.put("status", status); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + "application/x-www-form-urlencoded" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Updates a pet in the store with form data + * + * @param petId ID of pet that needs to be updated (required) + * @param name Updated name of the pet (optional) + * @param status Updated status of the pet (optional) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void updatePetWithForm(Long petId, String name, String status) throws ApiException { + updatePetWithFormWithHttpInfo(petId, name, status); + } + + /** + * Updates a pet in the store with form data + * + * @param petId ID of pet that needs to be updated (required) + * @param name Updated name of the pet (optional) + * @param status Updated status of the pet (optional) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse updatePetWithFormWithHttpInfo(Long petId, String name, String status) throws ApiException { + com.squareup.okhttp.Call call = updatePetWithFormCall(petId, name, status, null, null); + return apiClient.execute(call); + } + + /** + * Updates a pet in the store with form data (asynchronously) + * + * @param petId ID of pet that needs to be updated (required) + * @param name Updated name of the pet (optional) + * @param status Updated status of the pet (optional) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call updatePetWithFormAsync(Long petId, String name, String status, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = updatePetWithFormCall(petId, name, status, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for uploadFile */ + private com.squareup.okhttp.Call uploadFileCall(Long petId, String additionalMetadata, File file, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException("Missing the required parameter 'petId' when calling uploadFile(Async)"); + } + + + // create path and map variables + String localVarPath = "/pet/{petId}/uploadImage".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + if (additionalMetadata != null) + localVarFormParams.put("additionalMetadata", additionalMetadata); + if (file != null) + localVarFormParams.put("file", file); + + final String[] localVarAccepts = { + "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + "multipart/form-data" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * uploads an image + * + * @param petId ID of pet to update (required) + * @param additionalMetadata Additional data to pass to server (optional) + * @param file file to upload (optional) + * @return ModelApiResponse + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ModelApiResponse uploadFile(Long petId, String additionalMetadata, File file) throws ApiException { + ApiResponse resp = uploadFileWithHttpInfo(petId, additionalMetadata, file); + return resp.getData(); + } + + /** + * uploads an image + * + * @param petId ID of pet to update (required) + * @param additionalMetadata Additional data to pass to server (optional) + * @param file file to upload (optional) + * @return ApiResponse<ModelApiResponse> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse uploadFileWithHttpInfo(Long petId, String additionalMetadata, File file) throws ApiException { + com.squareup.okhttp.Call call = uploadFileCall(petId, additionalMetadata, file, null, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return apiClient.execute(call, localVarReturnType); + } + + /** + * uploads an image (asynchronously) + * + * @param petId ID of pet to update (required) + * @param additionalMetadata Additional data to pass to server (optional) + * @param file file to upload (optional) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call uploadFileAsync(Long petId, String additionalMetadata, File file, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = uploadFileCall(petId, additionalMetadata, file, progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; + } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/StoreApi.java index 5d960d0b104..43c530ee964 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/StoreApi.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/StoreApi.java @@ -1,3 +1,28 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.api; import io.swagger.client.ApiCallback; @@ -11,10 +36,6 @@ import io.swagger.client.ProgressResponseBody; import com.google.gson.reflect.TypeToken; -import com.squareup.okhttp.Call; -import com.squareup.okhttp.Interceptor; -import com.squareup.okhttp.Response; - import java.io.IOException; import io.swagger.client.model.Order; @@ -26,436 +47,436 @@ import java.util.List; import java.util.Map; public class StoreApi { - private ApiClient apiClient; + private ApiClient apiClient; - public StoreApi() { - this(Configuration.getDefaultApiClient()); - } - - public StoreApi(ApiClient apiClient) { - this.apiClient = apiClient; - } - - public ApiClient getApiClient() { - return apiClient; - } - - public void setApiClient(ApiClient apiClient) { - this.apiClient = apiClient; - } - - /* Build call for deleteOrder */ - private Call deleteOrderCall(String orderId, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'orderId' is set - if (orderId == null) { - throw new ApiException("Missing the required parameter 'orderId' when calling deleteOrder(Async)"); - } - - - // create path and map variables - String localVarPath = "/store/order/{orderId}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.toString())); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new Interceptor() { - @Override - public Response intercept(Interceptor.Chain chain) throws IOException { - Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); + public StoreApi() { + this(Configuration.getDefaultApiClient()); } - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * Delete purchase order by ID - * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors - * @param orderId ID of the order that needs to be deleted (required) - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void deleteOrder(String orderId) throws ApiException { - deleteOrderWithHttpInfo(orderId); - } - - /** - * Delete purchase order by ID - * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors - * @param orderId ID of the order that needs to be deleted (required) - * @return ApiResponse - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse deleteOrderWithHttpInfo(String orderId) throws ApiException { - Call call = deleteOrderCall(orderId, null, null); - return apiClient.execute(call); - } - - /** - * Delete purchase order by ID (asynchronously) - * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors - * @param orderId ID of the order that needs to be deleted (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public Call deleteOrderAsync(String orderId, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; + public StoreApi(ApiClient apiClient) { + this.apiClient = apiClient; } - Call call = deleteOrderCall(orderId, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } - /* Build call for getInventory */ - private Call getInventoryCall(final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - - // create path and map variables - String localVarPath = "/store/inventory".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new Interceptor() { - @Override - public Response intercept(Interceptor.Chain chain) throws IOException { - Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); + public ApiClient getApiClient() { + return apiClient; } - String[] localVarAuthNames = new String[] { "api_key" }; - return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * Returns pet inventories by status - * Returns a map of status codes to quantities - * @return Map - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public Map getInventory() throws ApiException { - ApiResponse> resp = getInventoryWithHttpInfo(); - return resp.getData(); - } - - /** - * Returns pet inventories by status - * Returns a map of status codes to quantities - * @return ApiResponse> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse> getInventoryWithHttpInfo() throws ApiException { - Call call = getInventoryCall(null, null); - Type localVarReturnType = new TypeToken>(){}.getType(); - return apiClient.execute(call, localVarReturnType); - } - - /** - * Returns pet inventories by status (asynchronously) - * Returns a map of status codes to quantities - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public Call getInventoryAsync(final ApiCallback> callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; } - Call call = getInventoryCall(progressListener, progressRequestListener); - Type localVarReturnType = new TypeToken>(){}.getType(); - apiClient.executeAsync(call, localVarReturnType, callback); - return call; - } - /* Build call for getOrderById */ - private Call getOrderByIdCall(Long orderId, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'orderId' is set - if (orderId == null) { - throw new ApiException("Missing the required parameter 'orderId' when calling getOrderById(Async)"); - } - - - // create path and map variables - String localVarPath = "/store/order/{orderId}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.toString())); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new Interceptor() { - @Override - public Response intercept(Interceptor.Chain chain) throws IOException { - Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); + /* Build call for deleteOrder */ + private com.squareup.okhttp.Call deleteOrderCall(String orderId, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'orderId' is set + if (orderId == null) { + throw new ApiException("Missing the required parameter 'orderId' when calling deleteOrder(Async)"); } - }); + + + // create path and map variables + String localVarPath = "/store/order/{orderId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.toString())); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * Find purchase order by ID - * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - * @param orderId ID of pet that needs to be fetched (required) - * @return Order - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public Order getOrderById(Long orderId) throws ApiException { - ApiResponse resp = getOrderByIdWithHttpInfo(orderId); - return resp.getData(); - } - - /** - * Find purchase order by ID - * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - * @param orderId ID of pet that needs to be fetched (required) - * @return ApiResponse - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse getOrderByIdWithHttpInfo(Long orderId) throws ApiException { - Call call = getOrderByIdCall(orderId, null, null); - Type localVarReturnType = new TypeToken(){}.getType(); - return apiClient.execute(call, localVarReturnType); - } - - /** - * Find purchase order by ID (asynchronously) - * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - * @param orderId ID of pet that needs to be fetched (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public Call getOrderByIdAsync(Long orderId, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; + /** + * Delete purchase order by ID + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * @param orderId ID of the order that needs to be deleted (required) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void deleteOrder(String orderId) throws ApiException { + deleteOrderWithHttpInfo(orderId); } - Call call = getOrderByIdCall(orderId, progressListener, progressRequestListener); - Type localVarReturnType = new TypeToken(){}.getType(); - apiClient.executeAsync(call, localVarReturnType, callback); - return call; - } - /* Build call for placeOrder */ - private Call placeOrderCall(Order body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = body; - - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException("Missing the required parameter 'body' when calling placeOrder(Async)"); - } - - - // create path and map variables - String localVarPath = "/store/order".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new Interceptor() { - @Override - public Response intercept(Interceptor.Chain chain) throws IOException { - Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); + /** + * Delete purchase order by ID + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * @param orderId ID of the order that needs to be deleted (required) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse deleteOrderWithHttpInfo(String orderId) throws ApiException { + com.squareup.okhttp.Call call = deleteOrderCall(orderId, null, null); + return apiClient.execute(call); } - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } + /** + * Delete purchase order by ID (asynchronously) + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * @param orderId ID of the order that needs to be deleted (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call deleteOrderAsync(String orderId, final ApiCallback callback) throws ApiException { - /** - * Place an order for a pet - * - * @param body order placed for purchasing the pet (required) - * @return Order - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public Order placeOrder(Order body) throws ApiException { - ApiResponse resp = placeOrderWithHttpInfo(body); - return resp.getData(); - } + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - /** - * Place an order for a pet - * - * @param body order placed for purchasing the pet (required) - * @return ApiResponse - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse placeOrderWithHttpInfo(Order body) throws ApiException { - Call call = placeOrderCall(body, null, null); - Type localVarReturnType = new TypeToken(){}.getType(); - return apiClient.execute(call, localVarReturnType); - } + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; - /** - * Place an order for a pet (asynchronously) - * - * @param body order placed for purchasing the pet (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public Call placeOrderAsync(Order body, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; } - }; - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); + com.squareup.okhttp.Call call = deleteOrderCall(orderId, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for getInventory */ + private com.squareup.okhttp.Call getInventoryCall(final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + + // create path and map variables + String localVarPath = "/store/inventory".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); } - }; + + String[] localVarAuthNames = new String[] { "api_key" }; + return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } - Call call = placeOrderCall(body, progressListener, progressRequestListener); - Type localVarReturnType = new TypeToken(){}.getType(); - apiClient.executeAsync(call, localVarReturnType, callback); - return call; - } + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + * @return Map<String, Integer> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public Map getInventory() throws ApiException { + ApiResponse> resp = getInventoryWithHttpInfo(); + return resp.getData(); + } + + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + * @return ApiResponse<Map<String, Integer>> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse> getInventoryWithHttpInfo() throws ApiException { + com.squareup.okhttp.Call call = getInventoryCall(null, null); + Type localVarReturnType = new TypeToken>(){}.getType(); + return apiClient.execute(call, localVarReturnType); + } + + /** + * Returns pet inventories by status (asynchronously) + * Returns a map of status codes to quantities + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call getInventoryAsync(final ApiCallback> callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = getInventoryCall(progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken>(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; + } + /* Build call for getOrderById */ + private com.squareup.okhttp.Call getOrderByIdCall(Long orderId, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'orderId' is set + if (orderId == null) { + throw new ApiException("Missing the required parameter 'orderId' when calling getOrderById(Async)"); + } + + + // create path and map variables + String localVarPath = "/store/order/{orderId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.toString())); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Find purchase order by ID + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * @param orderId ID of pet that needs to be fetched (required) + * @return Order + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public Order getOrderById(Long orderId) throws ApiException { + ApiResponse resp = getOrderByIdWithHttpInfo(orderId); + return resp.getData(); + } + + /** + * Find purchase order by ID + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * @param orderId ID of pet that needs to be fetched (required) + * @return ApiResponse<Order> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse getOrderByIdWithHttpInfo(Long orderId) throws ApiException { + com.squareup.okhttp.Call call = getOrderByIdCall(orderId, null, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return apiClient.execute(call, localVarReturnType); + } + + /** + * Find purchase order by ID (asynchronously) + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * @param orderId ID of pet that needs to be fetched (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call getOrderByIdAsync(Long orderId, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = getOrderByIdCall(orderId, progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; + } + /* Build call for placeOrder */ + private com.squareup.okhttp.Call placeOrderCall(Order body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException("Missing the required parameter 'body' when calling placeOrder(Async)"); + } + + + // create path and map variables + String localVarPath = "/store/order".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Place an order for a pet + * + * @param body order placed for purchasing the pet (required) + * @return Order + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public Order placeOrder(Order body) throws ApiException { + ApiResponse resp = placeOrderWithHttpInfo(body); + return resp.getData(); + } + + /** + * Place an order for a pet + * + * @param body order placed for purchasing the pet (required) + * @return ApiResponse<Order> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse placeOrderWithHttpInfo(Order body) throws ApiException { + com.squareup.okhttp.Call call = placeOrderCall(body, null, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return apiClient.execute(call, localVarReturnType); + } + + /** + * Place an order for a pet (asynchronously) + * + * @param body order placed for purchasing the pet (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call placeOrderAsync(Order body, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = placeOrderCall(body, progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; + } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/UserApi.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/UserApi.java index be0269ef28f..9a7054091a3 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/UserApi.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/UserApi.java @@ -1,3 +1,28 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.api; import io.swagger.client.ApiCallback; @@ -11,10 +36,6 @@ import io.swagger.client.ProgressResponseBody; import com.google.gson.reflect.TypeToken; -import com.squareup.okhttp.Call; -import com.squareup.okhttp.Interceptor; -import com.squareup.okhttp.Response; - import java.io.IOException; import io.swagger.client.model.User; @@ -26,861 +47,861 @@ import java.util.List; import java.util.Map; public class UserApi { - private ApiClient apiClient; + private ApiClient apiClient; - public UserApi() { - this(Configuration.getDefaultApiClient()); - } - - public UserApi(ApiClient apiClient) { - this.apiClient = apiClient; - } - - public ApiClient getApiClient() { - return apiClient; - } - - public void setApiClient(ApiClient apiClient) { - this.apiClient = apiClient; - } - - /* Build call for createUser */ - private Call createUserCall(User body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = body; - - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException("Missing the required parameter 'body' when calling createUser(Async)"); + public UserApi() { + this(Configuration.getDefaultApiClient()); } - - // create path and map variables - String localVarPath = "/user".replaceAll("\\{format\\}","json"); + public UserApi(ApiClient apiClient) { + this.apiClient = apiClient; + } - List localVarQueryParams = new ArrayList(); + public ApiClient getApiClient() { + return apiClient; + } - Map localVarHeaderParams = new HashMap(); + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new Interceptor() { - @Override - public Response intercept(Interceptor.Chain chain) throws IOException { - Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); + /* Build call for createUser */ + private com.squareup.okhttp.Call createUserCall(User body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException("Missing the required parameter 'body' when calling createUser(Async)"); } - }); - } + - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } + // create path and map variables + String localVarPath = "/user".replaceAll("\\{format\\}","json"); - /** - * Create user - * This can only be done by the logged in user. - * @param body Created user object (required) - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void createUser(User body) throws ApiException { - createUserWithHttpInfo(body); - } + List localVarQueryParams = new ArrayList(); - /** - * Create user - * This can only be done by the logged in user. - * @param body Created user object (required) - * @return ApiResponse - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse createUserWithHttpInfo(User body) throws ApiException { - Call call = createUserCall(body, null, null); - return apiClient.execute(call); - } + Map localVarHeaderParams = new HashMap(); - /** - * Create user (asynchronously) - * This can only be done by the logged in user. - * @param body Created user object (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public Call createUserAsync(User body, final ApiCallback callback) throws ApiException { + Map localVarFormParams = new HashMap(); - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); } - }; - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Create user + * This can only be done by the logged in user. + * @param body Created user object (required) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void createUser(User body) throws ApiException { + createUserWithHttpInfo(body); + } + + /** + * Create user + * This can only be done by the logged in user. + * @param body Created user object (required) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse createUserWithHttpInfo(User body) throws ApiException { + com.squareup.okhttp.Call call = createUserCall(body, null, null); + return apiClient.execute(call); + } + + /** + * Create user (asynchronously) + * This can only be done by the logged in user. + * @param body Created user object (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call createUserAsync(User body, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; } - }; + + com.squareup.okhttp.Call call = createUserCall(body, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; } - - Call call = createUserCall(body, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } - /* Build call for createUsersWithArrayInput */ - private Call createUsersWithArrayInputCall(List body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = body; - - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException("Missing the required parameter 'body' when calling createUsersWithArrayInput(Async)"); - } - - - // create path and map variables - String localVarPath = "/user/createWithArray".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new Interceptor() { - @Override - public Response intercept(Interceptor.Chain chain) throws IOException { - Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); + /* Build call for createUsersWithArrayInput */ + private com.squareup.okhttp.Call createUsersWithArrayInputCall(List body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException("Missing the required parameter 'body' when calling createUsersWithArrayInput(Async)"); } - }); - } + - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } + // create path and map variables + String localVarPath = "/user/createWithArray".replaceAll("\\{format\\}","json"); - /** - * Creates list of users with given input array - * - * @param body List of user object (required) - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void createUsersWithArrayInput(List body) throws ApiException { - createUsersWithArrayInputWithHttpInfo(body); - } + List localVarQueryParams = new ArrayList(); - /** - * Creates list of users with given input array - * - * @param body List of user object (required) - * @return ApiResponse - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse createUsersWithArrayInputWithHttpInfo(List body) throws ApiException { - Call call = createUsersWithArrayInputCall(body, null, null); - return apiClient.execute(call); - } + Map localVarHeaderParams = new HashMap(); - /** - * Creates list of users with given input array (asynchronously) - * - * @param body List of user object (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public Call createUsersWithArrayInputAsync(List body, final ApiCallback callback) throws ApiException { + Map localVarFormParams = new HashMap(); - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); } - }; - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Creates list of users with given input array + * + * @param body List of user object (required) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void createUsersWithArrayInput(List body) throws ApiException { + createUsersWithArrayInputWithHttpInfo(body); + } + + /** + * Creates list of users with given input array + * + * @param body List of user object (required) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse createUsersWithArrayInputWithHttpInfo(List body) throws ApiException { + com.squareup.okhttp.Call call = createUsersWithArrayInputCall(body, null, null); + return apiClient.execute(call); + } + + /** + * Creates list of users with given input array (asynchronously) + * + * @param body List of user object (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call createUsersWithArrayInputAsync(List body, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; } - }; + + com.squareup.okhttp.Call call = createUsersWithArrayInputCall(body, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; } - - Call call = createUsersWithArrayInputCall(body, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } - /* Build call for createUsersWithListInput */ - private Call createUsersWithListInputCall(List body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = body; - - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException("Missing the required parameter 'body' when calling createUsersWithListInput(Async)"); - } - - - // create path and map variables - String localVarPath = "/user/createWithList".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new Interceptor() { - @Override - public Response intercept(Interceptor.Chain chain) throws IOException { - Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); + /* Build call for createUsersWithListInput */ + private com.squareup.okhttp.Call createUsersWithListInputCall(List body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException("Missing the required parameter 'body' when calling createUsersWithListInput(Async)"); } - }); - } + - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } + // create path and map variables + String localVarPath = "/user/createWithList".replaceAll("\\{format\\}","json"); - /** - * Creates list of users with given input array - * - * @param body List of user object (required) - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void createUsersWithListInput(List body) throws ApiException { - createUsersWithListInputWithHttpInfo(body); - } + List localVarQueryParams = new ArrayList(); - /** - * Creates list of users with given input array - * - * @param body List of user object (required) - * @return ApiResponse - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse createUsersWithListInputWithHttpInfo(List body) throws ApiException { - Call call = createUsersWithListInputCall(body, null, null); - return apiClient.execute(call); - } + Map localVarHeaderParams = new HashMap(); - /** - * Creates list of users with given input array (asynchronously) - * - * @param body List of user object (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public Call createUsersWithListInputAsync(List body, final ApiCallback callback) throws ApiException { + Map localVarFormParams = new HashMap(); - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); } - }; - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Creates list of users with given input array + * + * @param body List of user object (required) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void createUsersWithListInput(List body) throws ApiException { + createUsersWithListInputWithHttpInfo(body); + } + + /** + * Creates list of users with given input array + * + * @param body List of user object (required) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse createUsersWithListInputWithHttpInfo(List body) throws ApiException { + com.squareup.okhttp.Call call = createUsersWithListInputCall(body, null, null); + return apiClient.execute(call); + } + + /** + * Creates list of users with given input array (asynchronously) + * + * @param body List of user object (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call createUsersWithListInputAsync(List body, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; } - }; + + com.squareup.okhttp.Call call = createUsersWithListInputCall(body, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; } - - Call call = createUsersWithListInputCall(body, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } - /* Build call for deleteUser */ - private Call deleteUserCall(String username, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'username' is set - if (username == null) { - throw new ApiException("Missing the required parameter 'username' when calling deleteUser(Async)"); - } - - - // create path and map variables - String localVarPath = "/user/{username}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new Interceptor() { - @Override - public Response intercept(Interceptor.Chain chain) throws IOException { - Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); + /* Build call for deleteUser */ + private com.squareup.okhttp.Call deleteUserCall(String username, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'username' is set + if (username == null) { + throw new ApiException("Missing the required parameter 'username' when calling deleteUser(Async)"); } - }); - } + - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } + // create path and map variables + String localVarPath = "/user/{username}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); - /** - * Delete user - * This can only be done by the logged in user. - * @param username The name that needs to be deleted (required) - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void deleteUser(String username) throws ApiException { - deleteUserWithHttpInfo(username); - } + List localVarQueryParams = new ArrayList(); - /** - * Delete user - * This can only be done by the logged in user. - * @param username The name that needs to be deleted (required) - * @return ApiResponse - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse deleteUserWithHttpInfo(String username) throws ApiException { - Call call = deleteUserCall(username, null, null); - return apiClient.execute(call); - } + Map localVarHeaderParams = new HashMap(); - /** - * Delete user (asynchronously) - * This can only be done by the logged in user. - * @param username The name that needs to be deleted (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public Call deleteUserAsync(String username, final ApiCallback callback) throws ApiException { + Map localVarFormParams = new HashMap(); - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); } - }; - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted (required) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void deleteUser(String username) throws ApiException { + deleteUserWithHttpInfo(username); + } + + /** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted (required) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse deleteUserWithHttpInfo(String username) throws ApiException { + com.squareup.okhttp.Call call = deleteUserCall(username, null, null); + return apiClient.execute(call); + } + + /** + * Delete user (asynchronously) + * This can only be done by the logged in user. + * @param username The name that needs to be deleted (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call deleteUserAsync(String username, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; } - }; + + com.squareup.okhttp.Call call = deleteUserCall(username, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; } - - Call call = deleteUserCall(username, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } - /* Build call for getUserByName */ - private Call getUserByNameCall(String username, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'username' is set - if (username == null) { - throw new ApiException("Missing the required parameter 'username' when calling getUserByName(Async)"); - } - - - // create path and map variables - String localVarPath = "/user/{username}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new Interceptor() { - @Override - public Response intercept(Interceptor.Chain chain) throws IOException { - Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); + /* Build call for getUserByName */ + private com.squareup.okhttp.Call getUserByNameCall(String username, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'username' is set + if (username == null) { + throw new ApiException("Missing the required parameter 'username' when calling getUserByName(Async)"); } - }); - } + - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } + // create path and map variables + String localVarPath = "/user/{username}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); - /** - * Get user by user name - * - * @param username The name that needs to be fetched. Use user1 for testing. (required) - * @return User - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public User getUserByName(String username) throws ApiException { - ApiResponse resp = getUserByNameWithHttpInfo(username); - return resp.getData(); - } + List localVarQueryParams = new ArrayList(); - /** - * Get user by user name - * - * @param username The name that needs to be fetched. Use user1 for testing. (required) - * @return ApiResponse - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse getUserByNameWithHttpInfo(String username) throws ApiException { - Call call = getUserByNameCall(username, null, null); - Type localVarReturnType = new TypeToken(){}.getType(); - return apiClient.execute(call, localVarReturnType); - } + Map localVarHeaderParams = new HashMap(); - /** - * Get user by user name (asynchronously) - * - * @param username The name that needs to be fetched. Use user1 for testing. (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public Call getUserByNameAsync(String username, final ApiCallback callback) throws ApiException { + Map localVarFormParams = new HashMap(); - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); } - }; - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Get user by user name + * + * @param username The name that needs to be fetched. Use user1 for testing. (required) + * @return User + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public User getUserByName(String username) throws ApiException { + ApiResponse resp = getUserByNameWithHttpInfo(username); + return resp.getData(); + } + + /** + * Get user by user name + * + * @param username The name that needs to be fetched. Use user1 for testing. (required) + * @return ApiResponse<User> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse getUserByNameWithHttpInfo(String username) throws ApiException { + com.squareup.okhttp.Call call = getUserByNameCall(username, null, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return apiClient.execute(call, localVarReturnType); + } + + /** + * Get user by user name (asynchronously) + * + * @param username The name that needs to be fetched. Use user1 for testing. (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call getUserByNameAsync(String username, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; } - }; + + com.squareup.okhttp.Call call = getUserByNameCall(username, progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; } - - Call call = getUserByNameCall(username, progressListener, progressRequestListener); - Type localVarReturnType = new TypeToken(){}.getType(); - apiClient.executeAsync(call, localVarReturnType, callback); - return call; - } - /* Build call for loginUser */ - private Call loginUserCall(String username, String password, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'username' is set - if (username == null) { - throw new ApiException("Missing the required parameter 'username' when calling loginUser(Async)"); - } - - // verify the required parameter 'password' is set - if (password == null) { - throw new ApiException("Missing the required parameter 'password' when calling loginUser(Async)"); - } - - - // create path and map variables - String localVarPath = "/user/login".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - if (username != null) - localVarQueryParams.addAll(apiClient.parameterToPairs("", "username", username)); - if (password != null) - localVarQueryParams.addAll(apiClient.parameterToPairs("", "password", password)); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new Interceptor() { - @Override - public Response intercept(Interceptor.Chain chain) throws IOException { - Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); + /* Build call for loginUser */ + private com.squareup.okhttp.Call loginUserCall(String username, String password, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'username' is set + if (username == null) { + throw new ApiException("Missing the required parameter 'username' when calling loginUser(Async)"); } - }); + + // verify the required parameter 'password' is set + if (password == null) { + throw new ApiException("Missing the required parameter 'password' when calling loginUser(Async)"); + } + + + // create path and map variables + String localVarPath = "/user/login".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + if (username != null) + localVarQueryParams.addAll(apiClient.parameterToPairs("", "username", username)); + if (password != null) + localVarQueryParams.addAll(apiClient.parameterToPairs("", "password", password)); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * Logs user into the system - * - * @param username The user name for login (required) - * @param password The password for login in clear text (required) - * @return String - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public String loginUser(String username, String password) throws ApiException { - ApiResponse resp = loginUserWithHttpInfo(username, password); - return resp.getData(); - } - - /** - * Logs user into the system - * - * @param username The user name for login (required) - * @param password The password for login in clear text (required) - * @return ApiResponse - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse loginUserWithHttpInfo(String username, String password) throws ApiException { - Call call = loginUserCall(username, password, null, null); - Type localVarReturnType = new TypeToken(){}.getType(); - return apiClient.execute(call, localVarReturnType); - } - - /** - * Logs user into the system (asynchronously) - * - * @param username The user name for login (required) - * @param password The password for login in clear text (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public Call loginUserAsync(String username, String password, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; + /** + * Logs user into the system + * + * @param username The user name for login (required) + * @param password The password for login in clear text (required) + * @return String + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public String loginUser(String username, String password) throws ApiException { + ApiResponse resp = loginUserWithHttpInfo(username, password); + return resp.getData(); } - Call call = loginUserCall(username, password, progressListener, progressRequestListener); - Type localVarReturnType = new TypeToken(){}.getType(); - apiClient.executeAsync(call, localVarReturnType, callback); - return call; - } - /* Build call for logoutUser */ - private Call logoutUserCall(final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - - // create path and map variables - String localVarPath = "/user/logout".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new Interceptor() { - @Override - public Response intercept(Interceptor.Chain chain) throws IOException { - Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); + /** + * Logs user into the system + * + * @param username The user name for login (required) + * @param password The password for login in clear text (required) + * @return ApiResponse<String> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse loginUserWithHttpInfo(String username, String password) throws ApiException { + com.squareup.okhttp.Call call = loginUserCall(username, password, null, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return apiClient.execute(call, localVarReturnType); } - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } + /** + * Logs user into the system (asynchronously) + * + * @param username The user name for login (required) + * @param password The password for login in clear text (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call loginUserAsync(String username, String password, final ApiCallback callback) throws ApiException { - /** - * Logs out current logged in user session - * - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void logoutUser() throws ApiException { - logoutUserWithHttpInfo(); - } + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - /** - * Logs out current logged in user session - * - * @return ApiResponse - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse logoutUserWithHttpInfo() throws ApiException { - Call call = logoutUserCall(null, null); - return apiClient.execute(call); - } + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; - /** - * Logs out current logged in user session (asynchronously) - * - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public Call logoutUserAsync(final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; } - }; - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); + com.squareup.okhttp.Call call = loginUserCall(username, password, progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; + } + /* Build call for logoutUser */ + private com.squareup.okhttp.Call logoutUserCall(final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + + // create path and map variables + String localVarPath = "/user/logout".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); } - }; + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } - Call call = logoutUserCall(progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } - /* Build call for updateUser */ - private Call updateUserCall(String username, User body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = body; - - // verify the required parameter 'username' is set - if (username == null) { - throw new ApiException("Missing the required parameter 'username' when calling updateUser(Async)"); + /** + * Logs out current logged in user session + * + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void logoutUser() throws ApiException { + logoutUserWithHttpInfo(); } - - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException("Missing the required parameter 'body' when calling updateUser(Async)"); + + /** + * Logs out current logged in user session + * + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse logoutUserWithHttpInfo() throws ApiException { + com.squareup.okhttp.Call call = logoutUserCall(null, null); + return apiClient.execute(call); } - - // create path and map variables - String localVarPath = "/user/{username}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); + /** + * Logs out current logged in user session (asynchronously) + * + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call logoutUserAsync(final ApiCallback callback) throws ApiException { - List localVarQueryParams = new ArrayList(); + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - Map localVarHeaderParams = new HashMap(); + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new Interceptor() { - @Override - public Response intercept(Interceptor.Chain chain) throws IOException { - Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; } - }); + + com.squareup.okhttp.Call call = logoutUserCall(progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for updateUser */ + private com.squareup.okhttp.Call updateUserCall(String username, User body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = body; + + // verify the required parameter 'username' is set + if (username == null) { + throw new ApiException("Missing the required parameter 'username' when calling updateUser(Async)"); + } + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException("Missing the required parameter 'body' when calling updateUser(Async)"); + } + + + // create path and map variables + String localVarPath = "/user/{username}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "PUT", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "PUT", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * Updated user - * This can only be done by the logged in user. - * @param username name that need to be deleted (required) - * @param body Updated user object (required) - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void updateUser(String username, User body) throws ApiException { - updateUserWithHttpInfo(username, body); - } - - /** - * Updated user - * This can only be done by the logged in user. - * @param username name that need to be deleted (required) - * @param body Updated user object (required) - * @return ApiResponse - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse updateUserWithHttpInfo(String username, User body) throws ApiException { - Call call = updateUserCall(username, body, null, null); - return apiClient.execute(call); - } - - /** - * Updated user (asynchronously) - * This can only be done by the logged in user. - * @param username name that need to be deleted (required) - * @param body Updated user object (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public Call updateUserAsync(String username, User body, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; + /** + * Updated user + * This can only be done by the logged in user. + * @param username name that need to be deleted (required) + * @param body Updated user object (required) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void updateUser(String username, User body) throws ApiException { + updateUserWithHttpInfo(username, body); } - Call call = updateUserCall(username, body, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } + /** + * Updated user + * This can only be done by the logged in user. + * @param username name that need to be deleted (required) + * @param body Updated user object (required) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse updateUserWithHttpInfo(String username, User body) throws ApiException { + com.squareup.okhttp.Call call = updateUserCall(username, body, null, null); + return apiClient.execute(call); + } + + /** + * Updated user (asynchronously) + * This can only be done by the logged in user. + * @param username name that need to be deleted (required) + * @param body Updated user object (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call updateUserAsync(String username, User body, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = updateUserCall(username, body, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/ApiKeyAuth.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/ApiKeyAuth.java index 468c1ad8410..6ba15566b60 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/ApiKeyAuth.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/ApiKeyAuth.java @@ -1,3 +1,28 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.auth; import io.swagger.client.Pair; @@ -5,7 +30,7 @@ import io.swagger.client.Pair; import java.util.Map; import java.util.List; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-06-03T00:41:49.229+08:00") + public class ApiKeyAuth implements Authentication { private final String location; private final String paramName; diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/Authentication.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/Authentication.java index 98b1a6900b9..a063a6998b5 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/Authentication.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/Authentication.java @@ -1,3 +1,28 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.auth; import io.swagger.client.Pair; @@ -6,6 +31,11 @@ import java.util.Map; import java.util.List; public interface Authentication { - /** Apply authentication settings to header and query params. */ - void applyToParams(List queryParams, Map headerParams); + /** + * Apply authentication settings to header and query params. + * + * @param queryParams List of query parameters + * @param headerParams Map of header parameters + */ + void applyToParams(List queryParams, Map headerParams); } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/HttpBasicAuth.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/HttpBasicAuth.java index 6ed16d1db30..9ac184eda83 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/HttpBasicAuth.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/HttpBasicAuth.java @@ -1,3 +1,28 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.auth; import io.swagger.client.Pair; @@ -10,32 +35,32 @@ import java.util.List; import java.io.UnsupportedEncodingException; public class HttpBasicAuth implements Authentication { - private String username; - private String password; + private String username; + private String password; - public String getUsername() { - return username; - } - - public void setUsername(String username) { - this.username = username; - } - - public String getPassword() { - return password; - } - - public void setPassword(String password) { - this.password = password; - } - - @Override - public void applyToParams(List queryParams, Map headerParams) { - if (username == null && password == null) { - return; + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + @Override + public void applyToParams(List queryParams, Map headerParams) { + if (username == null && password == null) { + return; + } + headerParams.put("Authorization", Credentials.basic( + username == null ? "" : username, + password == null ? "" : password)); } - headerParams.put("Authorization", Credentials.basic( - username == null ? "" : username, - password == null ? "" : password)); - } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/OAuth.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/OAuth.java index 0b85d10068e..8802ebc92c8 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/OAuth.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/OAuth.java @@ -1,3 +1,28 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.auth; import io.swagger.client.Pair; @@ -5,7 +30,7 @@ import io.swagger.client.Pair; import java.util.Map; import java.util.List; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-06-03T00:41:49.229+08:00") + public class OAuth implements Authentication { private String accessToken; diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/OAuthFlow.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/OAuthFlow.java index 597ec99b48b..ec1f942b0f2 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/OAuthFlow.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/OAuthFlow.java @@ -1,5 +1,30 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.auth; public enum OAuthFlow { accessCode, implicit, password, application -} \ No newline at end of file +} diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java index ab464f65259..da61d03f8d2 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java @@ -1,3 +1,28 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; import java.util.Objects; @@ -14,72 +39,88 @@ import com.google.gson.annotations.SerializedName; * AdditionalPropertiesClass */ public class AdditionalPropertiesClass { - - @SerializedName("map_property") - private Map mapProperty = new HashMap(); + @SerializedName("map_property") + private Map mapProperty = new HashMap(); + @SerializedName("map_of_map_property") + private Map> mapOfMapProperty = new HashMap>(); - @SerializedName("map_of_map_property") - private Map> mapOfMapProperty = new HashMap>(); - - /** - **/ - @ApiModelProperty(value = "") - public Map getMapProperty() { - return mapProperty; - } - public void setMapProperty(Map mapProperty) { - this.mapProperty = mapProperty; - } - - /** - **/ - @ApiModelProperty(value = "") - public Map> getMapOfMapProperty() { - return mapOfMapProperty; - } - public void setMapOfMapProperty(Map> mapOfMapProperty) { - this.mapOfMapProperty = mapOfMapProperty; - } - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; + /** + * Get mapProperty + * @return mapProperty + **/ + @ApiModelProperty(value = "") + public Map getMapProperty() { + return mapProperty; } - if (o == null || getClass() != o.getClass()) { - return false; + + /** + * Set mapProperty + * + * @param mapProperty mapProperty + */ + public void setMapProperty(Map mapProperty) { + this.mapProperty = mapProperty; } - AdditionalPropertiesClass additionalPropertiesClass = (AdditionalPropertiesClass) o; - return Objects.equals(this.mapProperty, additionalPropertiesClass.mapProperty) && + + /** + * Get mapOfMapProperty + * @return mapOfMapProperty + **/ + @ApiModelProperty(value = "") + public Map> getMapOfMapProperty() { + return mapOfMapProperty; + } + + /** + * Set mapOfMapProperty + * + * @param mapOfMapProperty mapOfMapProperty + */ + public void setMapOfMapProperty(Map> mapOfMapProperty) { + this.mapOfMapProperty = mapOfMapProperty; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + AdditionalPropertiesClass additionalPropertiesClass = (AdditionalPropertiesClass) o; + return Objects.equals(this.mapProperty, additionalPropertiesClass.mapProperty) && Objects.equals(this.mapOfMapProperty, additionalPropertiesClass.mapOfMapProperty); - } - - @Override - public int hashCode() { - return Objects.hash(mapProperty, mapOfMapProperty); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class AdditionalPropertiesClass {\n"); - - sb.append(" mapProperty: ").append(toIndentedString(mapProperty)).append("\n"); - sb.append(" mapOfMapProperty: ").append(toIndentedString(mapOfMapProperty)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; } - return o.toString().replace("\n", "\n "); - } + + @Override + public int hashCode() { + return Objects.hash(mapProperty, mapOfMapProperty); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class AdditionalPropertiesClass {\n"); + + sb.append(" mapProperty: ").append(toIndentedString(mapProperty)).append("\n"); + sb.append(" mapOfMapProperty: ").append(toIndentedString(mapOfMapProperty)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + * + * @param o Object to be converted to indented string + */ + 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/Animal.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Animal.java index b83bc63db0e..dca1f555e38 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Animal.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Animal.java @@ -1,3 +1,28 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; import java.util.Objects; @@ -11,72 +36,88 @@ import com.google.gson.annotations.SerializedName; * Animal */ public class Animal { - - @SerializedName("className") - private String className = null; + @SerializedName("className") + private String className = null; + @SerializedName("color") + private String color = "red"; - @SerializedName("color") - private String color = "red"; - - /** - **/ - @ApiModelProperty(required = true, value = "") - public String getClassName() { - return className; - } - public void setClassName(String className) { - this.className = className; - } - - /** - **/ - @ApiModelProperty(value = "") - public String getColor() { - return color; - } - public void setColor(String color) { - this.color = color; - } - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; + /** + * Get className + * @return className + **/ + @ApiModelProperty(required = true, value = "") + public String getClassName() { + return className; } - if (o == null || getClass() != o.getClass()) { - return false; + + /** + * Set className + * + * @param className className + */ + public void setClassName(String className) { + this.className = className; } - Animal animal = (Animal) o; - return Objects.equals(this.className, animal.className) && + + /** + * Get color + * @return color + **/ + @ApiModelProperty(value = "") + public String getColor() { + return color; + } + + /** + * Set color + * + * @param color color + */ + public void setColor(String color) { + this.color = color; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Animal animal = (Animal) o; + return Objects.equals(this.className, animal.className) && Objects.equals(this.color, animal.color); - } - - @Override - public int hashCode() { - return Objects.hash(className, color); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class Animal {\n"); - - sb.append(" className: ").append(toIndentedString(className)).append("\n"); - sb.append(" color: ").append(toIndentedString(color)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; } - return o.toString().replace("\n", "\n "); - } + + @Override + public int hashCode() { + return Objects.hash(className, color); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Animal {\n"); + + sb.append(" className: ").append(toIndentedString(className)).append("\n"); + sb.append(" color: ").append(toIndentedString(color)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + * + * @param o Object to be converted to indented string + */ + 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/AnimalFarm.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/AnimalFarm.java index 8be2f1ecd0d..516ff068c08 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/AnimalFarm.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/AnimalFarm.java @@ -1,3 +1,28 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; import java.util.Objects; @@ -12,42 +37,44 @@ import com.google.gson.annotations.SerializedName; * AnimalFarm */ public class AnimalFarm extends ArrayList { - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + return true; } - if (o == null || getClass() != o.getClass()) { - return false; + + @Override + public int hashCode() { + return Objects.hash(super.hashCode()); } - 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"; + @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). + * + * @param o Object to be converted to indented string + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); } - return o.toString().replace("\n", "\n "); - } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ArrayTest.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ArrayTest.java index 19ad5d37499..9795e9b4d79 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ArrayTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ArrayTest.java @@ -1,3 +1,28 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; import java.util.Objects; @@ -13,87 +38,110 @@ import com.google.gson.annotations.SerializedName; * ArrayTest */ public class ArrayTest { - - @SerializedName("array_of_string") - private List arrayOfString = new ArrayList(); + @SerializedName("array_of_string") + private List arrayOfString = new ArrayList(); + @SerializedName("array_array_of_integer") + private List> arrayArrayOfInteger = new ArrayList>(); + @SerializedName("array_array_of_model") + private List> arrayArrayOfModel = new ArrayList>(); - @SerializedName("array_array_of_integer") - private List> arrayArrayOfInteger = new ArrayList>(); - - @SerializedName("array_array_of_model") - private List> arrayArrayOfModel = new ArrayList>(); - - /** - **/ - @ApiModelProperty(value = "") - public List getArrayOfString() { - return arrayOfString; - } - public void setArrayOfString(List arrayOfString) { - this.arrayOfString = arrayOfString; - } - - /** - **/ - @ApiModelProperty(value = "") - public List> getArrayArrayOfInteger() { - return arrayArrayOfInteger; - } - public void setArrayArrayOfInteger(List> arrayArrayOfInteger) { - this.arrayArrayOfInteger = arrayArrayOfInteger; - } - - /** - **/ - @ApiModelProperty(value = "") - public List> getArrayArrayOfModel() { - return arrayArrayOfModel; - } - public void setArrayArrayOfModel(List> arrayArrayOfModel) { - this.arrayArrayOfModel = arrayArrayOfModel; - } - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; + /** + * Get arrayOfString + * @return arrayOfString + **/ + @ApiModelProperty(value = "") + public List getArrayOfString() { + return arrayOfString; } - if (o == null || getClass() != o.getClass()) { - return false; + + /** + * Set arrayOfString + * + * @param arrayOfString arrayOfString + */ + public void setArrayOfString(List arrayOfString) { + this.arrayOfString = arrayOfString; } - ArrayTest arrayTest = (ArrayTest) o; - return Objects.equals(this.arrayOfString, arrayTest.arrayOfString) && + + /** + * Get arrayArrayOfInteger + * @return arrayArrayOfInteger + **/ + @ApiModelProperty(value = "") + public List> getArrayArrayOfInteger() { + return arrayArrayOfInteger; + } + + /** + * Set arrayArrayOfInteger + * + * @param arrayArrayOfInteger arrayArrayOfInteger + */ + public void setArrayArrayOfInteger(List> arrayArrayOfInteger) { + this.arrayArrayOfInteger = arrayArrayOfInteger; + } + + /** + * Get arrayArrayOfModel + * @return arrayArrayOfModel + **/ + @ApiModelProperty(value = "") + public List> getArrayArrayOfModel() { + return arrayArrayOfModel; + } + + /** + * Set arrayArrayOfModel + * + * @param arrayArrayOfModel arrayArrayOfModel + */ + public void setArrayArrayOfModel(List> arrayArrayOfModel) { + this.arrayArrayOfModel = arrayArrayOfModel; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ArrayTest arrayTest = (ArrayTest) o; + return Objects.equals(this.arrayOfString, arrayTest.arrayOfString) && Objects.equals(this.arrayArrayOfInteger, arrayTest.arrayArrayOfInteger) && Objects.equals(this.arrayArrayOfModel, arrayTest.arrayArrayOfModel); - } - - @Override - public int hashCode() { - return Objects.hash(arrayOfString, arrayArrayOfInteger, arrayArrayOfModel); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class ArrayTest {\n"); - - sb.append(" arrayOfString: ").append(toIndentedString(arrayOfString)).append("\n"); - sb.append(" arrayArrayOfInteger: ").append(toIndentedString(arrayArrayOfInteger)).append("\n"); - sb.append(" arrayArrayOfModel: ").append(toIndentedString(arrayArrayOfModel)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; } - return o.toString().replace("\n", "\n "); - } + + @Override + public int hashCode() { + return Objects.hash(arrayOfString, arrayArrayOfInteger, arrayArrayOfModel); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ArrayTest {\n"); + + sb.append(" arrayOfString: ").append(toIndentedString(arrayOfString)).append("\n"); + sb.append(" arrayArrayOfInteger: ").append(toIndentedString(arrayArrayOfInteger)).append("\n"); + sb.append(" arrayArrayOfModel: ").append(toIndentedString(arrayArrayOfModel)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + * + * @param o Object to be converted to indented string + */ + 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/Cat.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Cat.java index 7d190d48425..63bef8d8bbf 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Cat.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Cat.java @@ -1,3 +1,28 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; import java.util.Objects; @@ -12,88 +37,111 @@ import com.google.gson.annotations.SerializedName; * Cat */ public class Cat extends Animal { - - @SerializedName("className") - private String className = null; + @SerializedName("className") + private String className = null; + @SerializedName("color") + private String color = "red"; + @SerializedName("declawed") + private Boolean declawed = null; - @SerializedName("color") - private String color = "red"; - - @SerializedName("declawed") - private Boolean declawed = null; - - /** - **/ - @ApiModelProperty(required = true, value = "") - public String getClassName() { - return className; - } - public void setClassName(String className) { - this.className = className; - } - - /** - **/ - @ApiModelProperty(value = "") - public String getColor() { - return color; - } - public void setColor(String color) { - this.color = color; - } - - /** - **/ - @ApiModelProperty(value = "") - public Boolean getDeclawed() { - return declawed; - } - public void setDeclawed(Boolean declawed) { - this.declawed = declawed; - } - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; + /** + * Get className + * @return className + **/ + @ApiModelProperty(required = true, value = "") + public String getClassName() { + return className; } - if (o == null || getClass() != o.getClass()) { - return false; + + /** + * Set className + * + * @param className className + */ + public void setClassName(String className) { + this.className = className; } - Cat cat = (Cat) o; - return Objects.equals(this.className, cat.className) && + + /** + * Get color + * @return color + **/ + @ApiModelProperty(value = "") + public String getColor() { + return color; + } + + /** + * Set color + * + * @param color color + */ + public void setColor(String color) { + this.color = color; + } + + /** + * Get declawed + * @return declawed + **/ + @ApiModelProperty(value = "") + public Boolean getDeclawed() { + return declawed; + } + + /** + * Set declawed + * + * @param declawed declawed + */ + public void setDeclawed(Boolean declawed) { + this.declawed = declawed; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Cat cat = (Cat) o; + return Objects.equals(this.className, cat.className) && Objects.equals(this.color, cat.color) && Objects.equals(this.declawed, cat.declawed) && super.equals(o); - } - - @Override - public int hashCode() { - return Objects.hash(className, color, declawed, super.hashCode()); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class Cat {\n"); - sb.append(" ").append(toIndentedString(super.toString())).append("\n"); - sb.append(" className: ").append(toIndentedString(className)).append("\n"); - sb.append(" color: ").append(toIndentedString(color)).append("\n"); - sb.append(" declawed: ").append(toIndentedString(declawed)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; } - return o.toString().replace("\n", "\n "); - } + + @Override + public int hashCode() { + return Objects.hash(className, color, declawed, super.hashCode()); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Cat {\n"); + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + sb.append(" className: ").append(toIndentedString(className)).append("\n"); + sb.append(" color: ").append(toIndentedString(color)).append("\n"); + sb.append(" declawed: ").append(toIndentedString(declawed)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + * + * @param o Object to be converted to indented string + */ + 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/Category.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Category.java index f72d42a5746..31e61e56c25 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Category.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Category.java @@ -1,3 +1,28 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; import java.util.Objects; @@ -11,72 +36,88 @@ import com.google.gson.annotations.SerializedName; * Category */ public class Category { - - @SerializedName("id") - private Long id = null; + @SerializedName("id") + private Long id = null; + @SerializedName("name") + private String name = null; - @SerializedName("name") - private String name = null; - - /** - **/ - @ApiModelProperty(value = "") - public Long getId() { - return id; - } - public void setId(Long id) { - this.id = id; - } - - /** - **/ - @ApiModelProperty(value = "") - public String getName() { - return name; - } - public void setName(String name) { - this.name = name; - } - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; + /** + * Get id + * @return id + **/ + @ApiModelProperty(value = "") + public Long getId() { + return id; } - if (o == null || getClass() != o.getClass()) { - return false; + + /** + * Set id + * + * @param id id + */ + public void setId(Long id) { + this.id = id; } - Category category = (Category) o; - return Objects.equals(this.id, category.id) && + + /** + * Get name + * @return name + **/ + @ApiModelProperty(value = "") + public String getName() { + return name; + } + + /** + * Set name + * + * @param name 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(this.id, category.id) && Objects.equals(this.name, category.name); - } - - @Override - public int hashCode() { - return Objects.hash(id, name); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class Category {\n"); - - sb.append(" id: ").append(toIndentedString(id)).append("\n"); - sb.append(" name: ").append(toIndentedString(name)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; } - return o.toString().replace("\n", "\n "); - } + + @Override + public int hashCode() { + return Objects.hash(id, name); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Category {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + * + * @param o Object to be converted to indented string + */ + 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/Dog.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Dog.java index ba9f5ac5858..cba351a12c9 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Dog.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Dog.java @@ -1,3 +1,28 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; import java.util.Objects; @@ -12,88 +37,111 @@ import com.google.gson.annotations.SerializedName; * Dog */ public class Dog extends Animal { - - @SerializedName("className") - private String className = null; + @SerializedName("className") + private String className = null; + @SerializedName("color") + private String color = "red"; + @SerializedName("breed") + private String breed = null; - @SerializedName("color") - private String color = "red"; - - @SerializedName("breed") - private String breed = null; - - /** - **/ - @ApiModelProperty(required = true, value = "") - public String getClassName() { - return className; - } - public void setClassName(String className) { - this.className = className; - } - - /** - **/ - @ApiModelProperty(value = "") - public String getColor() { - return color; - } - public void setColor(String color) { - this.color = color; - } - - /** - **/ - @ApiModelProperty(value = "") - public String getBreed() { - return breed; - } - public void setBreed(String breed) { - this.breed = breed; - } - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; + /** + * Get className + * @return className + **/ + @ApiModelProperty(required = true, value = "") + public String getClassName() { + return className; } - if (o == null || getClass() != o.getClass()) { - return false; + + /** + * Set className + * + * @param className className + */ + public void setClassName(String className) { + this.className = className; } - Dog dog = (Dog) o; - return Objects.equals(this.className, dog.className) && + + /** + * Get color + * @return color + **/ + @ApiModelProperty(value = "") + public String getColor() { + return color; + } + + /** + * Set color + * + * @param color color + */ + public void setColor(String color) { + this.color = color; + } + + /** + * Get breed + * @return breed + **/ + @ApiModelProperty(value = "") + public String getBreed() { + return breed; + } + + /** + * Set breed + * + * @param breed breed + */ + public void setBreed(String breed) { + this.breed = breed; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Dog dog = (Dog) o; + return Objects.equals(this.className, dog.className) && Objects.equals(this.color, dog.color) && Objects.equals(this.breed, dog.breed) && super.equals(o); - } - - @Override - public int hashCode() { - return Objects.hash(className, color, breed, super.hashCode()); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class Dog {\n"); - sb.append(" ").append(toIndentedString(super.toString())).append("\n"); - sb.append(" className: ").append(toIndentedString(className)).append("\n"); - sb.append(" color: ").append(toIndentedString(color)).append("\n"); - sb.append(" breed: ").append(toIndentedString(breed)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; } - return o.toString().replace("\n", "\n "); - } + + @Override + public int hashCode() { + return Objects.hash(className, color, breed, super.hashCode()); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Dog {\n"); + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + sb.append(" className: ").append(toIndentedString(className)).append("\n"); + sb.append(" color: ").append(toIndentedString(color)).append("\n"); + sb.append(" breed: ").append(toIndentedString(breed)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + * + * @param o Object to be converted to indented string + */ + 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/EnumClass.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/EnumClass.java index 6426f26867c..af9ec9f32dc 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/EnumClass.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/EnumClass.java @@ -1,3 +1,28 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; import java.util.Objects; @@ -9,24 +34,24 @@ import com.google.gson.annotations.SerializedName; * Gets or Sets EnumClass */ public enum EnumClass { - @SerializedName("_abc") - _ABC("_abc"), + @SerializedName("_abc") + _ABC("_abc"), - @SerializedName("-efg") - _EFG("-efg"), + @SerializedName("-efg") + _EFG("-efg"), - @SerializedName("(xyz)") - _XYZ_("(xyz)"); + @SerializedName("(xyz)") + _XYZ_("(xyz)"); - private String value; + private String value; - EnumClass(String value) { - this.value = value; - } + EnumClass(String value) { + this.value = value; + } - @Override - public String toString() { - return String.valueOf(value); - } + @Override + public String toString() { + return String.valueOf(value); + } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/EnumTest.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/EnumTest.java index 9b3103c16d7..563a785d0b7 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/EnumTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/EnumTest.java @@ -1,3 +1,28 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; import java.util.Objects; @@ -11,8 +36,6 @@ import com.google.gson.annotations.SerializedName; * EnumTest */ public class EnumTest { - - /** * Gets or Sets enumString */ @@ -35,10 +58,8 @@ public class EnumTest { } } - @SerializedName("enum_string") - private EnumStringEnum enumString = null; - - + @SerializedName("enum_string") + private EnumStringEnum enumString = null; /** * Gets or Sets enumInteger */ @@ -61,10 +82,8 @@ public class EnumTest { } } - @SerializedName("enum_integer") - private EnumIntegerEnum enumInteger = null; - - + @SerializedName("enum_integer") + private EnumIntegerEnum enumInteger = null; /** * Gets or Sets enumNumber */ @@ -87,80 +106,106 @@ public class EnumTest { } } - @SerializedName("enum_number") - private EnumNumberEnum enumNumber = null; + @SerializedName("enum_number") + private EnumNumberEnum enumNumber = null; - /** - **/ - @ApiModelProperty(value = "") - public EnumStringEnum getEnumString() { - return enumString; - } - public void setEnumString(EnumStringEnum enumString) { - this.enumString = enumString; - } - - /** - **/ - @ApiModelProperty(value = "") - public EnumIntegerEnum getEnumInteger() { - return enumInteger; - } - public void setEnumInteger(EnumIntegerEnum enumInteger) { - this.enumInteger = enumInteger; - } - - /** - **/ - @ApiModelProperty(value = "") - public EnumNumberEnum getEnumNumber() { - return enumNumber; - } - public void setEnumNumber(EnumNumberEnum enumNumber) { - this.enumNumber = enumNumber; - } - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; + /** + * Get enumString + * @return enumString + **/ + @ApiModelProperty(value = "") + public EnumStringEnum getEnumString() { + return enumString; } - if (o == null || getClass() != o.getClass()) { - return false; + + /** + * Set enumString + * + * @param enumString enumString + */ + public void setEnumString(EnumStringEnum enumString) { + this.enumString = enumString; } - EnumTest enumTest = (EnumTest) o; - return Objects.equals(this.enumString, enumTest.enumString) && + + /** + * Get enumInteger + * @return enumInteger + **/ + @ApiModelProperty(value = "") + public EnumIntegerEnum getEnumInteger() { + return enumInteger; + } + + /** + * Set enumInteger + * + * @param enumInteger enumInteger + */ + public void setEnumInteger(EnumIntegerEnum enumInteger) { + this.enumInteger = enumInteger; + } + + /** + * Get enumNumber + * @return enumNumber + **/ + @ApiModelProperty(value = "") + public EnumNumberEnum getEnumNumber() { + return enumNumber; + } + + /** + * Set enumNumber + * + * @param enumNumber enumNumber + */ + public void setEnumNumber(EnumNumberEnum enumNumber) { + this.enumNumber = enumNumber; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + EnumTest enumTest = (EnumTest) o; + return Objects.equals(this.enumString, enumTest.enumString) && Objects.equals(this.enumInteger, enumTest.enumInteger) && Objects.equals(this.enumNumber, enumTest.enumNumber); - } - - @Override - public int hashCode() { - return Objects.hash(enumString, enumInteger, enumNumber); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class EnumTest {\n"); - - sb.append(" enumString: ").append(toIndentedString(enumString)).append("\n"); - sb.append(" enumInteger: ").append(toIndentedString(enumInteger)).append("\n"); - sb.append(" enumNumber: ").append(toIndentedString(enumNumber)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; } - return o.toString().replace("\n", "\n "); - } + + @Override + public int hashCode() { + return Objects.hash(enumString, enumInteger, enumNumber); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class EnumTest {\n"); + + sb.append(" enumString: ").append(toIndentedString(enumString)).append("\n"); + sb.append(" enumInteger: ").append(toIndentedString(enumInteger)).append("\n"); + sb.append(" enumNumber: ").append(toIndentedString(enumNumber)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + * + * @param o Object to be converted to indented string + */ + 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 af3fec2a2ea..66c4203c94e 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 @@ -1,10 +1,36 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; import java.util.Objects; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.math.BigDecimal; -import java.util.Date; +import org.joda.time.DateTime; +import org.joda.time.LocalDate; import com.google.gson.annotations.SerializedName; @@ -13,197 +39,288 @@ import com.google.gson.annotations.SerializedName; * FormatTest */ public class FormatTest { - - @SerializedName("integer") - private Integer integer = null; + @SerializedName("integer") + private Integer integer = null; + @SerializedName("int32") + private Integer int32 = null; + @SerializedName("int64") + private Long int64 = null; + @SerializedName("number") + private BigDecimal number = null; + @SerializedName("float") + private Float _float = null; + @SerializedName("double") + private Double _double = null; + @SerializedName("string") + private String string = null; + @SerializedName("byte") + private byte[] _byte = null; + @SerializedName("binary") + private byte[] binary = null; + @SerializedName("date") + private LocalDate date = null; + @SerializedName("dateTime") + private DateTime dateTime = null; + @SerializedName("uuid") + private String uuid = null; + @SerializedName("password") + private String password = null; - @SerializedName("int32") - private Integer int32 = null; - - @SerializedName("int64") - private Long int64 = null; - - @SerializedName("number") - private BigDecimal number = null; - - @SerializedName("float") - private Float _float = null; - - @SerializedName("double") - private Double _double = null; - - @SerializedName("string") - private String string = null; - - @SerializedName("byte") - private byte[] _byte = null; - - @SerializedName("binary") - private byte[] binary = null; - - @SerializedName("date") - private Date date = null; - - @SerializedName("dateTime") - private Date dateTime = null; - - @SerializedName("uuid") - private String uuid = null; - - @SerializedName("password") - private String password = null; - - /** - * minimum: 10.0 - * maximum: 100.0 - **/ - @ApiModelProperty(value = "") - public Integer getInteger() { - return integer; - } - public void setInteger(Integer integer) { - this.integer = integer; - } - - /** - * minimum: 20.0 - * maximum: 200.0 - **/ - @ApiModelProperty(value = "") - public Integer getInt32() { - return int32; - } - public void setInt32(Integer int32) { - this.int32 = int32; - } - - /** - **/ - @ApiModelProperty(value = "") - public Long getInt64() { - return int64; - } - public void setInt64(Long int64) { - this.int64 = int64; - } - - /** - * minimum: 32.1 - * maximum: 543.2 - **/ - @ApiModelProperty(required = true, value = "") - public BigDecimal getNumber() { - return number; - } - public void setNumber(BigDecimal number) { - this.number = number; - } - - /** - * minimum: 54.3 - * maximum: 987.6 - **/ - @ApiModelProperty(value = "") - public Float getFloat() { - return _float; - } - public void setFloat(Float _float) { - this._float = _float; - } - - /** - * minimum: 67.8 - * maximum: 123.4 - **/ - @ApiModelProperty(value = "") - public Double getDouble() { - return _double; - } - public void setDouble(Double _double) { - this._double = _double; - } - - /** - **/ - @ApiModelProperty(value = "") - public String getString() { - return string; - } - public void setString(String string) { - this.string = string; - } - - /** - **/ - @ApiModelProperty(required = true, value = "") - public byte[] getByte() { - return _byte; - } - public void setByte(byte[] _byte) { - this._byte = _byte; - } - - /** - **/ - @ApiModelProperty(value = "") - public byte[] getBinary() { - return binary; - } - public void setBinary(byte[] binary) { - this.binary = binary; - } - - /** - **/ - @ApiModelProperty(required = true, value = "") - public Date getDate() { - return date; - } - public void setDate(Date date) { - this.date = date; - } - - /** - **/ - @ApiModelProperty(value = "") - public Date getDateTime() { - return dateTime; - } - public void setDateTime(Date dateTime) { - this.dateTime = dateTime; - } - - /** - **/ - @ApiModelProperty(value = "") - public String getUuid() { - return uuid; - } - public void setUuid(String uuid) { - this.uuid = uuid; - } - - /** - **/ - @ApiModelProperty(required = true, value = "") - public String getPassword() { - return password; - } - public void setPassword(String password) { - this.password = password; - } - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; + /** + * Get integer + * minimum: 10.0 + * maximum: 100.0 + * @return integer + **/ + @ApiModelProperty(value = "") + public Integer getInteger() { + return integer; } - if (o == null || getClass() != o.getClass()) { - return false; + + /** + * Set integer + * + * @param integer integer + */ + public void setInteger(Integer integer) { + this.integer = integer; } - FormatTest formatTest = (FormatTest) o; - return Objects.equals(this.integer, formatTest.integer) && + + /** + * Get int32 + * minimum: 20.0 + * maximum: 200.0 + * @return int32 + **/ + @ApiModelProperty(value = "") + public Integer getInt32() { + return int32; + } + + /** + * Set int32 + * + * @param int32 int32 + */ + public void setInt32(Integer int32) { + this.int32 = int32; + } + + /** + * Get int64 + * @return int64 + **/ + @ApiModelProperty(value = "") + public Long getInt64() { + return int64; + } + + /** + * Set int64 + * + * @param int64 int64 + */ + public void setInt64(Long int64) { + this.int64 = int64; + } + + /** + * Get number + * minimum: 32.1 + * maximum: 543.2 + * @return number + **/ + @ApiModelProperty(required = true, value = "") + public BigDecimal getNumber() { + return number; + } + + /** + * Set number + * + * @param number number + */ + public void setNumber(BigDecimal number) { + this.number = number; + } + + /** + * Get _float + * minimum: 54.3 + * maximum: 987.6 + * @return _float + **/ + @ApiModelProperty(value = "") + public Float getFloat() { + return _float; + } + + /** + * Set _float + * + * @param _float _float + */ + public void setFloat(Float _float) { + this._float = _float; + } + + /** + * Get _double + * minimum: 67.8 + * maximum: 123.4 + * @return _double + **/ + @ApiModelProperty(value = "") + public Double getDouble() { + return _double; + } + + /** + * Set _double + * + * @param _double _double + */ + public void setDouble(Double _double) { + this._double = _double; + } + + /** + * Get string + * @return string + **/ + @ApiModelProperty(value = "") + public String getString() { + return string; + } + + /** + * Set string + * + * @param string string + */ + public void setString(String string) { + this.string = string; + } + + /** + * Get _byte + * @return _byte + **/ + @ApiModelProperty(required = true, value = "") + public byte[] getByte() { + return _byte; + } + + /** + * Set _byte + * + * @param _byte _byte + */ + public void setByte(byte[] _byte) { + this._byte = _byte; + } + + /** + * Get binary + * @return binary + **/ + @ApiModelProperty(value = "") + public byte[] getBinary() { + return binary; + } + + /** + * Set binary + * + * @param binary binary + */ + public void setBinary(byte[] binary) { + this.binary = binary; + } + + /** + * Get date + * @return date + **/ + @ApiModelProperty(required = true, value = "") + public LocalDate getDate() { + return date; + } + + /** + * Set date + * + * @param date date + */ + public void setDate(LocalDate date) { + this.date = date; + } + + /** + * Get dateTime + * @return dateTime + **/ + @ApiModelProperty(value = "") + public DateTime getDateTime() { + return dateTime; + } + + /** + * Set dateTime + * + * @param dateTime dateTime + */ + public void setDateTime(DateTime dateTime) { + this.dateTime = dateTime; + } + + /** + * Get uuid + * @return uuid + **/ + @ApiModelProperty(value = "") + public String getUuid() { + return uuid; + } + + /** + * Set uuid + * + * @param uuid uuid + */ + public void setUuid(String uuid) { + this.uuid = uuid; + } + + /** + * Get password + * @return password + **/ + @ApiModelProperty(required = true, value = "") + public String getPassword() { + return password; + } + + /** + * Set password + * + * @param password password + */ + public void setPassword(String password) { + this.password = password; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + FormatTest formatTest = (FormatTest) o; + return Objects.equals(this.integer, formatTest.integer) && Objects.equals(this.int32, formatTest.int32) && Objects.equals(this.int64, formatTest.int64) && Objects.equals(this.number, formatTest.number) && @@ -216,44 +333,46 @@ public class FormatTest { Objects.equals(this.dateTime, formatTest.dateTime) && Objects.equals(this.uuid, formatTest.uuid) && Objects.equals(this.password, formatTest.password); - } - - @Override - public int hashCode() { - return Objects.hash(integer, int32, int64, number, _float, _double, string, _byte, binary, date, dateTime, uuid, password); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class FormatTest {\n"); - - sb.append(" integer: ").append(toIndentedString(integer)).append("\n"); - sb.append(" int32: ").append(toIndentedString(int32)).append("\n"); - sb.append(" int64: ").append(toIndentedString(int64)).append("\n"); - sb.append(" number: ").append(toIndentedString(number)).append("\n"); - sb.append(" _float: ").append(toIndentedString(_float)).append("\n"); - sb.append(" _double: ").append(toIndentedString(_double)).append("\n"); - sb.append(" string: ").append(toIndentedString(string)).append("\n"); - sb.append(" _byte: ").append(toIndentedString(_byte)).append("\n"); - sb.append(" binary: ").append(toIndentedString(binary)).append("\n"); - sb.append(" date: ").append(toIndentedString(date)).append("\n"); - sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); - sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); - sb.append(" password: ").append(toIndentedString(password)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; } - return o.toString().replace("\n", "\n "); - } + + @Override + public int hashCode() { + return Objects.hash(integer, int32, int64, number, _float, _double, string, _byte, binary, date, dateTime, uuid, password); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class FormatTest {\n"); + + sb.append(" integer: ").append(toIndentedString(integer)).append("\n"); + sb.append(" int32: ").append(toIndentedString(int32)).append("\n"); + sb.append(" int64: ").append(toIndentedString(int64)).append("\n"); + sb.append(" number: ").append(toIndentedString(number)).append("\n"); + sb.append(" _float: ").append(toIndentedString(_float)).append("\n"); + sb.append(" _double: ").append(toIndentedString(_double)).append("\n"); + sb.append(" string: ").append(toIndentedString(string)).append("\n"); + sb.append(" _byte: ").append(toIndentedString(_byte)).append("\n"); + sb.append(" binary: ").append(toIndentedString(binary)).append("\n"); + sb.append(" date: ").append(toIndentedString(date)).append("\n"); + sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); + sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); + sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + * + * @param o Object to be converted to indented string + */ + 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/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java index 5748d6731cf..3c88142fc0a 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -1,13 +1,38 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; import java.util.Objects; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import io.swagger.client.model.Animal; -import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; +import org.joda.time.DateTime; import com.google.gson.annotations.SerializedName; @@ -16,87 +41,110 @@ import com.google.gson.annotations.SerializedName; * MixedPropertiesAndAdditionalPropertiesClass */ public class MixedPropertiesAndAdditionalPropertiesClass { - - @SerializedName("uuid") - private String uuid = null; + @SerializedName("uuid") + private String uuid = null; + @SerializedName("dateTime") + private DateTime dateTime = null; + @SerializedName("map") + private Map map = new HashMap(); - @SerializedName("dateTime") - private Date dateTime = null; - - @SerializedName("map") - private Map map = new HashMap(); - - /** - **/ - @ApiModelProperty(value = "") - public String getUuid() { - return uuid; - } - public void setUuid(String uuid) { - this.uuid = uuid; - } - - /** - **/ - @ApiModelProperty(value = "") - public Date getDateTime() { - return dateTime; - } - public void setDateTime(Date dateTime) { - this.dateTime = dateTime; - } - - /** - **/ - @ApiModelProperty(value = "") - public Map getMap() { - return map; - } - public void setMap(Map map) { - this.map = map; - } - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; + /** + * Get uuid + * @return uuid + **/ + @ApiModelProperty(value = "") + public String getUuid() { + return uuid; } - if (o == null || getClass() != o.getClass()) { - return false; + + /** + * Set uuid + * + * @param uuid uuid + */ + public void setUuid(String uuid) { + this.uuid = uuid; } - MixedPropertiesAndAdditionalPropertiesClass mixedPropertiesAndAdditionalPropertiesClass = (MixedPropertiesAndAdditionalPropertiesClass) o; - return Objects.equals(this.uuid, mixedPropertiesAndAdditionalPropertiesClass.uuid) && + + /** + * Get dateTime + * @return dateTime + **/ + @ApiModelProperty(value = "") + public DateTime getDateTime() { + return dateTime; + } + + /** + * Set dateTime + * + * @param dateTime dateTime + */ + public void setDateTime(DateTime dateTime) { + this.dateTime = dateTime; + } + + /** + * Get map + * @return map + **/ + @ApiModelProperty(value = "") + public Map getMap() { + return map; + } + + /** + * Set map + * + * @param map map + */ + public void setMap(Map map) { + this.map = map; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + MixedPropertiesAndAdditionalPropertiesClass mixedPropertiesAndAdditionalPropertiesClass = (MixedPropertiesAndAdditionalPropertiesClass) o; + return Objects.equals(this.uuid, mixedPropertiesAndAdditionalPropertiesClass.uuid) && Objects.equals(this.dateTime, mixedPropertiesAndAdditionalPropertiesClass.dateTime) && Objects.equals(this.map, mixedPropertiesAndAdditionalPropertiesClass.map); - } - - @Override - public int hashCode() { - return Objects.hash(uuid, dateTime, map); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class MixedPropertiesAndAdditionalPropertiesClass {\n"); - - sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); - sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); - sb.append(" map: ").append(toIndentedString(map)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; } - return o.toString().replace("\n", "\n "); - } + + @Override + public int hashCode() { + return Objects.hash(uuid, dateTime, map); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class MixedPropertiesAndAdditionalPropertiesClass {\n"); + + sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); + sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); + sb.append(" map: ").append(toIndentedString(map)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + * + * @param o Object to be converted to indented string + */ + 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/Model200Response.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Model200Response.java index 0ca445cb545..8c7227f3f4e 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Model200Response.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Model200Response.java @@ -1,3 +1,28 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; import java.util.Objects; @@ -12,57 +37,66 @@ import com.google.gson.annotations.SerializedName; */ @ApiModel(description = "Model for testing model name starting with number") public class Model200Response { - - @SerializedName("name") - private Integer name = null; + @SerializedName("name") + private Integer name = null; - /** - **/ - @ApiModelProperty(value = "") - public Integer getName() { - return name; - } - public void setName(Integer name) { - this.name = name; - } - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; + /** + * Get name + * @return name + **/ + @ApiModelProperty(value = "") + public Integer getName() { + return name; } - if (o == null || getClass() != o.getClass()) { - return false; + + /** + * Set name + * + * @param name name + */ + public void setName(Integer name) { + this.name = name; } - Model200Response _200Response = (Model200Response) o; - return Objects.equals(this.name, _200Response.name); - } - @Override - public int hashCode() { - return Objects.hash(name); - } - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class Model200Response {\n"); - - sb.append(" name: ").append(toIndentedString(name)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Model200Response _200Response = (Model200Response) o; + return Objects.equals(this.name, _200Response.name); + } + + @Override + public int hashCode() { + return Objects.hash(name); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Model200Response {\n"); + + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + * + * @param o Object to be converted to indented string + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); } - return o.toString().replace("\n", "\n "); - } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ModelApiResponse.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ModelApiResponse.java index da52eda160d..e72fe0c7dbe 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ModelApiResponse.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ModelApiResponse.java @@ -1,3 +1,28 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; import java.util.Objects; @@ -11,87 +36,110 @@ import com.google.gson.annotations.SerializedName; * ModelApiResponse */ public class ModelApiResponse { - - @SerializedName("code") - private Integer code = null; + @SerializedName("code") + private Integer code = null; + @SerializedName("type") + private String type = null; + @SerializedName("message") + private String message = null; - @SerializedName("type") - private String type = null; - - @SerializedName("message") - private String message = null; - - /** - **/ - @ApiModelProperty(value = "") - public Integer getCode() { - return code; - } - public void setCode(Integer code) { - this.code = code; - } - - /** - **/ - @ApiModelProperty(value = "") - public String getType() { - return type; - } - public void setType(String type) { - this.type = type; - } - - /** - **/ - @ApiModelProperty(value = "") - public String getMessage() { - return message; - } - public void setMessage(String message) { - this.message = message; - } - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; + /** + * Get code + * @return code + **/ + @ApiModelProperty(value = "") + public Integer getCode() { + return code; } - if (o == null || getClass() != o.getClass()) { - return false; + + /** + * Set code + * + * @param code code + */ + public void setCode(Integer code) { + this.code = code; } - ModelApiResponse _apiResponse = (ModelApiResponse) o; - return Objects.equals(this.code, _apiResponse.code) && + + /** + * Get type + * @return type + **/ + @ApiModelProperty(value = "") + public String getType() { + return type; + } + + /** + * Set type + * + * @param type type + */ + public void setType(String type) { + this.type = type; + } + + /** + * Get message + * @return message + **/ + @ApiModelProperty(value = "") + public String getMessage() { + return message; + } + + /** + * Set message + * + * @param message 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(this.code, _apiResponse.code) && Objects.equals(this.type, _apiResponse.type) && Objects.equals(this.message, _apiResponse.message); - } - - @Override - public int hashCode() { - return Objects.hash(code, type, message); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class ModelApiResponse {\n"); - - sb.append(" code: ").append(toIndentedString(code)).append("\n"); - sb.append(" type: ").append(toIndentedString(type)).append("\n"); - sb.append(" message: ").append(toIndentedString(message)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; } - return o.toString().replace("\n", "\n "); - } + + @Override + public int hashCode() { + return Objects.hash(code, type, message); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ModelApiResponse {\n"); + + sb.append(" code: ").append(toIndentedString(code)).append("\n"); + sb.append(" type: ").append(toIndentedString(type)).append("\n"); + sb.append(" message: ").append(toIndentedString(message)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + * + * @param o Object to be converted to indented string + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ModelReturn.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ModelReturn.java index 51aa1f4e055..52fd8ceaca1 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ModelReturn.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ModelReturn.java @@ -1,3 +1,28 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; import java.util.Objects; @@ -12,57 +37,66 @@ import com.google.gson.annotations.SerializedName; */ @ApiModel(description = "Model for testing reserved words") public class ModelReturn { - - @SerializedName("return") - private Integer _return = null; + @SerializedName("return") + private Integer _return = null; - /** - **/ - @ApiModelProperty(value = "") - public Integer getReturn() { - return _return; - } - public void setReturn(Integer _return) { - this._return = _return; - } - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; + /** + * Get _return + * @return _return + **/ + @ApiModelProperty(value = "") + public Integer getReturn() { + return _return; } - if (o == null || getClass() != o.getClass()) { - return false; + + /** + * Set _return + * + * @param _return _return + */ + public void setReturn(Integer _return) { + this._return = _return; } - ModelReturn _return = (ModelReturn) o; - return Objects.equals(this._return, _return._return); - } - @Override - public int hashCode() { - return Objects.hash(_return); - } - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class ModelReturn {\n"); - - sb.append(" _return: ").append(toIndentedString(_return)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ModelReturn _return = (ModelReturn) o; + return Objects.equals(this._return, _return._return); + } + + @Override + public int hashCode() { + return Objects.hash(_return); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ModelReturn {\n"); + + sb.append(" _return: ").append(toIndentedString(_return)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + * + * @param o Object to be converted to indented string + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); } - return o.toString().replace("\n", "\n "); - } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Name.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Name.java index e471107b3dc..fb4ef89df70 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Name.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Name.java @@ -1,3 +1,28 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; import java.util.Objects; @@ -12,96 +37,114 @@ import com.google.gson.annotations.SerializedName; */ @ApiModel(description = "Model for testing model name same as property name") public class Name { - - @SerializedName("name") - private Integer name = null; + @SerializedName("name") + private Integer name = null; + @SerializedName("snake_case") + private Integer snakeCase = null; + @SerializedName("property") + private String property = null; + @SerializedName("123Number") + private Integer _123Number = null; - @SerializedName("snake_case") - private Integer snakeCase = null; - - @SerializedName("property") - private String property = null; - - @SerializedName("123Number") - private Integer _123Number = null; - - /** - **/ - @ApiModelProperty(required = true, value = "") - public Integer getName() { - return name; - } - public void setName(Integer name) { - this.name = name; - } - - /** - **/ - @ApiModelProperty(value = "") - public Integer getSnakeCase() { - return snakeCase; - } - - /** - **/ - @ApiModelProperty(value = "") - public String getProperty() { - return property; - } - public void setProperty(String property) { - this.property = property; - } - - /** - **/ - @ApiModelProperty(value = "") - public Integer get123Number() { - return _123Number; - } - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; + /** + * Get name + * @return name + **/ + @ApiModelProperty(required = true, value = "") + public Integer getName() { + return name; } - if (o == null || getClass() != o.getClass()) { - return false; + + /** + * Set name + * + * @param name name + */ + public void setName(Integer name) { + this.name = name; } - Name name = (Name) o; - return Objects.equals(this.name, name.name) && + + /** + * Get snakeCase + * @return snakeCase + **/ + @ApiModelProperty(value = "") + public Integer getSnakeCase() { + return snakeCase; + } + + /** + * Get property + * @return property + **/ + @ApiModelProperty(value = "") + public String getProperty() { + return property; + } + + /** + * Set property + * + * @param property property + */ + public void setProperty(String property) { + this.property = property; + } + + /** + * Get _123Number + * @return _123Number + **/ + @ApiModelProperty(value = "") + public Integer get123Number() { + return _123Number; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Name name = (Name) o; + return Objects.equals(this.name, name.name) && Objects.equals(this.snakeCase, name.snakeCase) && Objects.equals(this.property, name.property) && Objects.equals(this._123Number, name._123Number); - } - - @Override - public int hashCode() { - return Objects.hash(name, snakeCase, property, _123Number); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class Name {\n"); - - sb.append(" name: ").append(toIndentedString(name)).append("\n"); - sb.append(" snakeCase: ").append(toIndentedString(snakeCase)).append("\n"); - sb.append(" property: ").append(toIndentedString(property)).append("\n"); - sb.append(" _123Number: ").append(toIndentedString(_123Number)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; } - return o.toString().replace("\n", "\n "); - } + + @Override + public int hashCode() { + return Objects.hash(name, snakeCase, property, _123Number); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Name {\n"); + + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" snakeCase: ").append(toIndentedString(snakeCase)).append("\n"); + sb.append(" property: ").append(toIndentedString(property)).append("\n"); + sb.append(" _123Number: ").append(toIndentedString(_123Number)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + * + * @param o Object to be converted to indented string + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Order.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Order.java index e5c87a21e5b..681715f12ed 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Order.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Order.java @@ -1,9 +1,34 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; import java.util.Objects; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; -import java.util.Date; +import org.joda.time.DateTime; import com.google.gson.annotations.SerializedName; @@ -12,20 +37,14 @@ import com.google.gson.annotations.SerializedName; * Order */ public class Order { - - @SerializedName("id") - private Long id = null; - - @SerializedName("petId") - private Long petId = null; - - @SerializedName("quantity") - private Integer quantity = null; - - @SerializedName("shipDate") - private Date shipDate = null; - - + @SerializedName("id") + private Long id = null; + @SerializedName("petId") + private Long petId = null; + @SerializedName("quantity") + private Integer quantity = null; + @SerializedName("shipDate") + private DateTime shipDate = null; /** * Order Status */ @@ -51,120 +70,168 @@ public class Order { } } - @SerializedName("status") - private StatusEnum status = null; + @SerializedName("status") + private StatusEnum status = null; + @SerializedName("complete") + private Boolean complete = false; - @SerializedName("complete") - private Boolean complete = false; - - /** - **/ - @ApiModelProperty(value = "") - public Long getId() { - return id; - } - public void setId(Long id) { - this.id = id; - } - - /** - **/ - @ApiModelProperty(value = "") - public Long getPetId() { - return petId; - } - public void setPetId(Long petId) { - this.petId = petId; - } - - /** - **/ - @ApiModelProperty(value = "") - public Integer getQuantity() { - return quantity; - } - public void setQuantity(Integer quantity) { - this.quantity = quantity; - } - - /** - **/ - @ApiModelProperty(value = "") - public Date getShipDate() { - return shipDate; - } - public void setShipDate(Date shipDate) { - this.shipDate = shipDate; - } - - /** - * Order Status - **/ - @ApiModelProperty(value = "Order Status") - public StatusEnum getStatus() { - return status; - } - public void setStatus(StatusEnum status) { - this.status = status; - } - - /** - **/ - @ApiModelProperty(value = "") - public Boolean getComplete() { - return complete; - } - public void setComplete(Boolean complete) { - this.complete = complete; - } - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; + /** + * Get id + * @return id + **/ + @ApiModelProperty(value = "") + public Long getId() { + return id; } - if (o == null || getClass() != o.getClass()) { - return false; + + /** + * Set id + * + * @param id id + */ + public void setId(Long id) { + this.id = id; } - Order order = (Order) o; - return Objects.equals(this.id, order.id) && + + /** + * Get petId + * @return petId + **/ + @ApiModelProperty(value = "") + public Long getPetId() { + return petId; + } + + /** + * Set petId + * + * @param petId petId + */ + public void setPetId(Long petId) { + this.petId = petId; + } + + /** + * Get quantity + * @return quantity + **/ + @ApiModelProperty(value = "") + public Integer getQuantity() { + return quantity; + } + + /** + * Set quantity + * + * @param quantity quantity + */ + public void setQuantity(Integer quantity) { + this.quantity = quantity; + } + + /** + * Get shipDate + * @return shipDate + **/ + @ApiModelProperty(value = "") + public DateTime getShipDate() { + return shipDate; + } + + /** + * Set shipDate + * + * @param shipDate shipDate + */ + public void setShipDate(DateTime shipDate) { + this.shipDate = shipDate; + } + + /** + * Order Status + * @return status + **/ + @ApiModelProperty(value = "Order Status") + public StatusEnum getStatus() { + return status; + } + + /** + * Set status + * + * @param status status + */ + public void setStatus(StatusEnum status) { + this.status = status; + } + + /** + * Get complete + * @return complete + **/ + @ApiModelProperty(value = "") + public Boolean getComplete() { + return complete; + } + + /** + * Set complete + * + * @param complete 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(this.id, order.id) && Objects.equals(this.petId, order.petId) && Objects.equals(this.quantity, order.quantity) && Objects.equals(this.shipDate, order.shipDate) && Objects.equals(this.status, order.status) && Objects.equals(this.complete, order.complete); - } - - @Override - public int hashCode() { - return Objects.hash(id, petId, quantity, shipDate, status, complete); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class Order {\n"); - - sb.append(" id: ").append(toIndentedString(id)).append("\n"); - sb.append(" petId: ").append(toIndentedString(petId)).append("\n"); - sb.append(" quantity: ").append(toIndentedString(quantity)).append("\n"); - sb.append(" shipDate: ").append(toIndentedString(shipDate)).append("\n"); - sb.append(" status: ").append(toIndentedString(status)).append("\n"); - sb.append(" complete: ").append(toIndentedString(complete)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; } - return o.toString().replace("\n", "\n "); - } + + @Override + public int hashCode() { + return Objects.hash(id, petId, quantity, shipDate, status, complete); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Order {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" petId: ").append(toIndentedString(petId)).append("\n"); + sb.append(" quantity: ").append(toIndentedString(quantity)).append("\n"); + sb.append(" shipDate: ").append(toIndentedString(shipDate)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append(" complete: ").append(toIndentedString(complete)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + * + * @param o Object to be converted to indented string + */ + 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/Pet.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Pet.java index bc18c39e75f..92c499ae757 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Pet.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Pet.java @@ -1,3 +1,28 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; import java.util.Objects; @@ -15,23 +40,16 @@ import com.google.gson.annotations.SerializedName; * Pet */ public class Pet { - - @SerializedName("id") - private Long id = null; - - @SerializedName("category") - private Category category = null; - - @SerializedName("name") - private String name = null; - - @SerializedName("photoUrls") - private List photoUrls = new ArrayList(); - - @SerializedName("tags") - private List tags = new ArrayList(); - - + @SerializedName("id") + private Long id = null; + @SerializedName("category") + private Category category = null; + @SerializedName("name") + private String name = null; + @SerializedName("photoUrls") + private List photoUrls = new ArrayList(); + @SerializedName("tags") + private List tags = new ArrayList(); /** * pet status in the store */ @@ -57,117 +75,166 @@ public class Pet { } } - @SerializedName("status") - private StatusEnum status = null; + @SerializedName("status") + private StatusEnum status = null; - /** - **/ - @ApiModelProperty(value = "") - public Long getId() { - return id; - } - public void setId(Long id) { - this.id = id; - } - - /** - **/ - @ApiModelProperty(value = "") - public Category getCategory() { - return category; - } - public void setCategory(Category category) { - this.category = category; - } - - /** - **/ - @ApiModelProperty(required = true, value = "") - public String getName() { - return name; - } - public void setName(String name) { - this.name = name; - } - - /** - **/ - @ApiModelProperty(required = true, value = "") - public List getPhotoUrls() { - return photoUrls; - } - public void setPhotoUrls(List photoUrls) { - this.photoUrls = photoUrls; - } - - /** - **/ - @ApiModelProperty(value = "") - public List getTags() { - return tags; - } - public void setTags(List tags) { - this.tags = tags; - } - - /** - * pet status in the store - **/ - @ApiModelProperty(value = "pet status in the store") - public StatusEnum getStatus() { - return status; - } - public void setStatus(StatusEnum status) { - this.status = status; - } - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; + /** + * Get id + * @return id + **/ + @ApiModelProperty(value = "") + public Long getId() { + return id; } - if (o == null || getClass() != o.getClass()) { - return false; + + /** + * Set id + * + * @param id id + */ + public void setId(Long id) { + this.id = id; } - Pet pet = (Pet) o; - return Objects.equals(this.id, pet.id) && + + /** + * Get category + * @return category + **/ + @ApiModelProperty(value = "") + public Category getCategory() { + return category; + } + + /** + * Set category + * + * @param category category + */ + public void setCategory(Category category) { + this.category = category; + } + + /** + * Get name + * @return name + **/ + @ApiModelProperty(required = true, value = "") + public String getName() { + return name; + } + + /** + * Set name + * + * @param name name + */ + public void setName(String name) { + this.name = name; + } + + /** + * Get photoUrls + * @return photoUrls + **/ + @ApiModelProperty(required = true, value = "") + public List getPhotoUrls() { + return photoUrls; + } + + /** + * Set photoUrls + * + * @param photoUrls photoUrls + */ + public void setPhotoUrls(List photoUrls) { + this.photoUrls = photoUrls; + } + + /** + * Get tags + * @return tags + **/ + @ApiModelProperty(value = "") + public List getTags() { + return tags; + } + + /** + * Set tags + * + * @param tags tags + */ + public void setTags(List tags) { + this.tags = tags; + } + + /** + * pet status in the store + * @return status + **/ + @ApiModelProperty(value = "pet status in the store") + public StatusEnum getStatus() { + return status; + } + + /** + * Set status + * + * @param status 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(this.id, pet.id) && Objects.equals(this.category, pet.category) && Objects.equals(this.name, pet.name) && Objects.equals(this.photoUrls, pet.photoUrls) && Objects.equals(this.tags, pet.tags) && Objects.equals(this.status, pet.status); - } - - @Override - public int hashCode() { - return Objects.hash(id, category, name, photoUrls, tags, status); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class Pet {\n"); - - sb.append(" id: ").append(toIndentedString(id)).append("\n"); - sb.append(" category: ").append(toIndentedString(category)).append("\n"); - sb.append(" name: ").append(toIndentedString(name)).append("\n"); - sb.append(" photoUrls: ").append(toIndentedString(photoUrls)).append("\n"); - sb.append(" tags: ").append(toIndentedString(tags)).append("\n"); - sb.append(" status: ").append(toIndentedString(status)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; } - return o.toString().replace("\n", "\n "); - } + + @Override + public int hashCode() { + return Objects.hash(id, category, name, photoUrls, tags, status); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Pet {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" category: ").append(toIndentedString(category)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" photoUrls: ").append(toIndentedString(photoUrls)).append("\n"); + sb.append(" tags: ").append(toIndentedString(tags)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + * + * @param o Object to be converted to indented string + */ + 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/ReadOnlyFirst.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ReadOnlyFirst.java index 2e6c3c4f7ff..a43413d0903 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ReadOnlyFirst.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ReadOnlyFirst.java @@ -1,3 +1,28 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; import java.util.Objects; @@ -11,69 +36,79 @@ import com.google.gson.annotations.SerializedName; * ReadOnlyFirst */ public class ReadOnlyFirst { - - @SerializedName("bar") - private String bar = null; + @SerializedName("bar") + private String bar = null; + @SerializedName("baz") + private String baz = null; - @SerializedName("baz") - private String baz = null; - - /** - **/ - @ApiModelProperty(value = "") - public String getBar() { - return bar; - } - - /** - **/ - @ApiModelProperty(value = "") - public String getBaz() { - return baz; - } - public void setBaz(String baz) { - this.baz = baz; - } - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; + /** + * Get bar + * @return bar + **/ + @ApiModelProperty(value = "") + public String getBar() { + return bar; } - if (o == null || getClass() != o.getClass()) { - return false; + + /** + * Get baz + * @return baz + **/ + @ApiModelProperty(value = "") + public String getBaz() { + return baz; } - ReadOnlyFirst readOnlyFirst = (ReadOnlyFirst) o; - return Objects.equals(this.bar, readOnlyFirst.bar) && + + /** + * Set baz + * + * @param baz baz + */ + public void setBaz(String baz) { + this.baz = baz; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ReadOnlyFirst readOnlyFirst = (ReadOnlyFirst) o; + return Objects.equals(this.bar, readOnlyFirst.bar) && Objects.equals(this.baz, readOnlyFirst.baz); - } - - @Override - public int hashCode() { - return Objects.hash(bar, baz); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class ReadOnlyFirst {\n"); - - sb.append(" bar: ").append(toIndentedString(bar)).append("\n"); - sb.append(" baz: ").append(toIndentedString(baz)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; } - return o.toString().replace("\n", "\n "); - } + + @Override + public int hashCode() { + return Objects.hash(bar, baz); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ReadOnlyFirst {\n"); + + sb.append(" bar: ").append(toIndentedString(bar)).append("\n"); + sb.append(" baz: ").append(toIndentedString(baz)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + * + * @param o Object to be converted to indented string + */ + 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/SpecialModelName.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/SpecialModelName.java index 46cee3c51f8..1ed10e372ae 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/SpecialModelName.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/SpecialModelName.java @@ -1,3 +1,28 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; import java.util.Objects; @@ -11,57 +36,66 @@ import com.google.gson.annotations.SerializedName; * SpecialModelName */ public class SpecialModelName { - - @SerializedName("$special[property.name]") - private Long specialPropertyName = null; + @SerializedName("$special[property.name]") + private Long specialPropertyName = null; - /** - **/ - @ApiModelProperty(value = "") - public Long getSpecialPropertyName() { - return specialPropertyName; - } - public void setSpecialPropertyName(Long specialPropertyName) { - this.specialPropertyName = specialPropertyName; - } - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; + /** + * Get specialPropertyName + * @return specialPropertyName + **/ + @ApiModelProperty(value = "") + public Long getSpecialPropertyName() { + return specialPropertyName; } - if (o == null || getClass() != o.getClass()) { - return false; + + /** + * Set specialPropertyName + * + * @param specialPropertyName specialPropertyName + */ + public void setSpecialPropertyName(Long specialPropertyName) { + this.specialPropertyName = specialPropertyName; } - SpecialModelName specialModelName = (SpecialModelName) o; - return Objects.equals(this.specialPropertyName, specialModelName.specialPropertyName); - } - @Override - public int hashCode() { - return Objects.hash(specialPropertyName); - } - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class SpecialModelName {\n"); - - sb.append(" specialPropertyName: ").append(toIndentedString(specialPropertyName)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + SpecialModelName specialModelName = (SpecialModelName) o; + return Objects.equals(this.specialPropertyName, specialModelName.specialPropertyName); + } + + @Override + public int hashCode() { + return Objects.hash(specialPropertyName); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class SpecialModelName {\n"); + + sb.append(" specialPropertyName: ").append(toIndentedString(specialPropertyName)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + * + * @param o Object to be converted to indented string + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); } - return o.toString().replace("\n", "\n "); - } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Tag.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Tag.java index 600acee2ba7..a80ef012510 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Tag.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Tag.java @@ -1,3 +1,28 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; import java.util.Objects; @@ -11,72 +36,88 @@ import com.google.gson.annotations.SerializedName; * Tag */ public class Tag { - - @SerializedName("id") - private Long id = null; + @SerializedName("id") + private Long id = null; + @SerializedName("name") + private String name = null; - @SerializedName("name") - private String name = null; - - /** - **/ - @ApiModelProperty(value = "") - public Long getId() { - return id; - } - public void setId(Long id) { - this.id = id; - } - - /** - **/ - @ApiModelProperty(value = "") - public String getName() { - return name; - } - public void setName(String name) { - this.name = name; - } - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; + /** + * Get id + * @return id + **/ + @ApiModelProperty(value = "") + public Long getId() { + return id; } - if (o == null || getClass() != o.getClass()) { - return false; + + /** + * Set id + * + * @param id id + */ + public void setId(Long id) { + this.id = id; } - Tag tag = (Tag) o; - return Objects.equals(this.id, tag.id) && + + /** + * Get name + * @return name + **/ + @ApiModelProperty(value = "") + public String getName() { + return name; + } + + /** + * Set name + * + * @param name 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(this.id, tag.id) && Objects.equals(this.name, tag.name); - } - - @Override - public int hashCode() { - return Objects.hash(id, name); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class Tag {\n"); - - sb.append(" id: ").append(toIndentedString(id)).append("\n"); - sb.append(" name: ").append(toIndentedString(name)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; } - return o.toString().replace("\n", "\n "); - } + + @Override + public int hashCode() { + return Objects.hash(id, name); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Tag {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + * + * @param o Object to be converted to indented string + */ + 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/User.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/User.java index c8b44ce6562..cac9626602d 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/User.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/User.java @@ -1,3 +1,28 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.model; import java.util.Objects; @@ -11,123 +36,178 @@ import com.google.gson.annotations.SerializedName; * User */ public class User { - - @SerializedName("id") - private Long id = null; + @SerializedName("id") + private Long id = null; + @SerializedName("username") + private String username = null; + @SerializedName("firstName") + private String firstName = null; + @SerializedName("lastName") + private String lastName = null; + @SerializedName("email") + private String email = null; + @SerializedName("password") + private String password = null; + @SerializedName("phone") + private String phone = null; + @SerializedName("userStatus") + private Integer userStatus = null; - @SerializedName("username") - private String username = null; - - @SerializedName("firstName") - private String firstName = null; - - @SerializedName("lastName") - private String lastName = null; - - @SerializedName("email") - private String email = null; - - @SerializedName("password") - private String password = null; - - @SerializedName("phone") - private String phone = null; - - @SerializedName("userStatus") - private Integer userStatus = null; - - /** - **/ - @ApiModelProperty(value = "") - public Long getId() { - return id; - } - public void setId(Long id) { - this.id = id; - } - - /** - **/ - @ApiModelProperty(value = "") - public String getUsername() { - return username; - } - public void setUsername(String username) { - this.username = username; - } - - /** - **/ - @ApiModelProperty(value = "") - public String getFirstName() { - return firstName; - } - public void setFirstName(String firstName) { - this.firstName = firstName; - } - - /** - **/ - @ApiModelProperty(value = "") - public String getLastName() { - return lastName; - } - public void setLastName(String lastName) { - this.lastName = lastName; - } - - /** - **/ - @ApiModelProperty(value = "") - public String getEmail() { - return email; - } - public void setEmail(String email) { - this.email = email; - } - - /** - **/ - @ApiModelProperty(value = "") - public String getPassword() { - return password; - } - public void setPassword(String password) { - this.password = password; - } - - /** - **/ - @ApiModelProperty(value = "") - public String getPhone() { - return phone; - } - public void setPhone(String phone) { - this.phone = phone; - } - - /** - * User Status - **/ - @ApiModelProperty(value = "User Status") - public Integer getUserStatus() { - return userStatus; - } - public void setUserStatus(Integer userStatus) { - this.userStatus = userStatus; - } - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; + /** + * Get id + * @return id + **/ + @ApiModelProperty(value = "") + public Long getId() { + return id; } - if (o == null || getClass() != o.getClass()) { - return false; + + /** + * Set id + * + * @param id id + */ + public void setId(Long id) { + this.id = id; } - User user = (User) o; - return Objects.equals(this.id, user.id) && + + /** + * Get username + * @return username + **/ + @ApiModelProperty(value = "") + public String getUsername() { + return username; + } + + /** + * Set username + * + * @param username username + */ + public void setUsername(String username) { + this.username = username; + } + + /** + * Get firstName + * @return firstName + **/ + @ApiModelProperty(value = "") + public String getFirstName() { + return firstName; + } + + /** + * Set firstName + * + * @param firstName firstName + */ + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + /** + * Get lastName + * @return lastName + **/ + @ApiModelProperty(value = "") + public String getLastName() { + return lastName; + } + + /** + * Set lastName + * + * @param lastName lastName + */ + public void setLastName(String lastName) { + this.lastName = lastName; + } + + /** + * Get email + * @return email + **/ + @ApiModelProperty(value = "") + public String getEmail() { + return email; + } + + /** + * Set email + * + * @param email email + */ + public void setEmail(String email) { + this.email = email; + } + + /** + * Get password + * @return password + **/ + @ApiModelProperty(value = "") + public String getPassword() { + return password; + } + + /** + * Set password + * + * @param password password + */ + public void setPassword(String password) { + this.password = password; + } + + /** + * Get phone + * @return phone + **/ + @ApiModelProperty(value = "") + public String getPhone() { + return phone; + } + + /** + * Set phone + * + * @param phone phone + */ + public void setPhone(String phone) { + this.phone = phone; + } + + /** + * User Status + * @return userStatus + **/ + @ApiModelProperty(value = "User Status") + public Integer getUserStatus() { + return userStatus; + } + + /** + * Set userStatus + * + * @param userStatus 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(this.id, user.id) && Objects.equals(this.username, user.username) && Objects.equals(this.firstName, user.firstName) && Objects.equals(this.lastName, user.lastName) && @@ -135,39 +215,41 @@ public class User { Objects.equals(this.password, user.password) && Objects.equals(this.phone, user.phone) && Objects.equals(this.userStatus, user.userStatus); - } - - @Override - public int hashCode() { - return Objects.hash(id, username, firstName, lastName, email, password, phone, userStatus); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class User {\n"); - - sb.append(" id: ").append(toIndentedString(id)).append("\n"); - sb.append(" username: ").append(toIndentedString(username)).append("\n"); - sb.append(" firstName: ").append(toIndentedString(firstName)).append("\n"); - sb.append(" lastName: ").append(toIndentedString(lastName)).append("\n"); - sb.append(" email: ").append(toIndentedString(email)).append("\n"); - sb.append(" password: ").append(toIndentedString(password)).append("\n"); - sb.append(" phone: ").append(toIndentedString(phone)).append("\n"); - sb.append(" userStatus: ").append(toIndentedString(userStatus)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; } - return o.toString().replace("\n", "\n "); - } + + @Override + public int hashCode() { + return Objects.hash(id, username, firstName, lastName, email, password, phone, userStatus); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class User {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" username: ").append(toIndentedString(username)).append("\n"); + sb.append(" firstName: ").append(toIndentedString(firstName)).append("\n"); + sb.append(" lastName: ").append(toIndentedString(lastName)).append("\n"); + sb.append(" email: ").append(toIndentedString(email)).append("\n"); + sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" phone: ").append(toIndentedString(phone)).append("\n"); + sb.append(" userStatus: ").append(toIndentedString(userStatus)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + * + * @param o Object to be converted to indented string + */ + 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/test/java/io/swagger/client/JSONTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/JSONTest.java index fdc2e4c7d4a..8dab64b289e 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/JSONTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/JSONTest.java @@ -6,10 +6,10 @@ import io.swagger.client.model.Order; import java.lang.Exception; import java.lang.reflect.Type; -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.*; +import org.joda.time.DateTimeZone; +import org.joda.time.format.DateTimeFormatter; +import org.joda.time.format.ISODateTimeFormat; import org.junit.*; import static org.junit.Assert.*; @@ -27,29 +27,25 @@ public class JSONTest { @Test public void testDefaultDate() throws Exception { - final DateFormat datetimeFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); - datetimeFormat.setTimeZone(TimeZone.getTimeZone("UTC")); + final DateTimeFormatter datetimeFormat = ISODateTimeFormat.dateTime().withZone(DateTimeZone.UTC); final String dateStr = "2015-11-07T14:11:05.267Z"; - order.setShipDate(datetimeFormat.parse(dateStr)); + order.setShipDate(datetimeFormat.parseDateTime(dateStr)); String str = json.serialize(order); Type type = new TypeToken() { }.getType(); Order o = json.deserialize(str, type); - assertEquals(dateStr, datetimeFormat.format(o.getShipDate())); + assertEquals(dateStr, datetimeFormat.print(o.getShipDate())); } @Test public void testCustomDate() throws Exception { - final DateFormat datetimeFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX"); - datetimeFormat.setTimeZone(TimeZone.getTimeZone("GMT-2")); + final DateTimeFormatter datetimeFormat = ISODateTimeFormat.dateTimeNoMillis().withZone(DateTimeZone.forID("Etc/GMT+2")); final String dateStr = "2015-11-07T14:11:05-02:00"; - order.setShipDate(datetimeFormat.parse(dateStr)); + order.setShipDate(datetimeFormat.parseDateTime(dateStr)); - apiClient.setDatetimeFormat(datetimeFormat); - apiClient.setLenientDatetimeFormat(false); String str = json.serialize(order); Type type = new TypeToken() { }.getType(); Order o = json.deserialize(str, type); - assertEquals(dateStr, datetimeFormat.format(o.getShipDate())); + assertEquals(dateStr, datetimeFormat.print(o.getShipDate())); } } \ No newline at end of file diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/api/PetApiTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/api/PetApiTest.java index c25e0d8bfa2..8bfb7605093 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/api/PetApiTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/api/PetApiTest.java @@ -1,155 +1,395 @@ package io.swagger.client.api; -import io.swagger.client.ApiException; -import io.swagger.client.model.Pet; -import io.swagger.client.model.ModelApiResponse; -import java.io.File; -import org.junit.Test; +import io.swagger.TestUtils; +import io.swagger.client.*; +import io.swagger.client.auth.*; +import io.swagger.client.model.*; + +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileWriter; +import java.lang.reflect.Type; import java.util.ArrayList; +import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; -/** - * API tests for PetApi - */ +import org.junit.*; +import static org.junit.Assert.*; + public class PetApiTest { + PetApi api = null; - private final PetApi api = new PetApi(); - - - /** - * Add a new pet to the store - * - * - * - * @throws ApiException - * if the Api call fails - */ - @Test - public void addPetTest() throws ApiException { - Pet body = null; - // api.addPet(body); - - // TODO: test validations + @Before + public void setup() { + api = new PetApi(); + // setup authentication + ApiKeyAuth apiKeyAuth = (ApiKeyAuth) api.getApiClient().getAuthentication("api_key"); + apiKeyAuth.setApiKey("special-key"); } - - /** - * Deletes a pet - * - * - * - * @throws ApiException - * if the Api call fails - */ - @Test - public void deletePetTest() throws ApiException { - Long petId = null; - String apiKey = null; - // api.deletePet(petId, apiKey); - // TODO: test validations - } - - /** - * Finds Pets by status - * - * Multiple status values can be provided with comma separated strings - * - * @throws ApiException - * if the Api call fails - */ @Test - public void findPetsByStatusTest() throws ApiException { - List status = null; - // List response = api.findPetsByStatus(status); + public void testApiClient() { + // the default api client is used + assertEquals(Configuration.getDefaultApiClient(), api.getApiClient()); + assertNotNull(api.getApiClient()); + assertEquals("http://petstore.swagger.io/v2", api.getApiClient().getBasePath()); + assertFalse(api.getApiClient().isDebugging()); - // TODO: test validations + ApiClient oldClient = api.getApiClient(); + + ApiClient newClient = new ApiClient(); + newClient.setBasePath("http://example.com"); + newClient.setDebugging(true); + + // set api client via constructor + api = new PetApi(newClient); + assertNotNull(api.getApiClient()); + assertEquals("http://example.com", api.getApiClient().getBasePath()); + assertTrue(api.getApiClient().isDebugging()); + + // set api client via setter method + api.setApiClient(oldClient); + assertNotNull(api.getApiClient()); + assertEquals("http://petstore.swagger.io/v2", api.getApiClient().getBasePath()); + assertFalse(api.getApiClient().isDebugging()); } - - /** - * Finds Pets by tags - * - * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. - * - * @throws ApiException - * if the Api call fails - */ + @Test - public void findPetsByTagsTest() throws ApiException { - List tags = null; - // List response = api.findPetsByTags(tags); + public void testCreateAndGetPet() throws Exception { + Pet pet = createRandomPet(); + api.addPet(pet); - // TODO: test validations + Pet fetched = api.getPetById(pet.getId()); + assertNotNull(fetched); + assertEquals(pet.getId(), fetched.getId()); + assertNotNull(fetched.getCategory()); + assertEquals(fetched.getCategory().getName(), pet.getCategory().getName()); } - - /** - * Find pet by ID - * - * Returns a single pet - * - * @throws ApiException - * if the Api call fails - */ + + /* @Test - public void getPetByIdTest() throws ApiException { - Long petId = null; - // Pet response = api.getPetById(petId); + public void testCreateAndGetPetWithByteArray() throws Exception { + Pet pet = createRandomPet(); + byte[] bytes = serializeJson(pet, api.getApiClient()).getBytes(); + api.addPetUsingByteArray(bytes); - // TODO: test validations + byte[] fetchedBytes = api.petPetIdtestingByteArraytrueGet(pet.getId()); + Type type = new TypeToken(){}.getType(); + Pet fetched = deserializeJson(new String(fetchedBytes), type, api.getApiClient()); + assertNotNull(fetched); + assertEquals(pet.getId(), fetched.getId()); + assertNotNull(fetched.getCategory()); + assertEquals(fetched.getCategory().getName(), pet.getCategory().getName()); } - - /** - * Update an existing pet - * - * - * - * @throws ApiException - * if the Api call fails - */ + */ + @Test - public void updatePetTest() throws ApiException { - Pet body = null; - // api.updatePet(body); + public void testCreateAndGetPetWithHttpInfo() throws Exception { + Pet pet = createRandomPet(); + api.addPetWithHttpInfo(pet); - // TODO: test validations + ApiResponse resp = api.getPetByIdWithHttpInfo(pet.getId()); + assertEquals(200, resp.getStatusCode()); + assertEquals("application/json", resp.getHeaders().get("Content-Type").get(0)); + Pet fetched = resp.getData(); + assertNotNull(fetched); + assertEquals(pet.getId(), fetched.getId()); + assertNotNull(fetched.getCategory()); + assertEquals(fetched.getCategory().getName(), pet.getCategory().getName()); } - - /** - * Updates a pet in the store with form data - * - * - * - * @throws ApiException - * if the Api call fails - */ + @Test - public void updatePetWithFormTest() throws ApiException { - Long petId = null; - String name = null; - String status = null; - // api.updatePetWithForm(petId, name, status); + public void testCreateAndGetPetAsync() throws Exception { + Pet pet = createRandomPet(); + api.addPet(pet); + // to store returned Pet or error message/exception + final Map result = new HashMap(); - // TODO: test validations + api.getPetByIdAsync(pet.getId(), new ApiCallback() { + @Override + public void onFailure(ApiException e, int statusCode, Map> responseHeaders) { + result.put("error", e.getMessage()); + } + + @Override + public void onSuccess(Pet pet, int statusCode, Map> responseHeaders) { + result.put("pet", pet); + } + + @Override + public void onUploadProgress(long bytesWritten, long contentLength, boolean done) { + //empty + } + + @Override + public void onDownloadProgress(long bytesRead, long contentLength, boolean done) { + //empty + } + }); + // the API call should be executed asynchronously, so result should be empty at the moment + assertTrue(result.isEmpty()); + + // wait for the asynchronous call to finish (at most 10 seconds) + final int maxTry = 10; + int tryCount = 1; + Pet fetched = null; + do { + if (tryCount > maxTry) fail("have not got result of getPetByIdAsync after 10 seconds"); + Thread.sleep(1000); + tryCount += 1; + if (result.get("error") != null) fail((String) result.get("error")); + if (result.get("pet") != null) { + fetched = (Pet) result.get("pet"); + break; + } + } while (result.isEmpty()); + assertNotNull(fetched); + assertEquals(pet.getId(), fetched.getId()); + assertNotNull(fetched.getCategory()); + assertEquals(fetched.getCategory().getName(), pet.getCategory().getName()); + + // test getting a nonexistent pet + result.clear(); + api.getPetByIdAsync(new Long(-10000), new ApiCallback() { + @Override + public void onFailure(ApiException e, int statusCode, Map> responseHeaders) { + result.put("exception", e); + } + + @Override + public void onSuccess(Pet pet, int statusCode, Map> responseHeaders) { + result.put("pet", pet); + } + + @Override + public void onUploadProgress(long bytesWritten, long contentLength, boolean done) { + //empty + } + + @Override + public void onDownloadProgress(long bytesRead, long contentLength, boolean done) { + //empty + } + }); + // the API call should be executed asynchronously, so result should be empty at the moment + assertTrue(result.isEmpty()); + + // wait for the asynchronous call to finish (at most 10 seconds) + tryCount = 1; + ApiException exception = null; + do { + if (tryCount > maxTry) fail("have not got result of getPetByIdAsync after 10 seconds"); + Thread.sleep(1000); + tryCount += 1; + if (result.get("pet") != null) fail("expected an error"); + if (result.get("exception") != null) { + exception = (ApiException) result.get("exception"); + break; + } + } while (result.isEmpty()); + assertNotNull(exception); + assertEquals(404, exception.getCode()); + assertEquals("Not Found", exception.getMessage()); + assertEquals("application/json", exception.getResponseHeaders().get("Content-Type").get(0)); } - - /** - * uploads an image - * - * - * - * @throws ApiException - * if the Api call fails - */ + + /* @Test - public void uploadFileTest() throws ApiException { - Long petId = null; - String additionalMetadata = null; - File file = null; - // ModelApiResponse response = api.uploadFile(petId, additionalMetadata, file); + public void testGetPetByIdInObject() throws Exception { + Pet pet = new Pet(); + pet.setId(TestUtils.nextId()); + pet.setName("pet " + pet.getId()); - // TODO: test validations + Category category = new Category(); + category.setId(TestUtils.nextId()); + category.setName("category " + category.getId()); + pet.setCategory(category); + + pet.setStatus(Pet.StatusEnum.PENDING); + List photos = Arrays.asList(new String[]{"http://foo.bar.com/1"}); + pet.setPhotoUrls(photos); + + api.addPet(pet); + + InlineResponse200 fetched = api.getPetByIdInObject(pet.getId()); + assertEquals(pet.getId(), fetched.getId()); + assertEquals(pet.getName(), fetched.getName()); + + Object categoryObj = fetched.getCategory(); + assertNotNull(categoryObj); + assertTrue(categoryObj instanceof Map); + + Map categoryMap = (Map) categoryObj; + Object categoryIdObj = categoryMap.get("id"); + // NOTE: Gson parses integer value to double. + assertTrue(categoryIdObj instanceof Double); + Long categoryIdLong = ((Double) categoryIdObj).longValue(); + assertEquals(category.getId(), categoryIdLong); + assertEquals(category.getName(), categoryMap.get("name")); + } + */ + + @Test + public void testUpdatePet() throws Exception { + Pet pet = createRandomPet(); + pet.setName("programmer"); + + api.updatePet(pet); + + Pet fetched = api.getPetById(pet.getId()); + assertNotNull(fetched); + assertEquals(pet.getId(), fetched.getId()); + assertNotNull(fetched.getCategory()); + assertEquals(fetched.getCategory().getName(), pet.getCategory().getName()); + } + + @Test + public void testFindPetsByStatus() throws Exception { + Pet pet = createRandomPet(); + pet.setName("programmer"); + pet.setStatus(Pet.StatusEnum.PENDING); + + api.updatePet(pet); + + List pets = api.findPetsByStatus(Arrays.asList(new String[]{"pending"})); + assertNotNull(pets); + + boolean found = false; + for (Pet fetched : pets) { + if (fetched.getId().equals(pet.getId())) { + found = true; + break; + } + } + + assertTrue(found); + + api.deletePet(pet.getId(), null); + } + + @Test + public void testFindPetsByTags() throws Exception { + Pet pet = createRandomPet(); + pet.setName("monster"); + pet.setStatus(Pet.StatusEnum.AVAILABLE); + + List tags = new ArrayList(); + Tag tag1 = new Tag(); + tag1.setName("friendly"); + tags.add(tag1); + pet.setTags(tags); + + api.updatePet(pet); + + List pets = api.findPetsByTags(Arrays.asList(new String[]{"friendly"})); + assertNotNull(pets); + + boolean found = false; + for (Pet fetched : pets) { + if (fetched.getId().equals(pet.getId())) { + found = true; + break; + } + } + assertTrue(found); + + api.deletePet(pet.getId(), null); + } + + @Test + public void testUpdatePetWithForm() throws Exception { + Pet pet = createRandomPet(); + pet.setName("frank"); + api.addPet(pet); + + Pet fetched = api.getPetById(pet.getId()); + + api.updatePetWithForm(fetched.getId(), "furt", null); + Pet updated = api.getPetById(fetched.getId()); + + assertEquals(updated.getName(), "furt"); + } + + @Test + public void testDeletePet() throws Exception { + Pet pet = createRandomPet(); + api.addPet(pet); + + Pet fetched = api.getPetById(pet.getId()); + api.deletePet(fetched.getId(), null); + + try { + fetched = api.getPetById(fetched.getId()); + fail("expected an error"); + } catch (ApiException e) { + assertEquals(404, e.getCode()); + } + } + + @Test + public void testUploadFile() throws Exception { + Pet pet = createRandomPet(); + api.addPet(pet); + + File file = new File("hello.txt"); + BufferedWriter writer = new BufferedWriter(new FileWriter(file)); + writer.write("Hello world!"); + writer.close(); + + api.uploadFile(pet.getId(), "a test file", new File(file.getAbsolutePath())); + } + + @Test + public void testEqualsAndHashCode() { + Pet pet1 = new Pet(); + Pet pet2 = new Pet(); + assertTrue(pet1.equals(pet2)); + assertTrue(pet2.equals(pet1)); + assertTrue(pet1.hashCode() == pet2.hashCode()); + assertTrue(pet1.equals(pet1)); + assertTrue(pet1.hashCode() == pet1.hashCode()); + + pet2.setName("really-happy"); + pet2.setPhotoUrls(Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"})); + assertFalse(pet1.equals(pet2)); + assertFalse(pet2.equals(pet1)); + assertFalse(pet1.hashCode() == (pet2.hashCode())); + assertTrue(pet2.equals(pet2)); + assertTrue(pet2.hashCode() == pet2.hashCode()); + + pet1.setName("really-happy"); + pet1.setPhotoUrls(Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"})); + assertTrue(pet1.equals(pet2)); + assertTrue(pet2.equals(pet1)); + assertTrue(pet1.hashCode() == pet2.hashCode()); + assertTrue(pet1.equals(pet1)); + assertTrue(pet1.hashCode() == pet1.hashCode()); + } + + private Pet createRandomPet() { + Pet pet = new Pet(); + pet.setId(TestUtils.nextId()); + pet.setName("gorilla"); + + Category category = new Category(); + category.setName("really-happy"); + + pet.setCategory(category); + pet.setStatus(Pet.StatusEnum.AVAILABLE); + List photos = Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"}); + pet.setPhotoUrls(photos); + + return pet; + } + + private String serializeJson(Object o, ApiClient apiClient) { + return apiClient.getJSON().serialize(o); + } + + private T deserializeJson(String json, Type type, ApiClient apiClient) { + return (T) apiClient.getJSON().deserialize(json, type); } - } diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/api/StoreApiTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/api/StoreApiTest.java index 31abbbeae4e..491001cfce3 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/api/StoreApiTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/api/StoreApiTest.java @@ -1,83 +1,105 @@ package io.swagger.client.api; +import io.swagger.TestUtils; import io.swagger.client.ApiException; -import io.swagger.client.model.Order; -import org.junit.Test; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; +import io.swagger.client.auth.*; +import io.swagger.client.model.*; + +import java.lang.reflect.Field; import java.util.Map; +import java.text.SimpleDateFormat; + +import org.joda.time.DateTime; +import org.joda.time.DateTimeZone; +import org.junit.*; +import static org.junit.Assert.*; -/** - * API tests for StoreApi - */ public class StoreApiTest { + StoreApi api = null; - private final StoreApi api = new StoreApi(); - - - /** - * Delete purchase order by ID - * - * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors - * - * @throws ApiException - * if the Api call fails - */ - @Test - public void deleteOrderTest() throws ApiException { - String orderId = null; - // api.deleteOrder(orderId); - - // TODO: test validations + @Before + public void setup() { + api = new StoreApi(); + // setup authentication + ApiKeyAuth apiKeyAuth = (ApiKeyAuth) api.getApiClient().getAuthentication("api_key"); + apiKeyAuth.setApiKey("special-key"); + // set custom date format that is used by the petstore server + // Note: it would still work without this setting as okhttp-gson Java client supports + // various date formats by default (with lenientDatetimeFormat enabled), including + // the one used by petstore server + api.getApiClient().setDatetimeFormat(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ")); + api.getApiClient().setLenientDatetimeFormat(false); } - - /** - * Returns pet inventories by status - * - * Returns a map of status codes to quantities - * - * @throws ApiException - * if the Api call fails - */ - @Test - public void getInventoryTest() throws ApiException { - // Map response = api.getInventory(); - // TODO: test validations - } - - /** - * Find purchase order by ID - * - * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - * - * @throws ApiException - * if the Api call fails - */ @Test - public void getOrderByIdTest() throws ApiException { - Long orderId = null; - // Order response = api.getOrderById(orderId); - - // TODO: test validations + public void testGetInventory() throws Exception { + Map inventory = api.getInventory(); + assertTrue(inventory.keySet().size() > 0); } - - /** - * Place an order for a pet - * - * - * - * @throws ApiException - * if the Api call fails - */ + + /* @Test - public void placeOrderTest() throws ApiException { - Order body = null; - // Order response = api.placeOrder(body); + public void testGetInventoryInObject() throws Exception { + Object inventoryObj = api.getInventoryInObject(); + assertTrue(inventoryObj instanceof Map); - // TODO: test validations + Map inventoryMap = (Map) inventoryObj; + assertTrue(inventoryMap.keySet().size() > 0); + + Map.Entry firstEntry = (Map.Entry) inventoryMap.entrySet().iterator().next(); + assertTrue(firstEntry.getKey() instanceof String); + // NOTE: Gson parses integer value to double. + assertTrue(firstEntry.getValue() instanceof Double); + } + */ + + @Test + public void testPlaceOrder() throws Exception { + Order order = createOrder(); + api.placeOrder(order); + + Order fetched = api.getOrderById(order.getId()); + assertEquals(order.getId(), fetched.getId()); + assertEquals(order.getPetId(), fetched.getPetId()); + assertEquals(order.getQuantity(), fetched.getQuantity()); + assertEquals(order.getShipDate().withZone(DateTimeZone.UTC), fetched.getShipDate().withZone(DateTimeZone.UTC)); + } + + @Test + public void testDeleteOrder() throws Exception { + Order order = createOrder(); + api.placeOrder(order); + + Order fetched = api.getOrderById(order.getId()); + assertEquals(fetched.getId(), order.getId()); + + api.deleteOrder(String.valueOf(order.getId())); + + try { + api.getOrderById(order.getId()); + // fail("expected an error"); + } catch (ApiException e) { + // ok + } + } + + private Order createOrder() { + Order order = new Order(); + order.setPetId(new Long(200)); + order.setQuantity(new Integer(13)); + order.setShipDate(DateTime.now()); + order.setStatus(Order.StatusEnum.PLACED); + order.setComplete(true); + + try { + Field idField = Order.class.getDeclaredField("id"); + idField.setAccessible(true); + idField.set(order, TestUtils.nextId()); + } catch (Exception e) { + throw new RuntimeException(e); + } + + return order; } - } diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/api/UserApiTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/api/UserApiTest.java index 7e96762ff4e..b47a146d737 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/api/UserApiTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/api/UserApiTest.java @@ -1,149 +1,87 @@ package io.swagger.client.api; -import io.swagger.client.ApiException; -import io.swagger.client.model.User; -import org.junit.Test; +import io.swagger.TestUtils; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; +import io.swagger.client.auth.*; +import io.swagger.client.model.*; + +import java.util.Arrays; + +import org.junit.*; +import static org.junit.Assert.*; -/** - * API tests for UserApi - */ public class UserApiTest { + UserApi api = null; - private final UserApi api = new UserApi(); - - - /** - * Create user - * - * This can only be done by the logged in user. - * - * @throws ApiException - * if the Api call fails - */ - @Test - public void createUserTest() throws ApiException { - User body = null; - // api.createUser(body); - - // TODO: test validations + @Before + public void setup() { + api = new UserApi(); + // setup authentication + ApiKeyAuth apiKeyAuth = (ApiKeyAuth) api.getApiClient().getAuthentication("api_key"); + apiKeyAuth.setApiKey("special-key"); } - - /** - * Creates list of users with given input array - * - * - * - * @throws ApiException - * if the Api call fails - */ - @Test - public void createUsersWithArrayInputTest() throws ApiException { - List body = null; - // api.createUsersWithArrayInput(body); - // TODO: test validations - } - - /** - * Creates list of users with given input array - * - * - * - * @throws ApiException - * if the Api call fails - */ @Test - public void createUsersWithListInputTest() throws ApiException { - List body = null; - // api.createUsersWithListInput(body); + public void testCreateUser() throws Exception { + User user = createUser(); - // TODO: test validations + api.createUser(user); + + User fetched = api.getUserByName(user.getUsername()); + assertEquals(user.getId(), fetched.getId()); } - - /** - * Delete user - * - * This can only be done by the logged in user. - * - * @throws ApiException - * if the Api call fails - */ + @Test - public void deleteUserTest() throws ApiException { - String username = null; - // api.deleteUser(username); + public void testCreateUsersWithArray() throws Exception { + User user1 = createUser(); + user1.setUsername("user" + user1.getId()); + User user2 = createUser(); + user2.setUsername("user" + user2.getId()); - // TODO: test validations + api.createUsersWithArrayInput(Arrays.asList(new User[]{user1, user2})); + + User fetched = api.getUserByName(user1.getUsername()); + assertEquals(user1.getId(), fetched.getId()); } - - /** - * Get user by user name - * - * - * - * @throws ApiException - * if the Api call fails - */ + @Test - public void getUserByNameTest() throws ApiException { - String username = null; - // User response = api.getUserByName(username); + public void testCreateUsersWithList() throws Exception { + User user1 = createUser(); + user1.setUsername("user" + user1.getId()); + User user2 = createUser(); + user2.setUsername("user" + user2.getId()); - // TODO: test validations + api.createUsersWithListInput(Arrays.asList(new User[]{user1, user2})); + + User fetched = api.getUserByName(user1.getUsername()); + assertEquals(user1.getId(), fetched.getId()); } - - /** - * Logs user into the system - * - * - * - * @throws ApiException - * if the Api call fails - */ + @Test - public void loginUserTest() throws ApiException { - String username = null; - String password = null; - // String response = api.loginUser(username, password); + public void testLoginUser() throws Exception { + User user = createUser(); + api.createUser(user); - // TODO: test validations + String token = api.loginUser(user.getUsername(), user.getPassword()); + assertTrue(token.startsWith("logged in user session:")); } - - /** - * Logs out current logged in user session - * - * - * - * @throws ApiException - * if the Api call fails - */ + @Test - public void logoutUserTest() throws ApiException { - // api.logoutUser(); - - // TODO: test validations + public void logoutUser() throws Exception { + api.logoutUser(); } - - /** - * Updated user - * - * This can only be done by the logged in user. - * - * @throws ApiException - * if the Api call fails - */ - @Test - public void updateUserTest() throws ApiException { - String username = null; - User body = null; - // api.updateUser(username, body); - // TODO: test validations + private User createUser() { + User user = new User(); + user.setId(TestUtils.nextId()); + user.setUsername("fred" + user.getId()); + user.setFirstName("Fred"); + user.setLastName("Meyer"); + user.setEmail("fred@fredmeyer.com"); + user.setPassword("xxXXxx"); + user.setPhone("408-867-5309"); + user.setUserStatus(123); + + return user; } - } diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/petstore/test/PetApiTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/petstore/test/PetApiTest.java deleted file mode 100644 index e378356d0d4..00000000000 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/petstore/test/PetApiTest.java +++ /dev/null @@ -1,398 +0,0 @@ -package io.swagger.petstore.test; - -import com.google.gson.reflect.TypeToken; - -import io.swagger.TestUtils; - -import io.swagger.client.*; -import io.swagger.client.api.*; -import io.swagger.client.auth.*; -import io.swagger.client.model.*; - -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileWriter; -import java.lang.reflect.Type; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.junit.*; -import static org.junit.Assert.*; - -public class PetApiTest { - PetApi api = null; - - @Before - public void setup() { - api = new PetApi(); - // setup authentication - ApiKeyAuth apiKeyAuth = (ApiKeyAuth) api.getApiClient().getAuthentication("api_key"); - apiKeyAuth.setApiKey("special-key"); - } - - @Test - public void testApiClient() { - // the default api client is used - assertEquals(Configuration.getDefaultApiClient(), api.getApiClient()); - assertNotNull(api.getApiClient()); - assertEquals("http://petstore.swagger.io/v2", api.getApiClient().getBasePath()); - assertFalse(api.getApiClient().isDebugging()); - - ApiClient oldClient = api.getApiClient(); - - ApiClient newClient = new ApiClient(); - newClient.setBasePath("http://example.com"); - newClient.setDebugging(true); - - // set api client via constructor - api = new PetApi(newClient); - assertNotNull(api.getApiClient()); - assertEquals("http://example.com", api.getApiClient().getBasePath()); - assertTrue(api.getApiClient().isDebugging()); - - // set api client via setter method - api.setApiClient(oldClient); - assertNotNull(api.getApiClient()); - assertEquals("http://petstore.swagger.io/v2", api.getApiClient().getBasePath()); - assertFalse(api.getApiClient().isDebugging()); - } - - @Test - public void testCreateAndGetPet() throws Exception { - Pet pet = createRandomPet(); - api.addPet(pet); - - Pet fetched = api.getPetById(pet.getId()); - assertNotNull(fetched); - assertEquals(pet.getId(), fetched.getId()); - assertNotNull(fetched.getCategory()); - assertEquals(fetched.getCategory().getName(), pet.getCategory().getName()); - } - - /* - @Test - public void testCreateAndGetPetWithByteArray() throws Exception { - Pet pet = createRandomPet(); - byte[] bytes = serializeJson(pet, api.getApiClient()).getBytes(); - api.addPetUsingByteArray(bytes); - - byte[] fetchedBytes = api.petPetIdtestingByteArraytrueGet(pet.getId()); - Type type = new TypeToken(){}.getType(); - Pet fetched = deserializeJson(new String(fetchedBytes), type, api.getApiClient()); - assertNotNull(fetched); - assertEquals(pet.getId(), fetched.getId()); - assertNotNull(fetched.getCategory()); - assertEquals(fetched.getCategory().getName(), pet.getCategory().getName()); - } - */ - - @Test - public void testCreateAndGetPetWithHttpInfo() throws Exception { - Pet pet = createRandomPet(); - api.addPetWithHttpInfo(pet); - - ApiResponse resp = api.getPetByIdWithHttpInfo(pet.getId()); - assertEquals(200, resp.getStatusCode()); - assertEquals("application/json", resp.getHeaders().get("Content-Type").get(0)); - Pet fetched = resp.getData(); - assertNotNull(fetched); - assertEquals(pet.getId(), fetched.getId()); - assertNotNull(fetched.getCategory()); - assertEquals(fetched.getCategory().getName(), pet.getCategory().getName()); - } - - @Test - public void testCreateAndGetPetAsync() throws Exception { - Pet pet = createRandomPet(); - api.addPet(pet); - // to store returned Pet or error message/exception - final Map result = new HashMap(); - - api.getPetByIdAsync(pet.getId(), new ApiCallback() { - @Override - public void onFailure(ApiException e, int statusCode, Map> responseHeaders) { - result.put("error", e.getMessage()); - } - - @Override - public void onSuccess(Pet pet, int statusCode, Map> responseHeaders) { - result.put("pet", pet); - } - - @Override - public void onUploadProgress(long bytesWritten, long contentLength, boolean done) { - //empty - } - - @Override - public void onDownloadProgress(long bytesRead, long contentLength, boolean done) { - //empty - } - }); - // the API call should be executed asynchronously, so result should be empty at the moment - assertTrue(result.isEmpty()); - - // wait for the asynchronous call to finish (at most 10 seconds) - final int maxTry = 10; - int tryCount = 1; - Pet fetched = null; - do { - if (tryCount > maxTry) fail("have not got result of getPetByIdAsync after 10 seconds"); - Thread.sleep(1000); - tryCount += 1; - if (result.get("error") != null) fail((String) result.get("error")); - if (result.get("pet") != null) { - fetched = (Pet) result.get("pet"); - break; - } - } while (result.isEmpty()); - assertNotNull(fetched); - assertEquals(pet.getId(), fetched.getId()); - assertNotNull(fetched.getCategory()); - assertEquals(fetched.getCategory().getName(), pet.getCategory().getName()); - - // test getting a nonexistent pet - result.clear(); - api.getPetByIdAsync(new Long(-10000), new ApiCallback() { - @Override - public void onFailure(ApiException e, int statusCode, Map> responseHeaders) { - result.put("exception", e); - } - - @Override - public void onSuccess(Pet pet, int statusCode, Map> responseHeaders) { - result.put("pet", pet); - } - - @Override - public void onUploadProgress(long bytesWritten, long contentLength, boolean done) { - //empty - } - - @Override - public void onDownloadProgress(long bytesRead, long contentLength, boolean done) { - //empty - } - }); - // the API call should be executed asynchronously, so result should be empty at the moment - assertTrue(result.isEmpty()); - - // wait for the asynchronous call to finish (at most 10 seconds) - tryCount = 1; - ApiException exception = null; - do { - if (tryCount > maxTry) fail("have not got result of getPetByIdAsync after 10 seconds"); - Thread.sleep(1000); - tryCount += 1; - if (result.get("pet") != null) fail("expected an error"); - if (result.get("exception") != null) { - exception = (ApiException) result.get("exception"); - break; - } - } while (result.isEmpty()); - assertNotNull(exception); - assertEquals(404, exception.getCode()); - assertEquals("Not Found", exception.getMessage()); - assertEquals("application/json", exception.getResponseHeaders().get("Content-Type").get(0)); - } - - /* - @Test - public void testGetPetByIdInObject() throws Exception { - Pet pet = new Pet(); - pet.setId(TestUtils.nextId()); - pet.setName("pet " + pet.getId()); - - Category category = new Category(); - category.setId(TestUtils.nextId()); - category.setName("category " + category.getId()); - pet.setCategory(category); - - pet.setStatus(Pet.StatusEnum.PENDING); - List photos = Arrays.asList(new String[]{"http://foo.bar.com/1"}); - pet.setPhotoUrls(photos); - - api.addPet(pet); - - InlineResponse200 fetched = api.getPetByIdInObject(pet.getId()); - assertEquals(pet.getId(), fetched.getId()); - assertEquals(pet.getName(), fetched.getName()); - - Object categoryObj = fetched.getCategory(); - assertNotNull(categoryObj); - assertTrue(categoryObj instanceof Map); - - Map categoryMap = (Map) categoryObj; - Object categoryIdObj = categoryMap.get("id"); - // NOTE: Gson parses integer value to double. - assertTrue(categoryIdObj instanceof Double); - Long categoryIdLong = ((Double) categoryIdObj).longValue(); - assertEquals(category.getId(), categoryIdLong); - assertEquals(category.getName(), categoryMap.get("name")); - } - */ - - @Test - public void testUpdatePet() throws Exception { - Pet pet = createRandomPet(); - pet.setName("programmer"); - - api.updatePet(pet); - - Pet fetched = api.getPetById(pet.getId()); - assertNotNull(fetched); - assertEquals(pet.getId(), fetched.getId()); - assertNotNull(fetched.getCategory()); - assertEquals(fetched.getCategory().getName(), pet.getCategory().getName()); - } - - @Test - public void testFindPetsByStatus() throws Exception { - Pet pet = createRandomPet(); - pet.setName("programmer"); - pet.setStatus(Pet.StatusEnum.PENDING); - - api.updatePet(pet); - - List pets = api.findPetsByStatus(Arrays.asList(new String[]{"pending"})); - assertNotNull(pets); - - boolean found = false; - for (Pet fetched : pets) { - if (fetched.getId().equals(pet.getId())) { - found = true; - break; - } - } - - assertTrue(found); - - api.deletePet(pet.getId(), null); - } - - @Test - public void testFindPetsByTags() throws Exception { - Pet pet = createRandomPet(); - pet.setName("monster"); - pet.setStatus(Pet.StatusEnum.AVAILABLE); - - List tags = new ArrayList(); - Tag tag1 = new Tag(); - tag1.setName("friendly"); - tags.add(tag1); - pet.setTags(tags); - - api.updatePet(pet); - - List pets = api.findPetsByTags(Arrays.asList(new String[]{"friendly"})); - assertNotNull(pets); - - boolean found = false; - for (Pet fetched : pets) { - if (fetched.getId().equals(pet.getId())) { - found = true; - break; - } - } - assertTrue(found); - - api.deletePet(pet.getId(), null); - } - - @Test - public void testUpdatePetWithForm() throws Exception { - Pet pet = createRandomPet(); - pet.setName("frank"); - api.addPet(pet); - - Pet fetched = api.getPetById(pet.getId()); - - api.updatePetWithForm(fetched.getId(), "furt", null); - Pet updated = api.getPetById(fetched.getId()); - - assertEquals(updated.getName(), "furt"); - } - - @Test - public void testDeletePet() throws Exception { - Pet pet = createRandomPet(); - api.addPet(pet); - - Pet fetched = api.getPetById(pet.getId()); - api.deletePet(fetched.getId(), null); - - try { - fetched = api.getPetById(fetched.getId()); - fail("expected an error"); - } catch (ApiException e) { - assertEquals(404, e.getCode()); - } - } - - @Test - public void testUploadFile() throws Exception { - Pet pet = createRandomPet(); - api.addPet(pet); - - File file = new File("hello.txt"); - BufferedWriter writer = new BufferedWriter(new FileWriter(file)); - writer.write("Hello world!"); - writer.close(); - - api.uploadFile(pet.getId(), "a test file", new File(file.getAbsolutePath())); - } - - @Test - public void testEqualsAndHashCode() { - Pet pet1 = new Pet(); - Pet pet2 = new Pet(); - assertTrue(pet1.equals(pet2)); - assertTrue(pet2.equals(pet1)); - assertTrue(pet1.hashCode() == pet2.hashCode()); - assertTrue(pet1.equals(pet1)); - assertTrue(pet1.hashCode() == pet1.hashCode()); - - pet2.setName("really-happy"); - pet2.setPhotoUrls(Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"})); - assertFalse(pet1.equals(pet2)); - assertFalse(pet2.equals(pet1)); - assertFalse(pet1.hashCode() == (pet2.hashCode())); - assertTrue(pet2.equals(pet2)); - assertTrue(pet2.hashCode() == pet2.hashCode()); - - pet1.setName("really-happy"); - pet1.setPhotoUrls(Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"})); - assertTrue(pet1.equals(pet2)); - assertTrue(pet2.equals(pet1)); - assertTrue(pet1.hashCode() == pet2.hashCode()); - assertTrue(pet1.equals(pet1)); - assertTrue(pet1.hashCode() == pet1.hashCode()); - } - - private Pet createRandomPet() { - Pet pet = new Pet(); - pet.setId(TestUtils.nextId()); - pet.setName("gorilla"); - - Category category = new Category(); - category.setName("really-happy"); - - pet.setCategory(category); - pet.setStatus(Pet.StatusEnum.AVAILABLE); - List photos = Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"}); - pet.setPhotoUrls(photos); - - return pet; - } - - private String serializeJson(Object o, ApiClient apiClient) { - return apiClient.getJSON().serialize(o); - } - - private T deserializeJson(String json, Type type, ApiClient apiClient) { - return (T) apiClient.getJSON().deserialize(json, type); - } -} diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/petstore/test/StoreApiTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/petstore/test/StoreApiTest.java deleted file mode 100644 index 0d1910dc1e7..00000000000 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/petstore/test/StoreApiTest.java +++ /dev/null @@ -1,104 +0,0 @@ -package io.swagger.petstore.test; - -import io.swagger.TestUtils; -import io.swagger.client.ApiException; - -import io.swagger.client.*; -import io.swagger.client.api.*; -import io.swagger.client.auth.*; -import io.swagger.client.model.*; - -import java.lang.reflect.Field; -import java.util.Map; -import java.text.SimpleDateFormat; - -import org.junit.*; -import static org.junit.Assert.*; - -public class StoreApiTest { - StoreApi api = null; - - @Before - public void setup() { - api = new StoreApi(); - // setup authentication - ApiKeyAuth apiKeyAuth = (ApiKeyAuth) api.getApiClient().getAuthentication("api_key"); - apiKeyAuth.setApiKey("special-key"); - // set custom date format that is used by the petstore server - // Note: it would still work without this setting as okhttp-gson Java client supports - // various date formats by default (with lenientDatetimeFormat enabled), including - // the one used by petstore server - api.getApiClient().setDatetimeFormat(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ")); - api.getApiClient().setLenientDatetimeFormat(false); - } - - @Test - public void testGetInventory() throws Exception { - Map inventory = api.getInventory(); - assertTrue(inventory.keySet().size() > 0); - } - - /* - @Test - public void testGetInventoryInObject() throws Exception { - Object inventoryObj = api.getInventoryInObject(); - assertTrue(inventoryObj instanceof Map); - - Map inventoryMap = (Map) inventoryObj; - assertTrue(inventoryMap.keySet().size() > 0); - - Map.Entry firstEntry = (Map.Entry) inventoryMap.entrySet().iterator().next(); - assertTrue(firstEntry.getKey() instanceof String); - // NOTE: Gson parses integer value to double. - assertTrue(firstEntry.getValue() instanceof Double); - } - */ - - @Test - public void testPlaceOrder() throws Exception { - Order order = createOrder(); - api.placeOrder(order); - - Order fetched = api.getOrderById(order.getId()); - assertEquals(order.getId(), fetched.getId()); - assertEquals(order.getPetId(), fetched.getPetId()); - assertEquals(order.getQuantity(), fetched.getQuantity()); - } - - @Test - public void testDeleteOrder() throws Exception { - Order order = createOrder(); - api.placeOrder(order); - - Order fetched = api.getOrderById(order.getId()); - assertEquals(fetched.getId(), order.getId()); - - api.deleteOrder(String.valueOf(order.getId())); - - try { - api.getOrderById(order.getId()); - // fail("expected an error"); - } catch (ApiException e) { - // ok - } - } - - private Order createOrder() { - Order order = new Order(); - order.setPetId(new Long(200)); - order.setQuantity(new Integer(13)); - order.setShipDate(new java.util.Date()); - order.setStatus(Order.StatusEnum.PLACED); - order.setComplete(true); - - try { - Field idField = Order.class.getDeclaredField("id"); - idField.setAccessible(true); - idField.set(order, TestUtils.nextId()); - } catch (Exception e) { - throw new RuntimeException(e); - } - - return order; - } -} diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/petstore/test/UserApiTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/petstore/test/UserApiTest.java deleted file mode 100644 index 195e5c1e861..00000000000 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/petstore/test/UserApiTest.java +++ /dev/null @@ -1,88 +0,0 @@ -package io.swagger.petstore.test; - -import io.swagger.TestUtils; - -import io.swagger.client.api.*; -import io.swagger.client.auth.*; -import io.swagger.client.model.*; - -import java.util.Arrays; - -import org.junit.*; -import static org.junit.Assert.*; - -public class UserApiTest { - UserApi api = null; - - @Before - public void setup() { - api = new UserApi(); - // setup authentication - ApiKeyAuth apiKeyAuth = (ApiKeyAuth) api.getApiClient().getAuthentication("api_key"); - apiKeyAuth.setApiKey("special-key"); - } - - @Test - public void testCreateUser() throws Exception { - User user = createUser(); - - api.createUser(user); - - User fetched = api.getUserByName(user.getUsername()); - assertEquals(user.getId(), fetched.getId()); - } - - @Test - public void testCreateUsersWithArray() throws Exception { - User user1 = createUser(); - user1.setUsername("user" + user1.getId()); - User user2 = createUser(); - user2.setUsername("user" + user2.getId()); - - api.createUsersWithArrayInput(Arrays.asList(new User[]{user1, user2})); - - User fetched = api.getUserByName(user1.getUsername()); - assertEquals(user1.getId(), fetched.getId()); - } - - @Test - public void testCreateUsersWithList() throws Exception { - User user1 = createUser(); - user1.setUsername("user" + user1.getId()); - User user2 = createUser(); - user2.setUsername("user" + user2.getId()); - - api.createUsersWithListInput(Arrays.asList(new User[]{user1, user2})); - - User fetched = api.getUserByName(user1.getUsername()); - assertEquals(user1.getId(), fetched.getId()); - } - - @Test - public void testLoginUser() throws Exception { - User user = createUser(); - api.createUser(user); - - String token = api.loginUser(user.getUsername(), user.getPassword()); - assertTrue(token.startsWith("logged in user session:")); - } - - @Test - public void logoutUser() throws Exception { - api.logoutUser(); - } - - private User createUser() { - User user = new User(); - user.setId(TestUtils.nextId()); - user.setUsername("fred" + user.getId()); - user.setFirstName("Fred"); - user.setLastName("Meyer"); - user.setEmail("fred@fredmeyer.com"); - user.setPassword("xxXXxx"); - user.setPhone("408-867-5309"); - user.setUserStatus(123); - - return user; - } -} diff --git a/samples/client/petstore/java/retrofit/.swagger-codegen-ignore b/samples/client/petstore/java/retrofit/.swagger-codegen-ignore new file mode 100644 index 00000000000..19d3377182e --- /dev/null +++ b/samples/client/petstore/java/retrofit/.swagger-codegen-ignore @@ -0,0 +1,23 @@ +# Swagger Codegen Ignore +# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell Swagger Codgen to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# Thsi matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/client/petstore/java/retrofit/LICENSE b/samples/client/petstore/java/retrofit/LICENSE new file mode 100644 index 00000000000..8dada3edaf5 --- /dev/null +++ b/samples/client/petstore/java/retrofit/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/samples/client/petstore/java/retrofit/build.gradle b/samples/client/petstore/java/retrofit/build.gradle index 079d1240a39..401b362d172 100644 --- a/samples/client/petstore/java/retrofit/build.gradle +++ b/samples/client/petstore/java/retrofit/build.gradle @@ -99,6 +99,7 @@ ext { retrofit_version = "1.9.0" swagger_annotations_version = "1.5.8" junit_version = "4.12" + jodatime_version = "2.9.3" } dependencies { @@ -106,5 +107,6 @@ dependencies { compile "com.squareup.retrofit:retrofit:$retrofit_version" compile "io.swagger:swagger-annotations:$swagger_annotations_version" compile "org.apache.oltu.oauth2:org.apache.oltu.oauth2.client:$oltu_version" + compile "joda-time:joda-time:$jodatime_version" testCompile "junit:junit:$junit_version" } diff --git a/samples/client/petstore/java/retrofit/build.sbt b/samples/client/petstore/java/retrofit/build.sbt new file mode 100644 index 00000000000..629c85c2bf3 --- /dev/null +++ b/samples/client/petstore/java/retrofit/build.sbt @@ -0,0 +1,20 @@ +lazy val root = (project in file(".")). + settings( + organization := "io.swagger", + name := "swagger-petstore-retrofit", + version := "1.0.0", + scalaVersion := "2.11.4", + scalacOptions ++= Seq("-feature"), + javacOptions in compile ++= Seq("-Xlint:deprecation"), + publishArtifact in (Compile, packageDoc) := false, + resolvers += Resolver.mavenLocal, + libraryDependencies ++= Seq( + "com.squareup.okhttp" % "okhttp" % "2.7.5" % "compile", + "com.squareup.retrofit" % "retrofit" % "1.9.0" % "compile", + "io.swagger" % "swagger-annotations" % "1.5.8" % "compile", + "org.apache.oltu.oauth2" % "org.apache.oltu.oauth2.client" % "1.0.1" % "compile", + "joda-time" % "joda-time" % "2.9.3" % "compile", + "junit" % "junit" % "4.12" % "test", + "com.novocode" % "junit-interface" % "0.10" % "test" + ) + ) diff --git a/samples/client/petstore/java/retrofit/gradle/wrapper/gradle-wrapper.properties b/samples/client/petstore/java/retrofit/gradle/wrapper/gradle-wrapper.properties index 0c81b118d92..b7a36473955 100644 --- a/samples/client/petstore/java/retrofit/gradle/wrapper/gradle-wrapper.properties +++ b/samples/client/petstore/java/retrofit/gradle/wrapper/gradle-wrapper.properties @@ -1,4 +1,4 @@ -#Tue May 17 23:04:28 CST 2016 +#Tue May 17 23:08:05 CST 2016 distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME diff --git a/samples/client/petstore/java/retrofit/gradlew b/samples/client/petstore/java/retrofit/gradlew old mode 100755 new mode 100644 diff --git a/samples/client/petstore/java/retrofit/hello.txt b/samples/client/petstore/java/retrofit/hello.txt deleted file mode 100644 index 6769dd60bdf..00000000000 --- a/samples/client/petstore/java/retrofit/hello.txt +++ /dev/null @@ -1 +0,0 @@ -Hello world! \ No newline at end of file diff --git a/samples/client/petstore/java/retrofit/pom.xml b/samples/client/petstore/java/retrofit/pom.xml index 2fe5ddc8efc..ee6ce62988f 100644 --- a/samples/client/petstore/java/retrofit/pom.xml +++ b/samples/client/petstore/java/retrofit/pom.xml @@ -127,6 +127,11 @@ okhttp ${okhttp-version} + + joda-time + joda-time + ${jodatime-version} + @@ -140,6 +145,7 @@ 1.5.8 1.9.0 2.7.5 + 2.9.3 1.0.1 1.0.0 4.12 diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/ApiClient.java index 6540997c319..fe5ad9b37fe 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/ApiClient.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/ApiClient.java @@ -9,6 +9,10 @@ import java.util.Map; import org.apache.oltu.oauth2.client.request.OAuthClientRequest.AuthenticationRequestBuilder; import org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuilder; +import org.joda.time.DateTime; +import org.joda.time.LocalDate; +import org.joda.time.format.DateTimeFormatter; +import org.joda.time.format.ISODateTimeFormat; import retrofit.RestAdapter; import retrofit.client.OkClient; @@ -22,6 +26,9 @@ import retrofit.mime.TypedOutput; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; import com.squareup.okhttp.Interceptor; import com.squareup.okhttp.OkHttpClient; @@ -107,6 +114,8 @@ public class ApiClient { public void createDefaultAdapter() { Gson gson = new GsonBuilder() .setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ") + .registerTypeAdapter(DateTime.class, new DateTimeTypeAdapter()) + .registerTypeAdapter(LocalDate.class, new LocalDateTypeAdapter()) .create(); okClient = new OkHttpClient(); @@ -338,3 +347,61 @@ class GsonConverterWrapper implements Converter { } } + +/** + * Gson TypeAdapter for Joda DateTime type + */ +class DateTimeTypeAdapter extends TypeAdapter { + + private final DateTimeFormatter formatter = ISODateTimeFormat.dateTime(); + + @Override + public void write(JsonWriter out, DateTime date) throws IOException { + if (date == null) { + out.nullValue(); + } else { + out.value(formatter.print(date)); + } + } + + @Override + public DateTime read(JsonReader in) throws IOException { + switch (in.peek()) { + case NULL: + in.nextNull(); + return null; + default: + String date = in.nextString(); + return formatter.parseDateTime(date); + } + } +} + +/** + * Gson TypeAdapter for Joda DateTime type + */ +class LocalDateTypeAdapter extends TypeAdapter { + + private final DateTimeFormatter formatter = ISODateTimeFormat.date(); + + @Override + public void write(JsonWriter out, LocalDate date) throws IOException { + if (date == null) { + out.nullValue(); + } else { + out.value(formatter.print(date)); + } + } + + @Override + public LocalDate read(JsonReader in) throws IOException { + switch (in.peek()) { + case NULL: + in.nextNull(); + return null; + default: + String date = in.nextString(); + return formatter.parseLocalDate(date); + } + } +} \ No newline at end of file diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/StringUtil.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/StringUtil.java index fb5b299a706..03c6c81e434 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/StringUtil.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/StringUtil.java @@ -1,6 +1,31 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-28T16:10:49.444+08:00") + public class StringUtil { /** * Check if the given array contains the given value (with case-insensitive comparison). diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/FakeApi.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/FakeApi.java index 89fb9ddba73..02b97c10bf8 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,8 +6,9 @@ import retrofit.Callback; import retrofit.http.*; import retrofit.mime.*; +import org.joda.time.LocalDate; import java.math.BigDecimal; -import java.util.Date; +import org.joda.time.DateTime; import java.util.ArrayList; import java.util.HashMap; @@ -16,9 +17,9 @@ import java.util.Map; public interface FakeApi { /** - * Fake endpoint for testing various parameters + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 * Sync method - * Fake endpoint for testing various parameters + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 * @param number None (required) * @param _double None (required) * @param string None (required) @@ -37,11 +38,11 @@ public interface FakeApi { @FormUrlEncoded @POST("/fake") Void testEndpointParameters( - @Field("number") BigDecimal number, @Field("double") Double _double, @Field("string") String string, @Field("byte") byte[] _byte, @Field("integer") Integer integer, @Field("int32") Integer int32, @Field("int64") Long int64, @Field("float") Float _float, @Field("binary") byte[] binary, @Field("date") 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") LocalDate date, @Field("dateTime") DateTime dateTime, @Field("password") String password ); /** - * Fake endpoint for testing various parameters + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 * Async method * @param number None (required) * @param _double None (required) @@ -62,6 +63,6 @@ public interface FakeApi { @FormUrlEncoded @POST("/fake") void testEndpointParameters( - @Field("number") BigDecimal number, @Field("double") Double _double, @Field("string") String string, @Field("byte") byte[] _byte, @Field("integer") Integer integer, @Field("int32") Integer int32, @Field("int64") Long int64, @Field("float") Float _float, @Field("binary") byte[] binary, @Field("date") 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") LocalDate date, @Field("dateTime") DateTime dateTime, @Field("password") String password, Callback cb ); } diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/PetApi.java index 66ed6aea981..a019a4bf886 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/PetApi.java @@ -7,8 +7,8 @@ import retrofit.http.*; import retrofit.mime.*; import io.swagger.client.model.Pet; -import java.io.File; import io.swagger.client.model.ModelApiResponse; +import java.io.File; import java.util.ArrayList; import java.util.HashMap; diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/auth/OAuthFlow.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/auth/OAuthFlow.java index 597ec99b48b..ec1f942b0f2 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/auth/OAuthFlow.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/auth/OAuthFlow.java @@ -1,5 +1,30 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.auth; public enum OAuthFlow { accessCode, implicit, password, application -} \ No newline at end of file +} diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java new file mode 100644 index 00000000000..839b04aa6c5 --- /dev/null +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java @@ -0,0 +1,84 @@ +package io.swagger.client.model; + +import java.util.Objects; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import com.google.gson.annotations.SerializedName; + + + + + +public class AdditionalPropertiesClass { + + @SerializedName("map_property") + private Map mapProperty = new HashMap(); + + @SerializedName("map_of_map_property") + private Map> mapOfMapProperty = new HashMap>(); + + /** + **/ + @ApiModelProperty(value = "") + public Map getMapProperty() { + return mapProperty; + } + public void setMapProperty(Map mapProperty) { + this.mapProperty = mapProperty; + } + + /** + **/ + @ApiModelProperty(value = "") + public Map> getMapOfMapProperty() { + return mapOfMapProperty; + } + public void setMapOfMapProperty(Map> mapOfMapProperty) { + this.mapOfMapProperty = mapOfMapProperty; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + AdditionalPropertiesClass additionalPropertiesClass = (AdditionalPropertiesClass) o; + return Objects.equals(mapProperty, additionalPropertiesClass.mapProperty) && + Objects.equals(mapOfMapProperty, additionalPropertiesClass.mapOfMapProperty); + } + + @Override + public int hashCode() { + return Objects.hash(mapProperty, mapOfMapProperty); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class AdditionalPropertiesClass {\n"); + + sb.append(" mapProperty: ").append(toIndentedString(mapProperty)).append("\n"); + sb.append(" mapOfMapProperty: ").append(toIndentedString(mapOfMapProperty)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Animal.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Animal.java index 8df24899fb0..9a14a1289fe 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Animal.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Animal.java @@ -15,6 +15,9 @@ public class Animal { @SerializedName("className") private String className = null; + @SerializedName("color") + private String color = "red"; + /** **/ @ApiModelProperty(required = true, value = "") @@ -25,6 +28,16 @@ public class Animal { this.className = className; } + /** + **/ + @ApiModelProperty(value = "") + public String getColor() { + return color; + } + public void setColor(String color) { + this.color = color; + } + @Override public boolean equals(Object o) { @@ -35,12 +48,13 @@ public class Animal { return false; } Animal animal = (Animal) o; - return Objects.equals(className, animal.className); + return Objects.equals(className, animal.className) && + Objects.equals(color, animal.color); } @Override public int hashCode() { - return Objects.hash(className); + return Objects.hash(className, color); } @Override @@ -49,6 +63,7 @@ public class Animal { sb.append("class Animal {\n"); sb.append(" className: ").append(toIndentedString(className)).append("\n"); + sb.append(" color: ").append(toIndentedString(color)).append("\n"); sb.append("}"); return sb.toString(); } diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ArrayTest.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ArrayTest.java new file mode 100644 index 00000000000..92337cc0246 --- /dev/null +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ArrayTest.java @@ -0,0 +1,98 @@ +package io.swagger.client.model; + +import java.util.Objects; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.util.ArrayList; +import java.util.List; + +import com.google.gson.annotations.SerializedName; + + + + + +public class ArrayTest { + + @SerializedName("array_of_string") + private List arrayOfString = new ArrayList(); + + @SerializedName("array_array_of_integer") + private List> arrayArrayOfInteger = new ArrayList>(); + + @SerializedName("array_array_of_model") + private List> arrayArrayOfModel = new ArrayList>(); + + /** + **/ + @ApiModelProperty(value = "") + public List getArrayOfString() { + return arrayOfString; + } + public void setArrayOfString(List arrayOfString) { + this.arrayOfString = arrayOfString; + } + + /** + **/ + @ApiModelProperty(value = "") + public List> getArrayArrayOfInteger() { + return arrayArrayOfInteger; + } + public void setArrayArrayOfInteger(List> arrayArrayOfInteger) { + this.arrayArrayOfInteger = arrayArrayOfInteger; + } + + /** + **/ + @ApiModelProperty(value = "") + public List> getArrayArrayOfModel() { + return arrayArrayOfModel; + } + public void setArrayArrayOfModel(List> arrayArrayOfModel) { + this.arrayArrayOfModel = arrayArrayOfModel; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ArrayTest arrayTest = (ArrayTest) o; + return Objects.equals(arrayOfString, arrayTest.arrayOfString) && + Objects.equals(arrayArrayOfInteger, arrayTest.arrayArrayOfInteger) && + Objects.equals(arrayArrayOfModel, arrayTest.arrayArrayOfModel); + } + + @Override + public int hashCode() { + return Objects.hash(arrayOfString, arrayArrayOfInteger, arrayArrayOfModel); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ArrayTest {\n"); + + sb.append(" arrayOfString: ").append(toIndentedString(arrayOfString)).append("\n"); + sb.append(" arrayArrayOfInteger: ").append(toIndentedString(arrayArrayOfInteger)).append("\n"); + sb.append(" arrayArrayOfModel: ").append(toIndentedString(arrayArrayOfModel)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Cat.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Cat.java index 60a99ed86da..287d6a4d94c 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Cat.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Cat.java @@ -16,6 +16,9 @@ public class Cat extends Animal { @SerializedName("className") private String className = null; + @SerializedName("color") + private String color = "red"; + @SerializedName("declawed") private Boolean declawed = null; @@ -29,6 +32,16 @@ public class Cat extends Animal { this.className = className; } + /** + **/ + @ApiModelProperty(value = "") + public String getColor() { + return color; + } + public void setColor(String color) { + this.color = color; + } + /** **/ @ApiModelProperty(value = "") @@ -50,12 +63,13 @@ public class Cat extends Animal { } Cat cat = (Cat) o; return Objects.equals(className, cat.className) && + Objects.equals(color, cat.color) && Objects.equals(declawed, cat.declawed); } @Override public int hashCode() { - return Objects.hash(className, declawed); + return Objects.hash(className, color, declawed); } @Override @@ -64,6 +78,7 @@ public class Cat extends Animal { sb.append("class Cat {\n"); sb.append(" ").append(toIndentedString(super.toString())).append("\n"); sb.append(" className: ").append(toIndentedString(className)).append("\n"); + sb.append(" color: ").append(toIndentedString(color)).append("\n"); sb.append(" declawed: ").append(toIndentedString(declawed)).append("\n"); sb.append("}"); return sb.toString(); diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Dog.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Dog.java index 1c31fc93746..5d2ead15f07 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Dog.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Dog.java @@ -16,6 +16,9 @@ public class Dog extends Animal { @SerializedName("className") private String className = null; + @SerializedName("color") + private String color = "red"; + @SerializedName("breed") private String breed = null; @@ -29,6 +32,16 @@ public class Dog extends Animal { this.className = className; } + /** + **/ + @ApiModelProperty(value = "") + public String getColor() { + return color; + } + public void setColor(String color) { + this.color = color; + } + /** **/ @ApiModelProperty(value = "") @@ -50,12 +63,13 @@ public class Dog extends Animal { } Dog dog = (Dog) o; return Objects.equals(className, dog.className) && + Objects.equals(color, dog.color) && Objects.equals(breed, dog.breed); } @Override public int hashCode() { - return Objects.hash(className, breed); + return Objects.hash(className, color, breed); } @Override @@ -64,6 +78,7 @@ public class Dog extends Animal { sb.append("class Dog {\n"); sb.append(" ").append(toIndentedString(super.toString())).append("\n"); sb.append(" className: ").append(toIndentedString(className)).append("\n"); + sb.append(" color: ").append(toIndentedString(color)).append("\n"); sb.append(" breed: ").append(toIndentedString(breed)).append("\n"); sb.append("}"); return sb.toString(); diff --git a/samples/client/petstore/java/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 694335531fd..6063cf33f77 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 @@ -4,7 +4,8 @@ import java.util.Objects; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.math.BigDecimal; -import java.util.Date; +import org.joda.time.DateTime; +import org.joda.time.LocalDate; import com.google.gson.annotations.SerializedName; @@ -42,10 +43,10 @@ public class FormatTest { private byte[] binary = null; @SerializedName("date") - private Date date = null; + private LocalDate date = null; @SerializedName("dateTime") - private Date dateTime = null; + private DateTime dateTime = null; @SerializedName("uuid") private String uuid = null; @@ -156,20 +157,20 @@ public class FormatTest { /** **/ @ApiModelProperty(required = true, value = "") - public Date getDate() { + public LocalDate getDate() { return date; } - public void setDate(Date date) { + public void setDate(LocalDate date) { this.date = date; } /** **/ @ApiModelProperty(value = "") - public Date getDateTime() { + public DateTime getDateTime() { return dateTime; } - public void setDateTime(Date dateTime) { + public void setDateTime(DateTime dateTime) { this.dateTime = dateTime; } diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java new file mode 100644 index 00000000000..cf7f73c705f --- /dev/null +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -0,0 +1,101 @@ +package io.swagger.client.model; + +import java.util.Objects; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.client.model.Animal; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.joda.time.DateTime; + +import com.google.gson.annotations.SerializedName; + + + + + +public class MixedPropertiesAndAdditionalPropertiesClass { + + @SerializedName("uuid") + private String uuid = null; + + @SerializedName("dateTime") + private DateTime dateTime = null; + + @SerializedName("map") + private Map map = new HashMap(); + + /** + **/ + @ApiModelProperty(value = "") + public String getUuid() { + return uuid; + } + public void setUuid(String uuid) { + this.uuid = uuid; + } + + /** + **/ + @ApiModelProperty(value = "") + public DateTime getDateTime() { + return dateTime; + } + public void setDateTime(DateTime dateTime) { + this.dateTime = dateTime; + } + + /** + **/ + @ApiModelProperty(value = "") + public Map getMap() { + return map; + } + public void setMap(Map map) { + this.map = map; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + MixedPropertiesAndAdditionalPropertiesClass mixedPropertiesAndAdditionalPropertiesClass = (MixedPropertiesAndAdditionalPropertiesClass) o; + return Objects.equals(uuid, mixedPropertiesAndAdditionalPropertiesClass.uuid) && + Objects.equals(dateTime, mixedPropertiesAndAdditionalPropertiesClass.dateTime) && + Objects.equals(map, mixedPropertiesAndAdditionalPropertiesClass.map); + } + + @Override + public int hashCode() { + return Objects.hash(uuid, dateTime, map); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class MixedPropertiesAndAdditionalPropertiesClass {\n"); + + sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); + sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); + sb.append(" map: ").append(toIndentedString(map)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Name.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Name.java index b24b87366a4..5aa60a1f6f1 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Name.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Name.java @@ -24,6 +24,9 @@ public class Name { @SerializedName("property") private String property = null; + @SerializedName("123Number") + private Integer _123Number = null; + /** **/ @ApiModelProperty(required = true, value = "") @@ -51,6 +54,13 @@ public class Name { this.property = property; } + /** + **/ + @ApiModelProperty(value = "") + public Integer get123Number() { + return _123Number; + } + @Override public boolean equals(Object o) { @@ -63,12 +73,13 @@ public class Name { Name name = (Name) o; return Objects.equals(name, name.name) && Objects.equals(snakeCase, name.snakeCase) && - Objects.equals(property, name.property); + Objects.equals(property, name.property) && + Objects.equals(_123Number, name._123Number); } @Override public int hashCode() { - return Objects.hash(name, snakeCase, property); + return Objects.hash(name, snakeCase, property, _123Number); } @Override @@ -79,6 +90,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(" _123Number: ").append(toIndentedString(_123Number)).append("\n"); sb.append("}"); return sb.toString(); } diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Order.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Order.java index 2f774c13834..569d1c0fe46 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Order.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Order.java @@ -3,7 +3,7 @@ package io.swagger.client.model; import java.util.Objects; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; -import java.util.Date; +import org.joda.time.DateTime; import com.google.gson.annotations.SerializedName; @@ -23,7 +23,7 @@ public class Order { private Integer quantity = null; @SerializedName("shipDate") - private Date shipDate = null; + private DateTime shipDate = null; /** @@ -90,10 +90,10 @@ public class Order { /** **/ @ApiModelProperty(value = "") - public Date getShipDate() { + public DateTime getShipDate() { return shipDate; } - public void setShipDate(Date shipDate) { + public void setShipDate(DateTime shipDate) { this.shipDate = shipDate; } diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ReadOnlyFirst.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ReadOnlyFirst.java new file mode 100644 index 00000000000..32e4f515bce --- /dev/null +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ReadOnlyFirst.java @@ -0,0 +1,78 @@ +package io.swagger.client.model; + +import java.util.Objects; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +import com.google.gson.annotations.SerializedName; + + + + + +public class ReadOnlyFirst { + + @SerializedName("bar") + private String bar = null; + + @SerializedName("baz") + private String baz = null; + + /** + **/ + @ApiModelProperty(value = "") + public String getBar() { + return bar; + } + + /** + **/ + @ApiModelProperty(value = "") + public String getBaz() { + return baz; + } + public void setBaz(String baz) { + this.baz = baz; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ReadOnlyFirst readOnlyFirst = (ReadOnlyFirst) o; + return Objects.equals(bar, readOnlyFirst.bar) && + Objects.equals(baz, readOnlyFirst.baz); + } + + @Override + public int hashCode() { + return Objects.hash(bar, baz); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ReadOnlyFirst {\n"); + + sb.append(" bar: ").append(toIndentedString(bar)).append("\n"); + sb.append(" baz: ").append(toIndentedString(baz)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} diff --git a/samples/client/petstore/java/retrofit/src/test/java/io/swagger/client/api/PetApiTest.java b/samples/client/petstore/java/retrofit/src/test/java/io/swagger/client/api/PetApiTest.java index 39b4dc05ee0..70f8b5aa13f 100644 --- a/samples/client/petstore/java/retrofit/src/test/java/io/swagger/client/api/PetApiTest.java +++ b/samples/client/petstore/java/retrofit/src/test/java/io/swagger/client/api/PetApiTest.java @@ -1,137 +1,190 @@ package io.swagger.client.api; -import io.swagger.client.ApiClient; -import io.swagger.client.model.Pet; -import io.swagger.client.model.ModelApiResponse; +import io.swagger.TestUtils; + +import io.swagger.client.*; +import io.swagger.client.CollectionFormats.*; +import io.swagger.client.model.*; + +import retrofit.RetrofitError; +import retrofit.mime.TypedFile; + +import java.io.BufferedWriter; import java.io.File; -import org.junit.Before; -import org.junit.Test; - +import java.io.FileWriter; import java.util.ArrayList; -import java.util.HashMap; +import java.util.Arrays; import java.util.List; -import java.util.Map; -/** - * API tests for PetApi - */ +import org.junit.*; +import static org.junit.Assert.*; + public class PetApiTest { - - private PetApi api; + PetApi api = null; @Before public void setup() { api = new ApiClient().createService(PetApi.class); } - - /** - * Add a new pet to the store - * - * - */ @Test - public void addPetTest() { - Pet body = null; - // Void response = api.addPet(body); + public void testCreateAndGetPet() throws Exception { + Pet pet = createRandomPet(); + api.addPet(pet); - // TODO: test validations + Pet fetched = api.getPetById(pet.getId()); + assertNotNull(fetched); + assertEquals(pet.getId(), fetched.getId()); + assertNotNull(fetched.getCategory()); + assertEquals(fetched.getCategory().getName(), pet.getCategory().getName()); } - - /** - * Deletes a pet - * - * - */ + @Test - public void deletePetTest() { - Long petId = null; - String apiKey = null; - // Void response = api.deletePet(petId, apiKey); + public void testUpdatePet() throws Exception { + Pet pet = createRandomPet(); + pet.setName("programmer"); - // TODO: test validations + api.updatePet(pet); + + Pet fetched = api.getPetById(pet.getId()); + assertNotNull(fetched); + assertEquals(pet.getId(), fetched.getId()); + assertNotNull(fetched.getCategory()); + assertEquals(fetched.getCategory().getName(), pet.getCategory().getName()); } - - /** - * Finds Pets by status - * - * Multiple status values can be provided with comma separated strings - */ + @Test - public void findPetsByStatusTest() { - List status = null; - // List response = api.findPetsByStatus(status); + public void testFindPetsByStatus() throws Exception { + Pet pet = createRandomPet(); + pet.setName("programmer"); + pet.setStatus(Pet.StatusEnum.AVAILABLE); - // TODO: test validations + api.updatePet(pet); + + List pets = api.findPetsByStatus(new CSVParams("available")); + assertNotNull(pets); + + boolean found = false; + for (Pet fetched : pets) { + if (fetched.getId().equals(pet.getId())) { + found = true; + break; + } + } + + assertTrue(found); } - - /** - * Finds Pets by tags - * - * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. - */ + @Test - public void findPetsByTagsTest() { - List tags = null; - // List response = api.findPetsByTags(tags); + public void testFindPetsByTags() throws Exception { + Pet pet = createRandomPet(); + pet.setName("monster"); + pet.setStatus(Pet.StatusEnum.AVAILABLE); - // TODO: test validations + List tags = new ArrayList(); + Tag tag1 = new Tag(); + tag1.setName("friendly"); + tags.add(tag1); + pet.setTags(tags); + + api.updatePet(pet); + + List pets = api.findPetsByTags(new CSVParams("friendly")); + assertNotNull(pets); + + boolean found = false; + for (Pet fetched : pets) { + if (fetched.getId().equals(pet.getId())) { + found = true; + break; + } + } + assertTrue(found); } - - /** - * Find pet by ID - * - * Returns a single pet - */ + @Test - public void getPetByIdTest() { - Long petId = null; - // Pet response = api.getPetById(petId); + public void testUpdatePetWithForm() throws Exception { + Pet pet = createRandomPet(); + pet.setName("frank"); + api.addPet(pet); - // TODO: test validations + Pet fetched = api.getPetById(pet.getId()); + + api.updatePetWithForm(fetched.getId(), "furt", null); + Pet updated = api.getPetById(fetched.getId()); + + assertEquals(updated.getName(), "furt"); } - - /** - * Update an existing pet - * - * - */ + @Test - public void updatePetTest() { - Pet body = null; - // Void response = api.updatePet(body); + public void testDeletePet() throws Exception { + Pet pet = createRandomPet(); + api.addPet(pet); - // TODO: test validations + Pet fetched = api.getPetById(pet.getId()); + api.deletePet(fetched.getId(), null); + + try { + fetched = api.getPetById(fetched.getId()); + fail("expected an error"); + } catch (RetrofitError e) { + assertEquals(404, e.getResponse().getStatus()); + } } - - /** - * Updates a pet in the store with form data - * - * - */ + @Test - public void updatePetWithFormTest() { - Long petId = null; - String name = null; - String status = null; - // Void response = api.updatePetWithForm(petId, name, status); + public void testUploadFile() throws Exception { + Pet pet = createRandomPet(); + api.addPet(pet); - // TODO: test validations + File file = new File("hello.txt"); + BufferedWriter writer = new BufferedWriter(new FileWriter(file)); + writer.write("Hello world!"); + writer.close(); + + api.uploadFile(pet.getId(), "a test file", new TypedFile("text/plain", file)); } - - /** - * uploads an image - * - * - */ + @Test - public void uploadFileTest() { - Long petId = null; - String additionalMetadata = null; - File file = null; - // ModelApiResponse response = api.uploadFile(petId, additionalMetadata, file); + public void testEqualsAndHashCode() { + Pet pet1 = new Pet(); + Pet pet2 = new Pet(); + assertTrue(pet1.equals(pet2)); + assertTrue(pet2.equals(pet1)); + assertTrue(pet1.hashCode() == pet2.hashCode()); + assertTrue(pet1.equals(pet1)); + assertTrue(pet1.hashCode() == pet1.hashCode()); - // TODO: test validations + pet2.setName("really-happy"); + pet2.setPhotoUrls(Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"})); + assertFalse(pet1.equals(pet2)); + assertFalse(pet2.equals(pet1)); + assertFalse(pet1.hashCode() == (pet2.hashCode())); + assertTrue(pet2.equals(pet2)); + assertTrue(pet2.hashCode() == pet2.hashCode()); + + pet1.setName("really-happy"); + pet1.setPhotoUrls(Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"})); + assertTrue(pet1.equals(pet2)); + assertTrue(pet2.equals(pet1)); + assertTrue(pet1.hashCode() == pet2.hashCode()); + assertTrue(pet1.equals(pet1)); + assertTrue(pet1.hashCode() == pet1.hashCode()); + } + + private Pet createRandomPet() { + Pet pet = new Pet(); + pet.setId(TestUtils.nextId()); + pet.setName("gorilla"); + + Category category = new Category(); + category.setName("really-happy"); + + pet.setCategory(category); + pet.setStatus(Pet.StatusEnum.AVAILABLE); + List photos = Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"}); + pet.setPhotoUrls(photos); + + return pet; } - } diff --git a/samples/client/petstore/java/retrofit/src/test/java/io/swagger/client/api/StoreApiTest.java b/samples/client/petstore/java/retrofit/src/test/java/io/swagger/client/api/StoreApiTest.java index 1da787edf19..a290fadb847 100644 --- a/samples/client/petstore/java/retrofit/src/test/java/io/swagger/client/api/StoreApiTest.java +++ b/samples/client/petstore/java/retrofit/src/test/java/io/swagger/client/api/StoreApiTest.java @@ -1,77 +1,80 @@ package io.swagger.client.api; -import io.swagger.client.ApiClient; -import io.swagger.client.model.Order; -import org.junit.Before; -import org.junit.Test; +import io.swagger.TestUtils; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; +import io.swagger.client.ApiClient; +import io.swagger.client.model.*; + +import org.joda.time.DateTime; +import org.joda.time.DateTimeZone; +import retrofit.RetrofitError; + +import java.lang.reflect.Field; import java.util.Map; -/** - * API tests for StoreApi - */ -public class StoreApiTest { +import org.junit.*; +import static org.junit.Assert.*; - private StoreApi api; +public class StoreApiTest { + StoreApi api = null; @Before public void setup() { api = new ApiClient().createService(StoreApi.class); } - - /** - * Delete purchase order by ID - * - * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors - */ @Test - public void deleteOrderTest() { - String orderId = null; - // Void response = api.deleteOrder(orderId); - - // TODO: test validations + public void testGetInventory() throws Exception { + Map inventory = api.getInventory(); + assertTrue(inventory.keySet().size() > 0); } - - /** - * Returns pet inventories by status - * - * Returns a map of status codes to quantities - */ + @Test - public void getInventoryTest() { - // Map response = api.getInventory(); + public void testPlaceOrder() throws Exception { + Order order = createOrder(); + api.placeOrder(order); - // TODO: test validations + Order fetched = api.getOrderById(order.getId()); + assertEquals(order.getId(), fetched.getId()); + assertEquals(order.getPetId(), fetched.getPetId()); + assertEquals(order.getQuantity(), fetched.getQuantity()); + assertEquals(order.getShipDate().withZone(DateTimeZone.UTC), fetched.getShipDate().withZone(DateTimeZone.UTC)); } - - /** - * Find purchase order by ID - * - * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - */ + @Test - public void getOrderByIdTest() { - Long orderId = null; - // Order response = api.getOrderById(orderId); + public void testDeleteOrder() throws Exception { + Order order = createOrder(); + api.placeOrder(order); - // TODO: test validations - } - - /** - * Place an order for a pet - * - * - */ - @Test - public void placeOrderTest() { - Order body = null; - // Order response = api.placeOrder(body); + Order fetched = api.getOrderById(order.getId()); + assertEquals(fetched.getId(), order.getId()); - // TODO: test validations + api.deleteOrder(String.valueOf(order.getId())); + + try { + api.getOrderById(order.getId()); + // fail("expected an error"); + } catch (RetrofitError e) { + // ok + } + } + + private Order createOrder() { + Order order = new Order(); + order.setPetId(new Long(200)); + order.setQuantity(new Integer(13)); + order.setShipDate(DateTime.now()); + order.setStatus(Order.StatusEnum.PLACED); + order.setComplete(true); + + try { + Field idField = Order.class.getDeclaredField("id"); + idField.setAccessible(true); + idField.set(order, TestUtils.nextId()); + } catch (Exception e) { + throw new RuntimeException(e); + } + + return order; } - } diff --git a/samples/client/petstore/java/retrofit/src/test/java/io/swagger/client/api/UserApiTest.java b/samples/client/petstore/java/retrofit/src/test/java/io/swagger/client/api/UserApiTest.java index cd8553d8419..84fae0e990f 100644 --- a/samples/client/petstore/java/retrofit/src/test/java/io/swagger/client/api/UserApiTest.java +++ b/samples/client/petstore/java/retrofit/src/test/java/io/swagger/client/api/UserApiTest.java @@ -1,131 +1,85 @@ package io.swagger.client.api; +import io.swagger.TestUtils; + import io.swagger.client.ApiClient; -import io.swagger.client.model.User; -import org.junit.Before; -import org.junit.Test; +import io.swagger.client.model.*; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -/** - * API tests for UserApi - */ +import java.util.Arrays; + +import org.junit.*; +import static org.junit.Assert.*; + public class UserApiTest { - - private UserApi api; + UserApi api = null; @Before public void setup() { api = new ApiClient().createService(UserApi.class); } - - /** - * Create user - * - * This can only be done by the logged in user. - */ @Test - public void createUserTest() { - User body = null; - // Void response = api.createUser(body); + public void testCreateUser() throws Exception { + User user = createUser(); - // TODO: test validations + api.createUser(user); + + User fetched = api.getUserByName(user.getUsername()); + assertEquals(user.getId(), fetched.getId()); } - - /** - * Creates list of users with given input array - * - * - */ + @Test - public void createUsersWithArrayInputTest() { - List body = null; - // Void response = api.createUsersWithArrayInput(body); + public void testCreateUsersWithArray() throws Exception { + User user1 = createUser(); + user1.setUsername("user" + user1.getId()); + User user2 = createUser(); + user2.setUsername("user" + user2.getId()); - // TODO: test validations + api.createUsersWithArrayInput(Arrays.asList(new User[]{user1, user2})); + + User fetched = api.getUserByName(user1.getUsername()); + assertEquals(user1.getId(), fetched.getId()); } - - /** - * Creates list of users with given input array - * - * - */ + @Test - public void createUsersWithListInputTest() { - List body = null; - // Void response = api.createUsersWithListInput(body); + public void testCreateUsersWithList() throws Exception { + User user1 = createUser(); + user1.setUsername("user" + user1.getId()); + User user2 = createUser(); + user2.setUsername("user" + user2.getId()); - // TODO: test validations + api.createUsersWithListInput(Arrays.asList(new User[]{user1, user2})); + + User fetched = api.getUserByName(user1.getUsername()); + assertEquals(user1.getId(), fetched.getId()); } - - /** - * Delete user - * - * This can only be done by the logged in user. - */ + @Test - public void deleteUserTest() { - String username = null; - // Void response = api.deleteUser(username); + public void testLoginUser() throws Exception { + User user = createUser(); + api.createUser(user); - // TODO: test validations + String token = api.loginUser(user.getUsername(), user.getPassword()); + assertTrue(token.startsWith("logged in user session:")); } - - /** - * Get user by user name - * - * - */ + @Test - public void getUserByNameTest() { - String username = null; - // User response = api.getUserByName(username); - - // TODO: test validations + public void logoutUser() throws Exception { + api.logoutUser(); } - - /** - * Logs user into the system - * - * - */ - @Test - public void loginUserTest() { - String username = null; - String password = null; - // String response = api.loginUser(username, password); - // TODO: test validations - } - - /** - * Logs out current logged in user session - * - * - */ - @Test - public void logoutUserTest() { - // Void response = api.logoutUser(); + private User createUser() { + User user = new User(); + user.setId(TestUtils.nextId()); + user.setUsername("fred" + user.getId()); + user.setFirstName("Fred"); + user.setLastName("Meyer"); + user.setEmail("fred@fredmeyer.com"); + user.setPassword("xxXXxx"); + user.setPhone("408-867-5309"); + user.setUserStatus(123); - // TODO: test validations + return user; } - - /** - * Updated user - * - * This can only be done by the logged in user. - */ - @Test - public void updateUserTest() { - String username = null; - User body = null; - // Void response = api.updateUser(username, body); - - // TODO: test validations - } - } diff --git a/samples/client/petstore/java/retrofit/src/test/java/io/swagger/petstore/test/PetApiTest.java b/samples/client/petstore/java/retrofit/src/test/java/io/swagger/petstore/test/PetApiTest.java deleted file mode 100644 index 9fa93650d54..00000000000 --- a/samples/client/petstore/java/retrofit/src/test/java/io/swagger/petstore/test/PetApiTest.java +++ /dev/null @@ -1,191 +0,0 @@ -package io.swagger.petstore.test; - -import io.swagger.TestUtils; - -import io.swagger.client.*; -import io.swagger.client.CollectionFormats.*; -import io.swagger.client.api.*; -import io.swagger.client.model.*; - -import retrofit.RetrofitError; -import retrofit.mime.TypedFile; - -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileWriter; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import org.junit.*; -import static org.junit.Assert.*; - -public class PetApiTest { - PetApi api = null; - - @Before - public void setup() { - api = new ApiClient().createService(PetApi.class); - } - - @Test - public void testCreateAndGetPet() throws Exception { - Pet pet = createRandomPet(); - api.addPet(pet); - - Pet fetched = api.getPetById(pet.getId()); - assertNotNull(fetched); - assertEquals(pet.getId(), fetched.getId()); - assertNotNull(fetched.getCategory()); - assertEquals(fetched.getCategory().getName(), pet.getCategory().getName()); - } - - @Test - public void testUpdatePet() throws Exception { - Pet pet = createRandomPet(); - pet.setName("programmer"); - - api.updatePet(pet); - - Pet fetched = api.getPetById(pet.getId()); - assertNotNull(fetched); - assertEquals(pet.getId(), fetched.getId()); - assertNotNull(fetched.getCategory()); - assertEquals(fetched.getCategory().getName(), pet.getCategory().getName()); - } - - @Test - public void testFindPetsByStatus() throws Exception { - Pet pet = createRandomPet(); - pet.setName("programmer"); - pet.setStatus(Pet.StatusEnum.AVAILABLE); - - api.updatePet(pet); - - List pets = api.findPetsByStatus(new CSVParams("available")); - assertNotNull(pets); - - boolean found = false; - for (Pet fetched : pets) { - if (fetched.getId().equals(pet.getId())) { - found = true; - break; - } - } - - assertTrue(found); - } - - @Test - public void testFindPetsByTags() throws Exception { - Pet pet = createRandomPet(); - pet.setName("monster"); - pet.setStatus(Pet.StatusEnum.AVAILABLE); - - List tags = new ArrayList(); - Tag tag1 = new Tag(); - tag1.setName("friendly"); - tags.add(tag1); - pet.setTags(tags); - - api.updatePet(pet); - - List pets = api.findPetsByTags(new CSVParams("friendly")); - assertNotNull(pets); - - boolean found = false; - for (Pet fetched : pets) { - if (fetched.getId().equals(pet.getId())) { - found = true; - break; - } - } - assertTrue(found); - } - - @Test - public void testUpdatePetWithForm() throws Exception { - Pet pet = createRandomPet(); - pet.setName("frank"); - api.addPet(pet); - - Pet fetched = api.getPetById(pet.getId()); - - api.updatePetWithForm(fetched.getId(), "furt", null); - Pet updated = api.getPetById(fetched.getId()); - - assertEquals(updated.getName(), "furt"); - } - - @Test - public void testDeletePet() throws Exception { - Pet pet = createRandomPet(); - api.addPet(pet); - - Pet fetched = api.getPetById(pet.getId()); - api.deletePet(fetched.getId(), null); - - try { - fetched = api.getPetById(fetched.getId()); - fail("expected an error"); - } catch (RetrofitError e) { - assertEquals(404, e.getResponse().getStatus()); - } - } - - @Test - public void testUploadFile() throws Exception { - Pet pet = createRandomPet(); - api.addPet(pet); - - File file = new File("hello.txt"); - BufferedWriter writer = new BufferedWriter(new FileWriter(file)); - writer.write("Hello world!"); - writer.close(); - - api.uploadFile(pet.getId(), "a test file", new TypedFile("text/plain", file)); - } - - @Test - public void testEqualsAndHashCode() { - Pet pet1 = new Pet(); - Pet pet2 = new Pet(); - assertTrue(pet1.equals(pet2)); - assertTrue(pet2.equals(pet1)); - assertTrue(pet1.hashCode() == pet2.hashCode()); - assertTrue(pet1.equals(pet1)); - assertTrue(pet1.hashCode() == pet1.hashCode()); - - pet2.setName("really-happy"); - pet2.setPhotoUrls(Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"})); - assertFalse(pet1.equals(pet2)); - assertFalse(pet2.equals(pet1)); - assertFalse(pet1.hashCode() == (pet2.hashCode())); - assertTrue(pet2.equals(pet2)); - assertTrue(pet2.hashCode() == pet2.hashCode()); - - pet1.setName("really-happy"); - pet1.setPhotoUrls(Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"})); - assertTrue(pet1.equals(pet2)); - assertTrue(pet2.equals(pet1)); - assertTrue(pet1.hashCode() == pet2.hashCode()); - assertTrue(pet1.equals(pet1)); - assertTrue(pet1.hashCode() == pet1.hashCode()); - } - - private Pet createRandomPet() { - Pet pet = new Pet(); - pet.setId(TestUtils.nextId()); - pet.setName("gorilla"); - - Category category = new Category(); - category.setName("really-happy"); - - pet.setCategory(category); - pet.setStatus(Pet.StatusEnum.AVAILABLE); - List photos = Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"}); - pet.setPhotoUrls(photos); - - return pet; - } -} diff --git a/samples/client/petstore/java/retrofit/src/test/java/io/swagger/petstore/test/StoreApiTest.java b/samples/client/petstore/java/retrofit/src/test/java/io/swagger/petstore/test/StoreApiTest.java deleted file mode 100644 index c823245355a..00000000000 --- a/samples/client/petstore/java/retrofit/src/test/java/io/swagger/petstore/test/StoreApiTest.java +++ /dev/null @@ -1,78 +0,0 @@ -package io.swagger.petstore.test; - -import io.swagger.TestUtils; - -import io.swagger.client.ApiClient; -import io.swagger.client.api.*; -import io.swagger.client.model.*; - -import retrofit.RetrofitError; - -import java.lang.reflect.Field; -import java.util.Map; - -import org.junit.*; -import static org.junit.Assert.*; - -public class StoreApiTest { - StoreApi api = null; - - @Before - public void setup() { - api = new ApiClient().createService(StoreApi.class); - } - - @Test - public void testGetInventory() throws Exception { - Map inventory = api.getInventory(); - assertTrue(inventory.keySet().size() > 0); - } - - @Test - public void testPlaceOrder() throws Exception { - Order order = createOrder(); - api.placeOrder(order); - - Order fetched = api.getOrderById(order.getId()); - assertEquals(order.getId(), fetched.getId()); - assertEquals(order.getPetId(), fetched.getPetId()); - assertEquals(order.getQuantity(), fetched.getQuantity()); - } - - @Test - public void testDeleteOrder() throws Exception { - Order order = createOrder(); - api.placeOrder(order); - - Order fetched = api.getOrderById(order.getId()); - assertEquals(fetched.getId(), order.getId()); - - api.deleteOrder(String.valueOf(order.getId())); - - try { - api.getOrderById(order.getId()); - // fail("expected an error"); - } catch (RetrofitError e) { - // ok - } - } - - private Order createOrder() { - Order order = new Order(); - order.setPetId(new Long(200)); - order.setQuantity(new Integer(13)); - order.setShipDate(new java.util.Date()); - order.setStatus(Order.StatusEnum.PLACED); - order.setComplete(true); - - try { - Field idField = Order.class.getDeclaredField("id"); - idField.setAccessible(true); - idField.set(order, TestUtils.nextId()); - } catch (Exception e) { - throw new RuntimeException(e); - } - - return order; - } -} diff --git a/samples/client/petstore/java/retrofit/src/test/java/io/swagger/petstore/test/UserApiTest.java b/samples/client/petstore/java/retrofit/src/test/java/io/swagger/petstore/test/UserApiTest.java deleted file mode 100644 index 9b949445cc3..00000000000 --- a/samples/client/petstore/java/retrofit/src/test/java/io/swagger/petstore/test/UserApiTest.java +++ /dev/null @@ -1,86 +0,0 @@ -package io.swagger.petstore.test; - -import io.swagger.TestUtils; - -import io.swagger.client.ApiClient; -import io.swagger.client.api.*; -import io.swagger.client.model.*; - - -import java.util.Arrays; - -import org.junit.*; -import static org.junit.Assert.*; - -public class UserApiTest { - UserApi api = null; - - @Before - public void setup() { - api = new ApiClient().createService(UserApi.class); - } - - @Test - public void testCreateUser() throws Exception { - User user = createUser(); - - api.createUser(user); - - User fetched = api.getUserByName(user.getUsername()); - assertEquals(user.getId(), fetched.getId()); - } - - @Test - public void testCreateUsersWithArray() throws Exception { - User user1 = createUser(); - user1.setUsername("user" + user1.getId()); - User user2 = createUser(); - user2.setUsername("user" + user2.getId()); - - api.createUsersWithArrayInput(Arrays.asList(new User[]{user1, user2})); - - User fetched = api.getUserByName(user1.getUsername()); - assertEquals(user1.getId(), fetched.getId()); - } - - @Test - public void testCreateUsersWithList() throws Exception { - User user1 = createUser(); - user1.setUsername("user" + user1.getId()); - User user2 = createUser(); - user2.setUsername("user" + user2.getId()); - - api.createUsersWithListInput(Arrays.asList(new User[]{user1, user2})); - - User fetched = api.getUserByName(user1.getUsername()); - assertEquals(user1.getId(), fetched.getId()); - } - - @Test - public void testLoginUser() throws Exception { - User user = createUser(); - api.createUser(user); - - String token = api.loginUser(user.getUsername(), user.getPassword()); - assertTrue(token.startsWith("logged in user session:")); - } - - @Test - public void logoutUser() throws Exception { - api.logoutUser(); - } - - private User createUser() { - User user = new User(); - user.setId(TestUtils.nextId()); - user.setUsername("fred" + user.getId()); - user.setFirstName("Fred"); - user.setLastName("Meyer"); - user.setEmail("fred@fredmeyer.com"); - user.setPassword("xxXXxx"); - user.setPhone("408-867-5309"); - user.setUserStatus(123); - - return user; - } -} diff --git a/samples/client/petstore/java/retrofit2/.swagger-codegen-ignore b/samples/client/petstore/java/retrofit2/.swagger-codegen-ignore new file mode 100644 index 00000000000..19d3377182e --- /dev/null +++ b/samples/client/petstore/java/retrofit2/.swagger-codegen-ignore @@ -0,0 +1,23 @@ +# Swagger Codegen Ignore +# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell Swagger Codgen to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# Thsi matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/client/petstore/java/retrofit2/LICENSE b/samples/client/petstore/java/retrofit2/LICENSE new file mode 100644 index 00000000000..8dada3edaf5 --- /dev/null +++ b/samples/client/petstore/java/retrofit2/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/samples/client/petstore/java/retrofit2/build.gradle b/samples/client/petstore/java/retrofit2/build.gradle index 6b96656a4a8..4287ae6e53f 100644 --- a/samples/client/petstore/java/retrofit2/build.gradle +++ b/samples/client/petstore/java/retrofit2/build.gradle @@ -98,17 +98,16 @@ ext { retrofit_version = "2.0.2" swagger_annotations_version = "1.5.8" junit_version = "4.12" - + jodatime_version = "2.9.3" } dependencies { compile "com.squareup.retrofit2:retrofit:$retrofit_version" compile "com.squareup.retrofit2:converter-scalars:$retrofit_version" compile "com.squareup.retrofit2:converter-gson:$retrofit_version" - - compile "io.swagger:swagger-annotations:$swagger_annotations_version" compile "org.apache.oltu.oauth2:org.apache.oltu.oauth2.client:$oltu_version" + compile "joda-time:joda-time:$jodatime_version" testCompile "junit:junit:$junit_version" } diff --git a/samples/client/petstore/java/retrofit2/build.sbt b/samples/client/petstore/java/retrofit2/build.sbt new file mode 100644 index 00000000000..c42d32f7b53 --- /dev/null +++ b/samples/client/petstore/java/retrofit2/build.sbt @@ -0,0 +1,21 @@ +lazy val root = (project in file(".")). + settings( + organization := "io.swagger", + name := "swagger-petstore-retrofit2", + version := "1.0.0", + scalaVersion := "2.11.4", + scalacOptions ++= Seq("-feature"), + javacOptions in compile ++= Seq("-Xlint:deprecation"), + publishArtifact in (Compile, packageDoc) := false, + resolvers += Resolver.mavenLocal, + libraryDependencies ++= Seq( + "com.squareup.retrofit2" % "retrofit" % "2.0.2" % "compile", + "com.squareup.retrofit2" % "converter-scalars" % "2.0.2" % "compile", + "com.squareup.retrofit2" % "converter-gson" % "2.0.2" % "compile", + "io.swagger" % "swagger-annotations" % "1.5.8" % "compile", + "org.apache.oltu.oauth2" % "org.apache.oltu.oauth2.client" % "1.0.1" % "compile", + "joda-time" % "joda-time" % "2.9.3" % "compile", + "junit" % "junit" % "4.12" % "test", + "com.novocode" % "junit-interface" % "0.10" % "test" + ) + ) diff --git a/samples/client/petstore/java/retrofit2/docs/AdditionalPropertiesClass.md b/samples/client/petstore/java/retrofit2/docs/AdditionalPropertiesClass.md index c72785d450f..0437c4dd8cc 100644 --- a/samples/client/petstore/java/retrofit2/docs/AdditionalPropertiesClass.md +++ b/samples/client/petstore/java/retrofit2/docs/AdditionalPropertiesClass.md @@ -4,6 +4,8 @@ ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- +**mapProperty** | **Map<String, String>** | | [optional] +**mapOfMapProperty** | [**Map<String, Map<String, String>>**](Map.md) | | [optional] diff --git a/samples/client/petstore/java/retrofit2/docs/ArrayTest.md b/samples/client/petstore/java/retrofit2/docs/ArrayTest.md index 73c3e5305ad..9feee16427f 100644 --- a/samples/client/petstore/java/retrofit2/docs/ArrayTest.md +++ b/samples/client/petstore/java/retrofit2/docs/ArrayTest.md @@ -4,6 +4,9 @@ ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- +**arrayOfString** | **List<String>** | | [optional] +**arrayArrayOfInteger** | [**List<List<Long>>**](List.md) | | [optional] +**arrayArrayOfModel** | [**List<List<ReadOnlyFirst>>**](List.md) | | [optional] diff --git a/samples/client/petstore/java/retrofit2/docs/FakeApi.md b/samples/client/petstore/java/retrofit2/docs/FakeApi.md index 55f7cef2df4..e077fa5c821 100644 --- a/samples/client/petstore/java/retrofit2/docs/FakeApi.md +++ b/samples/client/petstore/java/retrofit2/docs/FakeApi.md @@ -32,8 +32,8 @@ 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 +LocalDate date = new LocalDate(); // LocalDate | None +DateTime dateTime = new DateTime(); // DateTime | None String password = "password_example"; // String | None try { Void result = apiInstance.testEndpointParameters(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password); @@ -57,8 +57,8 @@ Name | Type | Description | Notes **int64** | **Long**| None | [optional] **_float** | **Float**| None | [optional] **binary** | **byte[]**| None | [optional] - **date** | **Date**| None | [optional] - **dateTime** | **Date**| None | [optional] + **date** | **LocalDate**| None | [optional] + **dateTime** | **DateTime**| None | [optional] **password** | **String**| None | [optional] ### Return type diff --git a/samples/client/petstore/java/retrofit2/docs/FormatTest.md b/samples/client/petstore/java/retrofit2/docs/FormatTest.md index dc2b559dad2..44de7d9511a 100644 --- a/samples/client/petstore/java/retrofit2/docs/FormatTest.md +++ b/samples/client/petstore/java/retrofit2/docs/FormatTest.md @@ -13,8 +13,8 @@ Name | Type | Description | Notes **string** | **String** | | [optional] **_byte** | **byte[]** | | **binary** | **byte[]** | | [optional] -**date** | [**Date**](Date.md) | | -**dateTime** | [**Date**](Date.md) | | [optional] +**date** | [**LocalDate**](LocalDate.md) | | +**dateTime** | [**DateTime**](DateTime.md) | | [optional] **uuid** | **String** | | [optional] **password** | **String** | | diff --git a/samples/client/petstore/java/retrofit2/docs/MixedPropertiesAndAdditionalPropertiesClass.md b/samples/client/petstore/java/retrofit2/docs/MixedPropertiesAndAdditionalPropertiesClass.md index fcdbd390517..e3487bcc501 100644 --- a/samples/client/petstore/java/retrofit2/docs/MixedPropertiesAndAdditionalPropertiesClass.md +++ b/samples/client/petstore/java/retrofit2/docs/MixedPropertiesAndAdditionalPropertiesClass.md @@ -5,7 +5,8 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **uuid** | **String** | | [optional] -**dateTime** | [**Date**](Date.md) | | [optional] +**dateTime** | [**DateTime**](DateTime.md) | | [optional] +**map** | [**Map<String, Animal>**](Animal.md) | | [optional] diff --git a/samples/client/petstore/java/retrofit2/docs/Order.md b/samples/client/petstore/java/retrofit2/docs/Order.md index 29ca3ddbc6b..a1089f5384e 100644 --- a/samples/client/petstore/java/retrofit2/docs/Order.md +++ b/samples/client/petstore/java/retrofit2/docs/Order.md @@ -7,7 +7,7 @@ Name | Type | Description | Notes **id** | **Long** | | [optional] **petId** | **Long** | | [optional] **quantity** | **Integer** | | [optional] -**shipDate** | [**Date**](Date.md) | | [optional] +**shipDate** | [**DateTime**](DateTime.md) | | [optional] **status** | [**StatusEnum**](#StatusEnum) | Order Status | [optional] **complete** | **Boolean** | | [optional] diff --git a/samples/client/petstore/java/retrofit2/gradle/wrapper/gradle-wrapper.properties b/samples/client/petstore/java/retrofit2/gradle/wrapper/gradle-wrapper.properties index 77483e70e76..b7a36473955 100644 --- a/samples/client/petstore/java/retrofit2/gradle/wrapper/gradle-wrapper.properties +++ b/samples/client/petstore/java/retrofit2/gradle/wrapper/gradle-wrapper.properties @@ -1,4 +1,4 @@ -#Tue May 17 23:04:50 CST 2016 +#Tue May 17 23:08:05 CST 2016 distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME diff --git a/samples/client/petstore/java/retrofit2/pom.xml b/samples/client/petstore/java/retrofit2/pom.xml index 05774ac3834..26c32613c1f 100644 --- a/samples/client/petstore/java/retrofit2/pom.xml +++ b/samples/client/petstore/java/retrofit2/pom.xml @@ -132,6 +132,11 @@ org.apache.oltu.oauth2.client ${oltu-version} + + joda-time + joda-time + ${jodatime-version} + @@ -144,8 +149,7 @@ 1.5.8 2.0.2 - - 3.2.0 + 2.9.3 1.0.1 1.0.0 4.12 diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/ApiClient.java index e49bdf24d7b..305b8b783e4 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/ApiClient.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/ApiClient.java @@ -9,6 +9,10 @@ import java.util.Map; import org.apache.oltu.oauth2.client.request.OAuthClientRequest.AuthenticationRequestBuilder; import org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuilder; +import org.joda.time.DateTime; +import org.joda.time.LocalDate; +import org.joda.time.format.DateTimeFormatter; +import org.joda.time.format.ISODateTimeFormat; import retrofit2.Converter; import retrofit2.Retrofit; @@ -19,6 +23,9 @@ import retrofit2.converter.scalars.ScalarsConverterFactory; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; import okhttp3.Interceptor; import okhttp3.OkHttpClient; import okhttp3.RequestBody; @@ -107,6 +114,8 @@ public class ApiClient { public void createDefaultAdapter() { Gson gson = new GsonBuilder() .setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ") + .registerTypeAdapter(DateTime.class, new DateTimeTypeAdapter()) + .registerTypeAdapter(LocalDate.class, new LocalDateTypeAdapter()) .create(); okClient = new OkHttpClient(); @@ -345,3 +354,58 @@ class GsonCustomConverterFactory extends Converter.Factory } } + +/** + * Gson TypeAdapter for Joda DateTime type + */ +class DateTimeTypeAdapter extends TypeAdapter { + + private final DateTimeFormatter formatter = ISODateTimeFormat.dateTime(); + + @Override + public void write(JsonWriter out, DateTime date) throws IOException { + if (date == null) { + out.nullValue(); + } else { + out.value(formatter.print(date)); + } + } + + @Override + public DateTime read(JsonReader in) throws IOException { + switch (in.peek()) { + case NULL: + in.nextNull(); + return null; + default: + String date = in.nextString(); + return formatter.parseDateTime(date); + } + } +} + +class LocalDateTypeAdapter extends TypeAdapter { + + private final DateTimeFormatter formatter = ISODateTimeFormat.date(); + + @Override + public void write(JsonWriter out, LocalDate date) throws IOException { + if (date == null) { + out.nullValue(); + } else { + out.value(formatter.print(date)); + } + } + + @Override + public LocalDate read(JsonReader in) throws IOException { + switch (in.peek()) { + case NULL: + in.nextNull(); + return null; + default: + String date = in.nextString(); + return formatter.parseLocalDate(date); + } + } +} \ No newline at end of file diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/StringUtil.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/StringUtil.java index 244ee20eb5b..03c6c81e434 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/StringUtil.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/StringUtil.java @@ -1,6 +1,31 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-17T10:34:26.353+02:00") + public class StringUtil { /** * Check if the given array contains the given value (with case-insensitive comparison). diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/FakeApi.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/FakeApi.java index 75fe792872a..91bd85c1b33 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,8 +8,9 @@ import retrofit2.http.*; import okhttp3.RequestBody; +import org.joda.time.LocalDate; import java.math.BigDecimal; -import java.util.Date; +import org.joda.time.DateTime; import java.util.ArrayList; import java.util.HashMap; @@ -38,7 +39,7 @@ public interface FakeApi { @FormUrlEncoded @POST("fake") Call testEndpointParameters( - @Field("number") BigDecimal number, @Field("double") Double _double, @Field("string") String string, @Field("byte") byte[] _byte, @Field("integer") Integer integer, @Field("int32") Integer int32, @Field("int64") Long int64, @Field("float") Float _float, @Field("binary") byte[] binary, @Field("date") 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") LocalDate date, @Field("dateTime") DateTime dateTime, @Field("password") String password ); } diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/auth/OAuthFlow.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/auth/OAuthFlow.java index 597ec99b48b..ec1f942b0f2 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/auth/OAuthFlow.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/auth/OAuthFlow.java @@ -1,5 +1,30 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.auth; public enum OAuthFlow { accessCode, implicit, password, application -} \ No newline at end of file +} diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java new file mode 100644 index 00000000000..839b04aa6c5 --- /dev/null +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java @@ -0,0 +1,84 @@ +package io.swagger.client.model; + +import java.util.Objects; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import com.google.gson.annotations.SerializedName; + + + + + +public class AdditionalPropertiesClass { + + @SerializedName("map_property") + private Map mapProperty = new HashMap(); + + @SerializedName("map_of_map_property") + private Map> mapOfMapProperty = new HashMap>(); + + /** + **/ + @ApiModelProperty(value = "") + public Map getMapProperty() { + return mapProperty; + } + public void setMapProperty(Map mapProperty) { + this.mapProperty = mapProperty; + } + + /** + **/ + @ApiModelProperty(value = "") + public Map> getMapOfMapProperty() { + return mapOfMapProperty; + } + public void setMapOfMapProperty(Map> mapOfMapProperty) { + this.mapOfMapProperty = mapOfMapProperty; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + AdditionalPropertiesClass additionalPropertiesClass = (AdditionalPropertiesClass) o; + return Objects.equals(mapProperty, additionalPropertiesClass.mapProperty) && + Objects.equals(mapOfMapProperty, additionalPropertiesClass.mapOfMapProperty); + } + + @Override + public int hashCode() { + return Objects.hash(mapProperty, mapOfMapProperty); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class AdditionalPropertiesClass {\n"); + + sb.append(" mapProperty: ").append(toIndentedString(mapProperty)).append("\n"); + sb.append(" mapOfMapProperty: ").append(toIndentedString(mapOfMapProperty)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/ArrayTest.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/ArrayTest.java new file mode 100644 index 00000000000..92337cc0246 --- /dev/null +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/ArrayTest.java @@ -0,0 +1,98 @@ +package io.swagger.client.model; + +import java.util.Objects; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.util.ArrayList; +import java.util.List; + +import com.google.gson.annotations.SerializedName; + + + + + +public class ArrayTest { + + @SerializedName("array_of_string") + private List arrayOfString = new ArrayList(); + + @SerializedName("array_array_of_integer") + private List> arrayArrayOfInteger = new ArrayList>(); + + @SerializedName("array_array_of_model") + private List> arrayArrayOfModel = new ArrayList>(); + + /** + **/ + @ApiModelProperty(value = "") + public List getArrayOfString() { + return arrayOfString; + } + public void setArrayOfString(List arrayOfString) { + this.arrayOfString = arrayOfString; + } + + /** + **/ + @ApiModelProperty(value = "") + public List> getArrayArrayOfInteger() { + return arrayArrayOfInteger; + } + public void setArrayArrayOfInteger(List> arrayArrayOfInteger) { + this.arrayArrayOfInteger = arrayArrayOfInteger; + } + + /** + **/ + @ApiModelProperty(value = "") + public List> getArrayArrayOfModel() { + return arrayArrayOfModel; + } + public void setArrayArrayOfModel(List> arrayArrayOfModel) { + this.arrayArrayOfModel = arrayArrayOfModel; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ArrayTest arrayTest = (ArrayTest) o; + return Objects.equals(arrayOfString, arrayTest.arrayOfString) && + Objects.equals(arrayArrayOfInteger, arrayTest.arrayArrayOfInteger) && + Objects.equals(arrayArrayOfModel, arrayTest.arrayArrayOfModel); + } + + @Override + public int hashCode() { + return Objects.hash(arrayOfString, arrayArrayOfInteger, arrayArrayOfModel); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ArrayTest {\n"); + + sb.append(" arrayOfString: ").append(toIndentedString(arrayOfString)).append("\n"); + sb.append(" arrayArrayOfInteger: ").append(toIndentedString(arrayArrayOfInteger)).append("\n"); + sb.append(" arrayArrayOfModel: ").append(toIndentedString(arrayArrayOfModel)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} diff --git a/samples/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 694335531fd..6063cf33f77 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 @@ -4,7 +4,8 @@ import java.util.Objects; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.math.BigDecimal; -import java.util.Date; +import org.joda.time.DateTime; +import org.joda.time.LocalDate; import com.google.gson.annotations.SerializedName; @@ -42,10 +43,10 @@ public class FormatTest { private byte[] binary = null; @SerializedName("date") - private Date date = null; + private LocalDate date = null; @SerializedName("dateTime") - private Date dateTime = null; + private DateTime dateTime = null; @SerializedName("uuid") private String uuid = null; @@ -156,20 +157,20 @@ public class FormatTest { /** **/ @ApiModelProperty(required = true, value = "") - public Date getDate() { + public LocalDate getDate() { return date; } - public void setDate(Date date) { + public void setDate(LocalDate date) { this.date = date; } /** **/ @ApiModelProperty(value = "") - public Date getDateTime() { + public DateTime getDateTime() { return dateTime; } - public void setDateTime(Date dateTime) { + public void setDateTime(DateTime dateTime) { this.dateTime = dateTime; } diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java new file mode 100644 index 00000000000..cf7f73c705f --- /dev/null +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -0,0 +1,101 @@ +package io.swagger.client.model; + +import java.util.Objects; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.client.model.Animal; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.joda.time.DateTime; + +import com.google.gson.annotations.SerializedName; + + + + + +public class MixedPropertiesAndAdditionalPropertiesClass { + + @SerializedName("uuid") + private String uuid = null; + + @SerializedName("dateTime") + private DateTime dateTime = null; + + @SerializedName("map") + private Map map = new HashMap(); + + /** + **/ + @ApiModelProperty(value = "") + public String getUuid() { + return uuid; + } + public void setUuid(String uuid) { + this.uuid = uuid; + } + + /** + **/ + @ApiModelProperty(value = "") + public DateTime getDateTime() { + return dateTime; + } + public void setDateTime(DateTime dateTime) { + this.dateTime = dateTime; + } + + /** + **/ + @ApiModelProperty(value = "") + public Map getMap() { + return map; + } + public void setMap(Map map) { + this.map = map; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + MixedPropertiesAndAdditionalPropertiesClass mixedPropertiesAndAdditionalPropertiesClass = (MixedPropertiesAndAdditionalPropertiesClass) o; + return Objects.equals(uuid, mixedPropertiesAndAdditionalPropertiesClass.uuid) && + Objects.equals(dateTime, mixedPropertiesAndAdditionalPropertiesClass.dateTime) && + Objects.equals(map, mixedPropertiesAndAdditionalPropertiesClass.map); + } + + @Override + public int hashCode() { + return Objects.hash(uuid, dateTime, map); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class MixedPropertiesAndAdditionalPropertiesClass {\n"); + + sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); + sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); + sb.append(" map: ").append(toIndentedString(map)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Order.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Order.java index 2f774c13834..569d1c0fe46 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Order.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Order.java @@ -3,7 +3,7 @@ package io.swagger.client.model; import java.util.Objects; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; -import java.util.Date; +import org.joda.time.DateTime; import com.google.gson.annotations.SerializedName; @@ -23,7 +23,7 @@ public class Order { private Integer quantity = null; @SerializedName("shipDate") - private Date shipDate = null; + private DateTime shipDate = null; /** @@ -90,10 +90,10 @@ public class Order { /** **/ @ApiModelProperty(value = "") - public Date getShipDate() { + public DateTime getShipDate() { return shipDate; } - public void setShipDate(Date shipDate) { + public void setShipDate(DateTime shipDate) { this.shipDate = shipDate; } diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/ReadOnlyFirst.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/ReadOnlyFirst.java new file mode 100644 index 00000000000..32e4f515bce --- /dev/null +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/ReadOnlyFirst.java @@ -0,0 +1,78 @@ +package io.swagger.client.model; + +import java.util.Objects; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +import com.google.gson.annotations.SerializedName; + + + + + +public class ReadOnlyFirst { + + @SerializedName("bar") + private String bar = null; + + @SerializedName("baz") + private String baz = null; + + /** + **/ + @ApiModelProperty(value = "") + public String getBar() { + return bar; + } + + /** + **/ + @ApiModelProperty(value = "") + public String getBaz() { + return baz; + } + public void setBaz(String baz) { + this.baz = baz; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ReadOnlyFirst readOnlyFirst = (ReadOnlyFirst) o; + return Objects.equals(bar, readOnlyFirst.bar) && + Objects.equals(baz, readOnlyFirst.baz); + } + + @Override + public int hashCode() { + return Objects.hash(bar, baz); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ReadOnlyFirst {\n"); + + sb.append(" bar: ").append(toIndentedString(bar)).append("\n"); + sb.append(" baz: ").append(toIndentedString(baz)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} diff --git a/samples/client/petstore/java/retrofit2/src/test/java/io/swagger/TestUtils.java b/samples/client/petstore/java/retrofit2/src/test/java/io/swagger/TestUtils.java new file mode 100644 index 00000000000..bf5a476ab29 --- /dev/null +++ b/samples/client/petstore/java/retrofit2/src/test/java/io/swagger/TestUtils.java @@ -0,0 +1,17 @@ +package io.swagger; + +import java.util.Random; +import java.util.concurrent.atomic.AtomicLong; + +public class TestUtils { + private static final AtomicLong atomicId = createAtomicId(); + + public static long nextId() { + return atomicId.getAndIncrement(); + } + + private static AtomicLong createAtomicId() { + int baseId = new Random(System.currentTimeMillis()).nextInt(1000000) + 20000; + return new AtomicLong((long) baseId); + } +} diff --git a/samples/client/petstore/java/retrofit2/src/test/java/io/swagger/client/api/PetApiTest.java b/samples/client/petstore/java/retrofit2/src/test/java/io/swagger/client/api/PetApiTest.java index 39b4dc05ee0..8b554674623 100644 --- a/samples/client/petstore/java/retrofit2/src/test/java/io/swagger/client/api/PetApiTest.java +++ b/samples/client/petstore/java/retrofit2/src/test/java/io/swagger/client/api/PetApiTest.java @@ -1,137 +1,190 @@ package io.swagger.client.api; +import io.swagger.TestUtils; + import io.swagger.client.ApiClient; -import io.swagger.client.model.Pet; -import io.swagger.client.model.ModelApiResponse; +import io.swagger.client.CollectionFormats.*; +import io.swagger.client.api.*; +import io.swagger.client.model.*; + +import java.io.BufferedWriter; import java.io.File; -import org.junit.Before; -import org.junit.Test; - +import java.io.FileWriter; import java.util.ArrayList; -import java.util.HashMap; +import java.util.Arrays; import java.util.List; -import java.util.Map; -/** - * API tests for PetApi - */ +import org.junit.*; + +import retrofit2.Response; + +import okhttp3.MediaType; +import okhttp3.RequestBody; + +import static org.junit.Assert.*; + public class PetApiTest { - - private PetApi api; + PetApi api = null; @Before public void setup() { api = new ApiClient().createService(PetApi.class); } - - /** - * Add a new pet to the store - * - * - */ @Test - public void addPetTest() { - Pet body = null; - // Void response = api.addPet(body); + public void testCreateAndGetPet() throws Exception { + Pet pet = createRandomPet(); + Response rp2 = api.addPet(pet).execute(); - // TODO: test validations + Response rp = api.getPetById(pet.getId()).execute(); + Pet fetched = rp.body(); + assertNotNull(fetched); + assertEquals(pet.getId(), fetched.getId()); + assertNotNull(fetched.getCategory()); + assertEquals(fetched.getCategory().getName(), pet.getCategory().getName()); } - - /** - * Deletes a pet - * - * - */ + @Test - public void deletePetTest() { - Long petId = null; - String apiKey = null; - // Void response = api.deletePet(petId, apiKey); + public void testUpdatePet() throws Exception { + Pet pet = createRandomPet(); + pet.setName("programmer"); - // TODO: test validations + api.updatePet(pet).execute(); + + Pet fetched = api.getPetById(pet.getId()).execute().body(); + assertNotNull(fetched); + assertEquals(pet.getId(), fetched.getId()); + assertNotNull(fetched.getCategory()); + assertEquals(fetched.getCategory().getName(), pet.getCategory().getName()); } - - /** - * Finds Pets by status - * - * Multiple status values can be provided with comma separated strings - */ + @Test - public void findPetsByStatusTest() { - List status = null; - // List response = api.findPetsByStatus(status); + public void testFindPetsByStatus() throws Exception { + Pet pet = createRandomPet(); + pet.setName("programmer"); + pet.setStatus(Pet.StatusEnum.AVAILABLE); - // TODO: test validations + api.updatePet(pet).execute(); + + List pets = api.findPetsByStatus(new CSVParams("available")).execute().body(); + assertNotNull(pets); + + boolean found = false; + for (Pet fetched : pets) { + if (fetched.getId().equals(pet.getId())) { + found = true; + break; + } + } + + assertTrue(found); } - - /** - * Finds Pets by tags - * - * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. - */ + @Test - public void findPetsByTagsTest() { - List tags = null; - // List response = api.findPetsByTags(tags); + public void testFindPetsByTags() throws Exception { + Pet pet = createRandomPet(); + pet.setName("monster"); + pet.setStatus(Pet.StatusEnum.AVAILABLE); - // TODO: test validations + List tags = new ArrayList(); + Tag tag1 = new Tag(); + tag1.setName("friendly"); + tags.add(tag1); + pet.setTags(tags); + + api.updatePet(pet).execute(); + + List pets = api.findPetsByTags(new CSVParams("friendly")).execute().body(); + assertNotNull(pets); + + boolean found = false; + for (Pet fetched : pets) { + if (fetched.getId().equals(pet.getId())) { + found = true; + break; + } + } + assertTrue(found); } - - /** - * Find pet by ID - * - * Returns a single pet - */ + @Test - public void getPetByIdTest() { - Long petId = null; - // Pet response = api.getPetById(petId); + public void testUpdatePetWithForm() throws Exception { + Pet pet = createRandomPet(); + pet.setName("frank"); + api.addPet(pet).execute(); - // TODO: test validations + Pet fetched = api.getPetById(pet.getId()).execute().body(); + + api.updatePetWithForm(fetched.getId(), "furt", null).execute(); + Pet updated = api.getPetById(fetched.getId()).execute().body(); + + assertEquals(updated.getName(), "furt"); } - - /** - * Update an existing pet - * - * - */ + @Test - public void updatePetTest() { - Pet body = null; - // Void response = api.updatePet(body); + public void testDeletePet() throws Exception { + Pet pet = createRandomPet(); + api.addPet(pet).execute(); - // TODO: test validations + Pet fetched = api.getPetById(pet.getId()).execute().body(); + api.deletePet(fetched.getId(), null).execute(); + + assertFalse(api.getPetById(fetched.getId()).execute().isSuccessful()); } - - /** - * Updates a pet in the store with form data - * - * - */ + @Test - public void updatePetWithFormTest() { - Long petId = null; - String name = null; - String status = null; - // Void response = api.updatePetWithForm(petId, name, status); + public void testUploadFile() throws Exception { + Pet pet = createRandomPet(); + api.addPet(pet).execute(); - // TODO: test validations + File file = new File("hello.txt"); + BufferedWriter writer = new BufferedWriter(new FileWriter(file)); + writer.write("Hello world!"); + writer.close(); + + api.uploadFile(pet.getId(), null, RequestBody.create(MediaType.parse("text/plain"), file)).execute(); } - - /** - * uploads an image - * - * - */ + @Test - public void uploadFileTest() { - Long petId = null; - String additionalMetadata = null; - File file = null; - // ModelApiResponse response = api.uploadFile(petId, additionalMetadata, file); + public void testEqualsAndHashCode() { + Pet pet1 = new Pet(); + Pet pet2 = new Pet(); + assertTrue(pet1.equals(pet2)); + assertTrue(pet2.equals(pet1)); + assertTrue(pet1.hashCode() == pet2.hashCode()); + assertTrue(pet1.equals(pet1)); + assertTrue(pet1.hashCode() == pet1.hashCode()); - // TODO: test validations + pet2.setName("really-happy"); + pet2.setPhotoUrls(Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"})); + assertFalse(pet1.equals(pet2)); + assertFalse(pet2.equals(pet1)); + assertFalse(pet1.hashCode() == (pet2.hashCode())); + assertTrue(pet2.equals(pet2)); + assertTrue(pet2.hashCode() == pet2.hashCode()); + + pet1.setName("really-happy"); + pet1.setPhotoUrls(Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"})); + assertTrue(pet1.equals(pet2)); + assertTrue(pet2.equals(pet1)); + assertTrue(pet1.hashCode() == pet2.hashCode()); + assertTrue(pet1.equals(pet1)); + assertTrue(pet1.hashCode() == pet1.hashCode()); + } + + private Pet createRandomPet() { + Pet pet = new Pet(); + pet.setId(TestUtils.nextId()); + pet.setName("gorilla"); + + Category category = new Category(); + category.setName("really-happy"); + + pet.setCategory(category); + pet.setStatus(Pet.StatusEnum.AVAILABLE); + List photos = Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"}); + pet.setPhotoUrls(photos); + + return pet; } - } diff --git a/samples/client/petstore/java/retrofit2/src/test/java/io/swagger/client/api/StoreApiTest.java b/samples/client/petstore/java/retrofit2/src/test/java/io/swagger/client/api/StoreApiTest.java index 1da787edf19..4a8fd9a50bd 100644 --- a/samples/client/petstore/java/retrofit2/src/test/java/io/swagger/client/api/StoreApiTest.java +++ b/samples/client/petstore/java/retrofit2/src/test/java/io/swagger/client/api/StoreApiTest.java @@ -1,77 +1,77 @@ package io.swagger.client.api; -import io.swagger.client.ApiClient; -import io.swagger.client.model.Order; -import org.junit.Before; -import org.junit.Test; +import io.swagger.TestUtils; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; +import io.swagger.client.ApiClient; +import io.swagger.client.api.*; +import io.swagger.client.model.*; + +import java.lang.reflect.Field; import java.util.Map; -/** - * API tests for StoreApi - */ -public class StoreApiTest { +import org.joda.time.DateTime; +import org.joda.time.DateTimeZone; +import org.junit.*; - private StoreApi api; +import retrofit2.Response; +import static org.junit.Assert.*; + +public class StoreApiTest { + StoreApi api = null; @Before public void setup() { api = new ApiClient().createService(StoreApi.class); } - - /** - * Delete purchase order by ID - * - * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors - */ @Test - public void deleteOrderTest() { - String orderId = null; - // Void response = api.deleteOrder(orderId); - - // TODO: test validations + public void testGetInventory() throws Exception { + Map inventory = api.getInventory().execute().body(); + assertTrue(inventory.keySet().size() > 0); } - - /** - * Returns pet inventories by status - * - * Returns a map of status codes to quantities - */ + @Test - public void getInventoryTest() { - // Map response = api.getInventory(); + public void testPlaceOrder() throws Exception { + Order order = createOrder(); + api.placeOrder(order).execute(); - // TODO: test validations + Order fetched = api.getOrderById(order.getId()).execute().body(); + assertEquals(order.getId(), fetched.getId()); + assertEquals(order.getPetId(), fetched.getPetId()); + assertEquals(order.getQuantity(), fetched.getQuantity()); + assertEquals(order.getShipDate().withZone(DateTimeZone.UTC), fetched.getShipDate().withZone(DateTimeZone.UTC)); } - - /** - * Find purchase order by ID - * - * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - */ + @Test - public void getOrderByIdTest() { - Long orderId = null; - // Order response = api.getOrderById(orderId); + public void testDeleteOrder() throws Exception { + Order order = createOrder(); + Response aa = api.placeOrder(order).execute(); - // TODO: test validations - } - - /** - * Place an order for a pet - * - * - */ - @Test - public void placeOrderTest() { - Order body = null; - // Order response = api.placeOrder(body); + Order fetched = api.getOrderById(order.getId()).execute().body(); + assertEquals(fetched.getId(), order.getId()); - // TODO: test validations + api.deleteOrder(String.valueOf(order.getId())).execute(); + + api.getOrderById(order.getId()).execute(); + //also in retrofit 1 should return an error but don't, check server api impl. + } + + private Order createOrder() { + Order order = new Order(); + order.setPetId(new Long(200)); + order.setQuantity(new Integer(13)); + order.setShipDate(DateTime.now()); + order.setStatus(Order.StatusEnum.PLACED); + order.setComplete(true); + + try { + Field idField = Order.class.getDeclaredField("id"); + idField.setAccessible(true); + idField.set(order, TestUtils.nextId()); + } catch (Exception e) { + throw new RuntimeException(e); + } + + return order; } - } diff --git a/samples/client/petstore/java/retrofit2/src/test/java/io/swagger/client/api/UserApiTest.java b/samples/client/petstore/java/retrofit2/src/test/java/io/swagger/client/api/UserApiTest.java index cd8553d8419..70fbb8fef98 100644 --- a/samples/client/petstore/java/retrofit2/src/test/java/io/swagger/client/api/UserApiTest.java +++ b/samples/client/petstore/java/retrofit2/src/test/java/io/swagger/client/api/UserApiTest.java @@ -1,131 +1,86 @@ package io.swagger.client.api; +import io.swagger.TestUtils; + import io.swagger.client.ApiClient; -import io.swagger.client.model.User; -import org.junit.Before; -import org.junit.Test; +import io.swagger.client.api.*; +import io.swagger.client.model.*; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -/** - * API tests for UserApi - */ +import java.util.Arrays; + +import org.junit.*; +import static org.junit.Assert.*; + public class UserApiTest { - - private UserApi api; + UserApi api = null; @Before public void setup() { api = new ApiClient().createService(UserApi.class); } - - /** - * Create user - * - * This can only be done by the logged in user. - */ @Test - public void createUserTest() { - User body = null; - // Void response = api.createUser(body); + public void testCreateUser() throws Exception { + User user = createUser(); - // TODO: test validations + api.createUser(user).execute(); + + User fetched = api.getUserByName(user.getUsername()).execute().body(); + assertEquals(user.getId(), fetched.getId()); } - - /** - * Creates list of users with given input array - * - * - */ + @Test - public void createUsersWithArrayInputTest() { - List body = null; - // Void response = api.createUsersWithArrayInput(body); + public void testCreateUsersWithArray() throws Exception { + User user1 = createUser(); + user1.setUsername("user" + user1.getId()); + User user2 = createUser(); + user2.setUsername("user" + user2.getId()); - // TODO: test validations + api.createUsersWithArrayInput(Arrays.asList(new User[]{user1, user2})).execute(); + + User fetched = api.getUserByName(user1.getUsername()).execute().body(); + assertEquals(user1.getId(), fetched.getId()); } - - /** - * Creates list of users with given input array - * - * - */ + @Test - public void createUsersWithListInputTest() { - List body = null; - // Void response = api.createUsersWithListInput(body); + public void testCreateUsersWithList() throws Exception { + User user1 = createUser(); + user1.setUsername("user" + user1.getId()); + User user2 = createUser(); + user2.setUsername("user" + user2.getId()); - // TODO: test validations + api.createUsersWithListInput(Arrays.asList(new User[]{user1, user2})).execute(); + + User fetched = api.getUserByName(user1.getUsername()).execute().body(); + assertEquals(user1.getId(), fetched.getId()); } - - /** - * Delete user - * - * This can only be done by the logged in user. - */ + @Test - public void deleteUserTest() { - String username = null; - // Void response = api.deleteUser(username); + public void testLoginUser() throws Exception { + User user = createUser(); + api.createUser(user).execute(); - // TODO: test validations + String token = api.loginUser(user.getUsername(), user.getPassword()).execute().body(); + assertTrue(token.startsWith("logged in user session:")); } - - /** - * Get user by user name - * - * - */ + @Test - public void getUserByNameTest() { - String username = null; - // User response = api.getUserByName(username); - - // TODO: test validations + public void logoutUser() throws Exception { + api.logoutUser().execute(); } - - /** - * Logs user into the system - * - * - */ - @Test - public void loginUserTest() { - String username = null; - String password = null; - // String response = api.loginUser(username, password); - // TODO: test validations - } - - /** - * Logs out current logged in user session - * - * - */ - @Test - public void logoutUserTest() { - // Void response = api.logoutUser(); + private User createUser() { + User user = new User(); + user.setId(TestUtils.nextId()); + user.setUsername("fred"); + user.setFirstName("Fred"); + user.setLastName("Meyer"); + user.setEmail("fred@fredmeyer.com"); + user.setPassword("xxXXxx"); + user.setPhone("408-867-5309"); + user.setUserStatus(123); - // TODO: test validations + return user; } - - /** - * Updated user - * - * This can only be done by the logged in user. - */ - @Test - public void updateUserTest() { - String username = null; - User body = null; - // Void response = api.updateUser(username, body); - - // TODO: test validations - } - } diff --git a/samples/client/petstore/java/retrofit2rx/.swagger-codegen-ignore b/samples/client/petstore/java/retrofit2rx/.swagger-codegen-ignore new file mode 100644 index 00000000000..19d3377182e --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/.swagger-codegen-ignore @@ -0,0 +1,23 @@ +# Swagger Codegen Ignore +# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell Swagger Codgen to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# Thsi matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/client/petstore/java/retrofit2rx/LICENSE b/samples/client/petstore/java/retrofit2rx/LICENSE new file mode 100644 index 00000000000..8dada3edaf5 --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/samples/client/petstore/java/retrofit2rx/build.gradle b/samples/client/petstore/java/retrofit2rx/build.gradle index cbd0119e24b..8d9fa82e69a 100644 --- a/samples/client/petstore/java/retrofit2rx/build.gradle +++ b/samples/client/petstore/java/retrofit2rx/build.gradle @@ -99,7 +99,7 @@ ext { swagger_annotations_version = "1.5.8" junit_version = "4.12" rx_java_version = "1.1.3" - + jodatime_version = "2.9.3" } dependencies { @@ -108,10 +108,9 @@ dependencies { compile "com.squareup.retrofit2:converter-gson:$retrofit_version" compile "com.squareup.retrofit2:adapter-rxjava:$retrofit_version" compile "io.reactivex:rxjava:$rx_java_version" - - compile "io.swagger:swagger-annotations:$swagger_annotations_version" compile "org.apache.oltu.oauth2:org.apache.oltu.oauth2.client:$oltu_version" + compile "joda-time:joda-time:$jodatime_version" testCompile "junit:junit:$junit_version" } diff --git a/samples/client/petstore/java/retrofit2rx/build.sbt b/samples/client/petstore/java/retrofit2rx/build.sbt new file mode 100644 index 00000000000..3e999d082e0 --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/build.sbt @@ -0,0 +1,23 @@ +lazy val root = (project in file(".")). + settings( + organization := "io.swagger", + name := "swagger-petstore-retrofit2-rx", + version := "1.0.0", + scalaVersion := "2.11.4", + scalacOptions ++= Seq("-feature"), + javacOptions in compile ++= Seq("-Xlint:deprecation"), + publishArtifact in (Compile, packageDoc) := false, + resolvers += Resolver.mavenLocal, + libraryDependencies ++= Seq( + "com.squareup.retrofit2" % "retrofit" % "2.0.2" % "compile", + "com.squareup.retrofit2" % "converter-scalars" % "2.0.2" % "compile", + "com.squareup.retrofit2" % "converter-gson" % "2.0.2" % "compile", + "com.squareup.retrofit2" % "adapter-rxjava" % "2.0.2" % "compile", + "io.reactivex" % "rxjava" % "1.1.3" % "compile", + "io.swagger" % "swagger-annotations" % "1.5.8" % "compile", + "org.apache.oltu.oauth2" % "org.apache.oltu.oauth2.client" % "1.0.1" % "compile", + "joda-time" % "joda-time" % "2.9.3" % "compile", + "junit" % "junit" % "4.12" % "test", + "com.novocode" % "junit-interface" % "0.10" % "test" + ) + ) diff --git a/samples/client/petstore/java/retrofit2rx/docs/AdditionalPropertiesClass.md b/samples/client/petstore/java/retrofit2rx/docs/AdditionalPropertiesClass.md index c72785d450f..0437c4dd8cc 100644 --- a/samples/client/petstore/java/retrofit2rx/docs/AdditionalPropertiesClass.md +++ b/samples/client/petstore/java/retrofit2rx/docs/AdditionalPropertiesClass.md @@ -4,6 +4,8 @@ ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- +**mapProperty** | **Map<String, String>** | | [optional] +**mapOfMapProperty** | [**Map<String, Map<String, String>>**](Map.md) | | [optional] diff --git a/samples/client/petstore/java/retrofit2rx/docs/ArrayTest.md b/samples/client/petstore/java/retrofit2rx/docs/ArrayTest.md index 73c3e5305ad..9feee16427f 100644 --- a/samples/client/petstore/java/retrofit2rx/docs/ArrayTest.md +++ b/samples/client/petstore/java/retrofit2rx/docs/ArrayTest.md @@ -4,6 +4,9 @@ ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- +**arrayOfString** | **List<String>** | | [optional] +**arrayArrayOfInteger** | [**List<List<Long>>**](List.md) | | [optional] +**arrayArrayOfModel** | [**List<List<ReadOnlyFirst>>**](List.md) | | [optional] diff --git a/samples/client/petstore/java/retrofit2rx/docs/FakeApi.md b/samples/client/petstore/java/retrofit2rx/docs/FakeApi.md index 55f7cef2df4..e077fa5c821 100644 --- a/samples/client/petstore/java/retrofit2rx/docs/FakeApi.md +++ b/samples/client/petstore/java/retrofit2rx/docs/FakeApi.md @@ -32,8 +32,8 @@ 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 +LocalDate date = new LocalDate(); // LocalDate | None +DateTime dateTime = new DateTime(); // DateTime | None String password = "password_example"; // String | None try { Void result = apiInstance.testEndpointParameters(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password); @@ -57,8 +57,8 @@ Name | Type | Description | Notes **int64** | **Long**| None | [optional] **_float** | **Float**| None | [optional] **binary** | **byte[]**| None | [optional] - **date** | **Date**| None | [optional] - **dateTime** | **Date**| None | [optional] + **date** | **LocalDate**| None | [optional] + **dateTime** | **DateTime**| None | [optional] **password** | **String**| None | [optional] ### Return type diff --git a/samples/client/petstore/java/retrofit2rx/docs/FormatTest.md b/samples/client/petstore/java/retrofit2rx/docs/FormatTest.md index dc2b559dad2..44de7d9511a 100644 --- a/samples/client/petstore/java/retrofit2rx/docs/FormatTest.md +++ b/samples/client/petstore/java/retrofit2rx/docs/FormatTest.md @@ -13,8 +13,8 @@ Name | Type | Description | Notes **string** | **String** | | [optional] **_byte** | **byte[]** | | **binary** | **byte[]** | | [optional] -**date** | [**Date**](Date.md) | | -**dateTime** | [**Date**](Date.md) | | [optional] +**date** | [**LocalDate**](LocalDate.md) | | +**dateTime** | [**DateTime**](DateTime.md) | | [optional] **uuid** | **String** | | [optional] **password** | **String** | | diff --git a/samples/client/petstore/java/retrofit2rx/docs/MixedPropertiesAndAdditionalPropertiesClass.md b/samples/client/petstore/java/retrofit2rx/docs/MixedPropertiesAndAdditionalPropertiesClass.md index fcdbd390517..e3487bcc501 100644 --- a/samples/client/petstore/java/retrofit2rx/docs/MixedPropertiesAndAdditionalPropertiesClass.md +++ b/samples/client/petstore/java/retrofit2rx/docs/MixedPropertiesAndAdditionalPropertiesClass.md @@ -5,7 +5,8 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **uuid** | **String** | | [optional] -**dateTime** | [**Date**](Date.md) | | [optional] +**dateTime** | [**DateTime**](DateTime.md) | | [optional] +**map** | [**Map<String, Animal>**](Animal.md) | | [optional] diff --git a/samples/client/petstore/java/retrofit2rx/docs/Order.md b/samples/client/petstore/java/retrofit2rx/docs/Order.md index 29ca3ddbc6b..a1089f5384e 100644 --- a/samples/client/petstore/java/retrofit2rx/docs/Order.md +++ b/samples/client/petstore/java/retrofit2rx/docs/Order.md @@ -7,7 +7,7 @@ Name | Type | Description | Notes **id** | **Long** | | [optional] **petId** | **Long** | | [optional] **quantity** | **Integer** | | [optional] -**shipDate** | [**Date**](Date.md) | | [optional] +**shipDate** | [**DateTime**](DateTime.md) | | [optional] **status** | [**StatusEnum**](#StatusEnum) | Order Status | [optional] **complete** | **Boolean** | | [optional] diff --git a/samples/client/petstore/java/retrofit2rx/gradle/wrapper/gradle-wrapper.properties b/samples/client/petstore/java/retrofit2rx/gradle/wrapper/gradle-wrapper.properties index d28218b9a14..b7a36473955 100644 --- a/samples/client/petstore/java/retrofit2rx/gradle/wrapper/gradle-wrapper.properties +++ b/samples/client/petstore/java/retrofit2rx/gradle/wrapper/gradle-wrapper.properties @@ -1,4 +1,4 @@ -#Tue May 17 23:05:31 CST 2016 +#Tue May 17 23:08:05 CST 2016 distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME diff --git a/samples/client/petstore/java/retrofit2rx/pom.xml b/samples/client/petstore/java/retrofit2rx/pom.xml index 79d826c3a41..322fd209415 100644 --- a/samples/client/petstore/java/retrofit2rx/pom.xml +++ b/samples/client/petstore/java/retrofit2rx/pom.xml @@ -132,6 +132,11 @@ org.apache.oltu.oauth2.client ${oltu-version} + + joda-time + joda-time + ${jodatime-version} + io.reactivex rxjava @@ -155,7 +160,7 @@ 1.5.8 2.0.2 1.1.3 - 3.2.0 + 2.9.3 1.0.1 1.0.0 4.12 diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/ApiClient.java index 32799fdf3d8..9e424881cbd 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/ApiClient.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/ApiClient.java @@ -9,6 +9,10 @@ import java.util.Map; import org.apache.oltu.oauth2.client.request.OAuthClientRequest.AuthenticationRequestBuilder; import org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuilder; +import org.joda.time.DateTime; +import org.joda.time.LocalDate; +import org.joda.time.format.DateTimeFormatter; +import org.joda.time.format.ISODateTimeFormat; import retrofit2.Converter; import retrofit2.Retrofit; @@ -19,6 +23,9 @@ import retrofit2.converter.scalars.ScalarsConverterFactory; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; import okhttp3.Interceptor; import okhttp3.OkHttpClient; import okhttp3.RequestBody; @@ -107,6 +114,8 @@ public class ApiClient { public void createDefaultAdapter() { Gson gson = new GsonBuilder() .setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ") + .registerTypeAdapter(DateTime.class, new DateTimeTypeAdapter()) + .registerTypeAdapter(LocalDate.class, new LocalDateTypeAdapter()) .create(); okClient = new OkHttpClient(); @@ -345,3 +354,58 @@ class GsonCustomConverterFactory extends Converter.Factory } } + +/** + * Gson TypeAdapter for Joda DateTime type + */ +class DateTimeTypeAdapter extends TypeAdapter { + + private final DateTimeFormatter formatter = ISODateTimeFormat.dateTime(); + + @Override + public void write(JsonWriter out, DateTime date) throws IOException { + if (date == null) { + out.nullValue(); + } else { + out.value(formatter.print(date)); + } + } + + @Override + public DateTime read(JsonReader in) throws IOException { + switch (in.peek()) { + case NULL: + in.nextNull(); + return null; + default: + String date = in.nextString(); + return formatter.parseDateTime(date); + } + } +} + +class LocalDateTypeAdapter extends TypeAdapter { + + private final DateTimeFormatter formatter = ISODateTimeFormat.date(); + + @Override + public void write(JsonWriter out, LocalDate date) throws IOException { + if (date == null) { + out.nullValue(); + } else { + out.value(formatter.print(date)); + } + } + + @Override + public LocalDate read(JsonReader in) throws IOException { + switch (in.peek()) { + case NULL: + in.nextNull(); + return null; + default: + String date = in.nextString(); + return formatter.parseLocalDate(date); + } + } +} \ No newline at end of file diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/StringUtil.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/StringUtil.java index 4f33efd8991..03c6c81e434 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/StringUtil.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/StringUtil.java @@ -1,6 +1,31 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-17T10:34:31.551+02:00") + public class StringUtil { /** * Check if the given array contains the given value (with case-insensitive comparison). diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/FakeApi.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/FakeApi.java index cc0d5605548..5e0511922fb 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/FakeApi.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/FakeApi.java @@ -8,8 +8,9 @@ import retrofit2.http.*; import okhttp3.RequestBody; +import org.joda.time.LocalDate; import java.math.BigDecimal; -import java.util.Date; +import org.joda.time.DateTime; import java.util.ArrayList; import java.util.HashMap; @@ -38,7 +39,7 @@ public interface FakeApi { @FormUrlEncoded @POST("fake") Observable testEndpointParameters( - @Field("number") BigDecimal number, @Field("double") Double _double, @Field("string") String string, @Field("byte") byte[] _byte, @Field("integer") Integer integer, @Field("int32") Integer int32, @Field("int64") Long int64, @Field("float") Float _float, @Field("binary") byte[] binary, @Field("date") 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") LocalDate date, @Field("dateTime") DateTime dateTime, @Field("password") String password ); } diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/auth/OAuthFlow.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/auth/OAuthFlow.java index 597ec99b48b..ec1f942b0f2 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/auth/OAuthFlow.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/auth/OAuthFlow.java @@ -1,5 +1,30 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.client.auth; public enum OAuthFlow { accessCode, implicit, password, application -} \ No newline at end of file +} diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java new file mode 100644 index 00000000000..839b04aa6c5 --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java @@ -0,0 +1,84 @@ +package io.swagger.client.model; + +import java.util.Objects; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import com.google.gson.annotations.SerializedName; + + + + + +public class AdditionalPropertiesClass { + + @SerializedName("map_property") + private Map mapProperty = new HashMap(); + + @SerializedName("map_of_map_property") + private Map> mapOfMapProperty = new HashMap>(); + + /** + **/ + @ApiModelProperty(value = "") + public Map getMapProperty() { + return mapProperty; + } + public void setMapProperty(Map mapProperty) { + this.mapProperty = mapProperty; + } + + /** + **/ + @ApiModelProperty(value = "") + public Map> getMapOfMapProperty() { + return mapOfMapProperty; + } + public void setMapOfMapProperty(Map> mapOfMapProperty) { + this.mapOfMapProperty = mapOfMapProperty; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + AdditionalPropertiesClass additionalPropertiesClass = (AdditionalPropertiesClass) o; + return Objects.equals(mapProperty, additionalPropertiesClass.mapProperty) && + Objects.equals(mapOfMapProperty, additionalPropertiesClass.mapOfMapProperty); + } + + @Override + public int hashCode() { + return Objects.hash(mapProperty, mapOfMapProperty); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class AdditionalPropertiesClass {\n"); + + sb.append(" mapProperty: ").append(toIndentedString(mapProperty)).append("\n"); + sb.append(" mapOfMapProperty: ").append(toIndentedString(mapOfMapProperty)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/ArrayTest.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/ArrayTest.java new file mode 100644 index 00000000000..92337cc0246 --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/ArrayTest.java @@ -0,0 +1,98 @@ +package io.swagger.client.model; + +import java.util.Objects; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.util.ArrayList; +import java.util.List; + +import com.google.gson.annotations.SerializedName; + + + + + +public class ArrayTest { + + @SerializedName("array_of_string") + private List arrayOfString = new ArrayList(); + + @SerializedName("array_array_of_integer") + private List> arrayArrayOfInteger = new ArrayList>(); + + @SerializedName("array_array_of_model") + private List> arrayArrayOfModel = new ArrayList>(); + + /** + **/ + @ApiModelProperty(value = "") + public List getArrayOfString() { + return arrayOfString; + } + public void setArrayOfString(List arrayOfString) { + this.arrayOfString = arrayOfString; + } + + /** + **/ + @ApiModelProperty(value = "") + public List> getArrayArrayOfInteger() { + return arrayArrayOfInteger; + } + public void setArrayArrayOfInteger(List> arrayArrayOfInteger) { + this.arrayArrayOfInteger = arrayArrayOfInteger; + } + + /** + **/ + @ApiModelProperty(value = "") + public List> getArrayArrayOfModel() { + return arrayArrayOfModel; + } + public void setArrayArrayOfModel(List> arrayArrayOfModel) { + this.arrayArrayOfModel = arrayArrayOfModel; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ArrayTest arrayTest = (ArrayTest) o; + return Objects.equals(arrayOfString, arrayTest.arrayOfString) && + Objects.equals(arrayArrayOfInteger, arrayTest.arrayArrayOfInteger) && + Objects.equals(arrayArrayOfModel, arrayTest.arrayArrayOfModel); + } + + @Override + public int hashCode() { + return Objects.hash(arrayOfString, arrayArrayOfInteger, arrayArrayOfModel); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ArrayTest {\n"); + + sb.append(" arrayOfString: ").append(toIndentedString(arrayOfString)).append("\n"); + sb.append(" arrayArrayOfInteger: ").append(toIndentedString(arrayArrayOfInteger)).append("\n"); + sb.append(" arrayArrayOfModel: ").append(toIndentedString(arrayArrayOfModel)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} diff --git a/samples/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 694335531fd..6063cf33f77 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 @@ -4,7 +4,8 @@ import java.util.Objects; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.math.BigDecimal; -import java.util.Date; +import org.joda.time.DateTime; +import org.joda.time.LocalDate; import com.google.gson.annotations.SerializedName; @@ -42,10 +43,10 @@ public class FormatTest { private byte[] binary = null; @SerializedName("date") - private Date date = null; + private LocalDate date = null; @SerializedName("dateTime") - private Date dateTime = null; + private DateTime dateTime = null; @SerializedName("uuid") private String uuid = null; @@ -156,20 +157,20 @@ public class FormatTest { /** **/ @ApiModelProperty(required = true, value = "") - public Date getDate() { + public LocalDate getDate() { return date; } - public void setDate(Date date) { + public void setDate(LocalDate date) { this.date = date; } /** **/ @ApiModelProperty(value = "") - public Date getDateTime() { + public DateTime getDateTime() { return dateTime; } - public void setDateTime(Date dateTime) { + public void setDateTime(DateTime dateTime) { this.dateTime = dateTime; } diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java new file mode 100644 index 00000000000..cf7f73c705f --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -0,0 +1,101 @@ +package io.swagger.client.model; + +import java.util.Objects; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.client.model.Animal; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.joda.time.DateTime; + +import com.google.gson.annotations.SerializedName; + + + + + +public class MixedPropertiesAndAdditionalPropertiesClass { + + @SerializedName("uuid") + private String uuid = null; + + @SerializedName("dateTime") + private DateTime dateTime = null; + + @SerializedName("map") + private Map map = new HashMap(); + + /** + **/ + @ApiModelProperty(value = "") + public String getUuid() { + return uuid; + } + public void setUuid(String uuid) { + this.uuid = uuid; + } + + /** + **/ + @ApiModelProperty(value = "") + public DateTime getDateTime() { + return dateTime; + } + public void setDateTime(DateTime dateTime) { + this.dateTime = dateTime; + } + + /** + **/ + @ApiModelProperty(value = "") + public Map getMap() { + return map; + } + public void setMap(Map map) { + this.map = map; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + MixedPropertiesAndAdditionalPropertiesClass mixedPropertiesAndAdditionalPropertiesClass = (MixedPropertiesAndAdditionalPropertiesClass) o; + return Objects.equals(uuid, mixedPropertiesAndAdditionalPropertiesClass.uuid) && + Objects.equals(dateTime, mixedPropertiesAndAdditionalPropertiesClass.dateTime) && + Objects.equals(map, mixedPropertiesAndAdditionalPropertiesClass.map); + } + + @Override + public int hashCode() { + return Objects.hash(uuid, dateTime, map); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class MixedPropertiesAndAdditionalPropertiesClass {\n"); + + sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); + sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); + sb.append(" map: ").append(toIndentedString(map)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Order.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Order.java index 2f774c13834..569d1c0fe46 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Order.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Order.java @@ -3,7 +3,7 @@ package io.swagger.client.model; import java.util.Objects; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; -import java.util.Date; +import org.joda.time.DateTime; import com.google.gson.annotations.SerializedName; @@ -23,7 +23,7 @@ public class Order { private Integer quantity = null; @SerializedName("shipDate") - private Date shipDate = null; + private DateTime shipDate = null; /** @@ -90,10 +90,10 @@ public class Order { /** **/ @ApiModelProperty(value = "") - public Date getShipDate() { + public DateTime getShipDate() { return shipDate; } - public void setShipDate(Date shipDate) { + public void setShipDate(DateTime shipDate) { this.shipDate = shipDate; } diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/ReadOnlyFirst.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/ReadOnlyFirst.java new file mode 100644 index 00000000000..32e4f515bce --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/ReadOnlyFirst.java @@ -0,0 +1,78 @@ +package io.swagger.client.model; + +import java.util.Objects; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +import com.google.gson.annotations.SerializedName; + + + + + +public class ReadOnlyFirst { + + @SerializedName("bar") + private String bar = null; + + @SerializedName("baz") + private String baz = null; + + /** + **/ + @ApiModelProperty(value = "") + public String getBar() { + return bar; + } + + /** + **/ + @ApiModelProperty(value = "") + public String getBaz() { + return baz; + } + public void setBaz(String baz) { + this.baz = baz; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ReadOnlyFirst readOnlyFirst = (ReadOnlyFirst) o; + return Objects.equals(bar, readOnlyFirst.bar) && + Objects.equals(baz, readOnlyFirst.baz); + } + + @Override + public int hashCode() { + return Objects.hash(bar, baz); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ReadOnlyFirst {\n"); + + sb.append(" bar: ").append(toIndentedString(bar)).append("\n"); + sb.append(" baz: ").append(toIndentedString(baz)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} diff --git a/samples/client/petstore/java/retrofit2rx/src/test/java/io/swagger/client/api/PetApiTest.java b/samples/client/petstore/java/retrofit2rx/src/test/java/io/swagger/client/api/PetApiTest.java index 39b4dc05ee0..8fa02bed636 100644 --- a/samples/client/petstore/java/retrofit2rx/src/test/java/io/swagger/client/api/PetApiTest.java +++ b/samples/client/petstore/java/retrofit2rx/src/test/java/io/swagger/client/api/PetApiTest.java @@ -1,137 +1,254 @@ package io.swagger.client.api; import io.swagger.client.ApiClient; -import io.swagger.client.model.Pet; -import io.swagger.client.model.ModelApiResponse; +import io.swagger.client.CollectionFormats.*; +import io.swagger.client.model.*; + +import java.io.BufferedWriter; import java.io.File; -import org.junit.Before; -import org.junit.Test; - +import java.io.FileWriter; import java.util.ArrayList; -import java.util.HashMap; +import java.util.Arrays; import java.util.List; -import java.util.Map; -/** - * API tests for PetApi - */ +import org.junit.*; + +import okhttp3.MediaType; +import okhttp3.RequestBody; + +import static org.junit.Assert.*; + public class PetApiTest { - - private PetApi api; + PetApi api = null; @Before public void setup() { api = new ApiClient().createService(PetApi.class); } - - /** - * Add a new pet to the store - * - * - */ @Test - public void addPetTest() { - Pet body = null; - // Void response = api.addPet(body); + public void testCreateAndGetPet() throws Exception { + final Pet pet = createRandomPet(); + api.addPet(pet).subscribe(new SkeletonSubscriber() { + @Override + public void onCompleted() { + api.getPetById(pet.getId()).subscribe(new SkeletonSubscriber() { + @Override + public void onNext(Pet fetched) { + assertNotNull(fetched); + assertEquals(pet.getId(), fetched.getId()); + assertNotNull(fetched.getCategory()); + assertEquals(fetched.getCategory().getName(), pet.getCategory().getName()); + } + }); + + } + }); - // TODO: test validations } - - /** - * Deletes a pet - * - * - */ + @Test - public void deletePetTest() { - Long petId = null; - String apiKey = null; - // Void response = api.deletePet(petId, apiKey); + public void testUpdatePet() throws Exception { + final Pet pet = createRandomPet(); + pet.setName("programmer"); + + api.updatePet(pet).subscribe(new SkeletonSubscriber() { + @Override + public void onCompleted() { + api.getPetById(pet.getId()).subscribe(new SkeletonSubscriber() { + @Override + public void onNext(Pet fetched) { + assertNotNull(fetched); + assertEquals(pet.getId(), fetched.getId()); + assertNotNull(fetched.getCategory()); + assertEquals(fetched.getCategory().getName(), pet.getCategory().getName()); + } + }); + + } + }); - // TODO: test validations } - - /** - * Finds Pets by status - * - * Multiple status values can be provided with comma separated strings - */ + @Test - public void findPetsByStatusTest() { - List status = null; - // List response = api.findPetsByStatus(status); + public void testFindPetsByStatus() throws Exception { + final Pet pet = createRandomPet(); + pet.setName("programmer"); + pet.setStatus(Pet.StatusEnum.AVAILABLE); + + api.updatePet(pet).subscribe(new SkeletonSubscriber() { + @Override + public void onCompleted() { + api.findPetsByStatus(new CSVParams("available")).subscribe(new SkeletonSubscriber>() { + @Override + public void onNext(List pets) { + assertNotNull(pets); + + boolean found = false; + for (Pet fetched : pets) { + if (fetched.getId().equals(pet.getId())) { + found = true; + break; + } + } + + assertTrue(found); + } + }); + + } + }); - // TODO: test validations } - - /** - * Finds Pets by tags - * - * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. - */ + @Test - public void findPetsByTagsTest() { - List tags = null; - // List response = api.findPetsByTags(tags); + public void testFindPetsByTags() throws Exception { + final Pet pet = createRandomPet(); + pet.setName("monster"); + pet.setStatus(Pet.StatusEnum.AVAILABLE); + + List tags = new ArrayList(); + Tag tag1 = new Tag(); + tag1.setName("friendly"); + tags.add(tag1); + pet.setTags(tags); + + api.updatePet(pet).subscribe(new SkeletonSubscriber() { + @Override + public void onCompleted() { + api.findPetsByTags(new CSVParams("friendly")).subscribe(new SkeletonSubscriber>() { + @Override + public void onNext(List pets) { + assertNotNull(pets); + + boolean found = false; + for (Pet fetched : pets) { + if (fetched.getId().equals(pet.getId())) { + found = true; + break; + } + } + assertTrue(found); + } + }); + + } + }); - // TODO: test validations } - - /** - * Find pet by ID - * - * Returns a single pet - */ + @Test - public void getPetByIdTest() { - Long petId = null; - // Pet response = api.getPetById(petId); + public void testUpdatePetWithForm() throws Exception { + final Pet pet = createRandomPet(); + pet.setName("frank"); + api.addPet(pet).subscribe(SkeletonSubscriber.failTestOnError()); + api.getPetById(pet.getId()).subscribe(new SkeletonSubscriber() { + @Override + public void onNext(final Pet fetched) { + api.updatePetWithForm(fetched.getId(), "furt", null) + .subscribe(new SkeletonSubscriber() { + @Override + public void onCompleted() { + api.getPetById(fetched.getId()).subscribe(new SkeletonSubscriber() { + @Override + public void onNext(Pet updated) { + assertEquals(updated.getName(), "furt"); + } + }); + + } + }); + } + }); + - // TODO: test validations } - - /** - * Update an existing pet - * - * - */ + @Test - public void updatePetTest() { - Pet body = null; - // Void response = api.updatePet(body); + public void testDeletePet() throws Exception { + Pet pet = createRandomPet(); + api.addPet(pet).subscribe(SkeletonSubscriber.failTestOnError()); - // TODO: test validations + api.getPetById(pet.getId()).subscribe(new SkeletonSubscriber() { + @Override + public void onNext(Pet fetched) { + + api.deletePet(fetched.getId(), null).subscribe(SkeletonSubscriber.failTestOnError()); + api.getPetById(fetched.getId()).subscribe(new SkeletonSubscriber() { + @Override + public void onNext(Pet deletedPet) { + fail("Should not have found deleted pet."); + } + + @Override + public void onError(Throwable e) { + // expected, because the pet has been deleted. + } + }); + } + }); } - - /** - * Updates a pet in the store with form data - * - * - */ + @Test - public void updatePetWithFormTest() { - Long petId = null; - String name = null; - String status = null; - // Void response = api.updatePetWithForm(petId, name, status); + public void testUploadFile() throws Exception { + File file = File.createTempFile("test", "hello.txt"); + BufferedWriter writer = new BufferedWriter(new FileWriter(file)); - // TODO: test validations + writer.write("Hello world!"); + writer.close(); + + Pet pet = createRandomPet(); + api.addPet(pet).subscribe(SkeletonSubscriber.failTestOnError()); + + RequestBody body = RequestBody.create(MediaType.parse("text/plain"), file); + api.uploadFile(pet.getId(), "a test file", body).subscribe(new SkeletonSubscriber() { + @Override + public void onError(Throwable e) { + // this also yields a 400 for other tests, so I guess it's okay... + } + }); } - - /** - * uploads an image - * - * - */ + @Test - public void uploadFileTest() { - Long petId = null; - String additionalMetadata = null; - File file = null; - // ModelApiResponse response = api.uploadFile(petId, additionalMetadata, file); + public void testEqualsAndHashCode() { + Pet pet1 = new Pet(); + Pet pet2 = new Pet(); + assertTrue(pet1.equals(pet2)); + assertTrue(pet2.equals(pet1)); + assertTrue(pet1.hashCode() == pet2.hashCode()); + assertTrue(pet1.equals(pet1)); + assertTrue(pet1.hashCode() == pet1.hashCode()); - // TODO: test validations + pet2.setName("really-happy"); + pet2.setPhotoUrls(Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"})); + assertFalse(pet1.equals(pet2)); + assertFalse(pet2.equals(pet1)); + assertFalse(pet1.hashCode() == (pet2.hashCode())); + assertTrue(pet2.equals(pet2)); + assertTrue(pet2.hashCode() == pet2.hashCode()); + + pet1.setName("really-happy"); + pet1.setPhotoUrls(Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"})); + assertTrue(pet1.equals(pet2)); + assertTrue(pet2.equals(pet1)); + assertTrue(pet1.hashCode() == pet2.hashCode()); + assertTrue(pet1.equals(pet1)); + assertTrue(pet1.hashCode() == pet1.hashCode()); + } + + private Pet createRandomPet() { + Pet pet = new Pet(); + pet.setId(System.currentTimeMillis()); + pet.setName("gorilla"); + + Category category = new Category(); + category.setName("really-happy"); + + pet.setCategory(category); + pet.setStatus(Pet.StatusEnum.AVAILABLE); + List photos = Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"}); + pet.setPhotoUrls(photos); + + return pet; } - } diff --git a/samples/client/petstore/java/retrofit2rx/src/test/java/io/swagger/client/api/SkeletonSubscriber.java b/samples/client/petstore/java/retrofit2rx/src/test/java/io/swagger/client/api/SkeletonSubscriber.java new file mode 100644 index 00000000000..47d0df05e28 --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/src/test/java/io/swagger/client/api/SkeletonSubscriber.java @@ -0,0 +1,30 @@ +package io.swagger.client.api; + +import junit.framework.TestFailure; +import rx.Subscriber; + +/** + * Skeleton subscriber for tests that will fail when onError() is called unexpectedly. + */ +public abstract class SkeletonSubscriber extends Subscriber { + + public static SkeletonSubscriber failTestOnError() { + return new SkeletonSubscriber() { + }; + } + + @Override + public void onCompleted() { + // space for rent + } + + @Override + public void onNext(T t) { + // space for rent + } + + @Override + public void onError(Throwable e) { + throw new RuntimeException("Subscriber onError() called with unhandled exception!", e); + } +} diff --git a/samples/client/petstore/java/retrofit2rx/src/test/java/io/swagger/client/api/StoreApiTest.java b/samples/client/petstore/java/retrofit2rx/src/test/java/io/swagger/client/api/StoreApiTest.java index 1da787edf19..62f1b194766 100644 --- a/samples/client/petstore/java/retrofit2rx/src/test/java/io/swagger/client/api/StoreApiTest.java +++ b/samples/client/petstore/java/retrofit2rx/src/test/java/io/swagger/client/api/StoreApiTest.java @@ -1,77 +1,98 @@ package io.swagger.client.api; import io.swagger.client.ApiClient; -import io.swagger.client.model.Order; -import org.junit.Before; -import org.junit.Test; +import io.swagger.client.model.*; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; +import java.lang.reflect.Field; import java.util.Map; -/** - * API tests for StoreApi - */ -public class StoreApiTest { +import org.joda.time.DateTime; +import org.joda.time.DateTimeZone; +import org.junit.*; - private StoreApi api; +import retrofit2.Response; + +import static org.junit.Assert.*; + +public class StoreApiTest { + StoreApi api = null; @Before public void setup() { api = new ApiClient().createService(StoreApi.class); } - - /** - * Delete purchase order by ID - * - * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors - */ @Test - public void deleteOrderTest() { - String orderId = null; - // Void response = api.deleteOrder(orderId); + public void testGetInventory() throws Exception { + api.getInventory().subscribe(new SkeletonSubscriber>() { + @Override + public void onNext(Map inventory) { + assertTrue(inventory.keySet().size() > 0); + } + }); - // TODO: test validations } - - /** - * Returns pet inventories by status - * - * Returns a map of status codes to quantities - */ + @Test - public void getInventoryTest() { - // Map response = api.getInventory(); - - // TODO: test validations + public void testPlaceOrder() throws Exception { + final Order order = createOrder(); + api.placeOrder(order).subscribe(SkeletonSubscriber.failTestOnError()); + api.getOrderById(order.getId()).subscribe(new SkeletonSubscriber() { + @Override + public void onNext(Order fetched) { + assertEquals(order.getId(), fetched.getId()); + assertEquals(order.getPetId(), fetched.getPetId()); + assertEquals(order.getQuantity(), fetched.getQuantity()); + assertEquals(order.getShipDate().withZone(DateTimeZone.UTC), fetched.getShipDate().withZone(DateTimeZone.UTC)); + } + }); } - - /** - * Find purchase order by ID - * - * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - */ + @Test - public void getOrderByIdTest() { - Long orderId = null; - // Order response = api.getOrderById(orderId); + public void testDeleteOrder() throws Exception { + final Order order = createOrder(); + api.placeOrder(order).subscribe(SkeletonSubscriber.failTestOnError()); - // TODO: test validations - } - - /** - * Place an order for a pet - * - * - */ - @Test - public void placeOrderTest() { - Order body = null; - // Order response = api.placeOrder(body); + api.getOrderById(order.getId()).subscribe(new SkeletonSubscriber() { + @Override + public void onNext(Order fetched) { + assertEquals(fetched.getId(), order.getId()); + } + }); - // TODO: test validations + + api.deleteOrder(String.valueOf(order.getId())).subscribe(SkeletonSubscriber.failTestOnError()); + api.getOrderById(order.getId()) + .subscribe(new SkeletonSubscriber() { + @Override + public void onNext(Order order) { + throw new RuntimeException("Should not have found deleted order."); + } + + @Override + public void onError(Throwable e) { + // should not find deleted order. + } + } + ); + } + + private Order createOrder() { + Order order = new Order(); + order.setPetId(new Long(200)); + order.setQuantity(new Integer(13)); + order.setShipDate(DateTime.now()); + order.setStatus(Order.StatusEnum.PLACED); + order.setComplete(true); + + try { + Field idField = Order.class.getDeclaredField("id"); + idField.setAccessible(true); + idField.set(order, System.currentTimeMillis()); + } catch (Exception e) { + throw new RuntimeException(e); + } + + return order; } - } diff --git a/samples/client/petstore/java/retrofit2rx/src/test/java/io/swagger/client/api/UserApiTest.java b/samples/client/petstore/java/retrofit2rx/src/test/java/io/swagger/client/api/UserApiTest.java index cd8553d8419..02c3942b210 100644 --- a/samples/client/petstore/java/retrofit2rx/src/test/java/io/swagger/client/api/UserApiTest.java +++ b/samples/client/petstore/java/retrofit2rx/src/test/java/io/swagger/client/api/UserApiTest.java @@ -1,131 +1,107 @@ package io.swagger.client.api; import io.swagger.client.ApiClient; -import io.swagger.client.model.User; -import org.junit.Before; -import org.junit.Test; +import io.swagger.client.model.*; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; + +import java.util.Arrays; + +import org.junit.*; + +import static org.junit.Assert.*; /** - * API tests for UserApi + * NOTE: This serves as a sample and test case for the generator, which is why this is java-7 code. + * Much looks much nicer with no anonymous classes. */ public class UserApiTest { - - private UserApi api; + UserApi api = null; @Before public void setup() { api = new ApiClient().createService(UserApi.class); } - - /** - * Create user - * - * This can only be done by the logged in user. - */ @Test - public void createUserTest() { - User body = null; - // Void response = api.createUser(body); + public void testCreateUser() throws Exception { + final User user = createUser(); - // TODO: test validations + api.createUser(user).subscribe(new SkeletonSubscriber() { + @Override + public void onCompleted() { + api.getUserByName(user.getUsername()).subscribe(new SkeletonSubscriber() { + @Override + public void onNext(User fetched) { + assertEquals(user.getId(), fetched.getId()); + } + }); + } + }); } - - /** - * Creates list of users with given input array - * - * - */ + @Test - public void createUsersWithArrayInputTest() { - List body = null; - // Void response = api.createUsersWithArrayInput(body); + public void testCreateUsersWithArray() throws Exception { + final User user1 = createUser(); + user1.setUsername("abc123"); + User user2 = createUser(); + user2.setUsername("123abc"); - // TODO: test validations + api.createUsersWithArrayInput(Arrays.asList(new User[]{user1, user2})).subscribe(SkeletonSubscriber.failTestOnError()); + + api.getUserByName(user1.getUsername()).subscribe(new SkeletonSubscriber() { + @Override + public void onNext(User fetched) { + assertEquals(user1.getId(), fetched.getId()); + } + }); } - - /** - * Creates list of users with given input array - * - * - */ + @Test - public void createUsersWithListInputTest() { - List body = null; - // Void response = api.createUsersWithListInput(body); + public void testCreateUsersWithList() throws Exception { + final User user1 = createUser(); + user1.setUsername("abc123"); + User user2 = createUser(); + user2.setUsername("123abc"); - // TODO: test validations + api.createUsersWithListInput(Arrays.asList(new User[]{user1, user2})).subscribe(SkeletonSubscriber.failTestOnError()); + + api.getUserByName(user1.getUsername()).subscribe(new SkeletonSubscriber() { + @Override + public void onNext(User fetched) { + assertEquals(user1.getId(), fetched.getId()); + } + }); } - - /** - * Delete user - * - * This can only be done by the logged in user. - */ + @Test - public void deleteUserTest() { - String username = null; - // Void response = api.deleteUser(username); + public void testLoginUser() throws Exception { + User user = createUser(); + api.createUser(user); - // TODO: test validations + api.loginUser(user.getUsername(), user.getPassword()).subscribe(new SkeletonSubscriber() { + @Override + public void onNext(String token) { + assertTrue(token.startsWith("logged in user session:")); + } + }); } - - /** - * Get user by user name - * - * - */ + @Test - public void getUserByNameTest() { - String username = null; - // User response = api.getUserByName(username); - - // TODO: test validations + public void logoutUser() throws Exception { + api.logoutUser(); } - - /** - * Logs user into the system - * - * - */ - @Test - public void loginUserTest() { - String username = null; - String password = null; - // String response = api.loginUser(username, password); - // TODO: test validations - } - - /** - * Logs out current logged in user session - * - * - */ - @Test - public void logoutUserTest() { - // Void response = api.logoutUser(); + private User createUser() { + User user = new User(); + user.setId(System.currentTimeMillis()); + user.setUsername("fred"); + user.setFirstName("Fred"); + user.setLastName("Meyer"); + user.setEmail("fred@fredmeyer.com"); + user.setPassword("xxXXxx"); + user.setPhone("408-867-5309"); + user.setUserStatus(123); - // TODO: test validations + return user; } - - /** - * Updated user - * - * This can only be done by the logged in user. - */ - @Test - public void updateUserTest() { - String username = null; - User body = null; - // Void response = api.updateUser(username, body); - - // TODO: test validations - } - -} +} \ No newline at end of file diff --git a/samples/client/petstore/objc/SwaggerClient/Core/SWGApiClient.m b/samples/client/petstore/objc/SwaggerClient/Core/SWGApiClient.m index 18c3233c331..66305707b17 100644 --- a/samples/client/petstore/objc/SwaggerClient/Core/SWGApiClient.m +++ b/samples/client/petstore/objc/SwaggerClient/Core/SWGApiClient.m @@ -259,6 +259,7 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) { self.requestSerializer = [AFHTTPRequestSerializer serializer]; } else { + self.requestSerializer = [AFHTTPRequestSerializer serializer]; NSAssert(NO, @"Unsupported request type %@", requestContentType); } @@ -274,7 +275,9 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) { queryParams = [self.sanitizer sanitizeForSerialization:queryParams]; headerParams = [self.sanitizer sanitizeForSerialization:headerParams]; formParams = [self.sanitizer sanitizeForSerialization:formParams]; - body = [self.sanitizer sanitizeForSerialization:body]; + if(![body isKindOfClass:[NSData class]]) { + body = [self.sanitizer sanitizeForSerialization:body]; + } // auth setting [self updateHeaderParams:&headerParams queryParams:&queryParams WithAuthSettings:authSettings]; diff --git a/samples/client/petstore/objc/SwaggerClient/Core/SWGJSONRequestSerializer.m b/samples/client/petstore/objc/SwaggerClient/Core/SWGJSONRequestSerializer.m index 631a20a5a6e..221765e4839 100644 --- a/samples/client/petstore/objc/SwaggerClient/Core/SWGJSONRequestSerializer.m +++ b/samples/client/petstore/objc/SwaggerClient/Core/SWGJSONRequestSerializer.m @@ -17,19 +17,21 @@ withParameters:(id)parameters error:(NSError *__autoreleasing *)error { + if (!parameters) { + return request; + } // If the body data which will be serialized isn't NSArray or NSDictionary // then put the data in the http request body directly. if ([parameters isKindOfClass:[NSArray class]] || [parameters isKindOfClass:[NSDictionary class]]) { return [super requestBySerializingRequest:request withParameters:parameters error:error]; - } else { - NSMutableURLRequest *mutableRequest = [request mutableCopy]; - - if (parameters) { - [mutableRequest setHTTPBody:[parameters dataUsingEncoding:self.stringEncoding]]; - } - - return mutableRequest; } + NSMutableURLRequest *mutableRequest = [request mutableCopy]; + if([parameters isKindOfClass:[NSData class]]) { + [mutableRequest setHTTPBody:parameters]; + } else { + [mutableRequest setHTTPBody:[parameters dataUsingEncoding:self.stringEncoding]]; + } + return mutableRequest; } @end diff --git a/samples/client/petstore/perl/.swagger-codegen-ignore b/samples/client/petstore/perl/.swagger-codegen-ignore new file mode 100644 index 00000000000..19d3377182e --- /dev/null +++ b/samples/client/petstore/perl/.swagger-codegen-ignore @@ -0,0 +1,23 @@ +# Swagger Codegen Ignore +# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell Swagger Codgen to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# Thsi matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/client/petstore/perl/LICENSE b/samples/client/petstore/perl/LICENSE new file mode 100644 index 00000000000..8dada3edaf5 --- /dev/null +++ b/samples/client/petstore/perl/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/samples/client/petstore/perl/README.md b/samples/client/petstore/perl/README.md index a4c5c47558a..5e12d98f02f 100644 --- a/samples/client/petstore/perl/README.md +++ b/samples/client/petstore/perl/README.md @@ -2,7 +2,7 @@ WWW::SwaggerClient::Role - a Moose role 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: \" \\ # VERSION @@ -10,7 +10,7 @@ Automatically generated by the [Swagger Codegen](https://github.com/swagger-api/ - API version: 1.0.0 - Package version: 1.0.0 -- Build date: 2016-04-13T22:41:41.133+08:00 +- Build date: 2016-06-10T22:39:40.931+08:00 - Build package: class io.swagger.codegen.languages.PerlClientCodegen ## A note on Moose @@ -223,6 +223,7 @@ Each of these calls returns a hashref with various useful pieces of information. To load the API packages: ```perl +use WWW::SwaggerClient::FakeApi; use WWW::SwaggerClient::PetApi; use WWW::SwaggerClient::StoreApi; use WWW::SwaggerClient::UserApi; @@ -231,17 +232,24 @@ use WWW::SwaggerClient::UserApi; To load the models: ```perl +use WWW::SwaggerClient::Object::AdditionalPropertiesClass; use WWW::SwaggerClient::Object::Animal; +use WWW::SwaggerClient::Object::AnimalFarm; use WWW::SwaggerClient::Object::ApiResponse; +use WWW::SwaggerClient::Object::ArrayTest; use WWW::SwaggerClient::Object::Cat; use WWW::SwaggerClient::Object::Category; use WWW::SwaggerClient::Object::Dog; +use WWW::SwaggerClient::Object::EnumClass; +use WWW::SwaggerClient::Object::EnumTest; use WWW::SwaggerClient::Object::FormatTest; +use WWW::SwaggerClient::Object::MixedPropertiesAndAdditionalPropertiesClass; use WWW::SwaggerClient::Object::Model200Response; use WWW::SwaggerClient::Object::ModelReturn; use WWW::SwaggerClient::Object::Name; use WWW::SwaggerClient::Object::Order; use WWW::SwaggerClient::Object::Pet; +use WWW::SwaggerClient::Object::ReadOnlyFirst; use WWW::SwaggerClient::Object::SpecialModelName; use WWW::SwaggerClient::Object::Tag; use WWW::SwaggerClient::Object::User; @@ -256,22 +264,30 @@ use lib 'lib'; use strict; use warnings; # load the API package +use WWW::SwaggerClient::FakeApi; use WWW::SwaggerClient::PetApi; use WWW::SwaggerClient::StoreApi; use WWW::SwaggerClient::UserApi; # load the models +use WWW::SwaggerClient::Object::AdditionalPropertiesClass; use WWW::SwaggerClient::Object::Animal; +use WWW::SwaggerClient::Object::AnimalFarm; use WWW::SwaggerClient::Object::ApiResponse; +use WWW::SwaggerClient::Object::ArrayTest; use WWW::SwaggerClient::Object::Cat; use WWW::SwaggerClient::Object::Category; use WWW::SwaggerClient::Object::Dog; +use WWW::SwaggerClient::Object::EnumClass; +use WWW::SwaggerClient::Object::EnumTest; use WWW::SwaggerClient::Object::FormatTest; +use WWW::SwaggerClient::Object::MixedPropertiesAndAdditionalPropertiesClass; use WWW::SwaggerClient::Object::Model200Response; use WWW::SwaggerClient::Object::ModelReturn; use WWW::SwaggerClient::Object::Name; use WWW::SwaggerClient::Object::Order; use WWW::SwaggerClient::Object::Pet; +use WWW::SwaggerClient::Object::ReadOnlyFirst; use WWW::SwaggerClient::Object::SpecialModelName; use WWW::SwaggerClient::Object::Tag; use WWW::SwaggerClient::Object::User; @@ -279,17 +295,25 @@ use WWW::SwaggerClient::Object::User; # for displaying the API response data use Data::Dumper; -# Configure OAuth2 access token for authorization: petstore_auth -$WWW::SwaggerClient::Configuration::access_token = 'YOUR_ACCESS_TOKEN'; - -my $api_instance = WWW::SwaggerClient::PetApi->new(); -my $body = WWW::SwaggerClient::Object::Pet->new(); # Pet | Pet object that needs to be added to the store +my $api_instance = WWW::SwaggerClient::FakeApi->new(); +my $number = 3.4; # Number | None +my $double = 1.2; # double | None +my $string = 'string_example'; # string | None +my $byte = 'B'; # string | None +my $integer = 56; # int | None +my $int32 = 56; # int | None +my $int64 = 789; # int | None +my $float = 3.4; # double | None +my $binary = 'B'; # string | None +my $date = DateTime->from_epoch(epoch => str2time('2013-10-20')); # DateTime | None +my $date_time = DateTime->from_epoch(epoch => str2time('2013-10-20T19:20:30+01:00')); # DateTime | None +my $password = 'password_example'; # string | None eval { - $api_instance->add_pet(body => $body); + $api_instance->test_endpoint_parameters(number => $number, double => $double, string => $string, byte => $byte, integer => $integer, int32 => $int32, int64 => $int64, float => $float, binary => $binary, date => $date, date_time => $date_time, password => $password); }; if ($@) { - warn "Exception when calling PetApi->add_pet: $@\n"; + warn "Exception when calling FakeApi->test_endpoint_parameters: $@\n"; } ``` @@ -300,6 +324,7 @@ All URIs are relative to *http://petstore.swagger.io/v2* Class | Method | HTTP request | Description ------------ | ------------- | ------------- | ------------- +*FakeApi* | [**test_endpoint_parameters**](docs/FakeApi.md#test_endpoint_parameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 *PetApi* | [**add_pet**](docs/PetApi.md#add_pet) | **POST** /pet | Add a new pet to the store *PetApi* | [**delete_pet**](docs/PetApi.md#delete_pet) | **DELETE** /pet/{petId} | Deletes a pet *PetApi* | [**find_pets_by_status**](docs/PetApi.md#find_pets_by_status) | **GET** /pet/findByStatus | Finds Pets by status @@ -323,17 +348,24 @@ Class | Method | HTTP request | Description # DOCUMENTATION FOR MODELS + - [WWW::SwaggerClient::Object::AdditionalPropertiesClass](docs/AdditionalPropertiesClass.md) - [WWW::SwaggerClient::Object::Animal](docs/Animal.md) + - [WWW::SwaggerClient::Object::AnimalFarm](docs/AnimalFarm.md) - [WWW::SwaggerClient::Object::ApiResponse](docs/ApiResponse.md) + - [WWW::SwaggerClient::Object::ArrayTest](docs/ArrayTest.md) - [WWW::SwaggerClient::Object::Cat](docs/Cat.md) - [WWW::SwaggerClient::Object::Category](docs/Category.md) - [WWW::SwaggerClient::Object::Dog](docs/Dog.md) + - [WWW::SwaggerClient::Object::EnumClass](docs/EnumClass.md) + - [WWW::SwaggerClient::Object::EnumTest](docs/EnumTest.md) - [WWW::SwaggerClient::Object::FormatTest](docs/FormatTest.md) + - [WWW::SwaggerClient::Object::MixedPropertiesAndAdditionalPropertiesClass](docs/MixedPropertiesAndAdditionalPropertiesClass.md) - [WWW::SwaggerClient::Object::Model200Response](docs/Model200Response.md) - [WWW::SwaggerClient::Object::ModelReturn](docs/ModelReturn.md) - [WWW::SwaggerClient::Object::Name](docs/Name.md) - [WWW::SwaggerClient::Object::Order](docs/Order.md) - [WWW::SwaggerClient::Object::Pet](docs/Pet.md) + - [WWW::SwaggerClient::Object::ReadOnlyFirst](docs/ReadOnlyFirst.md) - [WWW::SwaggerClient::Object::SpecialModelName](docs/SpecialModelName.md) - [WWW::SwaggerClient::Object::Tag](docs/Tag.md) - [WWW::SwaggerClient::Object::User](docs/User.md) @@ -351,7 +383,7 @@ Class | Method | HTTP request | Description - **Type**: OAuth - **Flow**: implicit -- **Authorizatoin URL**: http://petstore.swagger.io/api/oauth/dialog +- **Authorization URL**: http://petstore.swagger.io/api/oauth/dialog - **Scopes**: - **write:pets**: modify pets in your account - **read:pets**: read your pets diff --git a/samples/client/petstore/perl/docs/AdditionalPropertiesClass.md b/samples/client/petstore/perl/docs/AdditionalPropertiesClass.md new file mode 100644 index 00000000000..ab590075a14 --- /dev/null +++ b/samples/client/petstore/perl/docs/AdditionalPropertiesClass.md @@ -0,0 +1,16 @@ +# WWW::SwaggerClient::Object::AdditionalPropertiesClass + +## Load the model package +```perl +use WWW::SwaggerClient::Object::AdditionalPropertiesClass; +``` + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**map_property** | **HASH[string,string]** | | [optional] +**map_of_map_property** | **HASH[string,HASH[string,string]]** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/perl/docs/Animal.md b/samples/client/petstore/perl/docs/Animal.md index d243a90905d..38cc8ac0690 100644 --- a/samples/client/petstore/perl/docs/Animal.md +++ b/samples/client/petstore/perl/docs/Animal.md @@ -9,6 +9,7 @@ use WWW::SwaggerClient::Object::Animal; 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/perl/docs/AnimalFarm.md b/samples/client/petstore/perl/docs/AnimalFarm.md new file mode 100644 index 00000000000..18848e9c0ba --- /dev/null +++ b/samples/client/petstore/perl/docs/AnimalFarm.md @@ -0,0 +1,14 @@ +# WWW::SwaggerClient::Object::AnimalFarm + +## Load the model package +```perl +use WWW::SwaggerClient::Object::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/perl/docs/ArrayTest.md b/samples/client/petstore/perl/docs/ArrayTest.md new file mode 100644 index 00000000000..635c26a893a --- /dev/null +++ b/samples/client/petstore/perl/docs/ArrayTest.md @@ -0,0 +1,17 @@ +# WWW::SwaggerClient::Object::ArrayTest + +## Load the model package +```perl +use WWW::SwaggerClient::Object::ArrayTest; +``` + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**array_of_string** | **ARRAY[string]** | | [optional] +**array_array_of_integer** | **ARRAY[ARRAY[int]]** | | [optional] +**array_array_of_model** | **ARRAY[ARRAY[ReadOnlyFirst]]** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/perl/docs/Cat.md b/samples/client/petstore/perl/docs/Cat.md index 978e4202394..0539f73e502 100644 --- a/samples/client/petstore/perl/docs/Cat.md +++ b/samples/client/petstore/perl/docs/Cat.md @@ -9,6 +9,7 @@ use WWW::SwaggerClient::Object::Cat; Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **class_name** | **string** | | +**color** | **string** | | [optional] [default to 'red'] **declawed** | **boolean** | | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore/perl/docs/Dog.md b/samples/client/petstore/perl/docs/Dog.md index 16e399c3aae..16d3972d2b5 100644 --- a/samples/client/petstore/perl/docs/Dog.md +++ b/samples/client/petstore/perl/docs/Dog.md @@ -9,6 +9,7 @@ use WWW::SwaggerClient::Object::Dog; Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **class_name** | **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/perl/docs/EnumClass.md b/samples/client/petstore/perl/docs/EnumClass.md new file mode 100644 index 00000000000..c4e40dbf06b --- /dev/null +++ b/samples/client/petstore/perl/docs/EnumClass.md @@ -0,0 +1,14 @@ +# WWW::SwaggerClient::Object::EnumClass + +## Load the model package +```perl +use WWW::SwaggerClient::Object::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/perl/docs/EnumTest.md b/samples/client/petstore/perl/docs/EnumTest.md new file mode 100644 index 00000000000..0c3416150e1 --- /dev/null +++ b/samples/client/petstore/perl/docs/EnumTest.md @@ -0,0 +1,17 @@ +# WWW::SwaggerClient::Object::EnumTest + +## Load the model package +```perl +use WWW::SwaggerClient::Object::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/perl/docs/FakeApi.md b/samples/client/petstore/perl/docs/FakeApi.md new file mode 100644 index 00000000000..94c13795a10 --- /dev/null +++ b/samples/client/petstore/perl/docs/FakeApi.md @@ -0,0 +1,79 @@ +# WWW::SwaggerClient::FakeApi + +## Load the API package +```perl +use WWW::SwaggerClient::Object::FakeApi; +``` + +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** +> test_endpoint_parameters(number => $number, double => $double, string => $string, byte => $byte, integer => $integer, int32 => $int32, int64 => $int64, float => $float, binary => $binary, date => $date, date_time => $date_time, password => $password) + +Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + +Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + +### Example +```perl +use Data::Dumper; + +my $api_instance = WWW::SwaggerClient::FakeApi->new(); +my $number = 3.4; # Number | None +my $double = 1.2; # double | None +my $string = 'string_example'; # string | None +my $byte = 'B'; # string | None +my $integer = 56; # int | None +my $int32 = 56; # int | None +my $int64 = 789; # int | None +my $float = 3.4; # double | None +my $binary = 'B'; # string | None +my $date = DateTime->from_epoch(epoch => str2time('2013-10-20')); # DateTime | None +my $date_time = DateTime->from_epoch(epoch => str2time('2013-10-20T19:20:30+01:00')); # DateTime | None +my $password = 'password_example'; # string | None + +eval { + $api_instance->test_endpoint_parameters(number => $number, double => $double, string => $string, byte => $byte, integer => $integer, int32 => $int32, int64 => $int64, float => $float, binary => $binary, date => $date, date_time => $date_time, password => $password); +}; +if ($@) { + warn "Exception when calling FakeApi->test_endpoint_parameters: $@\n"; +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **number** | **Number**| None | + **double** | **double**| None | + **string** | **string**| None | + **byte** | **string**| None | + **integer** | **int**| None | [optional] + **int32** | **int**| None | [optional] + **int64** | **int**| None | [optional] + **float** | **double**| None | [optional] + **binary** | **string**| None | [optional] + **date** | **DateTime**| None | [optional] + **date_time** | **DateTime**| None | [optional] + **password** | **string**| None | [optional] + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/xml; charset=utf-8, application/json; charset=utf-8 + - **Accept**: application/xml; charset=utf-8, application/json; charset=utf-8 + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/perl/docs/FormatTest.md b/samples/client/petstore/perl/docs/FormatTest.md index 60cd71ac61f..9ba3aeaf17b 100644 --- a/samples/client/petstore/perl/docs/FormatTest.md +++ b/samples/client/petstore/perl/docs/FormatTest.md @@ -15,11 +15,12 @@ Name | Type | Description | Notes **float** | **double** | | [optional] **double** | **double** | | [optional] **string** | **string** | | [optional] -**byte** | **string** | | [optional] +**byte** | **string** | | **binary** | **string** | | [optional] -**date** | **DateTime** | | [optional] +**date** | **DateTime** | | **date_time** | **DateTime** | | [optional] -**password** | **string** | | [optional] +**uuid** | [**UUID**](UUID.md) | | [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/perl/docs/MixedPropertiesAndAdditionalPropertiesClass.md b/samples/client/petstore/perl/docs/MixedPropertiesAndAdditionalPropertiesClass.md new file mode 100644 index 00000000000..28bf101a8a1 --- /dev/null +++ b/samples/client/petstore/perl/docs/MixedPropertiesAndAdditionalPropertiesClass.md @@ -0,0 +1,17 @@ +# WWW::SwaggerClient::Object::MixedPropertiesAndAdditionalPropertiesClass + +## Load the model package +```perl +use WWW::SwaggerClient::Object::MixedPropertiesAndAdditionalPropertiesClass; +``` + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**uuid** | [**UUID**](UUID.md) | | [optional] +**date_time** | **DateTime** | | [optional] +**map** | [**HASH[string,Animal]**](Animal.md) | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/perl/docs/Name.md b/samples/client/petstore/perl/docs/Name.md index 7109642a08b..1407fb99bcb 100644 --- a/samples/client/petstore/perl/docs/Name.md +++ b/samples/client/petstore/perl/docs/Name.md @@ -10,6 +10,8 @@ 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/perl/docs/PetApi.md b/samples/client/petstore/perl/docs/PetApi.md index 829dc3a08ef..c2f4e2ce4ee 100644 --- a/samples/client/petstore/perl/docs/PetApi.md +++ b/samples/client/petstore/perl/docs/PetApi.md @@ -10,13 +10,10 @@ All URIs are relative to *http://petstore.swagger.io/v2* Method | HTTP request | Description ------------- | ------------- | ------------- [**add_pet**](PetApi.md#add_pet) | **POST** /pet | Add a new pet to the store -[**add_pet_using_byte_array**](PetApi.md#add_pet_using_byte_array) | **POST** /pet?testing_byte_array=true | Fake endpoint to test byte array in body parameter for adding a new pet to the store [**delete_pet**](PetApi.md#delete_pet) | **DELETE** /pet/{petId} | Deletes a pet [**find_pets_by_status**](PetApi.md#find_pets_by_status) | **GET** /pet/findByStatus | Finds Pets by status [**find_pets_by_tags**](PetApi.md#find_pets_by_tags) | **GET** /pet/findByTags | Finds Pets by tags [**get_pet_by_id**](PetApi.md#get_pet_by_id) | **GET** /pet/{petId} | Find pet by ID -[**get_pet_by_id_in_object**](PetApi.md#get_pet_by_id_in_object) | **GET** /pet/{petId}?response=inline_arbitrary_object | Fake endpoint to test inline arbitrary object return by 'Find pet by ID' -[**pet_pet_idtesting_byte_arraytrue_get**](PetApi.md#pet_pet_idtesting_byte_arraytrue_get) | **GET** /pet/{petId}?testing_byte_array=true | Fake endpoint to test byte array return by 'Find pet by ID' [**update_pet**](PetApi.md#update_pet) | **PUT** /pet | Update an existing pet [**update_pet_with_form**](PetApi.md#update_pet_with_form) | **POST** /pet/{petId} | Updates a pet in the store with form data [**upload_file**](PetApi.md#upload_file) | **POST** /pet/{petId}/uploadImage | uploads an image @@ -51,7 +48,7 @@ if ($@) { 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 @@ -64,53 +61,7 @@ void (empty response body) ### HTTP request headers - **Content-Type**: application/json, application/xml - - **Accept**: application/json, application/xml - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **add_pet_using_byte_array** -> add_pet_using_byte_array(body => $body) - -Fake endpoint to test byte array in body parameter for adding a new pet to the store - - - -### Example -```perl -use Data::Dumper; - -# Configure OAuth2 access token for authorization: petstore_auth -$WWW::SwaggerClient::Configuration::access_token = 'YOUR_ACCESS_TOKEN'; - -my $api_instance = WWW::SwaggerClient::PetApi->new(); -my $body = WWW::SwaggerClient::Object::string->new(); # string | Pet object in the form of byte array - -eval { - $api_instance->add_pet_using_byte_array(body => $body); -}; -if ($@) { - warn "Exception when calling PetApi->add_pet_using_byte_array: $@\n"; -} -``` - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **body** | **string**| Pet object in the form of byte array | [optional] - -### Return type - -void (empty response body) - -### Authorization - -[petstore_auth](../README.md#petstore_auth) - -### HTTP request headers - - - **Content-Type**: application/json, application/xml - - **Accept**: application/json, application/xml + - **Accept**: application/xml, application/json [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) @@ -158,7 +109,7 @@ void (empty response body) ### HTTP request headers - **Content-Type**: Not defined - - **Accept**: application/json, application/xml + - **Accept**: application/xml, application/json [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) @@ -177,7 +128,7 @@ use Data::Dumper; $WWW::SwaggerClient::Configuration::access_token = 'YOUR_ACCESS_TOKEN'; my $api_instance = WWW::SwaggerClient::PetApi->new(); -my $status = (); # ARRAY[string] | Status values that need to be considered for query +my $status = (); # ARRAY[string] | Status values that need to be considered for filter eval { my $result = $api_instance->find_pets_by_status(status => $status); @@ -192,7 +143,7 @@ if ($@) { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **status** | [**ARRAY[string]**](string.md)| Status values that need to be considered for query | [optional] [default to available] + **status** | [**ARRAY[string]**](string.md)| Status values that need to be considered for filter | ### Return type @@ -205,7 +156,7 @@ Name | Type | Description | Notes ### HTTP request headers - **Content-Type**: Not defined - - **Accept**: application/json, application/xml + - **Accept**: application/xml, application/json [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) @@ -214,7 +165,7 @@ Name | Type | Description | Notes Finds Pets by tags -Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. +Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. ### Example ```perl @@ -239,7 +190,7 @@ if ($@) { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **tags** | [**ARRAY[string]**](string.md)| Tags to filter by | [optional] + **tags** | [**ARRAY[string]**](string.md)| Tags to filter by | ### Return type @@ -252,7 +203,7 @@ Name | Type | Description | Notes ### HTTP request headers - **Content-Type**: Not defined - - **Accept**: application/json, application/xml + - **Accept**: application/xml, application/json [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) @@ -261,7 +212,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 ```perl @@ -271,11 +222,9 @@ use Data::Dumper; $WWW::SwaggerClient::Configuration::api_key->{'api_key'} = 'YOUR_API_KEY'; # uncomment below to setup prefix (e.g. Bearer) for API key, if needed #$WWW::SwaggerClient::Configuration::api_key_prefix->{'api_key'} = "Bearer"; -# Configure OAuth2 access token for authorization: petstore_auth -$WWW::SwaggerClient::Configuration::access_token = 'YOUR_ACCESS_TOKEN'; my $api_instance = WWW::SwaggerClient::PetApi->new(); -my $pet_id = 789; # int | ID of pet that needs to be fetched +my $pet_id = 789; # int | ID of pet to return eval { my $result = $api_instance->get_pet_by_id(pet_id => $pet_id); @@ -290,7 +239,7 @@ if ($@) { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **pet_id** | **int**| ID of pet that needs to be fetched | + **pet_id** | **int**| ID of pet to return | ### Return type @@ -298,114 +247,12 @@ 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 - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **get_pet_by_id_in_object** -> InlineResponse200 get_pet_by_id_in_object(pet_id => $pet_id) - -Fake endpoint to test inline arbitrary object return by 'Find pet by ID' - -Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions - -### Example -```perl -use Data::Dumper; - -# Configure API key authorization: api_key -$WWW::SwaggerClient::Configuration::api_key->{'api_key'} = 'YOUR_API_KEY'; -# uncomment below to setup prefix (e.g. Bearer) for API key, if needed -#$WWW::SwaggerClient::Configuration::api_key_prefix->{'api_key'} = "Bearer"; -# Configure OAuth2 access token for authorization: petstore_auth -$WWW::SwaggerClient::Configuration::access_token = 'YOUR_ACCESS_TOKEN'; - -my $api_instance = WWW::SwaggerClient::PetApi->new(); -my $pet_id = 789; # int | ID of pet that needs to be fetched - -eval { - my $result = $api_instance->get_pet_by_id_in_object(pet_id => $pet_id); - print Dumper($result); -}; -if ($@) { - warn "Exception when calling PetApi->get_pet_by_id_in_object: $@\n"; -} -``` - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **pet_id** | **int**| ID of pet that needs to be fetched | - -### Return type - -[**InlineResponse200**](InlineResponse200.md) - -### Authorization - -[api_key](../README.md#api_key), [petstore_auth](../README.md#petstore_auth) - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: application/json, application/xml - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **pet_pet_idtesting_byte_arraytrue_get** -> string pet_pet_idtesting_byte_arraytrue_get(pet_id => $pet_id) - -Fake endpoint to test byte array return by 'Find pet by ID' - -Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions - -### Example -```perl -use Data::Dumper; - -# Configure API key authorization: api_key -$WWW::SwaggerClient::Configuration::api_key->{'api_key'} = 'YOUR_API_KEY'; -# uncomment below to setup prefix (e.g. Bearer) for API key, if needed -#$WWW::SwaggerClient::Configuration::api_key_prefix->{'api_key'} = "Bearer"; -# Configure OAuth2 access token for authorization: petstore_auth -$WWW::SwaggerClient::Configuration::access_token = 'YOUR_ACCESS_TOKEN'; - -my $api_instance = WWW::SwaggerClient::PetApi->new(); -my $pet_id = 789; # int | ID of pet that needs to be fetched - -eval { - my $result = $api_instance->pet_pet_idtesting_byte_arraytrue_get(pet_id => $pet_id); - print Dumper($result); -}; -if ($@) { - warn "Exception when calling PetApi->pet_pet_idtesting_byte_arraytrue_get: $@\n"; -} -``` - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **pet_id** | **int**| ID of pet that needs to be fetched | - -### Return type - -**string** - -### Authorization - -[api_key](../README.md#api_key), [petstore_auth](../README.md#petstore_auth) - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: application/json, application/xml + - **Accept**: application/xml, application/json [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) @@ -438,7 +285,7 @@ if ($@) { 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 @@ -451,7 +298,7 @@ void (empty response body) ### HTTP request headers - **Content-Type**: application/json, application/xml - - **Accept**: application/json, application/xml + - **Accept**: application/xml, application/json [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) @@ -470,7 +317,7 @@ use Data::Dumper; $WWW::SwaggerClient::Configuration::access_token = 'YOUR_ACCESS_TOKEN'; my $api_instance = WWW::SwaggerClient::PetApi->new(); -my $pet_id = 'pet_id_example'; # string | ID of pet that needs to be updated +my $pet_id = 789; # int | ID of pet that needs to be updated my $name = 'name_example'; # string | Updated name of the pet my $status = 'status_example'; # string | Updated status of the pet @@ -486,7 +333,7 @@ if ($@) { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **pet_id** | **string**| ID of pet that needs to be updated | + **pet_id** | **int**| ID of pet that needs to be updated | **name** | **string**| Updated name of the pet | [optional] **status** | **string**| Updated status of the pet | [optional] @@ -501,12 +348,12 @@ void (empty response body) ### HTTP request headers - **Content-Type**: application/x-www-form-urlencoded - - **Accept**: application/json, application/xml + - **Accept**: application/xml, application/json [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **upload_file** -> upload_file(pet_id => $pet_id, additional_metadata => $additional_metadata, file => $file) +> ApiResponse upload_file(pet_id => $pet_id, additional_metadata => $additional_metadata, file => $file) uploads an image @@ -525,7 +372,8 @@ my $additional_metadata = 'additional_metadata_example'; # string | Additional d my $file = '/path/to/file.txt'; # File | file to upload eval { - $api_instance->upload_file(pet_id => $pet_id, additional_metadata => $additional_metadata, file => $file); + my $result = $api_instance->upload_file(pet_id => $pet_id, additional_metadata => $additional_metadata, file => $file); + print Dumper($result); }; if ($@) { warn "Exception when calling PetApi->upload_file: $@\n"; @@ -542,7 +390,7 @@ Name | Type | Description | Notes ### Return type -void (empty response body) +[**ApiResponse**](ApiResponse.md) ### Authorization @@ -551,7 +399,7 @@ void (empty response body) ### HTTP request headers - **Content-Type**: multipart/form-data - - **Accept**: application/json, application/xml + - **Accept**: application/json [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) diff --git a/samples/client/petstore/perl/docs/ReadOnlyFirst.md b/samples/client/petstore/perl/docs/ReadOnlyFirst.md new file mode 100644 index 00000000000..51f643016bc --- /dev/null +++ b/samples/client/petstore/perl/docs/ReadOnlyFirst.md @@ -0,0 +1,16 @@ +# WWW::SwaggerClient::Object::ReadOnlyFirst + +## Load the model package +```perl +use WWW::SwaggerClient::Object::ReadOnlyFirst; +``` + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**bar** | **string** | | [optional] +**baz** | **string** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/perl/docs/StoreApi.md b/samples/client/petstore/perl/docs/StoreApi.md index c5eb55a3f12..f0681b47167 100644 --- a/samples/client/petstore/perl/docs/StoreApi.md +++ b/samples/client/petstore/perl/docs/StoreApi.md @@ -10,9 +10,7 @@ All URIs are relative to *http://petstore.swagger.io/v2* Method | HTTP request | Description ------------- | ------------- | ------------- [**delete_order**](StoreApi.md#delete_order) | **DELETE** /store/order/{orderId} | Delete purchase order by ID -[**find_orders_by_status**](StoreApi.md#find_orders_by_status) | **GET** /store/findByStatus | Finds orders by status [**get_inventory**](StoreApi.md#get_inventory) | **GET** /store/inventory | Returns pet inventories by status -[**get_inventory_in_object**](StoreApi.md#get_inventory_in_object) | **GET** /store/inventory?response=arbitrary_object | Fake endpoint to test arbitrary object return by 'Get inventory' [**get_order_by_id**](StoreApi.md#get_order_by_id) | **GET** /store/order/{orderId} | Find purchase order by ID [**place_order**](StoreApi.md#place_order) | **POST** /store/order | Place an order for a pet @@ -56,60 +54,7 @@ No authorization required ### HTTP request headers - **Content-Type**: Not defined - - **Accept**: application/json, application/xml - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **find_orders_by_status** -> ARRAY[Order] find_orders_by_status(status => $status) - -Finds orders by status - -A single status value can be provided as a string - -### Example -```perl -use Data::Dumper; - -# Configure API key authorization: test_api_client_id -$WWW::SwaggerClient::Configuration::api_key->{'x-test_api_client_id'} = 'YOUR_API_KEY'; -# uncomment below to setup prefix (e.g. Bearer) for API key, if needed -#$WWW::SwaggerClient::Configuration::api_key_prefix->{'x-test_api_client_id'} = "Bearer"; -# Configure API key authorization: test_api_client_secret -$WWW::SwaggerClient::Configuration::api_key->{'x-test_api_client_secret'} = 'YOUR_API_KEY'; -# uncomment below to setup prefix (e.g. Bearer) for API key, if needed -#$WWW::SwaggerClient::Configuration::api_key_prefix->{'x-test_api_client_secret'} = "Bearer"; - -my $api_instance = WWW::SwaggerClient::StoreApi->new(); -my $status = 'status_example'; # string | Status value that needs to be considered for query - -eval { - my $result = $api_instance->find_orders_by_status(status => $status); - print Dumper($result); -}; -if ($@) { - warn "Exception when calling StoreApi->find_orders_by_status: $@\n"; -} -``` - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **status** | **string**| Status value that needs to be considered for query | [optional] [default to placed] - -### Return type - -[**ARRAY[Order]**](Order.md) - -### Authorization - -[test_api_client_id](../README.md#test_api_client_id), [test_api_client_secret](../README.md#test_api_client_secret) - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: application/json, application/xml + - **Accept**: application/xml, application/json [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) @@ -154,52 +99,7 @@ This endpoint does not need any parameter. ### HTTP request headers - **Content-Type**: Not defined - - **Accept**: application/json, application/xml - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **get_inventory_in_object** -> object get_inventory_in_object() - -Fake endpoint to test arbitrary object return by 'Get inventory' - -Returns an arbitrary object which is actually a map of status codes to quantities - -### Example -```perl -use Data::Dumper; - -# Configure API key authorization: api_key -$WWW::SwaggerClient::Configuration::api_key->{'api_key'} = 'YOUR_API_KEY'; -# uncomment below to setup prefix (e.g. Bearer) for API key, if needed -#$WWW::SwaggerClient::Configuration::api_key_prefix->{'api_key'} = "Bearer"; - -my $api_instance = WWW::SwaggerClient::StoreApi->new(); - -eval { - my $result = $api_instance->get_inventory_in_object(); - print Dumper($result); -}; -if ($@) { - warn "Exception when calling StoreApi->get_inventory_in_object: $@\n"; -} -``` - -### Parameters -This endpoint does not need any parameter. - -### Return type - -**object** - -### Authorization - -[api_key](../README.md#api_key) - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: application/json, application/xml + - **Accept**: application/json [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) @@ -214,17 +114,8 @@ For valid response try integer IDs with value <= 5 or > 10. Other values will ge ```perl use Data::Dumper; -# Configure API key authorization: test_api_key_header -$WWW::SwaggerClient::Configuration::api_key->{'test_api_key_header'} = 'YOUR_API_KEY'; -# uncomment below to setup prefix (e.g. Bearer) for API key, if needed -#$WWW::SwaggerClient::Configuration::api_key_prefix->{'test_api_key_header'} = "Bearer"; -# Configure API key authorization: test_api_key_query -$WWW::SwaggerClient::Configuration::api_key->{'test_api_key_query'} = 'YOUR_API_KEY'; -# uncomment below to setup prefix (e.g. Bearer) for API key, if needed -#$WWW::SwaggerClient::Configuration::api_key_prefix->{'test_api_key_query'} = "Bearer"; - my $api_instance = WWW::SwaggerClient::StoreApi->new(); -my $order_id = 'order_id_example'; # string | ID of pet that needs to be fetched +my $order_id = 789; # int | ID of pet that needs to be fetched eval { my $result = $api_instance->get_order_by_id(order_id => $order_id); @@ -239,7 +130,7 @@ if ($@) { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **order_id** | **string**| ID of pet that needs to be fetched | + **order_id** | **int**| ID of pet that needs to be fetched | ### Return type @@ -247,12 +138,12 @@ Name | Type | Description | Notes ### Authorization -[test_api_key_header](../README.md#test_api_key_header), [test_api_key_query](../README.md#test_api_key_query) +No authorization required ### HTTP request headers - **Content-Type**: Not defined - - **Accept**: application/json, application/xml + - **Accept**: application/xml, application/json [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) @@ -267,15 +158,6 @@ Place an order for a pet ```perl use Data::Dumper; -# Configure API key authorization: test_api_client_id -$WWW::SwaggerClient::Configuration::api_key->{'x-test_api_client_id'} = 'YOUR_API_KEY'; -# uncomment below to setup prefix (e.g. Bearer) for API key, if needed -#$WWW::SwaggerClient::Configuration::api_key_prefix->{'x-test_api_client_id'} = "Bearer"; -# Configure API key authorization: test_api_client_secret -$WWW::SwaggerClient::Configuration::api_key->{'x-test_api_client_secret'} = 'YOUR_API_KEY'; -# uncomment below to setup prefix (e.g. Bearer) for API key, if needed -#$WWW::SwaggerClient::Configuration::api_key_prefix->{'x-test_api_client_secret'} = "Bearer"; - my $api_instance = WWW::SwaggerClient::StoreApi->new(); my $body = WWW::SwaggerClient::Object::Order->new(); # Order | order placed for purchasing the pet @@ -292,7 +174,7 @@ if ($@) { 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 @@ -300,12 +182,12 @@ Name | Type | Description | Notes ### Authorization -[test_api_client_id](../README.md#test_api_client_id), [test_api_client_secret](../README.md#test_api_client_secret) +No authorization required ### HTTP request headers - **Content-Type**: Not defined - - **Accept**: application/json, application/xml + - **Accept**: application/xml, application/json [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) diff --git a/samples/client/petstore/perl/git_push.sh b/samples/client/petstore/perl/git_push.sh index 1a36388db02..ed374619b13 100644 --- a/samples/client/petstore/perl/git_push.sh +++ b/samples/client/petstore/perl/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/lib/WWW/SwaggerClient/ApiClient.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/ApiClient.pm index 3dfa6633ee5..9b990cd26b0 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/ApiClient.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/ApiClient.pm @@ -1,3 +1,34 @@ +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the swagger code generator program. +# Do not edit the class manually. +# Ref: https://github.com/swagger-api/swagger-codegen +# package WWW::SwaggerClient::ApiClient; use strict; diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/ApiFactory.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/ApiFactory.pm index 0ffd5498420..daf6735e804 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/ApiFactory.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/ApiFactory.pm @@ -1,3 +1,34 @@ +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the swagger code generator program. +# Do not edit the class manually. +# Ref: https://github.com/swagger-api/swagger-codegen +# package WWW::SwaggerClient::ApiFactory; use strict; diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Configuration.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Configuration.pm index 150db4cfac2..e99ca4df5fa 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Configuration.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Configuration.pm @@ -1,3 +1,34 @@ +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the swagger code generator program. +# Do not edit the class manually. +# Ref: https://github.com/swagger-api/swagger-codegen +# package WWW::SwaggerClient::Configuration; use strict; diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/FakeApi.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/FakeApi.pm new file mode 100644 index 00000000000..905690756bb --- /dev/null +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/FakeApi.pm @@ -0,0 +1,264 @@ +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the swagger code generator program. +# Do not edit the class manually. +# Ref: https://github.com/swagger-api/swagger-codegen +# +package WWW::SwaggerClient::FakeApi; + +require 5.6.0; +use strict; +use warnings; +use utf8; +use Exporter; +use Carp qw( croak ); +use Log::Any qw($log); + +use WWW::SwaggerClient::ApiClient; +use WWW::SwaggerClient::Configuration; + +use base "Class::Data::Inheritable"; + +__PACKAGE__->mk_classdata('method_documentation' => {}); + +sub new { + my $class = shift; + my (%self) = ( + 'api_client' => WWW::SwaggerClient::ApiClient->instance, + @_ + ); + + #my $self = { + # #api_client => $options->{api_client} + # api_client => $default_api_client + #}; + + bless \%self, $class; + +} + + +# +# test_endpoint_parameters +# +# Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +# +# @param Number $number None (required) +# @param double $double None (required) +# @param string $string None (required) +# @param string $byte None (required) +# @param int $integer None (optional) +# @param int $int32 None (optional) +# @param int $int64 None (optional) +# @param double $float None (optional) +# @param string $binary None (optional) +# @param DateTime $date None (optional) +# @param DateTime $date_time None (optional) +# @param string $password None (optional) +{ + my $params = { + 'number' => { + data_type => 'Number', + description => 'None', + required => '1', + }, + 'double' => { + data_type => 'double', + description => 'None', + required => '1', + }, + 'string' => { + data_type => 'string', + description => 'None', + required => '1', + }, + 'byte' => { + data_type => 'string', + description => 'None', + required => '1', + }, + 'integer' => { + data_type => 'int', + description => 'None', + required => '0', + }, + 'int32' => { + data_type => 'int', + description => 'None', + required => '0', + }, + 'int64' => { + data_type => 'int', + description => 'None', + required => '0', + }, + 'float' => { + data_type => 'double', + description => 'None', + required => '0', + }, + 'binary' => { + data_type => 'string', + description => 'None', + required => '0', + }, + 'date' => { + data_type => 'DateTime', + description => 'None', + required => '0', + }, + 'date_time' => { + data_type => 'DateTime', + description => 'None', + required => '0', + }, + 'password' => { + data_type => 'string', + description => 'None', + required => '0', + }, + }; + __PACKAGE__->method_documentation->{ test_endpoint_parameters } = { + summary => 'Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 ', + params => $params, + returns => undef, + }; +} +# @return void +# +sub test_endpoint_parameters { + my ($self, %args) = @_; + + # verify the required parameter 'number' is set + unless (exists $args{'number'}) { + croak("Missing the required parameter 'number' when calling test_endpoint_parameters"); + } + + # verify the required parameter 'double' is set + unless (exists $args{'double'}) { + croak("Missing the required parameter 'double' when calling test_endpoint_parameters"); + } + + # verify the required parameter 'string' is set + unless (exists $args{'string'}) { + croak("Missing the required parameter 'string' when calling test_endpoint_parameters"); + } + + # verify the required parameter 'byte' is set + unless (exists $args{'byte'}) { + croak("Missing the required parameter 'byte' when calling test_endpoint_parameters"); + } + + # parse inputs + my $_resource_path = '/fake'; + $_resource_path =~ s/{format}/json/; # default format to json + + my $_method = 'POST'; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; + + # 'Accept' and 'Content-Type' header + my $_header_accept = $self->{api_client}->select_header_accept('application/xml; charset=utf-8', 'application/json; charset=utf-8'); + if ($_header_accept) { + $header_params->{'Accept'} = $_header_accept; + } + $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type('application/xml; charset=utf-8', 'application/json; charset=utf-8'); + + # form params + if ( exists $args{'integer'} ) { + $form_params->{'integer'} = $self->{api_client}->to_form_value($args{'integer'}); + } + + # form params + if ( exists $args{'int32'} ) { + $form_params->{'int32'} = $self->{api_client}->to_form_value($args{'int32'}); + } + + # form params + if ( exists $args{'int64'} ) { + $form_params->{'int64'} = $self->{api_client}->to_form_value($args{'int64'}); + } + + # form params + if ( exists $args{'number'} ) { + $form_params->{'number'} = $self->{api_client}->to_form_value($args{'number'}); + } + + # form params + if ( exists $args{'float'} ) { + $form_params->{'float'} = $self->{api_client}->to_form_value($args{'float'}); + } + + # form params + if ( exists $args{'double'} ) { + $form_params->{'double'} = $self->{api_client}->to_form_value($args{'double'}); + } + + # form params + if ( exists $args{'string'} ) { + $form_params->{'string'} = $self->{api_client}->to_form_value($args{'string'}); + } + + # form params + if ( exists $args{'byte'} ) { + $form_params->{'byte'} = $self->{api_client}->to_form_value($args{'byte'}); + } + + # form params + if ( exists $args{'binary'} ) { + $form_params->{'binary'} = $self->{api_client}->to_form_value($args{'binary'}); + } + + # form params + if ( exists $args{'date'} ) { + $form_params->{'date'} = $self->{api_client}->to_form_value($args{'date'}); + } + + # form params + if ( exists $args{'date_time'} ) { + $form_params->{'dateTime'} = $self->{api_client}->to_form_value($args{'date_time'}); + } + + # form params + if ( exists $args{'password'} ) { + $form_params->{'password'} = $self->{api_client}->to_form_value($args{'password'}); + } + + my $_body_data; + # authentication setting, if any + my $auth_settings = [qw()]; + + # make the API Call + $self->{api_client}->call_api($_resource_path, $_method, + $query_params, $form_params, + $header_params, $_body_data, $auth_settings); + return; +} + +1; diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/AdditionalPropertiesClass.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/AdditionalPropertiesClass.pm new file mode 100644 index 00000000000..76c1f19543c --- /dev/null +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/AdditionalPropertiesClass.pm @@ -0,0 +1,198 @@ +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the swagger code generator program. +# Do not edit the class manually. +# Ref: https://github.com/swagger-api/swagger-codegen +# +package WWW::SwaggerClient::Object::AdditionalPropertiesClass; + +require 5.6.0; +use strict; +use warnings; +use utf8; +use JSON qw(decode_json); +use Data::Dumper; +use Module::Runtime qw(use_module); +use Log::Any qw($log); +use Date::Parse; +use DateTime; + +use base ("Class::Accessor", "Class::Data::Inheritable"); + + +# +# +# +# NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. +# REF: https://github.com/swagger-api/swagger-codegen +# + +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the swagger code generator program. +# Do not edit the class manually. +# Ref: https://github.com/swagger-api/swagger-codegen +# +__PACKAGE__->mk_classdata('attribute_map' => {}); +__PACKAGE__->mk_classdata('swagger_types' => {}); +__PACKAGE__->mk_classdata('method_documentation' => {}); +__PACKAGE__->mk_classdata('class_documentation' => {}); + +# new object +sub new { + my ($class, %args) = @_; + + my $self = bless {}, $class; + + foreach my $attribute (keys %{$class->attribute_map}) { + my $args_key = $class->attribute_map->{$attribute}; + $self->$attribute( $args{ $args_key } ); + } + + return $self; +} + +# return perl hash +sub to_hash { + return decode_json(JSON->new->convert_blessed->encode( shift )); +} + +# used by JSON for serialization +sub TO_JSON { + my $self = shift; + my $_data = {}; + foreach my $_key (keys %{$self->attribute_map}) { + if (defined $self->{$_key}) { + $_data->{$self->attribute_map->{$_key}} = $self->{$_key}; + } + } + return $_data; +} + +# from Perl hashref +sub from_hash { + my ($self, $hash) = @_; + + # loop through attributes and use swagger_types to deserialize the data + while ( my ($_key, $_type) = each %{$self->swagger_types} ) { + my $_json_attribute = $self->attribute_map->{$_key}; + if ($_type =~ /^array\[/i) { # array + my $_subclass = substr($_type, 6, -1); + my @_array = (); + foreach my $_element (@{$hash->{$_json_attribute}}) { + push @_array, $self->_deserialize($_subclass, $_element); + } + $self->{$_key} = \@_array; + } elsif (exists $hash->{$_json_attribute}) { #hash(model), primitive, datetime + $self->{$_key} = $self->_deserialize($_type, $hash->{$_json_attribute}); + } else { + $log->debugf("Warning: %s (%s) does not exist in input hash\n", $_key, $_json_attribute); + } + } + + return $self; +} + +# deserialize non-array data +sub _deserialize { + my ($self, $type, $data) = @_; + $log->debugf("deserializing %s with %s",Dumper($data), $type); + + if ($type eq 'DateTime') { + return DateTime->from_epoch(epoch => str2time($data)); + } elsif ( grep( /^$type$/, ('int', 'double', 'string', 'boolean'))) { + return $data; + } else { # hash(model) + my $_instance = eval "WWW::SwaggerClient::Object::$type->new()"; + return $_instance->from_hash($data); + } +} + + + +__PACKAGE__->class_documentation({description => '', + class => 'AdditionalPropertiesClass', + required => [], # TODO +} ); + +__PACKAGE__->method_documentation({ + 'map_property' => { + datatype => 'HASH[string,string]', + base_name => 'map_property', + description => '', + format => '', + read_only => '', + }, + 'map_of_map_property' => { + datatype => 'HASH[string,HASH[string,string]]', + base_name => 'map_of_map_property', + description => '', + format => '', + read_only => '', + }, +}); + +__PACKAGE__->swagger_types( { + 'map_property' => 'HASH[string,string]', + 'map_of_map_property' => 'HASH[string,HASH[string,string]]' +} ); + +__PACKAGE__->attribute_map( { + 'map_property' => 'map_property', + 'map_of_map_property' => 'map_of_map_property' +} ); + +__PACKAGE__->mk_accessors(keys %{__PACKAGE__->attribute_map}); + + +1; diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Animal.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Animal.pm index eb1b10034e9..443701ce326 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Animal.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Animal.pm @@ -1,3 +1,34 @@ +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the swagger code generator program. +# Do not edit the class manually. +# Ref: https://github.com/swagger-api/swagger-codegen +# package WWW::SwaggerClient::Object::Animal; require 5.6.0; @@ -17,9 +48,41 @@ use base ("Class::Accessor", "Class::Data::Inheritable"); # # # -#NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. +# NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. +# REF: https://github.com/swagger-api/swagger-codegen # +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the swagger code generator program. +# Do not edit the class manually. +# Ref: https://github.com/swagger-api/swagger-codegen +# __PACKAGE__->mk_classdata('attribute_map' => {}); __PACKAGE__->mk_classdata('swagger_types' => {}); __PACKAGE__->mk_classdata('method_documentation' => {}); @@ -110,14 +173,23 @@ __PACKAGE__->method_documentation({ format => '', read_only => '', }, + 'color' => { + datatype => 'string', + base_name => 'color', + description => '', + format => '', + read_only => '', + }, }); __PACKAGE__->swagger_types( { - 'class_name' => 'string' + 'class_name' => 'string', + 'color' => 'string' } ); __PACKAGE__->attribute_map( { - 'class_name' => 'className' + 'class_name' => 'className', + 'color' => 'color' } ); __PACKAGE__->mk_accessors(keys %{__PACKAGE__->attribute_map}); diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/AnimalFarm.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/AnimalFarm.pm new file mode 100644 index 00000000000..32424c88e52 --- /dev/null +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/AnimalFarm.pm @@ -0,0 +1,182 @@ +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the swagger code generator program. +# Do not edit the class manually. +# Ref: https://github.com/swagger-api/swagger-codegen +# +package WWW::SwaggerClient::Object::AnimalFarm; + +require 5.6.0; +use strict; +use warnings; +use utf8; +use JSON qw(decode_json); +use Data::Dumper; +use Module::Runtime qw(use_module); +use Log::Any qw($log); +use Date::Parse; +use DateTime; + +use base ("Class::Accessor", "Class::Data::Inheritable"); + + +# +# +# +# NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. +# REF: https://github.com/swagger-api/swagger-codegen +# + +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the swagger code generator program. +# Do not edit the class manually. +# Ref: https://github.com/swagger-api/swagger-codegen +# +__PACKAGE__->mk_classdata('attribute_map' => {}); +__PACKAGE__->mk_classdata('swagger_types' => {}); +__PACKAGE__->mk_classdata('method_documentation' => {}); +__PACKAGE__->mk_classdata('class_documentation' => {}); + +# new object +sub new { + my ($class, %args) = @_; + + my $self = bless {}, $class; + + foreach my $attribute (keys %{$class->attribute_map}) { + my $args_key = $class->attribute_map->{$attribute}; + $self->$attribute( $args{ $args_key } ); + } + + return $self; +} + +# return perl hash +sub to_hash { + return decode_json(JSON->new->convert_blessed->encode( shift )); +} + +# used by JSON for serialization +sub TO_JSON { + my $self = shift; + my $_data = {}; + foreach my $_key (keys %{$self->attribute_map}) { + if (defined $self->{$_key}) { + $_data->{$self->attribute_map->{$_key}} = $self->{$_key}; + } + } + return $_data; +} + +# from Perl hashref +sub from_hash { + my ($self, $hash) = @_; + + # loop through attributes and use swagger_types to deserialize the data + while ( my ($_key, $_type) = each %{$self->swagger_types} ) { + my $_json_attribute = $self->attribute_map->{$_key}; + if ($_type =~ /^array\[/i) { # array + my $_subclass = substr($_type, 6, -1); + my @_array = (); + foreach my $_element (@{$hash->{$_json_attribute}}) { + push @_array, $self->_deserialize($_subclass, $_element); + } + $self->{$_key} = \@_array; + } elsif (exists $hash->{$_json_attribute}) { #hash(model), primitive, datetime + $self->{$_key} = $self->_deserialize($_type, $hash->{$_json_attribute}); + } else { + $log->debugf("Warning: %s (%s) does not exist in input hash\n", $_key, $_json_attribute); + } + } + + return $self; +} + +# deserialize non-array data +sub _deserialize { + my ($self, $type, $data) = @_; + $log->debugf("deserializing %s with %s",Dumper($data), $type); + + if ($type eq 'DateTime') { + return DateTime->from_epoch(epoch => str2time($data)); + } elsif ( grep( /^$type$/, ('int', 'double', 'string', 'boolean'))) { + return $data; + } else { # hash(model) + my $_instance = eval "WWW::SwaggerClient::Object::$type->new()"; + return $_instance->from_hash($data); + } +} + + + +__PACKAGE__->class_documentation({description => '', + class => 'AnimalFarm', + required => [], # TODO +} ); + +__PACKAGE__->method_documentation({ +}); + +__PACKAGE__->swagger_types( { + +} ); + +__PACKAGE__->attribute_map( { + +} ); + +__PACKAGE__->mk_accessors(keys %{__PACKAGE__->attribute_map}); + + +1; diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/ApiResponse.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/ApiResponse.pm index 9203da585b7..d1ee5704703 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/ApiResponse.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/ApiResponse.pm @@ -1,3 +1,34 @@ +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the swagger code generator program. +# Do not edit the class manually. +# Ref: https://github.com/swagger-api/swagger-codegen +# package WWW::SwaggerClient::Object::ApiResponse; require 5.6.0; @@ -17,9 +48,41 @@ use base ("Class::Accessor", "Class::Data::Inheritable"); # # # -#NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. +# NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. +# REF: https://github.com/swagger-api/swagger-codegen # +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the swagger code generator program. +# Do not edit the class manually. +# Ref: https://github.com/swagger-api/swagger-codegen +# __PACKAGE__->mk_classdata('attribute_map' => {}); __PACKAGE__->mk_classdata('swagger_types' => {}); __PACKAGE__->mk_classdata('method_documentation' => {}); diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/ArrayTest.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/ArrayTest.pm new file mode 100644 index 00000000000..fa169ba4674 --- /dev/null +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/ArrayTest.pm @@ -0,0 +1,207 @@ +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the swagger code generator program. +# Do not edit the class manually. +# Ref: https://github.com/swagger-api/swagger-codegen +# +package WWW::SwaggerClient::Object::ArrayTest; + +require 5.6.0; +use strict; +use warnings; +use utf8; +use JSON qw(decode_json); +use Data::Dumper; +use Module::Runtime qw(use_module); +use Log::Any qw($log); +use Date::Parse; +use DateTime; + +use base ("Class::Accessor", "Class::Data::Inheritable"); + + +# +# +# +# NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. +# REF: https://github.com/swagger-api/swagger-codegen +# + +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the swagger code generator program. +# Do not edit the class manually. +# Ref: https://github.com/swagger-api/swagger-codegen +# +__PACKAGE__->mk_classdata('attribute_map' => {}); +__PACKAGE__->mk_classdata('swagger_types' => {}); +__PACKAGE__->mk_classdata('method_documentation' => {}); +__PACKAGE__->mk_classdata('class_documentation' => {}); + +# new object +sub new { + my ($class, %args) = @_; + + my $self = bless {}, $class; + + foreach my $attribute (keys %{$class->attribute_map}) { + my $args_key = $class->attribute_map->{$attribute}; + $self->$attribute( $args{ $args_key } ); + } + + return $self; +} + +# return perl hash +sub to_hash { + return decode_json(JSON->new->convert_blessed->encode( shift )); +} + +# used by JSON for serialization +sub TO_JSON { + my $self = shift; + my $_data = {}; + foreach my $_key (keys %{$self->attribute_map}) { + if (defined $self->{$_key}) { + $_data->{$self->attribute_map->{$_key}} = $self->{$_key}; + } + } + return $_data; +} + +# from Perl hashref +sub from_hash { + my ($self, $hash) = @_; + + # loop through attributes and use swagger_types to deserialize the data + while ( my ($_key, $_type) = each %{$self->swagger_types} ) { + my $_json_attribute = $self->attribute_map->{$_key}; + if ($_type =~ /^array\[/i) { # array + my $_subclass = substr($_type, 6, -1); + my @_array = (); + foreach my $_element (@{$hash->{$_json_attribute}}) { + push @_array, $self->_deserialize($_subclass, $_element); + } + $self->{$_key} = \@_array; + } elsif (exists $hash->{$_json_attribute}) { #hash(model), primitive, datetime + $self->{$_key} = $self->_deserialize($_type, $hash->{$_json_attribute}); + } else { + $log->debugf("Warning: %s (%s) does not exist in input hash\n", $_key, $_json_attribute); + } + } + + return $self; +} + +# deserialize non-array data +sub _deserialize { + my ($self, $type, $data) = @_; + $log->debugf("deserializing %s with %s",Dumper($data), $type); + + if ($type eq 'DateTime') { + return DateTime->from_epoch(epoch => str2time($data)); + } elsif ( grep( /^$type$/, ('int', 'double', 'string', 'boolean'))) { + return $data; + } else { # hash(model) + my $_instance = eval "WWW::SwaggerClient::Object::$type->new()"; + return $_instance->from_hash($data); + } +} + + + +__PACKAGE__->class_documentation({description => '', + class => 'ArrayTest', + required => [], # TODO +} ); + +__PACKAGE__->method_documentation({ + 'array_of_string' => { + datatype => 'ARRAY[string]', + base_name => 'array_of_string', + description => '', + format => '', + read_only => '', + }, + 'array_array_of_integer' => { + datatype => 'ARRAY[ARRAY[int]]', + base_name => 'array_array_of_integer', + description => '', + format => '', + read_only => '', + }, + 'array_array_of_model' => { + datatype => 'ARRAY[ARRAY[ReadOnlyFirst]]', + base_name => 'array_array_of_model', + description => '', + format => '', + read_only => '', + }, +}); + +__PACKAGE__->swagger_types( { + 'array_of_string' => 'ARRAY[string]', + 'array_array_of_integer' => 'ARRAY[ARRAY[int]]', + 'array_array_of_model' => 'ARRAY[ARRAY[ReadOnlyFirst]]' +} ); + +__PACKAGE__->attribute_map( { + 'array_of_string' => 'array_of_string', + 'array_array_of_integer' => 'array_array_of_integer', + 'array_array_of_model' => 'array_array_of_model' +} ); + +__PACKAGE__->mk_accessors(keys %{__PACKAGE__->attribute_map}); + + +1; diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Cat.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Cat.pm index 41e542afd9f..16d524d0c2d 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Cat.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Cat.pm @@ -1,3 +1,34 @@ +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the swagger code generator program. +# Do not edit the class manually. +# Ref: https://github.com/swagger-api/swagger-codegen +# package WWW::SwaggerClient::Object::Cat; require 5.6.0; @@ -17,9 +48,41 @@ use base ("Class::Accessor", "Class::Data::Inheritable"); # # # -#NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. +# NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. +# REF: https://github.com/swagger-api/swagger-codegen # +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the swagger code generator program. +# Do not edit the class manually. +# Ref: https://github.com/swagger-api/swagger-codegen +# __PACKAGE__->mk_classdata('attribute_map' => {}); __PACKAGE__->mk_classdata('swagger_types' => {}); __PACKAGE__->mk_classdata('method_documentation' => {}); @@ -110,6 +173,13 @@ __PACKAGE__->method_documentation({ format => '', read_only => '', }, + 'color' => { + datatype => 'string', + base_name => 'color', + description => '', + format => '', + read_only => '', + }, 'declawed' => { datatype => 'boolean', base_name => 'declawed', @@ -121,11 +191,13 @@ __PACKAGE__->method_documentation({ __PACKAGE__->swagger_types( { 'class_name' => 'string', + 'color' => 'string', 'declawed' => 'boolean' } ); __PACKAGE__->attribute_map( { 'class_name' => 'className', + 'color' => 'color', 'declawed' => 'declawed' } ); diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Category.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Category.pm index 2d49d6a99b8..30b83ba1e65 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Category.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Category.pm @@ -1,3 +1,34 @@ +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the swagger code generator program. +# Do not edit the class manually. +# Ref: https://github.com/swagger-api/swagger-codegen +# package WWW::SwaggerClient::Object::Category; require 5.6.0; @@ -17,9 +48,41 @@ use base ("Class::Accessor", "Class::Data::Inheritable"); # # # -#NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. +# NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. +# REF: https://github.com/swagger-api/swagger-codegen # +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the swagger code generator program. +# Do not edit the class manually. +# Ref: https://github.com/swagger-api/swagger-codegen +# __PACKAGE__->mk_classdata('attribute_map' => {}); __PACKAGE__->mk_classdata('swagger_types' => {}); __PACKAGE__->mk_classdata('method_documentation' => {}); diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Dog.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Dog.pm index 6ac41e2a9ff..4964f4dd97e 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Dog.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Dog.pm @@ -1,3 +1,34 @@ +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the swagger code generator program. +# Do not edit the class manually. +# Ref: https://github.com/swagger-api/swagger-codegen +# package WWW::SwaggerClient::Object::Dog; require 5.6.0; @@ -17,9 +48,41 @@ use base ("Class::Accessor", "Class::Data::Inheritable"); # # # -#NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. +# NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. +# REF: https://github.com/swagger-api/swagger-codegen # +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the swagger code generator program. +# Do not edit the class manually. +# Ref: https://github.com/swagger-api/swagger-codegen +# __PACKAGE__->mk_classdata('attribute_map' => {}); __PACKAGE__->mk_classdata('swagger_types' => {}); __PACKAGE__->mk_classdata('method_documentation' => {}); @@ -110,6 +173,13 @@ __PACKAGE__->method_documentation({ format => '', read_only => '', }, + 'color' => { + datatype => 'string', + base_name => 'color', + description => '', + format => '', + read_only => '', + }, 'breed' => { datatype => 'string', base_name => 'breed', @@ -121,11 +191,13 @@ __PACKAGE__->method_documentation({ __PACKAGE__->swagger_types( { 'class_name' => 'string', + 'color' => 'string', 'breed' => 'string' } ); __PACKAGE__->attribute_map( { 'class_name' => 'className', + 'color' => 'color', 'breed' => 'breed' } ); diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/EnumClass.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/EnumClass.pm new file mode 100644 index 00000000000..89ad6d8cc71 --- /dev/null +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/EnumClass.pm @@ -0,0 +1,182 @@ +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the swagger code generator program. +# Do not edit the class manually. +# Ref: https://github.com/swagger-api/swagger-codegen +# +package WWW::SwaggerClient::Object::EnumClass; + +require 5.6.0; +use strict; +use warnings; +use utf8; +use JSON qw(decode_json); +use Data::Dumper; +use Module::Runtime qw(use_module); +use Log::Any qw($log); +use Date::Parse; +use DateTime; + +use base ("Class::Accessor", "Class::Data::Inheritable"); + + +# +# +# +# NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. +# REF: https://github.com/swagger-api/swagger-codegen +# + +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the swagger code generator program. +# Do not edit the class manually. +# Ref: https://github.com/swagger-api/swagger-codegen +# +__PACKAGE__->mk_classdata('attribute_map' => {}); +__PACKAGE__->mk_classdata('swagger_types' => {}); +__PACKAGE__->mk_classdata('method_documentation' => {}); +__PACKAGE__->mk_classdata('class_documentation' => {}); + +# new object +sub new { + my ($class, %args) = @_; + + my $self = bless {}, $class; + + foreach my $attribute (keys %{$class->attribute_map}) { + my $args_key = $class->attribute_map->{$attribute}; + $self->$attribute( $args{ $args_key } ); + } + + return $self; +} + +# return perl hash +sub to_hash { + return decode_json(JSON->new->convert_blessed->encode( shift )); +} + +# used by JSON for serialization +sub TO_JSON { + my $self = shift; + my $_data = {}; + foreach my $_key (keys %{$self->attribute_map}) { + if (defined $self->{$_key}) { + $_data->{$self->attribute_map->{$_key}} = $self->{$_key}; + } + } + return $_data; +} + +# from Perl hashref +sub from_hash { + my ($self, $hash) = @_; + + # loop through attributes and use swagger_types to deserialize the data + while ( my ($_key, $_type) = each %{$self->swagger_types} ) { + my $_json_attribute = $self->attribute_map->{$_key}; + if ($_type =~ /^array\[/i) { # array + my $_subclass = substr($_type, 6, -1); + my @_array = (); + foreach my $_element (@{$hash->{$_json_attribute}}) { + push @_array, $self->_deserialize($_subclass, $_element); + } + $self->{$_key} = \@_array; + } elsif (exists $hash->{$_json_attribute}) { #hash(model), primitive, datetime + $self->{$_key} = $self->_deserialize($_type, $hash->{$_json_attribute}); + } else { + $log->debugf("Warning: %s (%s) does not exist in input hash\n", $_key, $_json_attribute); + } + } + + return $self; +} + +# deserialize non-array data +sub _deserialize { + my ($self, $type, $data) = @_; + $log->debugf("deserializing %s with %s",Dumper($data), $type); + + if ($type eq 'DateTime') { + return DateTime->from_epoch(epoch => str2time($data)); + } elsif ( grep( /^$type$/, ('int', 'double', 'string', 'boolean'))) { + return $data; + } else { # hash(model) + my $_instance = eval "WWW::SwaggerClient::Object::$type->new()"; + return $_instance->from_hash($data); + } +} + + + +__PACKAGE__->class_documentation({description => '', + class => 'EnumClass', + required => [], # TODO +} ); + +__PACKAGE__->method_documentation({ +}); + +__PACKAGE__->swagger_types( { + +} ); + +__PACKAGE__->attribute_map( { + +} ); + +__PACKAGE__->mk_accessors(keys %{__PACKAGE__->attribute_map}); + + +1; diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/EnumTest.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/EnumTest.pm new file mode 100644 index 00000000000..d1806d2b803 --- /dev/null +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/EnumTest.pm @@ -0,0 +1,207 @@ +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the swagger code generator program. +# Do not edit the class manually. +# Ref: https://github.com/swagger-api/swagger-codegen +# +package WWW::SwaggerClient::Object::EnumTest; + +require 5.6.0; +use strict; +use warnings; +use utf8; +use JSON qw(decode_json); +use Data::Dumper; +use Module::Runtime qw(use_module); +use Log::Any qw($log); +use Date::Parse; +use DateTime; + +use base ("Class::Accessor", "Class::Data::Inheritable"); + + +# +# +# +# NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. +# REF: https://github.com/swagger-api/swagger-codegen +# + +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the swagger code generator program. +# Do not edit the class manually. +# Ref: https://github.com/swagger-api/swagger-codegen +# +__PACKAGE__->mk_classdata('attribute_map' => {}); +__PACKAGE__->mk_classdata('swagger_types' => {}); +__PACKAGE__->mk_classdata('method_documentation' => {}); +__PACKAGE__->mk_classdata('class_documentation' => {}); + +# new object +sub new { + my ($class, %args) = @_; + + my $self = bless {}, $class; + + foreach my $attribute (keys %{$class->attribute_map}) { + my $args_key = $class->attribute_map->{$attribute}; + $self->$attribute( $args{ $args_key } ); + } + + return $self; +} + +# return perl hash +sub to_hash { + return decode_json(JSON->new->convert_blessed->encode( shift )); +} + +# used by JSON for serialization +sub TO_JSON { + my $self = shift; + my $_data = {}; + foreach my $_key (keys %{$self->attribute_map}) { + if (defined $self->{$_key}) { + $_data->{$self->attribute_map->{$_key}} = $self->{$_key}; + } + } + return $_data; +} + +# from Perl hashref +sub from_hash { + my ($self, $hash) = @_; + + # loop through attributes and use swagger_types to deserialize the data + while ( my ($_key, $_type) = each %{$self->swagger_types} ) { + my $_json_attribute = $self->attribute_map->{$_key}; + if ($_type =~ /^array\[/i) { # array + my $_subclass = substr($_type, 6, -1); + my @_array = (); + foreach my $_element (@{$hash->{$_json_attribute}}) { + push @_array, $self->_deserialize($_subclass, $_element); + } + $self->{$_key} = \@_array; + } elsif (exists $hash->{$_json_attribute}) { #hash(model), primitive, datetime + $self->{$_key} = $self->_deserialize($_type, $hash->{$_json_attribute}); + } else { + $log->debugf("Warning: %s (%s) does not exist in input hash\n", $_key, $_json_attribute); + } + } + + return $self; +} + +# deserialize non-array data +sub _deserialize { + my ($self, $type, $data) = @_; + $log->debugf("deserializing %s with %s",Dumper($data), $type); + + if ($type eq 'DateTime') { + return DateTime->from_epoch(epoch => str2time($data)); + } elsif ( grep( /^$type$/, ('int', 'double', 'string', 'boolean'))) { + return $data; + } else { # hash(model) + my $_instance = eval "WWW::SwaggerClient::Object::$type->new()"; + return $_instance->from_hash($data); + } +} + + + +__PACKAGE__->class_documentation({description => '', + class => 'EnumTest', + required => [], # TODO +} ); + +__PACKAGE__->method_documentation({ + 'enum_string' => { + datatype => 'string', + base_name => 'enum_string', + description => '', + format => '', + read_only => '', + }, + 'enum_integer' => { + datatype => 'int', + base_name => 'enum_integer', + description => '', + format => '', + read_only => '', + }, + 'enum_number' => { + datatype => 'double', + base_name => 'enum_number', + description => '', + format => '', + read_only => '', + }, +}); + +__PACKAGE__->swagger_types( { + 'enum_string' => 'string', + 'enum_integer' => 'int', + 'enum_number' => 'double' +} ); + +__PACKAGE__->attribute_map( { + 'enum_string' => 'enum_string', + 'enum_integer' => 'enum_integer', + 'enum_number' => 'enum_number' +} ); + +__PACKAGE__->mk_accessors(keys %{__PACKAGE__->attribute_map}); + + +1; diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/FormatTest.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/FormatTest.pm index 725c290b11d..c5779fbe5b9 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/FormatTest.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/FormatTest.pm @@ -1,3 +1,34 @@ +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the swagger code generator program. +# Do not edit the class manually. +# Ref: https://github.com/swagger-api/swagger-codegen +# package WWW::SwaggerClient::Object::FormatTest; require 5.6.0; @@ -17,9 +48,41 @@ use base ("Class::Accessor", "Class::Data::Inheritable"); # # # -#NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. +# NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. +# REF: https://github.com/swagger-api/swagger-codegen # +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the swagger code generator program. +# Do not edit the class manually. +# Ref: https://github.com/swagger-api/swagger-codegen +# __PACKAGE__->mk_classdata('attribute_map' => {}); __PACKAGE__->mk_classdata('swagger_types' => {}); __PACKAGE__->mk_classdata('method_documentation' => {}); @@ -180,6 +243,13 @@ __PACKAGE__->method_documentation({ format => '', read_only => '', }, + 'uuid' => { + datatype => 'UUID', + base_name => 'uuid', + description => '', + format => '', + read_only => '', + }, 'password' => { datatype => 'string', base_name => 'password', @@ -201,6 +271,7 @@ __PACKAGE__->swagger_types( { 'binary' => 'string', 'date' => 'DateTime', 'date_time' => 'DateTime', + 'uuid' => 'UUID', 'password' => 'string' } ); @@ -216,6 +287,7 @@ __PACKAGE__->attribute_map( { 'binary' => 'binary', 'date' => 'date', 'date_time' => 'dateTime', + 'uuid' => 'uuid', 'password' => 'password' } ); diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/MixedPropertiesAndAdditionalPropertiesClass.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/MixedPropertiesAndAdditionalPropertiesClass.pm new file mode 100644 index 00000000000..50a42581c27 --- /dev/null +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/MixedPropertiesAndAdditionalPropertiesClass.pm @@ -0,0 +1,207 @@ +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the swagger code generator program. +# Do not edit the class manually. +# Ref: https://github.com/swagger-api/swagger-codegen +# +package WWW::SwaggerClient::Object::MixedPropertiesAndAdditionalPropertiesClass; + +require 5.6.0; +use strict; +use warnings; +use utf8; +use JSON qw(decode_json); +use Data::Dumper; +use Module::Runtime qw(use_module); +use Log::Any qw($log); +use Date::Parse; +use DateTime; + +use base ("Class::Accessor", "Class::Data::Inheritable"); + + +# +# +# +# NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. +# REF: https://github.com/swagger-api/swagger-codegen +# + +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the swagger code generator program. +# Do not edit the class manually. +# Ref: https://github.com/swagger-api/swagger-codegen +# +__PACKAGE__->mk_classdata('attribute_map' => {}); +__PACKAGE__->mk_classdata('swagger_types' => {}); +__PACKAGE__->mk_classdata('method_documentation' => {}); +__PACKAGE__->mk_classdata('class_documentation' => {}); + +# new object +sub new { + my ($class, %args) = @_; + + my $self = bless {}, $class; + + foreach my $attribute (keys %{$class->attribute_map}) { + my $args_key = $class->attribute_map->{$attribute}; + $self->$attribute( $args{ $args_key } ); + } + + return $self; +} + +# return perl hash +sub to_hash { + return decode_json(JSON->new->convert_blessed->encode( shift )); +} + +# used by JSON for serialization +sub TO_JSON { + my $self = shift; + my $_data = {}; + foreach my $_key (keys %{$self->attribute_map}) { + if (defined $self->{$_key}) { + $_data->{$self->attribute_map->{$_key}} = $self->{$_key}; + } + } + return $_data; +} + +# from Perl hashref +sub from_hash { + my ($self, $hash) = @_; + + # loop through attributes and use swagger_types to deserialize the data + while ( my ($_key, $_type) = each %{$self->swagger_types} ) { + my $_json_attribute = $self->attribute_map->{$_key}; + if ($_type =~ /^array\[/i) { # array + my $_subclass = substr($_type, 6, -1); + my @_array = (); + foreach my $_element (@{$hash->{$_json_attribute}}) { + push @_array, $self->_deserialize($_subclass, $_element); + } + $self->{$_key} = \@_array; + } elsif (exists $hash->{$_json_attribute}) { #hash(model), primitive, datetime + $self->{$_key} = $self->_deserialize($_type, $hash->{$_json_attribute}); + } else { + $log->debugf("Warning: %s (%s) does not exist in input hash\n", $_key, $_json_attribute); + } + } + + return $self; +} + +# deserialize non-array data +sub _deserialize { + my ($self, $type, $data) = @_; + $log->debugf("deserializing %s with %s",Dumper($data), $type); + + if ($type eq 'DateTime') { + return DateTime->from_epoch(epoch => str2time($data)); + } elsif ( grep( /^$type$/, ('int', 'double', 'string', 'boolean'))) { + return $data; + } else { # hash(model) + my $_instance = eval "WWW::SwaggerClient::Object::$type->new()"; + return $_instance->from_hash($data); + } +} + + + +__PACKAGE__->class_documentation({description => '', + class => 'MixedPropertiesAndAdditionalPropertiesClass', + required => [], # TODO +} ); + +__PACKAGE__->method_documentation({ + 'uuid' => { + datatype => 'UUID', + base_name => 'uuid', + description => '', + format => '', + read_only => '', + }, + 'date_time' => { + datatype => 'DateTime', + base_name => 'dateTime', + description => '', + format => '', + read_only => '', + }, + 'map' => { + datatype => 'HASH[string,Animal]', + base_name => 'map', + description => '', + format => '', + read_only => '', + }, +}); + +__PACKAGE__->swagger_types( { + 'uuid' => 'UUID', + 'date_time' => 'DateTime', + 'map' => 'HASH[string,Animal]' +} ); + +__PACKAGE__->attribute_map( { + 'uuid' => 'uuid', + 'date_time' => 'dateTime', + 'map' => 'map' +} ); + +__PACKAGE__->mk_accessors(keys %{__PACKAGE__->attribute_map}); + + +1; diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Model200Response.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Model200Response.pm index d64f9497753..7bb7cce1a6e 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Model200Response.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Model200Response.pm @@ -1,3 +1,34 @@ +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the swagger code generator program. +# Do not edit the class manually. +# Ref: https://github.com/swagger-api/swagger-codegen +# package WWW::SwaggerClient::Object::Model200Response; require 5.6.0; @@ -17,9 +48,41 @@ use base ("Class::Accessor", "Class::Data::Inheritable"); # #Model for testing model name starting with number # -#NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. +# NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. +# REF: https://github.com/swagger-api/swagger-codegen # +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the swagger code generator program. +# Do not edit the class manually. +# Ref: https://github.com/swagger-api/swagger-codegen +# __PACKAGE__->mk_classdata('attribute_map' => {}); __PACKAGE__->mk_classdata('swagger_types' => {}); __PACKAGE__->mk_classdata('method_documentation' => {}); diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/ModelReturn.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/ModelReturn.pm index 682d26d7436..09af2a0884b 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/ModelReturn.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/ModelReturn.pm @@ -1,3 +1,34 @@ +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the swagger code generator program. +# Do not edit the class manually. +# Ref: https://github.com/swagger-api/swagger-codegen +# package WWW::SwaggerClient::Object::ModelReturn; require 5.6.0; @@ -17,9 +48,41 @@ use base ("Class::Accessor", "Class::Data::Inheritable"); # #Model for testing reserved words # -#NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. +# NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. +# REF: https://github.com/swagger-api/swagger-codegen # +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the swagger code generator program. +# Do not edit the class manually. +# Ref: https://github.com/swagger-api/swagger-codegen +# __PACKAGE__->mk_classdata('attribute_map' => {}); __PACKAGE__->mk_classdata('swagger_types' => {}); __PACKAGE__->mk_classdata('method_documentation' => {}); diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Name.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Name.pm index b5a58e0d5fa..50d950fb29a 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Name.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Name.pm @@ -1,3 +1,34 @@ +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the swagger code generator program. +# Do not edit the class manually. +# Ref: https://github.com/swagger-api/swagger-codegen +# package WWW::SwaggerClient::Object::Name; require 5.6.0; @@ -17,9 +48,41 @@ use base ("Class::Accessor", "Class::Data::Inheritable"); # #Model for testing model name same as property name # -#NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. +# NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. +# REF: https://github.com/swagger-api/swagger-codegen # +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the swagger code generator program. +# Do not edit the class manually. +# Ref: https://github.com/swagger-api/swagger-codegen +# __PACKAGE__->mk_classdata('attribute_map' => {}); __PACKAGE__->mk_classdata('swagger_types' => {}); __PACKAGE__->mk_classdata('method_documentation' => {}); @@ -117,16 +180,34 @@ __PACKAGE__->method_documentation({ format => '', read_only => '', }, + 'property' => { + datatype => 'string', + base_name => 'property', + description => '', + format => '', + read_only => '', + }, + '_123_number' => { + datatype => 'int', + base_name => '123Number', + description => '', + format => '', + read_only => '', + }, }); __PACKAGE__->swagger_types( { 'name' => 'int', - 'snake_case' => 'int' + 'snake_case' => 'int', + 'property' => 'string', + '_123_number' => 'int' } ); __PACKAGE__->attribute_map( { 'name' => 'name', - 'snake_case' => 'snake_case' + 'snake_case' => 'snake_case', + 'property' => 'property', + '_123_number' => '123Number' } ); __PACKAGE__->mk_accessors(keys %{__PACKAGE__->attribute_map}); diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Order.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Order.pm index 6590dba2293..c8fef7564cb 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Order.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Order.pm @@ -1,3 +1,34 @@ +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the swagger code generator program. +# Do not edit the class manually. +# Ref: https://github.com/swagger-api/swagger-codegen +# package WWW::SwaggerClient::Object::Order; require 5.6.0; @@ -17,9 +48,41 @@ use base ("Class::Accessor", "Class::Data::Inheritable"); # # # -#NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. +# NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. +# REF: https://github.com/swagger-api/swagger-codegen # +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the swagger code generator program. +# Do not edit the class manually. +# Ref: https://github.com/swagger-api/swagger-codegen +# __PACKAGE__->mk_classdata('attribute_map' => {}); __PACKAGE__->mk_classdata('swagger_types' => {}); __PACKAGE__->mk_classdata('method_documentation' => {}); diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Pet.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Pet.pm index 50334ab062a..e63f9a4a75a 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Pet.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Pet.pm @@ -1,3 +1,34 @@ +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the swagger code generator program. +# Do not edit the class manually. +# Ref: https://github.com/swagger-api/swagger-codegen +# package WWW::SwaggerClient::Object::Pet; require 5.6.0; @@ -17,9 +48,41 @@ use base ("Class::Accessor", "Class::Data::Inheritable"); # # # -#NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. +# NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. +# REF: https://github.com/swagger-api/swagger-codegen # +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the swagger code generator program. +# Do not edit the class manually. +# Ref: https://github.com/swagger-api/swagger-codegen +# __PACKAGE__->mk_classdata('attribute_map' => {}); __PACKAGE__->mk_classdata('swagger_types' => {}); __PACKAGE__->mk_classdata('method_documentation' => {}); diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/ReadOnlyFirst.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/ReadOnlyFirst.pm new file mode 100644 index 00000000000..45141fdd1ca --- /dev/null +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/ReadOnlyFirst.pm @@ -0,0 +1,198 @@ +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the swagger code generator program. +# Do not edit the class manually. +# Ref: https://github.com/swagger-api/swagger-codegen +# +package WWW::SwaggerClient::Object::ReadOnlyFirst; + +require 5.6.0; +use strict; +use warnings; +use utf8; +use JSON qw(decode_json); +use Data::Dumper; +use Module::Runtime qw(use_module); +use Log::Any qw($log); +use Date::Parse; +use DateTime; + +use base ("Class::Accessor", "Class::Data::Inheritable"); + + +# +# +# +# NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. +# REF: https://github.com/swagger-api/swagger-codegen +# + +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the swagger code generator program. +# Do not edit the class manually. +# Ref: https://github.com/swagger-api/swagger-codegen +# +__PACKAGE__->mk_classdata('attribute_map' => {}); +__PACKAGE__->mk_classdata('swagger_types' => {}); +__PACKAGE__->mk_classdata('method_documentation' => {}); +__PACKAGE__->mk_classdata('class_documentation' => {}); + +# new object +sub new { + my ($class, %args) = @_; + + my $self = bless {}, $class; + + foreach my $attribute (keys %{$class->attribute_map}) { + my $args_key = $class->attribute_map->{$attribute}; + $self->$attribute( $args{ $args_key } ); + } + + return $self; +} + +# return perl hash +sub to_hash { + return decode_json(JSON->new->convert_blessed->encode( shift )); +} + +# used by JSON for serialization +sub TO_JSON { + my $self = shift; + my $_data = {}; + foreach my $_key (keys %{$self->attribute_map}) { + if (defined $self->{$_key}) { + $_data->{$self->attribute_map->{$_key}} = $self->{$_key}; + } + } + return $_data; +} + +# from Perl hashref +sub from_hash { + my ($self, $hash) = @_; + + # loop through attributes and use swagger_types to deserialize the data + while ( my ($_key, $_type) = each %{$self->swagger_types} ) { + my $_json_attribute = $self->attribute_map->{$_key}; + if ($_type =~ /^array\[/i) { # array + my $_subclass = substr($_type, 6, -1); + my @_array = (); + foreach my $_element (@{$hash->{$_json_attribute}}) { + push @_array, $self->_deserialize($_subclass, $_element); + } + $self->{$_key} = \@_array; + } elsif (exists $hash->{$_json_attribute}) { #hash(model), primitive, datetime + $self->{$_key} = $self->_deserialize($_type, $hash->{$_json_attribute}); + } else { + $log->debugf("Warning: %s (%s) does not exist in input hash\n", $_key, $_json_attribute); + } + } + + return $self; +} + +# deserialize non-array data +sub _deserialize { + my ($self, $type, $data) = @_; + $log->debugf("deserializing %s with %s",Dumper($data), $type); + + if ($type eq 'DateTime') { + return DateTime->from_epoch(epoch => str2time($data)); + } elsif ( grep( /^$type$/, ('int', 'double', 'string', 'boolean'))) { + return $data; + } else { # hash(model) + my $_instance = eval "WWW::SwaggerClient::Object::$type->new()"; + return $_instance->from_hash($data); + } +} + + + +__PACKAGE__->class_documentation({description => '', + class => 'ReadOnlyFirst', + required => [], # TODO +} ); + +__PACKAGE__->method_documentation({ + 'bar' => { + datatype => 'string', + base_name => 'bar', + description => '', + format => '', + read_only => '', + }, + 'baz' => { + datatype => 'string', + base_name => 'baz', + description => '', + format => '', + read_only => '', + }, +}); + +__PACKAGE__->swagger_types( { + 'bar' => 'string', + 'baz' => 'string' +} ); + +__PACKAGE__->attribute_map( { + 'bar' => 'bar', + 'baz' => 'baz' +} ); + +__PACKAGE__->mk_accessors(keys %{__PACKAGE__->attribute_map}); + + +1; diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/SpecialModelName.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/SpecialModelName.pm index 5666b39c07b..e051fd994b6 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/SpecialModelName.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/SpecialModelName.pm @@ -1,3 +1,34 @@ +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the swagger code generator program. +# Do not edit the class manually. +# Ref: https://github.com/swagger-api/swagger-codegen +# package WWW::SwaggerClient::Object::SpecialModelName; require 5.6.0; @@ -17,9 +48,41 @@ use base ("Class::Accessor", "Class::Data::Inheritable"); # # # -#NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. +# NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. +# REF: https://github.com/swagger-api/swagger-codegen # +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the swagger code generator program. +# Do not edit the class manually. +# Ref: https://github.com/swagger-api/swagger-codegen +# __PACKAGE__->mk_classdata('attribute_map' => {}); __PACKAGE__->mk_classdata('swagger_types' => {}); __PACKAGE__->mk_classdata('method_documentation' => {}); diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Tag.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Tag.pm index b60ccc4a005..250a23c6870 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Tag.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Tag.pm @@ -1,3 +1,34 @@ +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the swagger code generator program. +# Do not edit the class manually. +# Ref: https://github.com/swagger-api/swagger-codegen +# package WWW::SwaggerClient::Object::Tag; require 5.6.0; @@ -17,9 +48,41 @@ use base ("Class::Accessor", "Class::Data::Inheritable"); # # # -#NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. +# NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. +# REF: https://github.com/swagger-api/swagger-codegen # +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the swagger code generator program. +# Do not edit the class manually. +# Ref: https://github.com/swagger-api/swagger-codegen +# __PACKAGE__->mk_classdata('attribute_map' => {}); __PACKAGE__->mk_classdata('swagger_types' => {}); __PACKAGE__->mk_classdata('method_documentation' => {}); diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/User.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/User.pm index 8b0555d8aaa..b5c5fcc6e7e 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/User.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/User.pm @@ -1,3 +1,34 @@ +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the swagger code generator program. +# Do not edit the class manually. +# Ref: https://github.com/swagger-api/swagger-codegen +# package WWW::SwaggerClient::Object::User; require 5.6.0; @@ -17,9 +48,41 @@ use base ("Class::Accessor", "Class::Data::Inheritable"); # # # -#NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. +# NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. +# REF: https://github.com/swagger-api/swagger-codegen # +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the swagger code generator program. +# Do not edit the class manually. +# Ref: https://github.com/swagger-api/swagger-codegen +# __PACKAGE__->mk_classdata('attribute_map' => {}); __PACKAGE__->mk_classdata('swagger_types' => {}); __PACKAGE__->mk_classdata('method_documentation' => {}); diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/PetApi.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/PetApi.pm index fd1b4092302..ecb7d70bf5b 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/PetApi.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/PetApi.pm @@ -1,21 +1,33 @@ -# -# Copyright 2016 SmartBear Software -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end comment + +=cut + # # NOTE: This class is auto generated by the swagger code generator program. # Do not edit the class manually. +# Ref: https://github.com/swagger-api/swagger-codegen # package WWW::SwaggerClient::PetApi; diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Role.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Role.pm index e72b12a22b8..cc146cb1890 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Role.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Role.pm @@ -1,3 +1,34 @@ +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the swagger code generator program. +# Do not edit the class manually. +# Ref: https://github.com/swagger-api/swagger-codegen +# package WWW::SwaggerClient::Role; use utf8; @@ -37,7 +68,7 @@ has version_info => ( is => 'ro', default => sub { { app_name => 'Swagger Petstore', app_version => '1.0.0', - generated_date => '2016-04-13T22:41:41.133+08:00', + generated_date => '2016-06-10T22:39:40.931+08:00', generator_class => 'class io.swagger.codegen.languages.PerlClientCodegen', } }, documentation => 'Information about the application version and the codegen codebase version' @@ -103,7 +134,7 @@ Automatically generated by the Perl Swagger Codegen project: =over 4 -=item Build date: 2016-04-13T22:41:41.133+08:00 +=item Build date: 2016-06-10T22:39:40.931+08:00 =item Build package: class io.swagger.codegen.languages.PerlClientCodegen diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Role/AutoDoc.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Role/AutoDoc.pm index d57c96c1798..55e8af85228 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Role/AutoDoc.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Role/AutoDoc.pm @@ -1,3 +1,34 @@ +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the swagger code generator program. +# Do not edit the class manually. +# Ref: https://github.com/swagger-api/swagger-codegen +# package WWW::SwaggerClient::Role::AutoDoc; use List::MoreUtils qw(uniq); diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/StoreApi.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/StoreApi.pm index 16a4f13cb1e..f29c64ec1a1 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/StoreApi.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/StoreApi.pm @@ -1,21 +1,33 @@ -# -# Copyright 2016 SmartBear Software -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end comment + +=cut + # # NOTE: This class is auto generated by the swagger code generator program. # Do not edit the class manually. +# Ref: https://github.com/swagger-api/swagger-codegen # package WWW::SwaggerClient::StoreApi; diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/UserApi.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/UserApi.pm index 75f56f56293..b6b5252e93e 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/UserApi.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/UserApi.pm @@ -1,21 +1,33 @@ -# -# Copyright 2016 SmartBear Software -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end comment + +=cut + # # NOTE: This class is auto generated by the swagger code generator program. # Do not edit the class manually. +# Ref: https://github.com/swagger-api/swagger-codegen # package WWW::SwaggerClient::UserApi; diff --git a/samples/client/petstore/perl/t/AdditionalPropertiesClassTest.t b/samples/client/petstore/perl/t/AdditionalPropertiesClassTest.t new file mode 100644 index 00000000000..03aa037413f --- /dev/null +++ b/samples/client/petstore/perl/t/AdditionalPropertiesClassTest.t @@ -0,0 +1,17 @@ +# NOTE: This class is auto generated by the Swagger Codegen +# Please update the test case below to test the model. + +use Test::More tests => 2; +use Test::Exception; + +use lib 'lib'; +use strict; +use warnings; + + +use_ok('WWW::SwaggerClient::Object::AdditionalPropertiesClass'); + +my $instance = WWW::SwaggerClient::Object::AdditionalPropertiesClass->new(); + +isa_ok($instance, 'WWW::SwaggerClient::Object::AdditionalPropertiesClass'); + diff --git a/samples/client/petstore/perl/t/AnimalFarmTest.t b/samples/client/petstore/perl/t/AnimalFarmTest.t new file mode 100644 index 00000000000..4c795259eec --- /dev/null +++ b/samples/client/petstore/perl/t/AnimalFarmTest.t @@ -0,0 +1,17 @@ +# NOTE: This class is auto generated by the Swagger Codegen +# Please update the test case below to test the model. + +use Test::More tests => 2; +use Test::Exception; + +use lib 'lib'; +use strict; +use warnings; + + +use_ok('WWW::SwaggerClient::Object::AnimalFarm'); + +my $instance = WWW::SwaggerClient::Object::AnimalFarm->new(); + +isa_ok($instance, 'WWW::SwaggerClient::Object::AnimalFarm'); + diff --git a/samples/client/petstore/perl/t/ArrayTestTest.t b/samples/client/petstore/perl/t/ArrayTestTest.t new file mode 100644 index 00000000000..3873ad59787 --- /dev/null +++ b/samples/client/petstore/perl/t/ArrayTestTest.t @@ -0,0 +1,17 @@ +# NOTE: This class is auto generated by the Swagger Codegen +# Please update the test case below to test the model. + +use Test::More tests => 2; +use Test::Exception; + +use lib 'lib'; +use strict; +use warnings; + + +use_ok('WWW::SwaggerClient::Object::ArrayTest'); + +my $instance = WWW::SwaggerClient::Object::ArrayTest->new(); + +isa_ok($instance, 'WWW::SwaggerClient::Object::ArrayTest'); + diff --git a/samples/client/petstore/perl/t/EnumClassTest.t b/samples/client/petstore/perl/t/EnumClassTest.t new file mode 100644 index 00000000000..c1843e3bab4 --- /dev/null +++ b/samples/client/petstore/perl/t/EnumClassTest.t @@ -0,0 +1,17 @@ +# NOTE: This class is auto generated by the Swagger Codegen +# Please update the test case below to test the model. + +use Test::More tests => 2; +use Test::Exception; + +use lib 'lib'; +use strict; +use warnings; + + +use_ok('WWW::SwaggerClient::Object::EnumClass'); + +my $instance = WWW::SwaggerClient::Object::EnumClass->new(); + +isa_ok($instance, 'WWW::SwaggerClient::Object::EnumClass'); + diff --git a/samples/client/petstore/perl/t/EnumTestTest.t b/samples/client/petstore/perl/t/EnumTestTest.t new file mode 100644 index 00000000000..6a72a3da4f7 --- /dev/null +++ b/samples/client/petstore/perl/t/EnumTestTest.t @@ -0,0 +1,17 @@ +# NOTE: This class is auto generated by the Swagger Codegen +# Please update the test case below to test the model. + +use Test::More tests => 2; +use Test::Exception; + +use lib 'lib'; +use strict; +use warnings; + + +use_ok('WWW::SwaggerClient::Object::EnumTest'); + +my $instance = WWW::SwaggerClient::Object::EnumTest->new(); + +isa_ok($instance, 'WWW::SwaggerClient::Object::EnumTest'); + diff --git a/samples/client/petstore/perl/t/FakeApiTest.t b/samples/client/petstore/perl/t/FakeApiTest.t new file mode 100644 index 00000000000..e57a0e5a048 --- /dev/null +++ b/samples/client/petstore/perl/t/FakeApiTest.t @@ -0,0 +1,52 @@ +# +# Copyright 2016 SmartBear Software +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# +# NOTE: This class is auto generated by Swagger Codegen +# Please update the test case below to test the API endpoints. +# +use Test::More tests => 1; #TODO update number of test cases +use Test::Exception; + +use lib 'lib'; +use strict; +use warnings; + +use_ok('WWW::SwaggerClient::FakeApi'); + +my $api = WWW::SwaggerClient::FakeApi->new(); +isa_ok($api, 'WWW::SwaggerClient::FakeApi'); + +# +# test_endpoint_parameters test +# +{ + my $number = undef; # replace NULL with a proper value + my $double = undef; # replace NULL with a proper value + my $string = undef; # replace NULL with a proper value + my $byte = undef; # replace NULL with a proper value + my $integer = undef; # replace NULL with a proper value + my $int32 = undef; # replace NULL with a proper value + my $int64 = undef; # replace NULL with a proper value + my $float = undef; # replace NULL with a proper value + my $binary = undef; # replace NULL with a proper value + my $date = undef; # replace NULL with a proper value + my $date_time = undef; # replace NULL with a proper value + my $password = undef; # replace NULL with a proper value + my $result = $api->test_endpoint_parameters(number => $number, double => $double, string => $string, byte => $byte, integer => $integer, int32 => $int32, int64 => $int64, float => $float, binary => $binary, date => $date, date_time => $date_time, password => $password); +} + + +1; diff --git a/samples/client/petstore/perl/t/MixedPropertiesAndAdditionalPropertiesClassTest.t b/samples/client/petstore/perl/t/MixedPropertiesAndAdditionalPropertiesClassTest.t new file mode 100644 index 00000000000..b6f764e8210 --- /dev/null +++ b/samples/client/petstore/perl/t/MixedPropertiesAndAdditionalPropertiesClassTest.t @@ -0,0 +1,17 @@ +# NOTE: This class is auto generated by the Swagger Codegen +# Please update the test case below to test the model. + +use Test::More tests => 2; +use Test::Exception; + +use lib 'lib'; +use strict; +use warnings; + + +use_ok('WWW::SwaggerClient::Object::MixedPropertiesAndAdditionalPropertiesClass'); + +my $instance = WWW::SwaggerClient::Object::MixedPropertiesAndAdditionalPropertiesClass->new(); + +isa_ok($instance, 'WWW::SwaggerClient::Object::MixedPropertiesAndAdditionalPropertiesClass'); + diff --git a/samples/client/petstore/perl/t/ReadOnlyFirstTest.t b/samples/client/petstore/perl/t/ReadOnlyFirstTest.t new file mode 100644 index 00000000000..9c35358bee1 --- /dev/null +++ b/samples/client/petstore/perl/t/ReadOnlyFirstTest.t @@ -0,0 +1,17 @@ +# NOTE: This class is auto generated by the Swagger Codegen +# Please update the test case below to test the model. + +use Test::More tests => 2; +use Test::Exception; + +use lib 'lib'; +use strict; +use warnings; + + +use_ok('WWW::SwaggerClient::Object::ReadOnlyFirst'); + +my $instance = WWW::SwaggerClient::Object::ReadOnlyFirst->new(); + +isa_ok($instance, 'WWW::SwaggerClient::Object::ReadOnlyFirst'); + diff --git a/samples/client/petstore/python/.gitignore b/samples/client/petstore/python/.gitignore index 1dbc687de01..a655050c263 100644 --- a/samples/client/petstore/python/.gitignore +++ b/samples/client/petstore/python/.gitignore @@ -44,6 +44,8 @@ nosetests.xml coverage.xml *,cover .hypothesis/ +venv/ +.python-version # Translations *.mo diff --git a/samples/client/petstore/python/Makefile b/samples/client/petstore/python/Makefile index 0f65e0c6ac3..52033cee703 100644 --- a/samples/client/petstore/python/Makefile +++ b/samples/client/petstore/python/Makefile @@ -15,7 +15,7 @@ clean: find . -name "__pycache__" -delete test: clean - bash ./test.sh + bash ./test_python2.sh test-all: clean - bash ./test-all.sh + bash ./test_python2_and_3.sh diff --git a/samples/client/petstore/python/README.md b/samples/client/petstore/python/README.md index 274de71c435..8fc15c13eec 100644 --- a/samples/client/petstore/python/README.md +++ b/samples/client/petstore/python/README.md @@ -1,11 +1,11 @@ -# swagger_client +# petstore_api This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ This Python package is automatically generated by the [Swagger Codegen](https://github.com/swagger-api/swagger-codegen) project: - API version: 1.0.0 - Package version: 1.0.0 -- Build date: 2016-06-02T12:44:41.178+09:00 +- Build date: 2016-06-09T08:00:02.342+09:00 - Build package: class io.swagger.codegen.languages.PythonClientCodegen ## Requirements. @@ -24,7 +24,7 @@ pip install git+https://github.com/GIT_USER_ID/GIT_REPO_ID.git Then import the package: ```python -import swagger_client +import petstore_api ``` ### Setuptools @@ -38,7 +38,7 @@ python setup.py install --user Then import the package: ```python -import swagger_client +import petstore_api ``` ## Getting Started @@ -47,11 +47,11 @@ Please follow the [installation procedure](#installation--usage) and then run th ```python import time -import swagger_client -from swagger_client.rest import ApiException +import petstore_api +from petstore_api.rest import ApiException from pprint import pprint # create an instance of the API class -api_instance = swagger_client.FakeApi +api_instance = petstore_api.FakeApi number = 3.4 # float | None double = 1.2 # float | None string = 'string_example' # str | None diff --git a/samples/client/petstore/python/docs/FakeApi.md b/samples/client/petstore/python/docs/FakeApi.md index 6853fa0bee9..16656613075 100644 --- a/samples/client/petstore/python/docs/FakeApi.md +++ b/samples/client/petstore/python/docs/FakeApi.md @@ -1,4 +1,4 @@ -# swagger_client.FakeApi +# petstore_api.FakeApi All URIs are relative to *http://petstore.swagger.io/v2* @@ -17,12 +17,12 @@ Fake endpoint for testing various parameters 假端點 偽のエンドポイン ### Example ```python import time -import swagger_client -from swagger_client.rest import ApiException +import petstore_api +from petstore_api.rest import ApiException from pprint import pprint # create an instance of the API class -api_instance = swagger_client.FakeApi() +api_instance = petstore_api.FakeApi() number = 3.4 # float | None double = 1.2 # float | None string = 'string_example' # str | None diff --git a/samples/client/petstore/python/docs/PetApi.md b/samples/client/petstore/python/docs/PetApi.md index fb69778f611..109b264942f 100644 --- a/samples/client/petstore/python/docs/PetApi.md +++ b/samples/client/petstore/python/docs/PetApi.md @@ -1,4 +1,4 @@ -# swagger_client.PetApi +# petstore_api.PetApi All URIs are relative to *http://petstore.swagger.io/v2* @@ -24,16 +24,16 @@ Add a new pet to the store ### Example ```python import time -import swagger_client -from swagger_client.rest import ApiException +import petstore_api +from petstore_api.rest import ApiException from pprint import pprint # Configure OAuth2 access token for authorization: petstore_auth -swagger_client.configuration.access_token = 'YOUR_ACCESS_TOKEN' +petstore_api.configuration.access_token = 'YOUR_ACCESS_TOKEN' # create an instance of the API class -api_instance = swagger_client.PetApi() -body = swagger_client.Pet() # Pet | Pet object that needs to be added to the store +api_instance = petstore_api.PetApi() +body = petstore_api.Pet() # Pet | Pet object that needs to be added to the store try: # Add a new pet to the store @@ -73,15 +73,15 @@ Deletes a pet ### Example ```python import time -import swagger_client -from swagger_client.rest import ApiException +import petstore_api +from petstore_api.rest import ApiException from pprint import pprint # Configure OAuth2 access token for authorization: petstore_auth -swagger_client.configuration.access_token = 'YOUR_ACCESS_TOKEN' +petstore_api.configuration.access_token = 'YOUR_ACCESS_TOKEN' # create an instance of the API class -api_instance = swagger_client.PetApi() +api_instance = petstore_api.PetApi() pet_id = 789 # int | Pet id to delete api_key = 'api_key_example' # str | (optional) @@ -124,15 +124,15 @@ Multiple status values can be provided with comma separated strings ### Example ```python import time -import swagger_client -from swagger_client.rest import ApiException +import petstore_api +from petstore_api.rest import ApiException from pprint import pprint # Configure OAuth2 access token for authorization: petstore_auth -swagger_client.configuration.access_token = 'YOUR_ACCESS_TOKEN' +petstore_api.configuration.access_token = 'YOUR_ACCESS_TOKEN' # create an instance of the API class -api_instance = swagger_client.PetApi() +api_instance = petstore_api.PetApi() status = ['status_example'] # list[str] | Status values that need to be considered for filter try: @@ -174,15 +174,15 @@ Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 ### Example ```python import time -import swagger_client -from swagger_client.rest import ApiException +import petstore_api +from petstore_api.rest import ApiException from pprint import pprint # Configure OAuth2 access token for authorization: petstore_auth -swagger_client.configuration.access_token = 'YOUR_ACCESS_TOKEN' +petstore_api.configuration.access_token = 'YOUR_ACCESS_TOKEN' # create an instance of the API class -api_instance = swagger_client.PetApi() +api_instance = petstore_api.PetApi() tags = ['tags_example'] # list[str] | Tags to filter by try: @@ -224,17 +224,17 @@ Returns a single pet ### Example ```python import time -import swagger_client -from swagger_client.rest import ApiException +import petstore_api +from petstore_api.rest import ApiException from pprint import pprint # Configure API key authorization: api_key -swagger_client.configuration.api_key['api_key'] = 'YOUR_API_KEY' +petstore_api.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' +# petstore_api.configuration.api_key_prefix['api_key'] = 'Bearer' # create an instance of the API class -api_instance = swagger_client.PetApi() +api_instance = petstore_api.PetApi() pet_id = 789 # int | ID of pet to return try: @@ -276,16 +276,16 @@ Update an existing pet ### Example ```python import time -import swagger_client -from swagger_client.rest import ApiException +import petstore_api +from petstore_api.rest import ApiException from pprint import pprint # Configure OAuth2 access token for authorization: petstore_auth -swagger_client.configuration.access_token = 'YOUR_ACCESS_TOKEN' +petstore_api.configuration.access_token = 'YOUR_ACCESS_TOKEN' # create an instance of the API class -api_instance = swagger_client.PetApi() -body = swagger_client.Pet() # Pet | Pet object that needs to be added to the store +api_instance = petstore_api.PetApi() +body = petstore_api.Pet() # Pet | Pet object that needs to be added to the store try: # Update an existing pet @@ -325,15 +325,15 @@ Updates a pet in the store with form data ### Example ```python import time -import swagger_client -from swagger_client.rest import ApiException +import petstore_api +from petstore_api.rest import ApiException from pprint import pprint # Configure OAuth2 access token for authorization: petstore_auth -swagger_client.configuration.access_token = 'YOUR_ACCESS_TOKEN' +petstore_api.configuration.access_token = 'YOUR_ACCESS_TOKEN' # create an instance of the API class -api_instance = swagger_client.PetApi() +api_instance = petstore_api.PetApi() pet_id = 789 # int | ID of pet that needs to be updated name = 'name_example' # str | Updated name of the pet (optional) status = 'status_example' # str | Updated status of the pet (optional) @@ -378,15 +378,15 @@ uploads an image ### Example ```python import time -import swagger_client -from swagger_client.rest import ApiException +import petstore_api +from petstore_api.rest import ApiException from pprint import pprint # Configure OAuth2 access token for authorization: petstore_auth -swagger_client.configuration.access_token = 'YOUR_ACCESS_TOKEN' +petstore_api.configuration.access_token = 'YOUR_ACCESS_TOKEN' # create an instance of the API class -api_instance = swagger_client.PetApi() +api_instance = petstore_api.PetApi() pet_id = 789 # int | ID of pet to update additional_metadata = 'additional_metadata_example' # str | Additional data to pass to server (optional) file = '/path/to/file.txt' # file | file to upload (optional) diff --git a/samples/client/petstore/python/docs/StoreApi.md b/samples/client/petstore/python/docs/StoreApi.md index 537009bde52..6b71a78659d 100644 --- a/samples/client/petstore/python/docs/StoreApi.md +++ b/samples/client/petstore/python/docs/StoreApi.md @@ -1,4 +1,4 @@ -# swagger_client.StoreApi +# petstore_api.StoreApi All URIs are relative to *http://petstore.swagger.io/v2* @@ -20,12 +20,12 @@ For valid response try integer IDs with value < 1000. Anything above 1000 or non ### Example ```python import time -import swagger_client -from swagger_client.rest import ApiException +import petstore_api +from petstore_api.rest import ApiException from pprint import pprint # create an instance of the API class -api_instance = swagger_client.StoreApi() +api_instance = petstore_api.StoreApi() order_id = 'order_id_example' # str | ID of the order that needs to be deleted try: @@ -66,17 +66,17 @@ Returns a map of status codes to quantities ### Example ```python import time -import swagger_client -from swagger_client.rest import ApiException +import petstore_api +from petstore_api.rest import ApiException from pprint import pprint # Configure API key authorization: api_key -swagger_client.configuration.api_key['api_key'] = 'YOUR_API_KEY' +petstore_api.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' +# petstore_api.configuration.api_key_prefix['api_key'] = 'Bearer' # create an instance of the API class -api_instance = swagger_client.StoreApi() +api_instance = petstore_api.StoreApi() try: # Returns pet inventories by status @@ -114,12 +114,12 @@ For valid response try integer IDs with value <= 5 or > 10. Other values will ge ### Example ```python import time -import swagger_client -from swagger_client.rest import ApiException +import petstore_api +from petstore_api.rest import ApiException from pprint import pprint # create an instance of the API class -api_instance = swagger_client.StoreApi() +api_instance = petstore_api.StoreApi() order_id = 789 # int | ID of pet that needs to be fetched try: @@ -161,13 +161,13 @@ Place an order for a pet ### Example ```python import time -import swagger_client -from swagger_client.rest import ApiException +import petstore_api +from petstore_api.rest import ApiException from pprint import pprint # create an instance of the API class -api_instance = swagger_client.StoreApi() -body = swagger_client.Order() # Order | order placed for purchasing the pet +api_instance = petstore_api.StoreApi() +body = petstore_api.Order() # Order | order placed for purchasing the pet try: # Place an order for a pet diff --git a/samples/client/petstore/python/docs/UserApi.md b/samples/client/petstore/python/docs/UserApi.md index 1975c1fe7f3..4009418b13c 100644 --- a/samples/client/petstore/python/docs/UserApi.md +++ b/samples/client/petstore/python/docs/UserApi.md @@ -1,4 +1,4 @@ -# swagger_client.UserApi +# petstore_api.UserApi All URIs are relative to *http://petstore.swagger.io/v2* @@ -24,13 +24,13 @@ This can only be done by the logged in user. ### Example ```python import time -import swagger_client -from swagger_client.rest import ApiException +import petstore_api +from petstore_api.rest import ApiException from pprint import pprint # create an instance of the API class -api_instance = swagger_client.UserApi() -body = swagger_client.User() # User | Created user object +api_instance = petstore_api.UserApi() +body = petstore_api.User() # User | Created user object try: # Create user @@ -70,13 +70,13 @@ Creates list of users with given input array ### Example ```python import time -import swagger_client -from swagger_client.rest import ApiException +import petstore_api +from petstore_api.rest import ApiException from pprint import pprint # create an instance of the API class -api_instance = swagger_client.UserApi() -body = [swagger_client.User()] # list[User] | List of user object +api_instance = petstore_api.UserApi() +body = [petstore_api.User()] # list[User] | List of user object try: # Creates list of users with given input array @@ -116,13 +116,13 @@ Creates list of users with given input array ### Example ```python import time -import swagger_client -from swagger_client.rest import ApiException +import petstore_api +from petstore_api.rest import ApiException from pprint import pprint # create an instance of the API class -api_instance = swagger_client.UserApi() -body = [swagger_client.User()] # list[User] | List of user object +api_instance = petstore_api.UserApi() +body = [petstore_api.User()] # list[User] | List of user object try: # Creates list of users with given input array @@ -162,12 +162,12 @@ This can only be done by the logged in user. ### Example ```python import time -import swagger_client -from swagger_client.rest import ApiException +import petstore_api +from petstore_api.rest import ApiException from pprint import pprint # create an instance of the API class -api_instance = swagger_client.UserApi() +api_instance = petstore_api.UserApi() username = 'username_example' # str | The name that needs to be deleted try: @@ -208,12 +208,12 @@ Get user by user name ### Example ```python import time -import swagger_client -from swagger_client.rest import ApiException +import petstore_api +from petstore_api.rest import ApiException from pprint import pprint # create an instance of the API class -api_instance = swagger_client.UserApi() +api_instance = petstore_api.UserApi() username = 'username_example' # str | The name that needs to be fetched. Use user1 for testing. try: @@ -255,12 +255,12 @@ Logs user into the system ### Example ```python import time -import swagger_client -from swagger_client.rest import ApiException +import petstore_api +from petstore_api.rest import ApiException from pprint import pprint # create an instance of the API class -api_instance = swagger_client.UserApi() +api_instance = petstore_api.UserApi() username = 'username_example' # str | The user name for login password = 'password_example' # str | The password for login in clear text @@ -304,12 +304,12 @@ Logs out current logged in user session ### Example ```python import time -import swagger_client -from swagger_client.rest import ApiException +import petstore_api +from petstore_api.rest import ApiException from pprint import pprint # create an instance of the API class -api_instance = swagger_client.UserApi() +api_instance = petstore_api.UserApi() try: # Logs out current logged in user session @@ -346,14 +346,14 @@ This can only be done by the logged in user. ### Example ```python import time -import swagger_client -from swagger_client.rest import ApiException +import petstore_api +from petstore_api.rest import ApiException from pprint import pprint # create an instance of the API class -api_instance = swagger_client.UserApi() +api_instance = petstore_api.UserApi() username = 'username_example' # str | name that need to be deleted -body = swagger_client.User() # User | Updated user object +body = petstore_api.User() # User | Updated user object try: # Updated user diff --git a/samples/client/petstore/python/swagger_client/__init__.py b/samples/client/petstore/python/petstore_api/__init__.py similarity index 99% rename from samples/client/petstore/python/swagger_client/__init__.py rename to samples/client/petstore/python/petstore_api/__init__.py index 13fbf2257b0..ae225644f73 100644 --- a/samples/client/petstore/python/swagger_client/__init__.py +++ b/samples/client/petstore/python/petstore_api/__init__.py @@ -8,13 +8,13 @@ OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io Generated by: https://github.com/swagger-api/swagger-codegen.git - + Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at - + http://www.apache.org/licenses/LICENSE-2.0 - + Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. diff --git a/samples/client/petstore/python/swagger_client/api_client.py b/samples/client/petstore/python/petstore_api/api_client.py similarity index 99% rename from samples/client/petstore/python/swagger_client/api_client.py rename to samples/client/petstore/python/petstore_api/api_client.py index 5d5a5fccc4c..5bc448a950c 100644 --- a/samples/client/petstore/python/swagger_client/api_client.py +++ b/samples/client/petstore/python/petstore_api/api_client.py @@ -191,7 +191,7 @@ class ApiClient(object): :return: The serialized form of data. """ types = (str, int, float, bool, tuple) - if sys.version_info < (3,0): + if sys.version_info < (3, 0): types = types + (unicode,) if isinstance(obj, type(None)): return None diff --git a/samples/client/petstore/python/swagger_client/apis/__init__.py b/samples/client/petstore/python/petstore_api/apis/__init__.py similarity index 100% rename from samples/client/petstore/python/swagger_client/apis/__init__.py rename to samples/client/petstore/python/petstore_api/apis/__init__.py diff --git a/samples/client/petstore/python/swagger_client/apis/fake_api.py b/samples/client/petstore/python/petstore_api/apis/fake_api.py similarity index 93% rename from samples/client/petstore/python/swagger_client/apis/fake_api.py rename to samples/client/petstore/python/petstore_api/apis/fake_api.py index f8c522d2bf8..317232217b8 100644 --- a/samples/client/petstore/python/swagger_client/apis/fake_api.py +++ b/samples/client/petstore/python/petstore_api/apis/fake_api.py @@ -8,13 +8,13 @@ OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io Generated by: https://github.com/swagger-api/swagger-codegen.git - + Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at - + http://www.apache.org/licenses/LICENSE-2.0 - + Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -95,7 +95,6 @@ class FakeApi(object): ) params[key] = val del params['kwargs'] - # verify the required parameter 'number' is set if ('number' not in params) or (params['number'] is None): raise ValueError("Missing the required parameter `number` when calling `test_endpoint_parameters`") @@ -109,31 +108,30 @@ 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: + 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: + 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: + 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: + 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): + 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: + 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: + 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: + 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: + 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: + 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: + 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: + 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/petstore_api/apis/pet_api.py similarity index 99% rename from samples/client/petstore/python/swagger_client/apis/pet_api.py rename to samples/client/petstore/python/petstore_api/apis/pet_api.py index dd730f31dfe..2f2ee4429c2 100644 --- a/samples/client/petstore/python/swagger_client/apis/pet_api.py +++ b/samples/client/petstore/python/petstore_api/apis/pet_api.py @@ -8,13 +8,13 @@ OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io Generated by: https://github.com/swagger-api/swagger-codegen.git - + Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at - + http://www.apache.org/licenses/LICENSE-2.0 - + Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -84,12 +84,10 @@ class PetApi(object): ) params[key] = val del params['kwargs'] - # verify the required parameter 'body' is set if ('body' not in params) or (params['body'] is None): raise ValueError("Missing the required parameter `body` when calling `add_pet`") - resource_path = '/pet'.replace('{format}', 'json') path_params = {} @@ -163,12 +161,10 @@ class PetApi(object): ) params[key] = val del params['kwargs'] - # verify the required parameter 'pet_id' is set if ('pet_id' not in params) or (params['pet_id'] is None): raise ValueError("Missing the required parameter `pet_id` when calling `delete_pet`") - resource_path = '/pet/{petId}'.replace('{format}', 'json') path_params = {} if 'pet_id' in params: @@ -243,12 +239,10 @@ class PetApi(object): ) params[key] = val del params['kwargs'] - # verify the required parameter 'status' is set if ('status' not in params) or (params['status'] is None): raise ValueError("Missing the required parameter `status` when calling `find_pets_by_status`") - resource_path = '/pet/findByStatus'.replace('{format}', 'json') path_params = {} @@ -321,12 +315,10 @@ class PetApi(object): ) params[key] = val del params['kwargs'] - # verify the required parameter 'tags' is set if ('tags' not in params) or (params['tags'] is None): raise ValueError("Missing the required parameter `tags` when calling `find_pets_by_tags`") - resource_path = '/pet/findByTags'.replace('{format}', 'json') path_params = {} @@ -399,12 +391,10 @@ class PetApi(object): ) params[key] = val del params['kwargs'] - # verify the required parameter 'pet_id' is set if ('pet_id' not in params) or (params['pet_id'] is None): raise ValueError("Missing the required parameter `pet_id` when calling `get_pet_by_id`") - resource_path = '/pet/{petId}'.replace('{format}', 'json') path_params = {} if 'pet_id' in params: @@ -477,12 +467,10 @@ class PetApi(object): ) params[key] = val del params['kwargs'] - # verify the required parameter 'body' is set if ('body' not in params) or (params['body'] is None): raise ValueError("Missing the required parameter `body` when calling `update_pet`") - resource_path = '/pet'.replace('{format}', 'json') path_params = {} @@ -557,12 +545,10 @@ class PetApi(object): ) params[key] = val del params['kwargs'] - # verify the required parameter 'pet_id' is set if ('pet_id' not in params) or (params['pet_id'] is None): raise ValueError("Missing the required parameter `pet_id` when calling `update_pet_with_form`") - resource_path = '/pet/{petId}'.replace('{format}', 'json') path_params = {} if 'pet_id' in params: @@ -641,12 +627,10 @@ class PetApi(object): ) params[key] = val del params['kwargs'] - # verify the required parameter 'pet_id' is set if ('pet_id' not in params) or (params['pet_id'] is None): raise ValueError("Missing the required parameter `pet_id` when calling `upload_file`") - 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/petstore_api/apis/store_api.py similarity index 98% rename from samples/client/petstore/python/swagger_client/apis/store_api.py rename to samples/client/petstore/python/petstore_api/apis/store_api.py index 61a2d50a5ff..e945b61509c 100644 --- a/samples/client/petstore/python/swagger_client/apis/store_api.py +++ b/samples/client/petstore/python/petstore_api/apis/store_api.py @@ -8,13 +8,13 @@ OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io Generated by: https://github.com/swagger-api/swagger-codegen.git - + Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at - + http://www.apache.org/licenses/LICENSE-2.0 - + Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -84,14 +84,12 @@ class StoreApi(object): ) params[key] = val del params['kwargs'] - # verify the required parameter 'order_id' is set if ('order_id' not in params) or (params['order_id'] is None): raise ValueError("Missing the required parameter `order_id` when calling `delete_order`") - if 'order_id' in params and params['order_id'] < 1.0: + 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: @@ -164,8 +162,6 @@ class StoreApi(object): params[key] = val del params['kwargs'] - - resource_path = '/store/inventory'.replace('{format}', 'json') path_params = {} @@ -236,16 +232,14 @@ class StoreApi(object): ) params[key] = val del params['kwargs'] - # verify the required parameter 'order_id' is set if ('order_id' not in params) or (params['order_id'] is None): raise ValueError("Missing the required parameter `order_id` when calling `get_order_by_id`") - if 'order_id' in params and params['order_id'] > 5.0: + 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: + 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: @@ -318,12 +312,10 @@ class StoreApi(object): ) params[key] = val del params['kwargs'] - # verify the required parameter 'body' is set if ('body' not in params) or (params['body'] is None): raise ValueError("Missing the required parameter `body` when calling `place_order`") - 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/petstore_api/apis/user_api.py similarity index 99% rename from samples/client/petstore/python/swagger_client/apis/user_api.py rename to samples/client/petstore/python/petstore_api/apis/user_api.py index 17865142a70..5a8f1815495 100644 --- a/samples/client/petstore/python/swagger_client/apis/user_api.py +++ b/samples/client/petstore/python/petstore_api/apis/user_api.py @@ -8,13 +8,13 @@ OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io Generated by: https://github.com/swagger-api/swagger-codegen.git - + Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at - + http://www.apache.org/licenses/LICENSE-2.0 - + Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -84,12 +84,10 @@ class UserApi(object): ) params[key] = val del params['kwargs'] - # verify the required parameter 'body' is set if ('body' not in params) or (params['body'] is None): raise ValueError("Missing the required parameter `body` when calling `create_user`") - resource_path = '/user'.replace('{format}', 'json') path_params = {} @@ -162,12 +160,10 @@ class UserApi(object): ) params[key] = val del params['kwargs'] - # verify the required parameter 'body' is set if ('body' not in params) or (params['body'] is None): raise ValueError("Missing the required parameter `body` when calling `create_users_with_array_input`") - resource_path = '/user/createWithArray'.replace('{format}', 'json') path_params = {} @@ -240,12 +236,10 @@ class UserApi(object): ) params[key] = val del params['kwargs'] - # verify the required parameter 'body' is set if ('body' not in params) or (params['body'] is None): raise ValueError("Missing the required parameter `body` when calling `create_users_with_list_input`") - resource_path = '/user/createWithList'.replace('{format}', 'json') path_params = {} @@ -318,12 +312,10 @@ class UserApi(object): ) params[key] = val del params['kwargs'] - # verify the required parameter 'username' is set if ('username' not in params) or (params['username'] is None): raise ValueError("Missing the required parameter `username` when calling `delete_user`") - resource_path = '/user/{username}'.replace('{format}', 'json') path_params = {} if 'username' in params: @@ -396,12 +388,10 @@ class UserApi(object): ) params[key] = val del params['kwargs'] - # verify the required parameter 'username' is set if ('username' not in params) or (params['username'] is None): raise ValueError("Missing the required parameter `username` when calling `get_user_by_name`") - resource_path = '/user/{username}'.replace('{format}', 'json') path_params = {} if 'username' in params: @@ -475,7 +465,6 @@ class UserApi(object): ) params[key] = val del params['kwargs'] - # verify the required parameter 'username' is set if ('username' not in params) or (params['username'] is None): raise ValueError("Missing the required parameter `username` when calling `login_user`") @@ -483,7 +472,6 @@ 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 = {} @@ -558,8 +546,6 @@ class UserApi(object): params[key] = val del params['kwargs'] - - resource_path = '/user/logout'.replace('{format}', 'json') path_params = {} @@ -631,7 +617,6 @@ class UserApi(object): ) params[key] = val del params['kwargs'] - # verify the required parameter 'username' is set if ('username' not in params) or (params['username'] is None): raise ValueError("Missing the required parameter `username` when calling `update_user`") @@ -639,7 +624,6 @@ 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/configuration.py b/samples/client/petstore/python/petstore_api/configuration.py similarity index 95% rename from samples/client/petstore/python/swagger_client/configuration.py rename to samples/client/petstore/python/petstore_api/configuration.py index a1efadf13b7..76f1f57c784 100644 --- a/samples/client/petstore/python/swagger_client/configuration.py +++ b/samples/client/petstore/python/petstore_api/configuration.py @@ -8,13 +8,13 @@ OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io Generated by: https://github.com/swagger-api/swagger-codegen.git - + Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at - + http://www.apache.org/licenses/LICENSE-2.0 - + Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -37,6 +37,7 @@ import logging from six import iteritems + def singleton(cls, *args, **kw): instances = {} @@ -79,10 +80,9 @@ class Configuration(object): # access token for OAuth self.access_token = "" - # Logging Settings self.logger = {} - self.logger["package_logger"] = logging.getLogger("swagger_client") + self.logger["package_logger"] = logging.getLogger("petstore_api") self.logger["urllib3_logger"] = logging.getLogger("urllib3") # Log format self.logger_format = '%(asctime)s %(levelname)s %(message)s' @@ -221,6 +221,14 @@ class Configuration(object): :return: The Auth Settings information dict. """ return { + + 'petstore_auth': + { + 'type': 'oauth2', + 'in': 'header', + 'key': 'Authorization', + 'value': 'Bearer ' + self.access_token + }, 'api_key': { 'type': 'api_key', diff --git a/samples/client/petstore/python/swagger_client/models/__init__.py b/samples/client/petstore/python/petstore_api/models/__init__.py similarity index 99% rename from samples/client/petstore/python/swagger_client/models/__init__.py rename to samples/client/petstore/python/petstore_api/models/__init__.py index a3c738c19a8..4ccf94c0415 100644 --- a/samples/client/petstore/python/swagger_client/models/__init__.py +++ b/samples/client/petstore/python/petstore_api/models/__init__.py @@ -8,13 +8,13 @@ OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io Generated by: https://github.com/swagger-api/swagger-codegen.git - + Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at - + http://www.apache.org/licenses/LICENSE-2.0 - + Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. diff --git a/samples/client/petstore/python/swagger_client/models/additional_properties_class.py b/samples/client/petstore/python/petstore_api/models/additional_properties_class.py similarity index 96% rename from samples/client/petstore/python/swagger_client/models/additional_properties_class.py rename to samples/client/petstore/python/petstore_api/models/additional_properties_class.py index c62cc80cd8a..b5383efed38 100644 --- a/samples/client/petstore/python/swagger_client/models/additional_properties_class.py +++ b/samples/client/petstore/python/petstore_api/models/additional_properties_class.py @@ -8,13 +8,13 @@ OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io Generated by: https://github.com/swagger-api/swagger-codegen.git - + Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at - + http://www.apache.org/licenses/LICENSE-2.0 - + Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -32,7 +32,7 @@ class AdditionalPropertiesClass(object): NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ - def __init__(self): + def __init__(self, map_property=None, map_of_map_property=None): """ AdditionalPropertiesClass - a model defined in Swagger @@ -51,8 +51,8 @@ class AdditionalPropertiesClass(object): 'map_of_map_property': 'map_of_map_property' } - self._map_property = None - self._map_of_map_property = None + self._map_property = map_property + self._map_of_map_property = map_of_map_property @property def map_property(self): @@ -74,7 +74,7 @@ class AdditionalPropertiesClass(object): :param map_property: The map_property of this AdditionalPropertiesClass. :type: dict(str, str) """ - + self._map_property = map_property @property @@ -97,7 +97,7 @@ class AdditionalPropertiesClass(object): :param map_of_map_property: The map_of_map_property of this AdditionalPropertiesClass. :type: dict(str, dict(str, str)) """ - + self._map_of_map_property = map_of_map_property def to_dict(self): @@ -149,4 +149,3 @@ class AdditionalPropertiesClass(object): Returns true if both objects are not equal """ return not self == other - diff --git a/samples/client/petstore/python/swagger_client/models/animal.py b/samples/client/petstore/python/petstore_api/models/animal.py similarity index 96% rename from samples/client/petstore/python/swagger_client/models/animal.py rename to samples/client/petstore/python/petstore_api/models/animal.py index 1fe5bc6d4ba..8a5b6499872 100644 --- a/samples/client/petstore/python/swagger_client/models/animal.py +++ b/samples/client/petstore/python/petstore_api/models/animal.py @@ -8,13 +8,13 @@ OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io Generated by: https://github.com/swagger-api/swagger-codegen.git - + Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at - + http://www.apache.org/licenses/LICENSE-2.0 - + Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -32,7 +32,7 @@ class Animal(object): NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ - def __init__(self): + def __init__(self, class_name=None, color='red'): """ Animal - a model defined in Swagger @@ -51,8 +51,8 @@ class Animal(object): 'color': 'color' } - self._class_name = None - self._color = 'red' + self._class_name = class_name + self._color = color @property def class_name(self): @@ -74,7 +74,7 @@ class Animal(object): :param class_name: The class_name of this Animal. :type: str """ - + self._class_name = class_name @property @@ -97,7 +97,7 @@ class Animal(object): :param color: The color of this Animal. :type: str """ - + self._color = color def to_dict(self): @@ -149,4 +149,3 @@ class Animal(object): Returns true if both objects are not equal """ return not self == other - diff --git a/samples/client/petstore/python/swagger_client/models/animal_farm.py b/samples/client/petstore/python/petstore_api/models/animal_farm.py similarity index 99% rename from samples/client/petstore/python/swagger_client/models/animal_farm.py rename to samples/client/petstore/python/petstore_api/models/animal_farm.py index d240be4b7ff..72fce33f252 100644 --- a/samples/client/petstore/python/swagger_client/models/animal_farm.py +++ b/samples/client/petstore/python/petstore_api/models/animal_farm.py @@ -8,13 +8,13 @@ OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io Generated by: https://github.com/swagger-api/swagger-codegen.git - + Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at - + http://www.apache.org/licenses/LICENSE-2.0 - + Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -49,7 +49,6 @@ class AnimalFarm(object): } - def to_dict(self): """ Returns the model properties as a dict @@ -99,4 +98,3 @@ class AnimalFarm(object): Returns true if both objects are not equal """ return not self == other - diff --git a/samples/client/petstore/python/swagger_client/models/api_response.py b/samples/client/petstore/python/petstore_api/models/api_response.py similarity index 96% rename from samples/client/petstore/python/swagger_client/models/api_response.py rename to samples/client/petstore/python/petstore_api/models/api_response.py index dfbe253b8d9..7cb5eb5c889 100644 --- a/samples/client/petstore/python/swagger_client/models/api_response.py +++ b/samples/client/petstore/python/petstore_api/models/api_response.py @@ -8,13 +8,13 @@ OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io Generated by: https://github.com/swagger-api/swagger-codegen.git - + Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at - + http://www.apache.org/licenses/LICENSE-2.0 - + Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -32,7 +32,7 @@ class ApiResponse(object): NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ - def __init__(self): + def __init__(self, code=None, type=None, message=None): """ ApiResponse - a model defined in Swagger @@ -53,9 +53,9 @@ class ApiResponse(object): 'message': 'message' } - self._code = None - self._type = None - self._message = None + self._code = code + self._type = type + self._message = message @property def code(self): @@ -77,7 +77,7 @@ class ApiResponse(object): :param code: The code of this ApiResponse. :type: int """ - + self._code = code @property @@ -100,7 +100,7 @@ class ApiResponse(object): :param type: The type of this ApiResponse. :type: str """ - + self._type = type @property @@ -123,7 +123,7 @@ class ApiResponse(object): :param message: The message of this ApiResponse. :type: str """ - + self._message = message def to_dict(self): @@ -175,4 +175,3 @@ class ApiResponse(object): Returns true if both objects are not equal """ return not self == other - diff --git a/samples/client/petstore/python/swagger_client/models/array_test.py b/samples/client/petstore/python/petstore_api/models/array_test.py similarity index 94% rename from samples/client/petstore/python/swagger_client/models/array_test.py rename to samples/client/petstore/python/petstore_api/models/array_test.py index def23e7cd5e..adaeecc2ed7 100644 --- a/samples/client/petstore/python/swagger_client/models/array_test.py +++ b/samples/client/petstore/python/petstore_api/models/array_test.py @@ -8,13 +8,13 @@ OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io Generated by: https://github.com/swagger-api/swagger-codegen.git - + Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at - + http://www.apache.org/licenses/LICENSE-2.0 - + Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -32,7 +32,7 @@ class ArrayTest(object): NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ - def __init__(self): + def __init__(self, array_of_string=None, array_array_of_integer=None, array_array_of_model=None): """ ArrayTest - a model defined in Swagger @@ -53,9 +53,9 @@ class ArrayTest(object): 'array_array_of_model': 'array_array_of_model' } - self._array_of_string = None - self._array_array_of_integer = None - self._array_array_of_model = None + self._array_of_string = array_of_string + self._array_array_of_integer = array_array_of_integer + self._array_array_of_model = array_array_of_model @property def array_of_string(self): @@ -77,7 +77,7 @@ class ArrayTest(object): :param array_of_string: The array_of_string of this ArrayTest. :type: list[str] """ - + self._array_of_string = array_of_string @property @@ -100,7 +100,7 @@ class ArrayTest(object): :param array_array_of_integer: The array_array_of_integer of this ArrayTest. :type: list[list[int]] """ - + self._array_array_of_integer = array_array_of_integer @property @@ -123,7 +123,7 @@ class ArrayTest(object): :param array_array_of_model: The array_array_of_model of this ArrayTest. :type: list[list[ReadOnlyFirst]] """ - + self._array_array_of_model = array_array_of_model def to_dict(self): @@ -175,4 +175,3 @@ class ArrayTest(object): Returns true if both objects are not equal """ return not self == other - diff --git a/samples/client/petstore/python/swagger_client/models/cat.py b/samples/client/petstore/python/petstore_api/models/cat.py similarity index 96% rename from samples/client/petstore/python/swagger_client/models/cat.py rename to samples/client/petstore/python/petstore_api/models/cat.py index 92fe431523c..a37e0b0674b 100644 --- a/samples/client/petstore/python/swagger_client/models/cat.py +++ b/samples/client/petstore/python/petstore_api/models/cat.py @@ -8,13 +8,13 @@ OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io Generated by: https://github.com/swagger-api/swagger-codegen.git - + Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at - + http://www.apache.org/licenses/LICENSE-2.0 - + Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -32,7 +32,7 @@ class Cat(object): NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ - def __init__(self): + def __init__(self, class_name=None, color='red', declawed=None): """ Cat - a model defined in Swagger @@ -53,9 +53,9 @@ class Cat(object): 'declawed': 'declawed' } - self._class_name = None - self._color = 'red' - self._declawed = None + self._class_name = class_name + self._color = color + self._declawed = declawed @property def class_name(self): @@ -77,7 +77,7 @@ class Cat(object): :param class_name: The class_name of this Cat. :type: str """ - + self._class_name = class_name @property @@ -100,7 +100,7 @@ class Cat(object): :param color: The color of this Cat. :type: str """ - + self._color = color @property @@ -123,7 +123,7 @@ class Cat(object): :param declawed: The declawed of this Cat. :type: bool """ - + self._declawed = declawed def to_dict(self): @@ -175,4 +175,3 @@ class Cat(object): Returns true if both objects are not equal """ return not self == other - diff --git a/samples/client/petstore/python/swagger_client/models/category.py b/samples/client/petstore/python/petstore_api/models/category.py similarity index 97% rename from samples/client/petstore/python/swagger_client/models/category.py rename to samples/client/petstore/python/petstore_api/models/category.py index 6962ce3a7a5..9adf7e1bab2 100644 --- a/samples/client/petstore/python/swagger_client/models/category.py +++ b/samples/client/petstore/python/petstore_api/models/category.py @@ -8,13 +8,13 @@ OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io Generated by: https://github.com/swagger-api/swagger-codegen.git - + Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at - + http://www.apache.org/licenses/LICENSE-2.0 - + Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -32,7 +32,7 @@ class Category(object): NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ - def __init__(self): + def __init__(self, id=None, name=None): """ Category - a model defined in Swagger @@ -51,8 +51,8 @@ class Category(object): 'name': 'name' } - self._id = None - self._name = None + self._id = id + self._name = name @property def id(self): @@ -74,7 +74,7 @@ class Category(object): :param id: The id of this Category. :type: int """ - + self._id = id @property @@ -97,7 +97,7 @@ class Category(object): :param name: The name of this Category. :type: str """ - + self._name = name def to_dict(self): @@ -149,4 +149,3 @@ class Category(object): Returns true if both objects are not equal """ return not self == other - diff --git a/samples/client/petstore/python/swagger_client/models/dog.py b/samples/client/petstore/python/petstore_api/models/dog.py similarity index 96% rename from samples/client/petstore/python/swagger_client/models/dog.py rename to samples/client/petstore/python/petstore_api/models/dog.py index 62b03f7a405..70225244a13 100644 --- a/samples/client/petstore/python/swagger_client/models/dog.py +++ b/samples/client/petstore/python/petstore_api/models/dog.py @@ -8,13 +8,13 @@ OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io Generated by: https://github.com/swagger-api/swagger-codegen.git - + Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at - + http://www.apache.org/licenses/LICENSE-2.0 - + Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -32,7 +32,7 @@ class Dog(object): NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ - def __init__(self): + def __init__(self, class_name=None, color='red', breed=None): """ Dog - a model defined in Swagger @@ -53,9 +53,9 @@ class Dog(object): 'breed': 'breed' } - self._class_name = None - self._color = 'red' - self._breed = None + self._class_name = class_name + self._color = color + self._breed = breed @property def class_name(self): @@ -77,7 +77,7 @@ class Dog(object): :param class_name: The class_name of this Dog. :type: str """ - + self._class_name = class_name @property @@ -100,7 +100,7 @@ class Dog(object): :param color: The color of this Dog. :type: str """ - + self._color = color @property @@ -123,7 +123,7 @@ class Dog(object): :param breed: The breed of this Dog. :type: str """ - + self._breed = breed def to_dict(self): @@ -175,4 +175,3 @@ class Dog(object): Returns true if both objects are not equal """ return not self == other - diff --git a/samples/client/petstore/python/swagger_client/models/enum_class.py b/samples/client/petstore/python/petstore_api/models/enum_class.py similarity index 99% rename from samples/client/petstore/python/swagger_client/models/enum_class.py rename to samples/client/petstore/python/petstore_api/models/enum_class.py index 1a7e9fec738..ec78827141b 100644 --- a/samples/client/petstore/python/swagger_client/models/enum_class.py +++ b/samples/client/petstore/python/petstore_api/models/enum_class.py @@ -8,13 +8,13 @@ OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io Generated by: https://github.com/swagger-api/swagger-codegen.git - + Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at - + http://www.apache.org/licenses/LICENSE-2.0 - + Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -49,7 +49,6 @@ class EnumClass(object): } - def to_dict(self): """ Returns the model properties as a dict @@ -99,4 +98,3 @@ class EnumClass(object): Returns true if both objects are not equal """ return not self == other - diff --git a/samples/client/petstore/python/swagger_client/models/enum_test.py b/samples/client/petstore/python/petstore_api/models/enum_test.py similarity index 96% rename from samples/client/petstore/python/swagger_client/models/enum_test.py rename to samples/client/petstore/python/petstore_api/models/enum_test.py index 0f6c734a5b4..faf89659ef2 100644 --- a/samples/client/petstore/python/swagger_client/models/enum_test.py +++ b/samples/client/petstore/python/petstore_api/models/enum_test.py @@ -8,13 +8,13 @@ OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io Generated by: https://github.com/swagger-api/swagger-codegen.git - + Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at - + http://www.apache.org/licenses/LICENSE-2.0 - + Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -32,7 +32,7 @@ class EnumTest(object): NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ - def __init__(self): + def __init__(self, enum_string=None, enum_integer=None, enum_number=None): """ EnumTest - a model defined in Swagger @@ -53,9 +53,9 @@ class EnumTest(object): 'enum_number': 'enum_number' } - self._enum_string = None - self._enum_integer = None - self._enum_number = None + self._enum_string = enum_string + self._enum_integer = enum_integer + self._enum_number = enum_number @property def enum_string(self): @@ -193,4 +193,3 @@ class EnumTest(object): Returns true if both objects are not equal """ return not self == other - diff --git a/samples/client/petstore/python/swagger_client/models/format_test.py b/samples/client/petstore/python/petstore_api/models/format_test.py similarity index 92% rename from samples/client/petstore/python/swagger_client/models/format_test.py rename to samples/client/petstore/python/petstore_api/models/format_test.py index b7aa17b3ee6..54522805164 100644 --- a/samples/client/petstore/python/swagger_client/models/format_test.py +++ b/samples/client/petstore/python/petstore_api/models/format_test.py @@ -8,13 +8,13 @@ OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io Generated by: https://github.com/swagger-api/swagger-codegen.git - + Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at - + http://www.apache.org/licenses/LICENSE-2.0 - + Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -32,7 +32,7 @@ class FormatTest(object): NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ - def __init__(self): + def __init__(self, integer=None, int32=None, int64=None, number=None, float=None, double=None, string=None, byte=None, binary=None, date=None, date_time=None, uuid=None, password=None): """ FormatTest - a model defined in Swagger @@ -73,19 +73,19 @@ class FormatTest(object): 'password': 'password' } - self._integer = None - self._int32 = None - self._int64 = None - self._number = None - self._float = None - self._double = None - self._string = None - self._byte = None - self._binary = None - self._date = None - self._date_time = None - self._uuid = None - self._password = None + self._integer = integer + self._int32 = int32 + self._int64 = int64 + self._number = number + self._float = float + self._double = double + self._string = string + self._byte = byte + self._binary = binary + self._date = date + self._date_time = date_time + self._uuid = uuid + self._password = password @property def integer(self): @@ -107,12 +107,12 @@ 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: + 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: + if integer < 10.0: raise ValueError("Invalid value for `integer`, must be a value greater than or equal to `10.0`") self._integer = integer @@ -137,12 +137,12 @@ 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: + 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: + if int32 < 20.0: raise ValueError("Invalid value for `int32`, must be a value greater than or equal to `20.0`") self._int32 = int32 @@ -167,7 +167,7 @@ class FormatTest(object): :param int64: The int64 of this FormatTest. :type: int """ - + self._int64 = int64 @property @@ -190,12 +190,12 @@ 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: + 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: + if number < 32.1: raise ValueError("Invalid value for `number`, must be a value greater than or equal to `32.1`") self._number = number @@ -220,12 +220,12 @@ 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: + 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: + if float < 54.3: raise ValueError("Invalid value for `float`, must be a value greater than or equal to `54.3`") self._float = float @@ -250,12 +250,12 @@ 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: + 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: + if double < 67.8: raise ValueError("Invalid value for `double`, must be a value greater than or equal to `67.8`") self._double = double @@ -280,10 +280,10 @@ 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): + 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 @@ -308,7 +308,7 @@ class FormatTest(object): :param byte: The byte of this FormatTest. :type: str """ - + self._byte = byte @property @@ -331,7 +331,7 @@ class FormatTest(object): :param binary: The binary of this FormatTest. :type: str """ - + self._binary = binary @property @@ -354,7 +354,7 @@ class FormatTest(object): :param date: The date of this FormatTest. :type: date """ - + self._date = date @property @@ -377,7 +377,7 @@ class FormatTest(object): :param date_time: The date_time of this FormatTest. :type: datetime """ - + self._date_time = date_time @property @@ -400,7 +400,7 @@ class FormatTest(object): :param uuid: The uuid of this FormatTest. :type: str """ - + self._uuid = uuid @property @@ -423,12 +423,12 @@ 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: + if len(password) > 64: raise ValueError("Invalid value for `password`, length must be less than `64`") - if len(password) < 10: + if len(password) < 10: raise ValueError("Invalid value for `password`, length must be greater than or equal to `10`") self._password = password @@ -482,4 +482,3 @@ class FormatTest(object): Returns true if both objects are not equal """ return not self == other - diff --git a/samples/client/petstore/python/swagger_client/models/mixed_properties_and_additional_properties_class.py b/samples/client/petstore/python/petstore_api/models/mixed_properties_and_additional_properties_class.py similarity index 96% rename from samples/client/petstore/python/swagger_client/models/mixed_properties_and_additional_properties_class.py rename to samples/client/petstore/python/petstore_api/models/mixed_properties_and_additional_properties_class.py index 2122cabdb53..9c4bdd2a851 100644 --- a/samples/client/petstore/python/swagger_client/models/mixed_properties_and_additional_properties_class.py +++ b/samples/client/petstore/python/petstore_api/models/mixed_properties_and_additional_properties_class.py @@ -8,13 +8,13 @@ OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io Generated by: https://github.com/swagger-api/swagger-codegen.git - + Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at - + http://www.apache.org/licenses/LICENSE-2.0 - + Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -32,7 +32,7 @@ class MixedPropertiesAndAdditionalPropertiesClass(object): NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ - def __init__(self): + def __init__(self, uuid=None, date_time=None, map=None): """ MixedPropertiesAndAdditionalPropertiesClass - a model defined in Swagger @@ -53,9 +53,9 @@ class MixedPropertiesAndAdditionalPropertiesClass(object): 'map': 'map' } - self._uuid = None - self._date_time = None - self._map = None + self._uuid = uuid + self._date_time = date_time + self._map = map @property def uuid(self): @@ -77,7 +77,7 @@ class MixedPropertiesAndAdditionalPropertiesClass(object): :param uuid: The uuid of this MixedPropertiesAndAdditionalPropertiesClass. :type: str """ - + self._uuid = uuid @property @@ -100,7 +100,7 @@ class MixedPropertiesAndAdditionalPropertiesClass(object): :param date_time: The date_time of this MixedPropertiesAndAdditionalPropertiesClass. :type: datetime """ - + self._date_time = date_time @property @@ -123,7 +123,7 @@ class MixedPropertiesAndAdditionalPropertiesClass(object): :param map: The map of this MixedPropertiesAndAdditionalPropertiesClass. :type: dict(str, Animal) """ - + self._map = map def to_dict(self): @@ -175,4 +175,3 @@ class MixedPropertiesAndAdditionalPropertiesClass(object): Returns true if both objects are not equal """ return not self == other - diff --git a/samples/client/petstore/python/swagger_client/models/model_200_response.py b/samples/client/petstore/python/petstore_api/models/model_200_response.py similarity index 97% rename from samples/client/petstore/python/swagger_client/models/model_200_response.py rename to samples/client/petstore/python/petstore_api/models/model_200_response.py index e566d5e16cd..95326567ada 100644 --- a/samples/client/petstore/python/swagger_client/models/model_200_response.py +++ b/samples/client/petstore/python/petstore_api/models/model_200_response.py @@ -8,13 +8,13 @@ OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io Generated by: https://github.com/swagger-api/swagger-codegen.git - + Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at - + http://www.apache.org/licenses/LICENSE-2.0 - + Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -32,7 +32,7 @@ class Model200Response(object): NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ - def __init__(self): + def __init__(self, name=None): """ Model200Response - a model defined in Swagger @@ -49,7 +49,7 @@ class Model200Response(object): 'name': 'name' } - self._name = None + self._name = name @property def name(self): @@ -71,7 +71,7 @@ class Model200Response(object): :param name: The name of this Model200Response. :type: int """ - + self._name = name def to_dict(self): @@ -123,4 +123,3 @@ class Model200Response(object): Returns true if both objects are not equal """ return not self == other - diff --git a/samples/client/petstore/python/swagger_client/models/model_return.py b/samples/client/petstore/python/petstore_api/models/model_return.py similarity index 97% rename from samples/client/petstore/python/swagger_client/models/model_return.py rename to samples/client/petstore/python/petstore_api/models/model_return.py index 840e64004d6..5587c068b0f 100644 --- a/samples/client/petstore/python/swagger_client/models/model_return.py +++ b/samples/client/petstore/python/petstore_api/models/model_return.py @@ -8,13 +8,13 @@ OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io Generated by: https://github.com/swagger-api/swagger-codegen.git - + Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at - + http://www.apache.org/licenses/LICENSE-2.0 - + Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -32,7 +32,7 @@ class ModelReturn(object): NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ - def __init__(self): + def __init__(self, _return=None): """ ModelReturn - a model defined in Swagger @@ -49,7 +49,7 @@ class ModelReturn(object): '_return': 'return' } - self.__return = None + self.__return = _return @property def _return(self): @@ -71,7 +71,7 @@ class ModelReturn(object): :param _return: The _return of this ModelReturn. :type: int """ - + self.__return = _return def to_dict(self): @@ -123,4 +123,3 @@ class ModelReturn(object): Returns true if both objects are not equal """ return not self == other - diff --git a/samples/client/petstore/python/swagger_client/models/name.py b/samples/client/petstore/python/petstore_api/models/name.py similarity index 87% rename from samples/client/petstore/python/swagger_client/models/name.py rename to samples/client/petstore/python/petstore_api/models/name.py index 8c66493dafa..fa489658960 100644 --- a/samples/client/petstore/python/swagger_client/models/name.py +++ b/samples/client/petstore/python/petstore_api/models/name.py @@ -8,13 +8,13 @@ OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io Generated by: https://github.com/swagger-api/swagger-codegen.git - + Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at - + http://www.apache.org/licenses/LICENSE-2.0 - + Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -32,7 +32,7 @@ class Name(object): NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ - def __init__(self): + def __init__(self, name=None, _property=None): """ Name - a model defined in Swagger @@ -55,10 +55,10 @@ class Name(object): '_123_number': '123Number' } - self._name = None self._snake_case = None - self.__property = None self.__123_number = None + self._name = name + self.__property = _property @property def name(self): @@ -80,7 +80,7 @@ class Name(object): :param name: The name of this Name. :type: int """ - + self._name = name @property @@ -94,18 +94,6 @@ class Name(object): """ return self._snake_case - @snake_case.setter - def snake_case(self, snake_case): - """ - Sets the snake_case of this Name. - - - :param snake_case: The snake_case of this Name. - :type: int - """ - - self._snake_case = snake_case - @property def _property(self): """ @@ -126,7 +114,7 @@ class Name(object): :param _property: The _property of this Name. :type: str """ - + self.__property = _property @property @@ -140,18 +128,6 @@ class Name(object): """ return self.__123_number - @_123_number.setter - def _123_number(self, _123_number): - """ - Sets the _123_number of this Name. - - - :param _123_number: The _123_number of this Name. - :type: int - """ - - self.__123_number = _123_number - def to_dict(self): """ Returns the model properties as a dict @@ -201,4 +177,3 @@ class Name(object): Returns true if both objects are not equal """ return not self == other - diff --git a/samples/client/petstore/python/swagger_client/models/order.py b/samples/client/petstore/python/petstore_api/models/order.py similarity index 95% rename from samples/client/petstore/python/swagger_client/models/order.py rename to samples/client/petstore/python/petstore_api/models/order.py index 54c30dea04c..98d36719006 100644 --- a/samples/client/petstore/python/swagger_client/models/order.py +++ b/samples/client/petstore/python/petstore_api/models/order.py @@ -8,13 +8,13 @@ OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io Generated by: https://github.com/swagger-api/swagger-codegen.git - + Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at - + http://www.apache.org/licenses/LICENSE-2.0 - + Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -32,7 +32,7 @@ class Order(object): NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ - def __init__(self): + def __init__(self, id=None, pet_id=None, quantity=None, ship_date=None, status=None, complete=False): """ Order - a model defined in Swagger @@ -59,12 +59,12 @@ class Order(object): 'complete': 'complete' } - self._id = None - self._pet_id = None - self._quantity = None - self._ship_date = None - self._status = None - self._complete = False + self._id = id + self._pet_id = pet_id + self._quantity = quantity + self._ship_date = ship_date + self._status = status + self._complete = complete @property def id(self): @@ -86,7 +86,7 @@ class Order(object): :param id: The id of this Order. :type: int """ - + self._id = id @property @@ -109,7 +109,7 @@ class Order(object): :param pet_id: The pet_id of this Order. :type: int """ - + self._pet_id = pet_id @property @@ -132,7 +132,7 @@ class Order(object): :param quantity: The quantity of this Order. :type: int """ - + self._quantity = quantity @property @@ -155,7 +155,7 @@ class Order(object): :param ship_date: The ship_date of this Order. :type: datetime """ - + self._ship_date = ship_date @property @@ -207,7 +207,7 @@ class Order(object): :param complete: The complete of this Order. :type: bool """ - + self._complete = complete def to_dict(self): @@ -259,4 +259,3 @@ class Order(object): Returns true if both objects are not equal """ return not self == other - diff --git a/samples/client/petstore/python/swagger_client/models/pet.py b/samples/client/petstore/python/petstore_api/models/pet.py similarity index 95% rename from samples/client/petstore/python/swagger_client/models/pet.py rename to samples/client/petstore/python/petstore_api/models/pet.py index f5dc79384b5..7a93da19db9 100644 --- a/samples/client/petstore/python/swagger_client/models/pet.py +++ b/samples/client/petstore/python/petstore_api/models/pet.py @@ -8,13 +8,13 @@ OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io Generated by: https://github.com/swagger-api/swagger-codegen.git - + Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at - + http://www.apache.org/licenses/LICENSE-2.0 - + Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -32,7 +32,7 @@ class Pet(object): NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ - def __init__(self): + def __init__(self, id=None, category=None, name=None, photo_urls=None, tags=None, status=None): """ Pet - a model defined in Swagger @@ -59,12 +59,12 @@ class Pet(object): 'status': 'status' } - self._id = None - self._category = None - self._name = None - self._photo_urls = None - self._tags = None - self._status = None + self._id = id + self._category = category + self._name = name + self._photo_urls = photo_urls + self._tags = tags + self._status = status @property def id(self): @@ -86,7 +86,7 @@ class Pet(object): :param id: The id of this Pet. :type: int """ - + self._id = id @property @@ -109,7 +109,7 @@ class Pet(object): :param category: The category of this Pet. :type: Category """ - + self._category = category @property @@ -132,7 +132,7 @@ class Pet(object): :param name: The name of this Pet. :type: str """ - + self._name = name @property @@ -155,7 +155,7 @@ class Pet(object): :param photo_urls: The photo_urls of this Pet. :type: list[str] """ - + self._photo_urls = photo_urls @property @@ -178,7 +178,7 @@ class Pet(object): :param tags: The tags of this Pet. :type: list[Tag] """ - + self._tags = tags @property @@ -259,4 +259,3 @@ class Pet(object): Returns true if both objects are not equal """ return not self == other - diff --git a/samples/client/petstore/python/swagger_client/models/read_only_first.py b/samples/client/petstore/python/petstore_api/models/read_only_first.py similarity index 92% rename from samples/client/petstore/python/swagger_client/models/read_only_first.py rename to samples/client/petstore/python/petstore_api/models/read_only_first.py index b4014f3a78b..c04d52501cf 100644 --- a/samples/client/petstore/python/swagger_client/models/read_only_first.py +++ b/samples/client/petstore/python/petstore_api/models/read_only_first.py @@ -8,13 +8,13 @@ OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io Generated by: https://github.com/swagger-api/swagger-codegen.git - + Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at - + http://www.apache.org/licenses/LICENSE-2.0 - + Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -32,7 +32,7 @@ class ReadOnlyFirst(object): NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ - def __init__(self): + def __init__(self, baz=None): """ ReadOnlyFirst - a model defined in Swagger @@ -52,7 +52,7 @@ class ReadOnlyFirst(object): } self._bar = None - self._baz = None + self._baz = baz @property def bar(self): @@ -65,18 +65,6 @@ class ReadOnlyFirst(object): """ return self._bar - @bar.setter - def bar(self, bar): - """ - Sets the bar of this ReadOnlyFirst. - - - :param bar: The bar of this ReadOnlyFirst. - :type: str - """ - - self._bar = bar - @property def baz(self): """ @@ -97,7 +85,7 @@ class ReadOnlyFirst(object): :param baz: The baz of this ReadOnlyFirst. :type: str """ - + self._baz = baz def to_dict(self): @@ -149,4 +137,3 @@ class ReadOnlyFirst(object): Returns true if both objects are not equal """ return not self == other - diff --git a/samples/client/petstore/python/swagger_client/models/special_model_name.py b/samples/client/petstore/python/petstore_api/models/special_model_name.py similarity index 96% rename from samples/client/petstore/python/swagger_client/models/special_model_name.py rename to samples/client/petstore/python/petstore_api/models/special_model_name.py index 9aac6ae248c..e48b7d79faf 100644 --- a/samples/client/petstore/python/swagger_client/models/special_model_name.py +++ b/samples/client/petstore/python/petstore_api/models/special_model_name.py @@ -8,13 +8,13 @@ OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io Generated by: https://github.com/swagger-api/swagger-codegen.git - + Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at - + http://www.apache.org/licenses/LICENSE-2.0 - + Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -32,7 +32,7 @@ class SpecialModelName(object): NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ - def __init__(self): + def __init__(self, special_property_name=None): """ SpecialModelName - a model defined in Swagger @@ -49,7 +49,7 @@ class SpecialModelName(object): 'special_property_name': '$special[property.name]' } - self._special_property_name = None + self._special_property_name = special_property_name @property def special_property_name(self): @@ -71,7 +71,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): @@ -123,4 +123,3 @@ class SpecialModelName(object): Returns true if both objects are not equal """ return not self == other - diff --git a/samples/client/petstore/python/swagger_client/models/tag.py b/samples/client/petstore/python/petstore_api/models/tag.py similarity index 97% rename from samples/client/petstore/python/swagger_client/models/tag.py rename to samples/client/petstore/python/petstore_api/models/tag.py index 9ba29be5cd1..95013b4fa8a 100644 --- a/samples/client/petstore/python/swagger_client/models/tag.py +++ b/samples/client/petstore/python/petstore_api/models/tag.py @@ -8,13 +8,13 @@ OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io Generated by: https://github.com/swagger-api/swagger-codegen.git - + Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at - + http://www.apache.org/licenses/LICENSE-2.0 - + Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -32,7 +32,7 @@ class Tag(object): NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ - def __init__(self): + def __init__(self, id=None, name=None): """ Tag - a model defined in Swagger @@ -51,8 +51,8 @@ class Tag(object): 'name': 'name' } - self._id = None - self._name = None + self._id = id + self._name = name @property def id(self): @@ -74,7 +74,7 @@ class Tag(object): :param id: The id of this Tag. :type: int """ - + self._id = id @property @@ -97,7 +97,7 @@ class Tag(object): :param name: The name of this Tag. :type: str """ - + self._name = name def to_dict(self): @@ -149,4 +149,3 @@ class Tag(object): Returns true if both objects are not equal """ return not self == other - diff --git a/samples/client/petstore/python/swagger_client/models/user.py b/samples/client/petstore/python/petstore_api/models/user.py similarity index 94% rename from samples/client/petstore/python/swagger_client/models/user.py rename to samples/client/petstore/python/petstore_api/models/user.py index 4559387a9fe..1caf604d825 100644 --- a/samples/client/petstore/python/swagger_client/models/user.py +++ b/samples/client/petstore/python/petstore_api/models/user.py @@ -8,13 +8,13 @@ OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io Generated by: https://github.com/swagger-api/swagger-codegen.git - + Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at - + http://www.apache.org/licenses/LICENSE-2.0 - + Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -32,7 +32,7 @@ class User(object): NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ - def __init__(self): + def __init__(self, id=None, username=None, first_name=None, last_name=None, email=None, password=None, phone=None, user_status=None): """ User - a model defined in Swagger @@ -63,14 +63,14 @@ class User(object): 'user_status': 'userStatus' } - self._id = None - self._username = None - self._first_name = None - self._last_name = None - self._email = None - self._password = None - self._phone = None - self._user_status = None + self._id = id + self._username = username + self._first_name = first_name + self._last_name = last_name + self._email = email + self._password = password + self._phone = phone + self._user_status = user_status @property def id(self): @@ -92,7 +92,7 @@ class User(object): :param id: The id of this User. :type: int """ - + self._id = id @property @@ -115,7 +115,7 @@ class User(object): :param username: The username of this User. :type: str """ - + self._username = username @property @@ -138,7 +138,7 @@ class User(object): :param first_name: The first_name of this User. :type: str """ - + self._first_name = first_name @property @@ -161,7 +161,7 @@ class User(object): :param last_name: The last_name of this User. :type: str """ - + self._last_name = last_name @property @@ -184,7 +184,7 @@ class User(object): :param email: The email of this User. :type: str """ - + self._email = email @property @@ -207,7 +207,7 @@ class User(object): :param password: The password of this User. :type: str """ - + self._password = password @property @@ -230,7 +230,7 @@ class User(object): :param phone: The phone of this User. :type: str """ - + self._phone = phone @property @@ -253,7 +253,7 @@ class User(object): :param user_status: The user_status of this User. :type: int """ - + self._user_status = user_status def to_dict(self): @@ -305,4 +305,3 @@ class User(object): Returns true if both objects are not equal """ return not self == other - diff --git a/samples/client/petstore/python/swagger_client/rest.py b/samples/client/petstore/python/petstore_api/rest.py similarity index 99% rename from samples/client/petstore/python/swagger_client/rest.py rename to samples/client/petstore/python/petstore_api/rest.py index de53bcacdb1..d27f1652706 100644 --- a/samples/client/petstore/python/swagger_client/rest.py +++ b/samples/client/petstore/python/petstore_api/rest.py @@ -8,13 +8,13 @@ OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io Generated by: https://github.com/swagger-api/swagger-codegen.git - + Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at - + http://www.apache.org/licenses/LICENSE-2.0 - + Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. diff --git a/samples/client/petstore/python/pom.xml b/samples/client/petstore/python/pom.xml index 147938617d2..6eaa49eaea9 100644 --- a/samples/client/petstore/python/pom.xml +++ b/samples/client/petstore/python/pom.xml @@ -1,6 +1,6 @@ 4.0.0 - com.wordnik + io.swagger PythonPetstoreClientTests pom 1.0-SNAPSHOT @@ -35,7 +35,7 @@ make - test + test-all diff --git a/samples/client/petstore/python/setup.cfg b/samples/client/petstore/python/setup.cfg index c9eef8726d6..26b7a359d58 100644 --- a/samples/client/petstore/python/setup.cfg +++ b/samples/client/petstore/python/setup.cfg @@ -4,7 +4,7 @@ verbosity=2 randomize=true exe=true with-coverage=true -cover-package=swagger_client +cover-package=petstore_api cover-erase=true [flake8] diff --git a/samples/client/petstore/python/setup.py b/samples/client/petstore/python/setup.py index a4d22d206ac..b15651ff2b5 100644 --- a/samples/client/petstore/python/setup.py +++ b/samples/client/petstore/python/setup.py @@ -8,13 +8,13 @@ OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io Generated by: https://github.com/swagger-api/swagger-codegen.git - + Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at - + http://www.apache.org/licenses/LICENSE-2.0 - + Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -25,11 +25,9 @@ import sys from setuptools import setup, find_packages -NAME = "swagger_client" +NAME = "petstore_api" VERSION = "1.0.0" - - # To install the library, run the following # # python setup.py install @@ -53,5 +51,3 @@ setup( This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ """ ) - - diff --git a/samples/client/petstore/python/swagger_client.egg-info/PKG-INFO b/samples/client/petstore/python/swagger_client.egg-info/PKG-INFO deleted file mode 100644 index 494a1526640..00000000000 --- a/samples/client/petstore/python/swagger_client.egg-info/PKG-INFO +++ /dev/null @@ -1,12 +0,0 @@ -Metadata-Version: 1.0 -Name: swagger-client -Version: 1.0.0 -Summary: Swagger Petstore -Home-page: UNKNOWN -Author: UNKNOWN -Author-email: apiteam@swagger.io -License: UNKNOWN -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: \" \ - -Keywords: Swagger,Swagger Petstore -Platform: UNKNOWN diff --git a/samples/client/petstore/python/swagger_client.egg-info/dependency_links.txt b/samples/client/petstore/python/swagger_client.egg-info/dependency_links.txt deleted file mode 100644 index 8b137891791..00000000000 --- a/samples/client/petstore/python/swagger_client.egg-info/dependency_links.txt +++ /dev/null @@ -1 +0,0 @@ - diff --git a/samples/client/petstore/python/swagger_client.egg-info/requires.txt b/samples/client/petstore/python/swagger_client.egg-info/requires.txt deleted file mode 100644 index 86355123cff..00000000000 --- a/samples/client/petstore/python/swagger_client.egg-info/requires.txt +++ /dev/null @@ -1,4 +0,0 @@ -urllib3 >= 1.15 -six >= 1.10 -certifi -python-dateutil diff --git a/samples/client/petstore/python/swagger_client.egg-info/top_level.txt b/samples/client/petstore/python/swagger_client.egg-info/top_level.txt deleted file mode 100644 index 01f6691e7ca..00000000000 --- a/samples/client/petstore/python/swagger_client.egg-info/top_level.txt +++ /dev/null @@ -1,3 +0,0 @@ -swagger_client -test -tests diff --git a/samples/client/petstore/python/swagger_client/models/inline_response_200.py b/samples/client/petstore/python/swagger_client/models/inline_response_200.py deleted file mode 100644 index f55ff5ee4d5..00000000000 --- a/samples/client/petstore/python/swagger_client/models/inline_response_200.py +++ /dev/null @@ -1,251 +0,0 @@ -# coding: utf-8 - -""" -Copyright 2016 SmartBear Software - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - - Ref: https://github.com/swagger-api/swagger-codegen -""" - -from pprint import pformat -from six import iteritems - - -class InlineResponse200(object): - """ - NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually. - """ - def __init__(self): - """ - InlineResponse200 - a model defined in Swagger - - :param dict swaggerTypes: The key is attribute name - and the value is attribute type. - :param dict attributeMap: The key is attribute name - and the value is json key in definition. - """ - self.swagger_types = { - 'tags': 'list[Tag]', - 'id': 'int', - 'category': 'object', - 'status': 'str', - 'name': 'str', - 'photo_urls': 'list[str]' - } - - self.attribute_map = { - 'tags': 'tags', - 'id': 'id', - 'category': 'category', - 'status': 'status', - 'name': 'name', - 'photo_urls': 'photoUrls' - } - - self._tags = None - self._id = None - self._category = None - self._status = None - self._name = None - self._photo_urls = None - - @property - def tags(self): - """ - Gets the tags of this InlineResponse200. - - - :return: The tags of this InlineResponse200. - :rtype: list[Tag] - """ - return self._tags - - @tags.setter - def tags(self, tags): - """ - Sets the tags of this InlineResponse200. - - - :param tags: The tags of this InlineResponse200. - :type: list[Tag] - """ - self._tags = tags - - @property - def id(self): - """ - Gets the id of this InlineResponse200. - - - :return: The id of this InlineResponse200. - :rtype: int - """ - return self._id - - @id.setter - def id(self, id): - """ - Sets the id of this InlineResponse200. - - - :param id: The id of this InlineResponse200. - :type: int - """ - self._id = id - - @property - def category(self): - """ - Gets the category of this InlineResponse200. - - - :return: The category of this InlineResponse200. - :rtype: object - """ - return self._category - - @category.setter - def category(self, category): - """ - Sets the category of this InlineResponse200. - - - :param category: The category of this InlineResponse200. - :type: object - """ - self._category = category - - @property - def status(self): - """ - Gets the status of this InlineResponse200. - pet status in the store - - :return: The status of this InlineResponse200. - :rtype: str - """ - return self._status - - @status.setter - def status(self, status): - """ - Sets the status of this InlineResponse200. - pet status in the store - - :param status: The status of this InlineResponse200. - :type: str - """ - allowed_values = ["available", "pending", "sold"] - if status not in allowed_values: - raise ValueError( - "Invalid value for `status`, must be one of {0}" - .format(allowed_values) - ) - self._status = status - - @property - def name(self): - """ - Gets the name of this InlineResponse200. - - - :return: The name of this InlineResponse200. - :rtype: str - """ - return self._name - - @name.setter - def name(self, name): - """ - Sets the name of this InlineResponse200. - - - :param name: The name of this InlineResponse200. - :type: str - """ - self._name = name - - @property - def photo_urls(self): - """ - Gets the photo_urls of this InlineResponse200. - - - :return: The photo_urls of this InlineResponse200. - :rtype: list[str] - """ - return self._photo_urls - - @photo_urls.setter - def photo_urls(self, photo_urls): - """ - Sets the photo_urls of this InlineResponse200. - - - :param photo_urls: The photo_urls of this InlineResponse200. - :type: list[str] - """ - self._photo_urls = photo_urls - - def to_dict(self): - """ - Returns the model properties as a dict - """ - result = {} - - for attr, _ in iteritems(self.swagger_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list(map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value - )) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict(map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") else item, - value.items() - )) - else: - result[attr] = value - - return result - - def to_str(self): - """ - Returns the string representation of the model - """ - return pformat(self.to_dict()) - - def __repr__(self): - """ - For `print` and `pprint` - """ - return self.to_str() - - def __eq__(self, other): - """ - Returns true if both objects are equal - """ - return self.__dict__ == other.__dict__ - - def __ne__(self, other): - """ - Returns true if both objects are not equal - """ - return not self == other - diff --git a/samples/client/petstore/python/test/test_additional_properties_class.py b/samples/client/petstore/python/test/test_additional_properties_class.py index 52163f2afec..de3d2bcd8b6 100644 --- a/samples/client/petstore/python/test/test_additional_properties_class.py +++ b/samples/client/petstore/python/test/test_additional_properties_class.py @@ -1,21 +1,25 @@ # coding: utf-8 """ -Copyright 2016 SmartBear Software + Swagger Petstore - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - http://www.apache.org/licenses/LICENSE-2.0 + OpenAPI spec version: 1.0.0 + Contact: apiteam@swagger.io + Generated by: https://github.com/swagger-api/swagger-codegen.git - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at - ref: https://github.com/swagger-api/swagger-codegen + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. """ from __future__ import absolute_import @@ -24,9 +28,9 @@ import os import sys import unittest -import swagger_client -from swagger_client.rest import ApiException -from swagger_client.models.additional_properties_class import AdditionalPropertiesClass +import petstore_api +from petstore_api.rest import ApiException +from petstore_api.models.additional_properties_class import AdditionalPropertiesClass class TestAdditionalPropertiesClass(unittest.TestCase): @@ -42,8 +46,8 @@ class TestAdditionalPropertiesClass(unittest.TestCase): """ Test AdditionalPropertiesClass """ - model = swagger_client.models.additional_properties_class.AdditionalPropertiesClass() + model = petstore_api.models.additional_properties_class.AdditionalPropertiesClass() if __name__ == '__main__': - unittest.main() \ No newline at end of file + unittest.main() diff --git a/samples/client/petstore/python/test/test_animal.py b/samples/client/petstore/python/test/test_animal.py index 279ed1850dd..7db98a10170 100644 --- a/samples/client/petstore/python/test/test_animal.py +++ b/samples/client/petstore/python/test/test_animal.py @@ -1,21 +1,25 @@ # coding: utf-8 """ -Copyright 2016 SmartBear Software + Swagger Petstore - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - http://www.apache.org/licenses/LICENSE-2.0 + OpenAPI spec version: 1.0.0 + Contact: apiteam@swagger.io + Generated by: https://github.com/swagger-api/swagger-codegen.git - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at - ref: https://github.com/swagger-api/swagger-codegen + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. """ from __future__ import absolute_import @@ -24,9 +28,9 @@ import os import sys import unittest -import swagger_client -from swagger_client.rest import ApiException -from swagger_client.models.animal import Animal +import petstore_api +from petstore_api.rest import ApiException +from petstore_api.models.animal import Animal class TestAnimal(unittest.TestCase): @@ -42,8 +46,8 @@ class TestAnimal(unittest.TestCase): """ Test Animal """ - model = swagger_client.models.animal.Animal() + model = petstore_api.models.animal.Animal() if __name__ == '__main__': - unittest.main() \ No newline at end of file + unittest.main() diff --git a/samples/client/petstore/python/test/test_animal_farm.py b/samples/client/petstore/python/test/test_animal_farm.py index 74dd22fd3b9..e4ecbf50478 100644 --- a/samples/client/petstore/python/test/test_animal_farm.py +++ b/samples/client/petstore/python/test/test_animal_farm.py @@ -1,21 +1,25 @@ # coding: utf-8 """ -Copyright 2016 SmartBear Software + Swagger Petstore - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - http://www.apache.org/licenses/LICENSE-2.0 + OpenAPI spec version: 1.0.0 + Contact: apiteam@swagger.io + Generated by: https://github.com/swagger-api/swagger-codegen.git - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at - ref: https://github.com/swagger-api/swagger-codegen + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. """ from __future__ import absolute_import @@ -24,9 +28,9 @@ import os import sys import unittest -import swagger_client -from swagger_client.rest import ApiException -from swagger_client.models.animal_farm import AnimalFarm +import petstore_api +from petstore_api.rest import ApiException +from petstore_api.models.animal_farm import AnimalFarm class TestAnimalFarm(unittest.TestCase): @@ -42,8 +46,8 @@ class TestAnimalFarm(unittest.TestCase): """ Test AnimalFarm """ - model = swagger_client.models.animal_farm.AnimalFarm() + model = petstore_api.models.animal_farm.AnimalFarm() if __name__ == '__main__': - unittest.main() \ No newline at end of file + unittest.main() diff --git a/samples/client/petstore/python/test/test_api_response.py b/samples/client/petstore/python/test/test_api_response.py index be73dbf373d..9c62f641cd7 100644 --- a/samples/client/petstore/python/test/test_api_response.py +++ b/samples/client/petstore/python/test/test_api_response.py @@ -1,21 +1,25 @@ # coding: utf-8 """ -Copyright 2016 SmartBear Software + Swagger Petstore - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - http://www.apache.org/licenses/LICENSE-2.0 + OpenAPI spec version: 1.0.0 + Contact: apiteam@swagger.io + Generated by: https://github.com/swagger-api/swagger-codegen.git - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at - ref: https://github.com/swagger-api/swagger-codegen + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. """ from __future__ import absolute_import @@ -24,9 +28,9 @@ import os import sys import unittest -import swagger_client -from swagger_client.rest import ApiException -from swagger_client.models.api_response import ApiResponse +import petstore_api +from petstore_api.rest import ApiException +from petstore_api.models.api_response import ApiResponse class TestApiResponse(unittest.TestCase): @@ -42,8 +46,8 @@ class TestApiResponse(unittest.TestCase): """ Test ApiResponse """ - model = swagger_client.models.api_response.ApiResponse() + model = petstore_api.models.api_response.ApiResponse() if __name__ == '__main__': - unittest.main() \ No newline at end of file + unittest.main() diff --git a/samples/client/petstore/python/test/test_array_test.py b/samples/client/petstore/python/test/test_array_test.py index 494596c842f..a5509779cc5 100644 --- a/samples/client/petstore/python/test/test_array_test.py +++ b/samples/client/petstore/python/test/test_array_test.py @@ -1,21 +1,25 @@ # coding: utf-8 """ -Copyright 2016 SmartBear Software + Swagger Petstore - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - http://www.apache.org/licenses/LICENSE-2.0 + OpenAPI spec version: 1.0.0 + Contact: apiteam@swagger.io + Generated by: https://github.com/swagger-api/swagger-codegen.git - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at - ref: https://github.com/swagger-api/swagger-codegen + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. """ from __future__ import absolute_import @@ -24,9 +28,9 @@ import os import sys import unittest -import swagger_client -from swagger_client.rest import ApiException -from swagger_client.models.array_test import ArrayTest +import petstore_api +from petstore_api.rest import ApiException +from petstore_api.models.array_test import ArrayTest class TestArrayTest(unittest.TestCase): @@ -42,8 +46,8 @@ class TestArrayTest(unittest.TestCase): """ Test ArrayTest """ - model = swagger_client.models.array_test.ArrayTest() + model = petstore_api.models.array_test.ArrayTest() if __name__ == '__main__': - unittest.main() \ No newline at end of file + unittest.main() diff --git a/samples/client/petstore/python/test/test_cat.py b/samples/client/petstore/python/test/test_cat.py index 728a824fa5b..3a9f7f1b75d 100644 --- a/samples/client/petstore/python/test/test_cat.py +++ b/samples/client/petstore/python/test/test_cat.py @@ -1,21 +1,25 @@ # coding: utf-8 """ -Copyright 2016 SmartBear Software + Swagger Petstore - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - http://www.apache.org/licenses/LICENSE-2.0 + OpenAPI spec version: 1.0.0 + Contact: apiteam@swagger.io + Generated by: https://github.com/swagger-api/swagger-codegen.git - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at - ref: https://github.com/swagger-api/swagger-codegen + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. """ from __future__ import absolute_import @@ -24,9 +28,9 @@ import os import sys import unittest -import swagger_client -from swagger_client.rest import ApiException -from swagger_client.models.cat import Cat +import petstore_api +from petstore_api.rest import ApiException +from petstore_api.models.cat import Cat class TestCat(unittest.TestCase): @@ -42,8 +46,8 @@ class TestCat(unittest.TestCase): """ Test Cat """ - model = swagger_client.models.cat.Cat() + model = petstore_api.models.cat.Cat() if __name__ == '__main__': - unittest.main() \ No newline at end of file + unittest.main() diff --git a/samples/client/petstore/python/test/test_category.py b/samples/client/petstore/python/test/test_category.py index 793fbdf41b0..f4f43796675 100644 --- a/samples/client/petstore/python/test/test_category.py +++ b/samples/client/petstore/python/test/test_category.py @@ -1,21 +1,25 @@ # coding: utf-8 """ -Copyright 2016 SmartBear Software + Swagger Petstore - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - http://www.apache.org/licenses/LICENSE-2.0 + OpenAPI spec version: 1.0.0 + Contact: apiteam@swagger.io + Generated by: https://github.com/swagger-api/swagger-codegen.git - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at - ref: https://github.com/swagger-api/swagger-codegen + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. """ from __future__ import absolute_import @@ -24,9 +28,9 @@ import os import sys import unittest -import swagger_client -from swagger_client.rest import ApiException -from swagger_client.models.category import Category +import petstore_api +from petstore_api.rest import ApiException +from petstore_api.models.category import Category class TestCategory(unittest.TestCase): @@ -42,8 +46,8 @@ class TestCategory(unittest.TestCase): """ Test Category """ - model = swagger_client.models.category.Category() + model = petstore_api.models.category.Category() if __name__ == '__main__': - unittest.main() \ No newline at end of file + unittest.main() diff --git a/samples/client/petstore/python/test/test_dog.py b/samples/client/petstore/python/test/test_dog.py index 044dc5be51f..6bac6d65c30 100644 --- a/samples/client/petstore/python/test/test_dog.py +++ b/samples/client/petstore/python/test/test_dog.py @@ -1,21 +1,25 @@ # coding: utf-8 """ -Copyright 2016 SmartBear Software + Swagger Petstore - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - http://www.apache.org/licenses/LICENSE-2.0 + OpenAPI spec version: 1.0.0 + Contact: apiteam@swagger.io + Generated by: https://github.com/swagger-api/swagger-codegen.git - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at - ref: https://github.com/swagger-api/swagger-codegen + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. """ from __future__ import absolute_import @@ -24,9 +28,9 @@ import os import sys import unittest -import swagger_client -from swagger_client.rest import ApiException -from swagger_client.models.dog import Dog +import petstore_api +from petstore_api.rest import ApiException +from petstore_api.models.dog import Dog class TestDog(unittest.TestCase): @@ -42,8 +46,8 @@ class TestDog(unittest.TestCase): """ Test Dog """ - model = swagger_client.models.dog.Dog() + model = petstore_api.models.dog.Dog() if __name__ == '__main__': - unittest.main() \ No newline at end of file + unittest.main() diff --git a/samples/client/petstore/python/test/test_enum_class.py b/samples/client/petstore/python/test/test_enum_class.py index 22e2b5ebb5c..6d9c50255df 100644 --- a/samples/client/petstore/python/test/test_enum_class.py +++ b/samples/client/petstore/python/test/test_enum_class.py @@ -1,21 +1,25 @@ # coding: utf-8 """ -Copyright 2016 SmartBear Software + Swagger Petstore - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - http://www.apache.org/licenses/LICENSE-2.0 + OpenAPI spec version: 1.0.0 + Contact: apiteam@swagger.io + Generated by: https://github.com/swagger-api/swagger-codegen.git - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at - ref: https://github.com/swagger-api/swagger-codegen + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. """ from __future__ import absolute_import @@ -24,9 +28,9 @@ import os import sys import unittest -import swagger_client -from swagger_client.rest import ApiException -from swagger_client.models.enum_class import EnumClass +import petstore_api +from petstore_api.rest import ApiException +from petstore_api.models.enum_class import EnumClass class TestEnumClass(unittest.TestCase): @@ -42,8 +46,8 @@ class TestEnumClass(unittest.TestCase): """ Test EnumClass """ - model = swagger_client.models.enum_class.EnumClass() + model = petstore_api.models.enum_class.EnumClass() if __name__ == '__main__': - unittest.main() \ No newline at end of file + unittest.main() diff --git a/samples/client/petstore/python/test/test_enum_test.py b/samples/client/petstore/python/test/test_enum_test.py index 49cb79e6bc3..aa8d86a6d78 100644 --- a/samples/client/petstore/python/test/test_enum_test.py +++ b/samples/client/petstore/python/test/test_enum_test.py @@ -1,21 +1,25 @@ # coding: utf-8 """ -Copyright 2016 SmartBear Software + Swagger Petstore - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - http://www.apache.org/licenses/LICENSE-2.0 + OpenAPI spec version: 1.0.0 + Contact: apiteam@swagger.io + Generated by: https://github.com/swagger-api/swagger-codegen.git - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at - ref: https://github.com/swagger-api/swagger-codegen + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. """ from __future__ import absolute_import @@ -24,9 +28,9 @@ import os import sys import unittest -import swagger_client -from swagger_client.rest import ApiException -from swagger_client.models.enum_test import EnumTest +import petstore_api +from petstore_api.rest import ApiException +from petstore_api.models.enum_test import EnumTest class TestEnumTest(unittest.TestCase): @@ -42,8 +46,8 @@ class TestEnumTest(unittest.TestCase): """ Test EnumTest """ - model = swagger_client.models.enum_test.EnumTest() + model = petstore_api.models.enum_test.EnumTest() if __name__ == '__main__': - unittest.main() \ No newline at end of file + unittest.main() diff --git a/samples/client/petstore/python/test/test_fake_api.py b/samples/client/petstore/python/test/test_fake_api.py index 29b71bdf81a..cddf28289ba 100644 --- a/samples/client/petstore/python/test/test_fake_api.py +++ b/samples/client/petstore/python/test/test_fake_api.py @@ -1,21 +1,25 @@ # coding: utf-8 """ -Copyright 2016 SmartBear Software + Swagger Petstore - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - http://www.apache.org/licenses/LICENSE-2.0 + OpenAPI spec version: 1.0.0 + Contact: apiteam@swagger.io + Generated by: https://github.com/swagger-api/swagger-codegen.git - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at - ref: https://github.com/swagger-api/swagger-codegen + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. """ from __future__ import absolute_import @@ -24,16 +28,16 @@ import os import sys import unittest -import swagger_client -from swagger_client.rest import ApiException -from swagger_client.apis.fake_api import FakeApi +import petstore_api +from petstore_api.rest import ApiException +from petstore_api.apis.fake_api import FakeApi class TestFakeApi(unittest.TestCase): """ FakeApi unit test stubs """ def setUp(self): - self.api = swagger_client.apis.fake_api.FakeApi() + self.api = petstore_api.apis.fake_api.FakeApi() def tearDown(self): pass @@ -42,10 +46,10 @@ class TestFakeApi(unittest.TestCase): """ Test case for test_endpoint_parameters - Fake endpoint for testing various parameters + Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 """ pass if __name__ == '__main__': - unittest.main() \ No newline at end of file + unittest.main() diff --git a/samples/client/petstore/python/test/test_format_test.py b/samples/client/petstore/python/test/test_format_test.py index 11101ad52da..2c3d0039dce 100644 --- a/samples/client/petstore/python/test/test_format_test.py +++ b/samples/client/petstore/python/test/test_format_test.py @@ -1,21 +1,25 @@ # coding: utf-8 """ -Copyright 2016 SmartBear Software + Swagger Petstore - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - http://www.apache.org/licenses/LICENSE-2.0 + OpenAPI spec version: 1.0.0 + Contact: apiteam@swagger.io + Generated by: https://github.com/swagger-api/swagger-codegen.git - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at - ref: https://github.com/swagger-api/swagger-codegen + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. """ from __future__ import absolute_import @@ -24,9 +28,9 @@ import os import sys import unittest -import swagger_client -from swagger_client.rest import ApiException -from swagger_client.models.format_test import FormatTest +import petstore_api +from petstore_api.rest import ApiException +from petstore_api.models.format_test import FormatTest class TestFormatTest(unittest.TestCase): @@ -42,8 +46,8 @@ class TestFormatTest(unittest.TestCase): """ Test FormatTest """ - model = swagger_client.models.format_test.FormatTest() + model = petstore_api.models.format_test.FormatTest() if __name__ == '__main__': - unittest.main() \ No newline at end of file + unittest.main() diff --git a/samples/client/petstore/python/test/test_mixed_properties_and_additional_properties_class.py b/samples/client/petstore/python/test/test_mixed_properties_and_additional_properties_class.py index 6cea606481c..90f13e029e2 100644 --- a/samples/client/petstore/python/test/test_mixed_properties_and_additional_properties_class.py +++ b/samples/client/petstore/python/test/test_mixed_properties_and_additional_properties_class.py @@ -1,21 +1,25 @@ # coding: utf-8 """ -Copyright 2016 SmartBear Software + Swagger Petstore - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - http://www.apache.org/licenses/LICENSE-2.0 + OpenAPI spec version: 1.0.0 + Contact: apiteam@swagger.io + Generated by: https://github.com/swagger-api/swagger-codegen.git - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at - ref: https://github.com/swagger-api/swagger-codegen + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. """ from __future__ import absolute_import @@ -24,9 +28,9 @@ import os import sys import unittest -import swagger_client -from swagger_client.rest import ApiException -from swagger_client.models.mixed_properties_and_additional_properties_class import MixedPropertiesAndAdditionalPropertiesClass +import petstore_api +from petstore_api.rest import ApiException +from petstore_api.models.mixed_properties_and_additional_properties_class import MixedPropertiesAndAdditionalPropertiesClass class TestMixedPropertiesAndAdditionalPropertiesClass(unittest.TestCase): @@ -42,8 +46,8 @@ class TestMixedPropertiesAndAdditionalPropertiesClass(unittest.TestCase): """ Test MixedPropertiesAndAdditionalPropertiesClass """ - model = swagger_client.models.mixed_properties_and_additional_properties_class.MixedPropertiesAndAdditionalPropertiesClass() + model = petstore_api.models.mixed_properties_and_additional_properties_class.MixedPropertiesAndAdditionalPropertiesClass() if __name__ == '__main__': - unittest.main() \ No newline at end of file + unittest.main() diff --git a/samples/client/petstore/python/test/test_model_200_response.py b/samples/client/petstore/python/test/test_model_200_response.py index 8328d2b9757..0b30fa81c89 100644 --- a/samples/client/petstore/python/test/test_model_200_response.py +++ b/samples/client/petstore/python/test/test_model_200_response.py @@ -1,21 +1,25 @@ # coding: utf-8 """ -Copyright 2016 SmartBear Software + Swagger Petstore - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - http://www.apache.org/licenses/LICENSE-2.0 + OpenAPI spec version: 1.0.0 + Contact: apiteam@swagger.io + Generated by: https://github.com/swagger-api/swagger-codegen.git - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at - ref: https://github.com/swagger-api/swagger-codegen + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. """ from __future__ import absolute_import @@ -24,9 +28,9 @@ import os import sys import unittest -import swagger_client -from swagger_client.rest import ApiException -from swagger_client.models.model_200_response import Model200Response +import petstore_api +from petstore_api.rest import ApiException +from petstore_api.models.model_200_response import Model200Response class TestModel200Response(unittest.TestCase): @@ -42,8 +46,8 @@ class TestModel200Response(unittest.TestCase): """ Test Model200Response """ - model = swagger_client.models.model_200_response.Model200Response() + model = petstore_api.models.model_200_response.Model200Response() if __name__ == '__main__': - unittest.main() \ No newline at end of file + unittest.main() diff --git a/samples/client/petstore/python/test/test_model_return.py b/samples/client/petstore/python/test/test_model_return.py index 4ff3f38b2eb..149d658c7cf 100644 --- a/samples/client/petstore/python/test/test_model_return.py +++ b/samples/client/petstore/python/test/test_model_return.py @@ -1,21 +1,25 @@ # coding: utf-8 """ -Copyright 2016 SmartBear Software + Swagger Petstore - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - http://www.apache.org/licenses/LICENSE-2.0 + OpenAPI spec version: 1.0.0 + Contact: apiteam@swagger.io + Generated by: https://github.com/swagger-api/swagger-codegen.git - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at - ref: https://github.com/swagger-api/swagger-codegen + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. """ from __future__ import absolute_import @@ -24,9 +28,9 @@ import os import sys import unittest -import swagger_client -from swagger_client.rest import ApiException -from swagger_client.models.model_return import ModelReturn +import petstore_api +from petstore_api.rest import ApiException +from petstore_api.models.model_return import ModelReturn class TestModelReturn(unittest.TestCase): @@ -42,8 +46,8 @@ class TestModelReturn(unittest.TestCase): """ Test ModelReturn """ - model = swagger_client.models.model_return.ModelReturn() + model = petstore_api.models.model_return.ModelReturn() if __name__ == '__main__': - unittest.main() \ No newline at end of file + unittest.main() diff --git a/samples/client/petstore/python/test/test_name.py b/samples/client/petstore/python/test/test_name.py index c3b27897eb1..ae3b6106d62 100644 --- a/samples/client/petstore/python/test/test_name.py +++ b/samples/client/petstore/python/test/test_name.py @@ -1,21 +1,25 @@ # coding: utf-8 """ -Copyright 2016 SmartBear Software + Swagger Petstore - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - http://www.apache.org/licenses/LICENSE-2.0 + OpenAPI spec version: 1.0.0 + Contact: apiteam@swagger.io + Generated by: https://github.com/swagger-api/swagger-codegen.git - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at - ref: https://github.com/swagger-api/swagger-codegen + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. """ from __future__ import absolute_import @@ -24,9 +28,9 @@ import os import sys import unittest -import swagger_client -from swagger_client.rest import ApiException -from swagger_client.models.name import Name +import petstore_api +from petstore_api.rest import ApiException +from petstore_api.models.name import Name class TestName(unittest.TestCase): @@ -42,8 +46,8 @@ class TestName(unittest.TestCase): """ Test Name """ - model = swagger_client.models.name.Name() + model = petstore_api.models.name.Name() if __name__ == '__main__': - unittest.main() \ No newline at end of file + unittest.main() diff --git a/samples/client/petstore/python/test/test_order.py b/samples/client/petstore/python/test/test_order.py index 23beefe346c..e2a1290ffc7 100644 --- a/samples/client/petstore/python/test/test_order.py +++ b/samples/client/petstore/python/test/test_order.py @@ -1,21 +1,25 @@ # coding: utf-8 """ -Copyright 2016 SmartBear Software + Swagger Petstore - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - http://www.apache.org/licenses/LICENSE-2.0 + OpenAPI spec version: 1.0.0 + Contact: apiteam@swagger.io + Generated by: https://github.com/swagger-api/swagger-codegen.git - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at - ref: https://github.com/swagger-api/swagger-codegen + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. """ from __future__ import absolute_import @@ -24,9 +28,9 @@ import os import sys import unittest -import swagger_client -from swagger_client.rest import ApiException -from swagger_client.models.order import Order +import petstore_api +from petstore_api.rest import ApiException +from petstore_api.models.order import Order class TestOrder(unittest.TestCase): @@ -42,8 +46,8 @@ class TestOrder(unittest.TestCase): """ Test Order """ - model = swagger_client.models.order.Order() + model = petstore_api.models.order.Order() if __name__ == '__main__': - unittest.main() \ No newline at end of file + unittest.main() diff --git a/samples/client/petstore/python/test/test_pet.py b/samples/client/petstore/python/test/test_pet.py index 471b7b4f67c..9148c0ac119 100644 --- a/samples/client/petstore/python/test/test_pet.py +++ b/samples/client/petstore/python/test/test_pet.py @@ -1,21 +1,25 @@ # coding: utf-8 """ -Copyright 2016 SmartBear Software + Swagger Petstore - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - http://www.apache.org/licenses/LICENSE-2.0 + OpenAPI spec version: 1.0.0 + Contact: apiteam@swagger.io + Generated by: https://github.com/swagger-api/swagger-codegen.git - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at - ref: https://github.com/swagger-api/swagger-codegen + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. """ from __future__ import absolute_import @@ -24,9 +28,9 @@ import os import sys import unittest -import swagger_client -from swagger_client.rest import ApiException -from swagger_client.models.pet import Pet +import petstore_api +from petstore_api.rest import ApiException +from petstore_api.models.pet import Pet class TestPet(unittest.TestCase): @@ -42,8 +46,8 @@ class TestPet(unittest.TestCase): """ Test Pet """ - model = swagger_client.models.pet.Pet() + model = petstore_api.models.pet.Pet() if __name__ == '__main__': - unittest.main() \ No newline at end of file + unittest.main() diff --git a/samples/client/petstore/python/test/test_pet_api.py b/samples/client/petstore/python/test/test_pet_api.py index 81ee6c76e9c..c9ef2d87c45 100644 --- a/samples/client/petstore/python/test/test_pet_api.py +++ b/samples/client/petstore/python/test/test_pet_api.py @@ -1,21 +1,25 @@ # coding: utf-8 """ -Copyright 2016 SmartBear Software + Swagger Petstore - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - http://www.apache.org/licenses/LICENSE-2.0 + OpenAPI spec version: 1.0.0 + Contact: apiteam@swagger.io + Generated by: https://github.com/swagger-api/swagger-codegen.git - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at - ref: https://github.com/swagger-api/swagger-codegen + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. """ from __future__ import absolute_import @@ -24,16 +28,16 @@ import os import sys import unittest -import swagger_client -from swagger_client.rest import ApiException -from swagger_client.apis.pet_api import PetApi +import petstore_api +from petstore_api.rest import ApiException +from petstore_api.apis.pet_api import PetApi class TestPetApi(unittest.TestCase): """ PetApi unit test stubs """ def setUp(self): - self.api = swagger_client.apis.pet_api.PetApi() + self.api = petstore_api.apis.pet_api.PetApi() def tearDown(self): pass @@ -104,4 +108,4 @@ class TestPetApi(unittest.TestCase): if __name__ == '__main__': - unittest.main() \ No newline at end of file + unittest.main() diff --git a/samples/client/petstore/python/test/test_read_only_first.py b/samples/client/petstore/python/test/test_read_only_first.py index d7073915dfe..3579ebefb48 100644 --- a/samples/client/petstore/python/test/test_read_only_first.py +++ b/samples/client/petstore/python/test/test_read_only_first.py @@ -1,21 +1,25 @@ # coding: utf-8 """ -Copyright 2016 SmartBear Software + Swagger Petstore - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - http://www.apache.org/licenses/LICENSE-2.0 + OpenAPI spec version: 1.0.0 + Contact: apiteam@swagger.io + Generated by: https://github.com/swagger-api/swagger-codegen.git - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at - ref: https://github.com/swagger-api/swagger-codegen + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. """ from __future__ import absolute_import @@ -24,9 +28,9 @@ import os import sys import unittest -import swagger_client -from swagger_client.rest import ApiException -from swagger_client.models.read_only_first import ReadOnlyFirst +import petstore_api +from petstore_api.rest import ApiException +from petstore_api.models.read_only_first import ReadOnlyFirst class TestReadOnlyFirst(unittest.TestCase): @@ -42,8 +46,8 @@ class TestReadOnlyFirst(unittest.TestCase): """ Test ReadOnlyFirst """ - model = swagger_client.models.read_only_first.ReadOnlyFirst() + model = petstore_api.models.read_only_first.ReadOnlyFirst() if __name__ == '__main__': - unittest.main() \ No newline at end of file + unittest.main() diff --git a/samples/client/petstore/python/test/test_special_model_name.py b/samples/client/petstore/python/test/test_special_model_name.py index 17c12655031..1991883e3c1 100644 --- a/samples/client/petstore/python/test/test_special_model_name.py +++ b/samples/client/petstore/python/test/test_special_model_name.py @@ -1,21 +1,25 @@ # coding: utf-8 """ -Copyright 2016 SmartBear Software + Swagger Petstore - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - http://www.apache.org/licenses/LICENSE-2.0 + OpenAPI spec version: 1.0.0 + Contact: apiteam@swagger.io + Generated by: https://github.com/swagger-api/swagger-codegen.git - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at - ref: https://github.com/swagger-api/swagger-codegen + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. """ from __future__ import absolute_import @@ -24,9 +28,9 @@ import os import sys import unittest -import swagger_client -from swagger_client.rest import ApiException -from swagger_client.models.special_model_name import SpecialModelName +import petstore_api +from petstore_api.rest import ApiException +from petstore_api.models.special_model_name import SpecialModelName class TestSpecialModelName(unittest.TestCase): @@ -42,8 +46,8 @@ class TestSpecialModelName(unittest.TestCase): """ Test SpecialModelName """ - model = swagger_client.models.special_model_name.SpecialModelName() + model = petstore_api.models.special_model_name.SpecialModelName() if __name__ == '__main__': - unittest.main() \ No newline at end of file + unittest.main() diff --git a/samples/client/petstore/python/test/test_store_api.py b/samples/client/petstore/python/test/test_store_api.py index e8dc0a64b1c..0278685372b 100644 --- a/samples/client/petstore/python/test/test_store_api.py +++ b/samples/client/petstore/python/test/test_store_api.py @@ -1,21 +1,25 @@ # coding: utf-8 """ -Copyright 2016 SmartBear Software + Swagger Petstore - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - http://www.apache.org/licenses/LICENSE-2.0 + OpenAPI spec version: 1.0.0 + Contact: apiteam@swagger.io + Generated by: https://github.com/swagger-api/swagger-codegen.git - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at - ref: https://github.com/swagger-api/swagger-codegen + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. """ from __future__ import absolute_import @@ -24,16 +28,16 @@ import os import sys import unittest -import swagger_client -from swagger_client.rest import ApiException -from swagger_client.apis.store_api import StoreApi +import petstore_api +from petstore_api.rest import ApiException +from petstore_api.apis.store_api import StoreApi class TestStoreApi(unittest.TestCase): """ StoreApi unit test stubs """ def setUp(self): - self.api = swagger_client.apis.store_api.StoreApi() + self.api = petstore_api.apis.store_api.StoreApi() def tearDown(self): pass @@ -72,4 +76,4 @@ class TestStoreApi(unittest.TestCase): if __name__ == '__main__': - unittest.main() \ No newline at end of file + unittest.main() diff --git a/samples/client/petstore/python/test/test_tag.py b/samples/client/petstore/python/test/test_tag.py index 35b51e4d7d2..c86dcbb1d5f 100644 --- a/samples/client/petstore/python/test/test_tag.py +++ b/samples/client/petstore/python/test/test_tag.py @@ -1,21 +1,25 @@ # coding: utf-8 """ -Copyright 2016 SmartBear Software + Swagger Petstore - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - http://www.apache.org/licenses/LICENSE-2.0 + OpenAPI spec version: 1.0.0 + Contact: apiteam@swagger.io + Generated by: https://github.com/swagger-api/swagger-codegen.git - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at - ref: https://github.com/swagger-api/swagger-codegen + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. """ from __future__ import absolute_import @@ -24,9 +28,9 @@ import os import sys import unittest -import swagger_client -from swagger_client.rest import ApiException -from swagger_client.models.tag import Tag +import petstore_api +from petstore_api.rest import ApiException +from petstore_api.models.tag import Tag class TestTag(unittest.TestCase): @@ -42,8 +46,8 @@ class TestTag(unittest.TestCase): """ Test Tag """ - model = swagger_client.models.tag.Tag() + model = petstore_api.models.tag.Tag() if __name__ == '__main__': - unittest.main() \ No newline at end of file + unittest.main() diff --git a/samples/client/petstore/python/test/test_user.py b/samples/client/petstore/python/test/test_user.py index 1aad154cbf8..328c07baa88 100644 --- a/samples/client/petstore/python/test/test_user.py +++ b/samples/client/petstore/python/test/test_user.py @@ -1,21 +1,25 @@ # coding: utf-8 """ -Copyright 2016 SmartBear Software + Swagger Petstore - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - http://www.apache.org/licenses/LICENSE-2.0 + OpenAPI spec version: 1.0.0 + Contact: apiteam@swagger.io + Generated by: https://github.com/swagger-api/swagger-codegen.git - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at - ref: https://github.com/swagger-api/swagger-codegen + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. """ from __future__ import absolute_import @@ -24,9 +28,9 @@ import os import sys import unittest -import swagger_client -from swagger_client.rest import ApiException -from swagger_client.models.user import User +import petstore_api +from petstore_api.rest import ApiException +from petstore_api.models.user import User class TestUser(unittest.TestCase): @@ -42,8 +46,8 @@ class TestUser(unittest.TestCase): """ Test User """ - model = swagger_client.models.user.User() + model = petstore_api.models.user.User() if __name__ == '__main__': - unittest.main() \ No newline at end of file + unittest.main() diff --git a/samples/client/petstore/python/test/test_user_api.py b/samples/client/petstore/python/test/test_user_api.py index 0205fe7383a..032d00af315 100644 --- a/samples/client/petstore/python/test/test_user_api.py +++ b/samples/client/petstore/python/test/test_user_api.py @@ -1,21 +1,25 @@ # coding: utf-8 """ -Copyright 2016 SmartBear Software + Swagger Petstore - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - http://www.apache.org/licenses/LICENSE-2.0 + OpenAPI spec version: 1.0.0 + Contact: apiteam@swagger.io + Generated by: https://github.com/swagger-api/swagger-codegen.git - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at - ref: https://github.com/swagger-api/swagger-codegen + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. """ from __future__ import absolute_import @@ -24,16 +28,16 @@ import os import sys import unittest -import swagger_client -from swagger_client.rest import ApiException -from swagger_client.apis.user_api import UserApi +import petstore_api +from petstore_api.rest import ApiException +from petstore_api.apis.user_api import UserApi class TestUserApi(unittest.TestCase): """ UserApi unit test stubs """ def setUp(self): - self.api = swagger_client.apis.user_api.UserApi() + self.api = petstore_api.apis.user_api.UserApi() def tearDown(self): pass @@ -104,4 +108,4 @@ class TestUserApi(unittest.TestCase): if __name__ == '__main__': - unittest.main() \ No newline at end of file + unittest.main() diff --git a/samples/client/petstore/python/tests/test_api_client.py b/samples/client/petstore/python/tests/test_api_client.py index 61c57cb7e46..972175835f3 100644 --- a/samples/client/petstore/python/tests/test_api_client.py +++ b/samples/client/petstore/python/tests/test_api_client.py @@ -12,8 +12,8 @@ import time import unittest from dateutil.parser import parse -import swagger_client -import swagger_client.configuration +import petstore_api +import petstore_api.configuration HOST = 'http://petstore.swagger.io/v2' @@ -21,20 +21,20 @@ HOST = 'http://petstore.swagger.io/v2' class ApiClientTests(unittest.TestCase): def setUp(self): - self.api_client = swagger_client.ApiClient(HOST) + self.api_client = petstore_api.ApiClient(HOST) def test_configuration(self): - swagger_client.configuration.api_key['api_key'] = '123456' - swagger_client.configuration.api_key_prefix['api_key'] = 'PREFIX' - swagger_client.configuration.username = 'test_username' - swagger_client.configuration.password = 'test_password' + petstore_api.configuration.api_key['api_key'] = '123456' + petstore_api.configuration.api_key_prefix['api_key'] = 'PREFIX' + petstore_api.configuration.username = 'test_username' + petstore_api.configuration.password = 'test_password' header_params = {'test1': 'value1'} query_params = {'test2': 'value2'} auth_settings = ['api_key', 'unknown'] # test prefix - self.assertEqual('PREFIX', swagger_client.configuration.api_key_prefix['api_key']) + self.assertEqual('PREFIX', petstore_api.configuration.api_key_prefix['api_key']) # update parameters based on auth setting self.api_client.update_params_for_auth(header_params, query_params, auth_settings) @@ -45,8 +45,8 @@ class ApiClientTests(unittest.TestCase): self.assertEqual(query_params['test2'], 'value2') # test basic auth - self.assertEqual('test_username', swagger_client.configuration.username) - self.assertEqual('test_password', swagger_client.configuration.password) + self.assertEqual('test_username', petstore_api.configuration.username) + self.assertEqual('test_password', petstore_api.configuration.password) def test_select_header_accept(self): accepts = ['APPLICATION/JSON', 'APPLICATION/XML'] @@ -139,17 +139,17 @@ class ApiClientTests(unittest.TestCase): "status": "available", "photoUrls": ["http://foo.bar.com/3", "http://foo.bar.com/4"]} - pet = swagger_client.Pet() + pet = petstore_api.Pet() pet.id = pet_dict["id"] pet.name = pet_dict["name"] - cate = swagger_client.Category() + cate = petstore_api.Category() cate.id = pet_dict["category"]["id"] cate.name = pet_dict["category"]["name"] pet.category = cate - tag1 = swagger_client.Tag() + tag1 = petstore_api.Tag() tag1.id = pet_dict["tags"][0]["id"] tag1.name = pet_dict["tags"][0]["name"] - tag2 = swagger_client.Tag() + tag2 = petstore_api.Tag() tag2.id = pet_dict["tags"][1]["id"] tag2.name = pet_dict["tags"][1]["name"] pet.tags = [tag1, tag2] diff --git a/samples/client/petstore/python/tests/test_api_exception.py b/samples/client/petstore/python/tests/test_api_exception.py index 790a18dffd0..8df2b681f01 100644 --- a/samples/client/petstore/python/tests/test_api_exception.py +++ b/samples/client/petstore/python/tests/test_api_exception.py @@ -3,7 +3,7 @@ """ Run the tests. $ pip install nose (optional) -$ cd swagger_client-python +$ cd petstore_api-python $ nosetests -v """ @@ -12,25 +12,25 @@ import sys import time import unittest -import swagger_client -from swagger_client.rest import ApiException +import petstore_api +from petstore_api.rest import ApiException class ApiExceptionTests(unittest.TestCase): def setUp(self): - self.api_client = swagger_client.ApiClient() - self.pet_api = swagger_client.PetApi(self.api_client) + self.api_client = petstore_api.ApiClient() + self.pet_api = petstore_api.PetApi(self.api_client) self.setUpModels() def setUpModels(self): - self.category = swagger_client.Category() + self.category = petstore_api.Category() self.category.id = int(time.time()) self.category.name = "dog" - self.tag = swagger_client.Tag() + self.tag = petstore_api.Tag() self.tag.id = int(time.time()) self.tag.name = "blank" - self.pet = swagger_client.Pet() + self.pet = petstore_api.Pet() self.pet.id = int(time.time()) self.pet.name = "hello kity" self.pet.photo_urls = ["http://foo.bar.com/1", "http://foo.bar.com/2"] @@ -44,7 +44,7 @@ class ApiExceptionTests(unittest.TestCase): def test_404_error(self): self.pet_api.add_pet(body=self.pet) self.pet_api.delete_pet(pet_id=self.pet.id) - + with self.checkRaiseRegex(ApiException, "Pet not found"): self.pet_api.get_pet_by_id(pet_id=self.pet.id) @@ -87,4 +87,3 @@ class ApiExceptionTests(unittest.TestCase): return self.assertRegexpMatches(text, expected_regex) return self.assertRegex(text, expected_regex) - diff --git a/samples/client/petstore/python/tests/test_deserialization.py b/samples/client/petstore/python/tests/test_deserialization.py index 1eae045ff76..143f22b64bd 100644 --- a/samples/client/petstore/python/tests/test_deserialization.py +++ b/samples/client/petstore/python/tests/test_deserialization.py @@ -11,13 +11,13 @@ import time import unittest import datetime -import swagger_client +import petstore_api class DeserializationTests(unittest.TestCase): def setUp(self): - self.api_client = swagger_client.ApiClient() + self.api_client = petstore_api.ApiClient() self.deserialize = self.api_client._ApiClient__deserialize def test_deserialize_dict_str_pet(self): @@ -45,7 +45,7 @@ class DeserializationTests(unittest.TestCase): deserialized = self.deserialize(data, 'dict(str, Pet)') self.assertTrue(isinstance(deserialized, dict)) - self.assertTrue(isinstance(deserialized['pet'], swagger_client.Pet)) + self.assertTrue(isinstance(deserialized['pet'], petstore_api.Pet)) def test_deserialize_dict_str_int(self): """ deserialize dict(str, int) """ @@ -78,12 +78,42 @@ class DeserializationTests(unittest.TestCase): def test_deserialize_pet(self): """ deserialize pet """ data = { + "id": 0, + "category": { + "id": 0, + "name": "string" + }, + "name": "doggie", + "photoUrls": [ + "string" + ], + "tags": [ + { + "id": 0, + "name": "string" + } + ], + "status": "available" + } + deserialized = self.deserialize(data, "Pet") + self.assertTrue(isinstance(deserialized, petstore_api.Pet)) + self.assertEqual(deserialized.id, 0) + self.assertEqual(deserialized.name, "doggie") + self.assertTrue(isinstance(deserialized.category, petstore_api.Category)) + self.assertEqual(deserialized.category.name, "string") + self.assertTrue(isinstance(deserialized.tags, list)) + self.assertEqual(deserialized.tags[0].name, "string") + + def test_deserialize_list_of_pet(self): + """ deserialize list[Pet] """ + data = [ + { "id": 0, "category": { "id": 0, "name": "string" }, - "name": "doggie", + "name": "doggie0", "photoUrls": [ "string" ], @@ -94,57 +124,28 @@ class DeserializationTests(unittest.TestCase): } ], "status": "available" - } - deserialized = self.deserialize(data, "Pet") - self.assertTrue(isinstance(deserialized, swagger_client.Pet)) - self.assertEqual(deserialized.id, 0) - self.assertEqual(deserialized.name, "doggie") - self.assertTrue(isinstance(deserialized.category, swagger_client.Category)) - self.assertEqual(deserialized.category.name, "string") - self.assertTrue(isinstance(deserialized.tags, list)) - self.assertEqual(deserialized.tags[0].name, "string") - - def test_deserialize_list_of_pet(self): - """ deserialize list[Pet] """ - data = [{ - "id": 0, - "category": { - "id": 0, - "name": "string" }, - "name": "doggie0", - "photoUrls": [ - "string" - ], - "tags": [ - { + { + "id": 1, + "category": { "id": 0, "name": "string" - } - ], - "status": "available" - }, - { - "id": 1, - "category": { - "id": 0, - "name": "string" - }, - "name": "doggie1", - "photoUrls": [ - "string" - ], - "tags": [ - { - "id": 0, - "name": "string" - } - ], - "status": "available" - }] + }, + "name": "doggie1", + "photoUrls": [ + "string" + ], + "tags": [ + { + "id": 0, + "name": "string" + } + ], + "status": "available" + }] deserialized = self.deserialize(data, "list[Pet]") self.assertTrue(isinstance(deserialized, list)) - self.assertTrue(isinstance(deserialized[0], swagger_client.Pet)) + self.assertTrue(isinstance(deserialized[0], petstore_api.Pet)) self.assertEqual(deserialized[0].id, 0) self.assertEqual(deserialized[1].id, 1) self.assertEqual(deserialized[0].name, "doggie0") diff --git a/samples/client/petstore/python/tests/test_order_model.py b/samples/client/petstore/python/tests/test_order_model.py index e411ca0103d..710f3c175a9 100644 --- a/samples/client/petstore/python/tests/test_order_model.py +++ b/samples/client/petstore/python/tests/test_order_model.py @@ -3,7 +3,7 @@ """ Run the tests. $ pip install nose (optional) -$ cd swagger_client-python +$ cd petstore_api-python $ nosetests -v """ @@ -11,13 +11,13 @@ import os import time import unittest -import swagger_client +import petstore_api class OrderModelTests(unittest.TestCase): def test_status(self): - order = swagger_client.Order() + order = petstore_api.Order() order.status = "placed" self.assertEqual("placed", order.status) diff --git a/samples/client/petstore/python/tests/test_pet_api.py b/samples/client/petstore/python/tests/test_pet_api.py index 300a7bee783..4b749fc044a 100644 --- a/samples/client/petstore/python/tests/test_pet_api.py +++ b/samples/client/petstore/python/tests/test_pet_api.py @@ -3,7 +3,7 @@ """ Run the tests. $ pip install nose (optional) -$ cd swagger_client-python +$ cd petstore_api-python $ nosetests -v """ @@ -11,8 +11,8 @@ import os import time import unittest -import swagger_client -from swagger_client.rest import ApiException +import petstore_api +from petstore_api.rest import ApiException HOST = 'http://petstore.swagger.io/v2' @@ -20,8 +20,8 @@ HOST = 'http://petstore.swagger.io/v2' class PetApiTests(unittest.TestCase): def setUp(self): - self.api_client = swagger_client.ApiClient(HOST) - self.pet_api = swagger_client.PetApi(self.api_client) + self.api_client = petstore_api.ApiClient(HOST) + self.pet_api = petstore_api.PetApi(self.api_client) self.setUpModels() self.setUpFiles() @@ -30,13 +30,13 @@ class PetApiTests(unittest.TestCase): time.sleep(1) def setUpModels(self): - self.category = swagger_client.Category() + self.category = petstore_api.Category() self.category.id = int(time.time()) self.category.name = "dog" - self.tag = swagger_client.Tag() + self.tag = petstore_api.Tag() self.tag.id = int(time.time()) self.tag.name = "swagger-codegen-python-pet-tag" - self.pet = swagger_client.Pet() + self.pet = petstore_api.Pet() self.pet.id = int(time.time()) self.pet.name = "hello kity" self.pet.photo_urls = ["http://foo.bar.com/1", "http://foo.bar.com/2"] @@ -50,22 +50,22 @@ class PetApiTests(unittest.TestCase): self.foo = os.path.join(self.test_file_dir, "foo.png") def test_create_api_instance(self): - pet_api = swagger_client.PetApi() - pet_api2 = swagger_client.PetApi() - api_client3 = swagger_client.ApiClient() + pet_api = petstore_api.PetApi() + pet_api2 = petstore_api.PetApi() + api_client3 = petstore_api.ApiClient() api_client3.user_agent = 'api client 3' - api_client4 = swagger_client.ApiClient() + api_client4 = petstore_api.ApiClient() api_client4.user_agent = 'api client 4' - pet_api3 = swagger_client.PetApi(api_client3) + pet_api3 = petstore_api.PetApi(api_client3) # same default api client self.assertEqual(pet_api.api_client, pet_api2.api_client) # confirm using the default api client in the config module - self.assertEqual(pet_api.api_client, swagger_client.configuration.api_client) + self.assertEqual(pet_api.api_client, petstore_api.configuration.api_client) # 2 different api clients are not the same self.assertNotEqual(api_client3, api_client4) # customized pet api not using the default api client - self.assertNotEqual(pet_api3.api_client, swagger_client.configuration.api_client) + self.assertNotEqual(pet_api3.api_client, petstore_api.configuration.api_client) # customized pet api not using the old pet api's api client self.assertNotEqual(pet_api3.api_client, pet_api2.api_client) diff --git a/samples/client/petstore/python/tests/test_pet_model.py b/samples/client/petstore/python/tests/test_pet_model.py index d2bd3c9ca3d..52cb55061da 100644 --- a/samples/client/petstore/python/tests/test_pet_model.py +++ b/samples/client/petstore/python/tests/test_pet_model.py @@ -3,7 +3,7 @@ """ Run the tests. $ pip install nose (optional) -$ cd swagger_client-python +$ cd petstore_api-python $ nosetests -v """ @@ -11,22 +11,22 @@ import os import time import unittest -import swagger_client +import petstore_api class PetModelTests(unittest.TestCase): def setUp(self): - self.pet = swagger_client.Pet() + self.pet = petstore_api.Pet() self.pet.name = "test name" self.pet.id = 1 self.pet.photo_urls = ["string"] self.pet.status = "available" - cate = swagger_client.Category() + cate = petstore_api.Category() cate.id = 1 cate.name = "dog" self.pet.category = cate - tag = swagger_client.Tag() + tag = petstore_api.Tag() tag.id = 1 self.pet.tags = [tag] @@ -40,29 +40,29 @@ class PetModelTests(unittest.TestCase): self.assertEqual(data, self.pet.to_str()) def test_equal(self): - self.pet1 = swagger_client.Pet() + self.pet1 = petstore_api.Pet() self.pet1.name = "test name" self.pet1.id = 1 self.pet1.photo_urls = ["string"] self.pet1.status = "available" - cate1 = swagger_client.Category() + cate1 = petstore_api.Category() cate1.id = 1 cate1.name = "dog" self.pet.category = cate1 - tag1 = swagger_client.Tag() + tag1 = petstore_api.Tag() tag1.id = 1 self.pet1.tags = [tag1] - self.pet2 = swagger_client.Pet() + self.pet2 = petstore_api.Pet() self.pet2.name = "test name" self.pet2.id = 1 self.pet2.photo_urls = ["string"] self.pet2.status = "available" - cate2 = swagger_client.Category() + cate2 = petstore_api.Category() cate2.id = 1 cate2.name = "dog" self.pet.category = cate2 - tag2 = swagger_client.Tag() + tag2 = petstore_api.Tag() tag2.id = 1 self.pet2.tags = [tag2] diff --git a/samples/client/petstore/python/tests/test_store_api.py b/samples/client/petstore/python/tests/test_store_api.py index 42b92d0879c..b7e80281707 100644 --- a/samples/client/petstore/python/tests/test_store_api.py +++ b/samples/client/petstore/python/tests/test_store_api.py @@ -11,14 +11,14 @@ import os import time import unittest -import swagger_client -from swagger_client.rest import ApiException +import petstore_api +from petstore_api.rest import ApiException class StoreApiTests(unittest.TestCase): def setUp(self): - self.store_api = swagger_client.StoreApi() + self.store_api = petstore_api.StoreApi() def tearDown(self): # sleep 1 sec between two every 2 tests diff --git a/samples/client/petstore/scala/.swagger-codegen-ignore b/samples/client/petstore/scala/.swagger-codegen-ignore new file mode 100644 index 00000000000..19d3377182e --- /dev/null +++ b/samples/client/petstore/scala/.swagger-codegen-ignore @@ -0,0 +1,23 @@ +# Swagger Codegen Ignore +# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell Swagger Codgen to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# Thsi matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/client/petstore/scala/LICENSE b/samples/client/petstore/scala/LICENSE new file mode 100644 index 00000000000..8dada3edaf5 --- /dev/null +++ b/samples/client/petstore/scala/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/samples/client/petstore/scala/build.gradle b/samples/client/petstore/scala/build.gradle new file mode 100644 index 00000000000..979db7783c4 --- /dev/null +++ b/samples/client/petstore/scala/build.gradle @@ -0,0 +1,120 @@ +apply plugin: 'idea' +apply plugin: 'eclipse' + +group = 'io.swagger' +version = '1.0.0' + +buildscript { + repositories { + jcenter() + } + dependencies { + classpath 'com.android.tools.build:gradle:1.5.+' + classpath 'com.github.dcendents:android-maven-gradle-plugin:1.3' + } +} + +repositories { + jcenter() +} + + +if(hasProperty('target') && target == 'android') { + + apply plugin: 'com.android.library' + apply plugin: 'com.github.dcendents.android-maven' + + android { + compileSdkVersion 23 + buildToolsVersion '23.0.2' + defaultConfig { + minSdkVersion 14 + targetSdkVersion 23 + } + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_7 + targetCompatibility JavaVersion.VERSION_1_7 + } + + // Rename the aar correctly + libraryVariants.all { variant -> + variant.outputs.each { output -> + def outputFile = output.outputFile + if (outputFile != null && outputFile.name.endsWith('.aar')) { + def fileName = "${project.name}-${variant.baseName}-${version}.aar" + output.outputFile = new File(outputFile.parent, fileName) + } + } + } + + dependencies { + provided 'javax.annotation:jsr250-api:1.0' + } + } + + afterEvaluate { + android.libraryVariants.all { variant -> + def task = project.tasks.create "jar${variant.name.capitalize()}", Jar + task.description = "Create jar artifact for ${variant.name}" + task.dependsOn variant.javaCompile + task.from variant.javaCompile.destinationDir + task.destinationDir = project.file("${project.buildDir}/outputs/jar") + task.archiveName = "${project.name}-${variant.baseName}-${version}.jar" + artifacts.add('archives', task); + } + } + + task sourcesJar(type: Jar) { + from android.sourceSets.main.java.srcDirs + classifier = 'sources' + } + + artifacts { + archives sourcesJar + } + +} else { + + apply plugin: 'scala' + apply plugin: 'java' + apply plugin: 'maven' + + sourceCompatibility = JavaVersion.VERSION_1_7 + targetCompatibility = JavaVersion.VERSION_1_7 + + install { + repositories.mavenInstaller { + pom.artifactId = 'swagger-scala-client' + } + } + + task execute(type:JavaExec) { + main = System.getProperty('mainClass') + classpath = sourceSets.main.runtimeClasspath + } +} + +ext { + scala_version = "2.10.4" + joda_version = "1.2" + jodatime_version = "2.2" + jersey_version = "1.19" + swagger_core_version = "1.5.8" + jersey_async_version = "1.0.5" + jackson_version = "2.4.2" + junit_version = "4.8.1" + scala_test_version = "2.2.4" +} + +dependencies { + compile "com.fasterxml.jackson.module:jackson-module-scala_2.10:$jackson_version" + compile "com.sun.jersey:jersey-client:$jersey_version" + compile "com.sun.jersey.contribs:jersey-multipart:$jersey_version" + compile "org.jfarcand:jersey-ahc-client:$jersey_async_version" + compile "org.scala-lang:scala-library:$scala_version" + compile "io.swagger:swagger-core:$swagger_core_version" + testCompile "org.scalatest:scalatest_2.10:$scala_test_version" + testCompile "junit:junit:$junit_version" + compile "joda-time:joda-time:$jodatime_version" + compile "org.joda:joda-convert:$joda_version" +} diff --git a/samples/client/petstore/scala/git_push.sh b/samples/client/petstore/scala/git_push.sh index 1a36388db02..ed374619b13 100644 --- a/samples/client/petstore/scala/git_push.sh +++ b/samples/client/petstore/scala/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/scala/gradle.properties b/samples/client/petstore/scala/gradle.properties new file mode 100644 index 00000000000..05644f0754a --- /dev/null +++ b/samples/client/petstore/scala/gradle.properties @@ -0,0 +1,2 @@ +# Uncomment to build for Android +#target = android \ No newline at end of file diff --git a/samples/client/petstore/scala/gradle/wrapper/gradle-wrapper.jar b/samples/client/petstore/scala/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 00000000000..2c6137b8789 Binary files /dev/null and b/samples/client/petstore/scala/gradle/wrapper/gradle-wrapper.jar differ diff --git a/samples/client/petstore/scala/gradle/wrapper/gradle-wrapper.properties b/samples/client/petstore/scala/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000000..b7a36473955 --- /dev/null +++ b/samples/client/petstore/scala/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Tue May 17 23:08:05 CST 2016 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-2.6-bin.zip diff --git a/samples/client/petstore/scala/gradlew b/samples/client/petstore/scala/gradlew new file mode 100755 index 00000000000..9d82f789151 --- /dev/null +++ b/samples/client/petstore/scala/gradlew @@ -0,0 +1,160 @@ +#!/usr/bin/env bash + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS="" + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn ( ) { + echo "$*" +} + +die ( ) { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; +esac + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin, switch paths to Windows format before running java +if $cygwin ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules +function splitJvmOpts() { + JVM_OPTS=("$@") +} +eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS +JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" + +exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" diff --git a/samples/client/petstore/scala/gradlew.bat b/samples/client/petstore/scala/gradlew.bat new file mode 100644 index 00000000000..72d362dafd8 --- /dev/null +++ b/samples/client/petstore/scala/gradlew.bat @@ -0,0 +1,90 @@ +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args +if "%@eval[2+2]" == "4" goto 4NT_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* +goto execute + +:4NT_args +@rem Get arguments from the 4NT Shell from JP Software +set CMD_LINE_ARGS=%$ + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/samples/client/petstore/scala/settings.gradle b/samples/client/petstore/scala/settings.gradle new file mode 100644 index 00000000000..5452c701c0e --- /dev/null +++ b/samples/client/petstore/scala/settings.gradle @@ -0,0 +1 @@ +rootProject.name = "swagger-scala-client" \ No newline at end of file diff --git a/samples/client/petstore/scala/src/main/scala/io/swagger/client/api/PetApi.scala b/samples/client/petstore/scala/src/main/scala/io/swagger/client/api/PetApi.scala index f7e82cd1b61..3208eb938d5 100644 --- a/samples/client/petstore/scala/src/main/scala/io/swagger/client/api/PetApi.scala +++ b/samples/client/petstore/scala/src/main/scala/io/swagger/client/api/PetApi.scala @@ -1,8 +1,8 @@ package io.swagger.client.api import io.swagger.client.model.Pet -import io.swagger.client.model.ApiResponse import java.io.File +import io.swagger.client.model.ApiResponse import io.swagger.client.ApiInvoker import io.swagger.client.ApiException diff --git a/samples/client/petstore/spring-stubs/.swagger-codegen-ignore b/samples/client/petstore/spring-stubs/.swagger-codegen-ignore new file mode 100644 index 00000000000..19d3377182e --- /dev/null +++ b/samples/client/petstore/spring-stubs/.swagger-codegen-ignore @@ -0,0 +1,23 @@ +# Swagger Codegen Ignore +# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell Swagger Codgen to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# Thsi matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/client/petstore/spring-stubs/LICENSE b/samples/client/petstore/spring-stubs/LICENSE new file mode 100644 index 00000000000..8dada3edaf5 --- /dev/null +++ b/samples/client/petstore/spring-stubs/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/samples/client/petstore/spring-stubs/README.md b/samples/client/petstore/spring-stubs/README.md new file mode 100644 index 00000000000..99663f64082 --- /dev/null +++ b/samples/client/petstore/spring-stubs/README.md @@ -0,0 +1,27 @@ + +# Swagger generated API stub + +Spring Framework stub + + +## Overview +This code was generated by the [swagger-codegen](https://github.com/swagger-api/swagger-codegen) project. +By using the [OpenAPI-Spec](https://github.com/swagger-api/swagger-core), you can easily generate an API stub. +This is an example of building API stub interfaces in Java using the Spring framework. + +The stubs generated can be used in your existing Spring-MVC or Spring-Boot application to create controller endpoints +by adding ```@Controller``` classes that implement the interface. Eg: +```java +@Controller +public class PetController implements PetApi { +// implement all PetApi methods +} +``` + +You can also use the interface to create [Spring-Cloud Feign clients](http://projects.spring.io/spring-cloud/spring-cloud.html#spring-cloud-feign-inheritance).Eg: +```java +@FeignClient(name="pet", url="http://petstore.swagger.io/v2") +public interface PetClient extends PetApi { + +} +``` diff --git a/samples/client/petstore/spring-stubs/pom.xml b/samples/client/petstore/spring-stubs/pom.xml new file mode 100644 index 00000000000..975433d48c8 --- /dev/null +++ b/samples/client/petstore/spring-stubs/pom.xml @@ -0,0 +1,41 @@ + + 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-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/client/petstore/spring-stubs/src/main/java/io/swagger/api/PetApi.java b/samples/client/petstore/spring-stubs/src/main/java/io/swagger/api/PetApi.java new file mode 100644 index 00000000000..d055f19cc23 --- /dev/null +++ b/samples/client/petstore/spring-stubs/src/main/java/io/swagger/api/PetApi.java @@ -0,0 +1,156 @@ +package io.swagger.api; + +import io.swagger.model.*; + +import io.swagger.model.Pet; +import io.swagger.model.ModelApiResponse; +import java.io.File; + +import io.swagger.annotations.*; + +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RequestPart; +import org.springframework.web.multipart.MultipartFile; + +import java.util.List; + +import static org.springframework.http.MediaType.*; + +@Api(value = "pet", description = "the pet API") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringBootServerCodegen", date = "2016-06-06T14:29:44.961+02:00") +public interface PetApi { + + @ApiOperation(value = "Add a new pet to the store", notes = "", response = Void.class, authorizations = { + @Authorization(value = "petstore_auth", scopes = { + @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }) + @ApiResponses(value = { + @ApiResponse(code = 405, message = "Invalid input", response = Void.class) }) + @RequestMapping(value = "/pet", + produces = "application/json", + consumes = "application/json", + method = RequestMethod.POST) + ResponseEntity addPet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @RequestBody Pet body); + + + @ApiOperation(value = "Deletes a pet", notes = "", response = Void.class, authorizations = { + @Authorization(value = "petstore_auth", scopes = { + @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }) + @ApiResponses(value = { + @ApiResponse(code = 400, message = "Invalid pet value", response = Void.class) }) + @RequestMapping(value = "/pet/{petId}", + produces = "application/json", + consumes = "application/json", + method = RequestMethod.DELETE) + ResponseEntity deletePet(@ApiParam(value = "Pet id to delete",required=true ) @PathVariable("petId") Long petId, + @ApiParam(value = "" ) @RequestHeader(value="api_key", required=false) String apiKey); + + + @ApiOperation(value = "Finds Pets by status", notes = "Multiple status values can be provided with comma separated strings", response = Pet.class, responseContainer = "List", authorizations = { + @Authorization(value = "petstore_auth", scopes = { + @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Pet.class), + @ApiResponse(code = 400, message = "Invalid status value", response = Pet.class) }) + @RequestMapping(value = "/pet/findByStatus", + produces = "application/json", + consumes = "application/json", + method = RequestMethod.GET) + ResponseEntity> findPetsByStatus(@ApiParam(value = "Status values that need to be considered for filter", required = true) @RequestParam(value = "status", required = true) List status); + + + @ApiOperation(value = "Finds Pets by tags", notes = "Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.", response = Pet.class, responseContainer = "List", authorizations = { + @Authorization(value = "petstore_auth", scopes = { + @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Pet.class), + @ApiResponse(code = 400, message = "Invalid tag value", response = Pet.class) }) + @RequestMapping(value = "/pet/findByTags", + produces = "application/json", + consumes = "application/json", + method = RequestMethod.GET) + ResponseEntity> findPetsByTags(@ApiParam(value = "Tags to filter by", required = true) @RequestParam(value = "tags", required = true) List tags); + + + @ApiOperation(value = "Find pet by ID", notes = "Returns a single pet", response = Pet.class, authorizations = { + @Authorization(value = "api_key") + }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Pet.class), + @ApiResponse(code = 400, message = "Invalid ID supplied", response = Pet.class), + @ApiResponse(code = 404, message = "Pet not found", response = Pet.class) }) + @RequestMapping(value = "/pet/{petId}", + produces = "application/json", + consumes = "application/json", + method = RequestMethod.GET) + ResponseEntity getPetById(@ApiParam(value = "ID of pet to return",required=true ) @PathVariable("petId") Long petId); + + + @ApiOperation(value = "Update an existing pet", notes = "", response = Void.class, authorizations = { + @Authorization(value = "petstore_auth", scopes = { + @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }) + @ApiResponses(value = { + @ApiResponse(code = 400, message = "Invalid ID supplied", response = Void.class), + @ApiResponse(code = 404, message = "Pet not found", response = Void.class), + @ApiResponse(code = 405, message = "Validation exception", response = Void.class) }) + @RequestMapping(value = "/pet", + produces = "application/json", + consumes = "application/json", + method = RequestMethod.PUT) + ResponseEntity updatePet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @RequestBody Pet body); + + + @ApiOperation(value = "Updates a pet in the store with form data", notes = "", response = Void.class, authorizations = { + @Authorization(value = "petstore_auth", scopes = { + @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }) + @ApiResponses(value = { + @ApiResponse(code = 405, message = "Invalid input", response = Void.class) }) + @RequestMapping(value = "/pet/{petId}", + produces = "application/json", + consumes = "application/x-www-form-urlencoded", + method = RequestMethod.POST) + ResponseEntity updatePetWithForm(@ApiParam(value = "ID of pet that needs to be updated",required=true ) @PathVariable("petId") Long petId, + @ApiParam(value = "Updated name of the pet" ) @RequestPart(value="name", required=false) String name, + @ApiParam(value = "Updated status of the pet" ) @RequestPart(value="status", required=false) String status); + + + @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 = "/pet/{petId}/uploadImage", + produces = "application/json", + consumes = "multipart/form-data", + method = RequestMethod.POST) + ResponseEntity uploadFile(@ApiParam(value = "ID of pet to update",required=true ) @PathVariable("petId") Long petId, + @ApiParam(value = "Additional data to pass to server" ) @RequestPart(value="additionalMetadata", required=false) String additionalMetadata, + @ApiParam(value = "file detail") @RequestPart("file") MultipartFile file); + +} diff --git a/samples/client/petstore/spring-stubs/src/main/java/io/swagger/api/StoreApi.java b/samples/client/petstore/spring-stubs/src/main/java/io/swagger/api/StoreApi.java new file mode 100644 index 00000000000..03c07525bb3 --- /dev/null +++ b/samples/client/petstore/spring-stubs/src/main/java/io/swagger/api/StoreApi.java @@ -0,0 +1,73 @@ +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.ResponseEntity; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RequestPart; +import org.springframework.web.multipart.MultipartFile; + +import java.util.List; + +import static org.springframework.http.MediaType.*; + +@Api(value = "store", description = "the store API") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringBootServerCodegen", date = "2016-06-06T14:29:44.961+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) + @ApiResponses(value = { + @ApiResponse(code = 400, message = "Invalid ID supplied", response = Void.class), + @ApiResponse(code = 404, message = "Order not found", response = Void.class) }) + @RequestMapping(value = "/store/order/{orderId}", + produces = "application/json", + consumes = "application/json", + method = RequestMethod.DELETE) + ResponseEntity deleteOrder(@ApiParam(value = "ID of the order that needs to be deleted",required=true ) @PathVariable("orderId") String orderId); + + + @ApiOperation(value = "Returns pet inventories by status", notes = "Returns a map of status codes to quantities", response = Integer.class, responseContainer = "Map", authorizations = { + @Authorization(value = "api_key") + }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Integer.class) }) + @RequestMapping(value = "/store/inventory", + produces = "application/json", + consumes = "application/json", + method = RequestMethod.GET) + ResponseEntity> getInventory(); + + + @ApiOperation(value = "Find purchase order by ID", notes = "For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions", response = Order.class) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Order.class), + @ApiResponse(code = 400, message = "Invalid ID supplied", response = Order.class), + @ApiResponse(code = 404, message = "Order not found", response = Order.class) }) + @RequestMapping(value = "/store/order/{orderId}", + produces = "application/json", + consumes = "application/json", + method = RequestMethod.GET) + ResponseEntity getOrderById(@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathVariable("orderId") Long orderId); + + + @ApiOperation(value = "Place an order for a pet", notes = "", response = Order.class) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Order.class), + @ApiResponse(code = 400, message = "Invalid Order", response = Order.class) }) + @RequestMapping(value = "/store/order", + produces = "application/json", + consumes = "application/json", + method = RequestMethod.POST) + ResponseEntity placeOrder(@ApiParam(value = "order placed for purchasing the pet" ,required=true ) @RequestBody Order body); + +} diff --git a/samples/client/petstore/spring-stubs/src/main/java/io/swagger/api/UserApi.java b/samples/client/petstore/spring-stubs/src/main/java/io/swagger/api/UserApi.java new file mode 100644 index 00000000000..3da36b4c67c --- /dev/null +++ b/samples/client/petstore/spring-stubs/src/main/java/io/swagger/api/UserApi.java @@ -0,0 +1,114 @@ +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.ResponseEntity; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RequestPart; +import org.springframework.web.multipart.MultipartFile; + +import java.util.List; + +import static org.springframework.http.MediaType.*; + +@Api(value = "user", description = "the user API") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringBootServerCodegen", date = "2016-06-06T14:29:44.961+02:00") +public interface 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 = "/user", + produces = "application/json", + consumes = "application/json", + method = RequestMethod.POST) + ResponseEntity createUser(@ApiParam(value = "Created user object" ,required=true ) @RequestBody User body); + + + @ApiOperation(value = "Creates list of users with given input array", notes = "", response = Void.class) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Void.class) }) + @RequestMapping(value = "/user/createWithArray", + produces = "application/json", + consumes = "application/json", + method = RequestMethod.POST) + ResponseEntity createUsersWithArrayInput(@ApiParam(value = "List of user object" ,required=true ) @RequestBody List body); + + + @ApiOperation(value = "Creates list of users with given input array", notes = "", response = Void.class) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Void.class) }) + @RequestMapping(value = "/user/createWithList", + produces = "application/json", + consumes = "application/json", + method = RequestMethod.POST) + ResponseEntity createUsersWithListInput(@ApiParam(value = "List of user object" ,required=true ) @RequestBody List body); + + + @ApiOperation(value = "Delete user", notes = "This can only be done by the logged in user.", response = Void.class) + @ApiResponses(value = { + @ApiResponse(code = 400, message = "Invalid username supplied", response = Void.class), + @ApiResponse(code = 404, message = "User not found", response = Void.class) }) + @RequestMapping(value = "/user/{username}", + produces = "application/json", + consumes = "application/json", + method = RequestMethod.DELETE) + ResponseEntity deleteUser(@ApiParam(value = "The name that needs to be deleted",required=true ) @PathVariable("username") String username); + + + @ApiOperation(value = "Get user by user name", notes = "", response = User.class) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = User.class), + @ApiResponse(code = 400, message = "Invalid username supplied", response = User.class), + @ApiResponse(code = 404, message = "User not found", response = User.class) }) + @RequestMapping(value = "/user/{username}", + produces = "application/json", + consumes = "application/json", + method = RequestMethod.GET) + ResponseEntity getUserByName(@ApiParam(value = "The name that needs to be fetched. Use user1 for testing. ",required=true ) @PathVariable("username") String username); + + + @ApiOperation(value = "Logs user into the system", notes = "", response = String.class) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = String.class), + @ApiResponse(code = 400, message = "Invalid username/password supplied", response = String.class) }) + @RequestMapping(value = "/user/login", + produces = "application/json", + consumes = "application/json", + method = RequestMethod.GET) + ResponseEntity loginUser(@ApiParam(value = "The user name for login", required = true) @RequestParam(value = "username", required = true) String username, + @ApiParam(value = "The password for login in clear text", required = true) @RequestParam(value = "password", required = true) String password); + + + @ApiOperation(value = "Logs out current logged in user session", notes = "", response = Void.class) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Void.class) }) + @RequestMapping(value = "/user/logout", + produces = "application/json", + consumes = "application/json", + method = RequestMethod.GET) + ResponseEntity logoutUser(); + + + @ApiOperation(value = "Updated user", notes = "This can only be done by the logged in user.", response = Void.class) + @ApiResponses(value = { + @ApiResponse(code = 400, message = "Invalid user supplied", response = Void.class), + @ApiResponse(code = 404, message = "User not found", response = Void.class) }) + @RequestMapping(value = "/user/{username}", + produces = "application/json", + consumes = "application/json", + method = RequestMethod.PUT) + ResponseEntity updateUser(@ApiParam(value = "name that need to be deleted",required=true ) @PathVariable("username") String username, + @ApiParam(value = "Updated user object" ,required=true ) @RequestBody User body); + +} diff --git a/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/Category.java b/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/Category.java new file mode 100644 index 00000000000..1c0dbbf75a7 --- /dev/null +++ b/samples/client/petstore/spring-stubs/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-06-06T14:29:44.961+02: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/client/petstore/spring-stubs/src/main/java/io/swagger/model/ModelApiResponse.java b/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/ModelApiResponse.java new file mode 100644 index 00000000000..818052af3a5 --- /dev/null +++ b/samples/client/petstore/spring-stubs/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-06-06T14:29:44.961+02: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/client/petstore/spring-stubs/src/main/java/io/swagger/model/Order.java b/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/Order.java new file mode 100644 index 00000000000..d3754b6e828 --- /dev/null +++ b/samples/client/petstore/spring-stubs/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-06-06T14:29:44.961+02: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/client/petstore/spring-stubs/src/main/java/io/swagger/model/Pet.java b/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/Pet.java new file mode 100644 index 00000000000..dbfcc186ba7 --- /dev/null +++ b/samples/client/petstore/spring-stubs/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-06-06T14:29:44.961+02: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/client/petstore/spring-stubs/src/main/java/io/swagger/model/Tag.java b/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/Tag.java new file mode 100644 index 00000000000..349ef702332 --- /dev/null +++ b/samples/client/petstore/spring-stubs/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-06-06T14:29:44.961+02: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/client/petstore/spring-stubs/src/main/java/io/swagger/model/User.java b/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/User.java new file mode 100644 index 00000000000..2ba7d2274aa --- /dev/null +++ b/samples/client/petstore/spring-stubs/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-06-06T14:29:44.961+02: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/client/petstore/swift-promisekit/.swagger-codegen-ignore b/samples/client/petstore/swift-promisekit/.swagger-codegen-ignore new file mode 100644 index 00000000000..19d3377182e --- /dev/null +++ b/samples/client/petstore/swift-promisekit/.swagger-codegen-ignore @@ -0,0 +1,23 @@ +# Swagger Codegen Ignore +# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell Swagger Codgen to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# Thsi matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/client/petstore/swift/.swagger-codegen-ignore b/samples/client/petstore/swift/.swagger-codegen-ignore new file mode 100644 index 00000000000..19d3377182e --- /dev/null +++ b/samples/client/petstore/swift/.swagger-codegen-ignore @@ -0,0 +1,23 @@ +# Swagger Codegen Ignore +# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell Swagger Codgen to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# Thsi matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/Models.swift b/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/Models.swift index 5a8eade51b3..cad60a236a7 100644 --- a/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/Models.swift +++ b/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/Models.swift @@ -34,17 +34,17 @@ public class Response { private var once = dispatch_once_t() class Decoders { static private var decoders = Dictionary AnyObject)>() - + static func addDecoder(clazz clazz: T.Type, decoder: ((AnyObject) -> T)) { let key = "\(T.self)" decoders[key] = { decoder($0) as! AnyObject } } - + static func decode(clazz clazz: [T].Type, source: AnyObject) -> [T] { let array = source as! [AnyObject] return array.map { Decoders.decode(clazz: T.self, source: $0) } } - + static func decode(clazz clazz: [Key:T].Type, source: AnyObject) -> [Key:T] { let sourceDictionary = source as! [Key: AnyObject] var dictionary = [Key:T]() @@ -53,7 +53,7 @@ class Decoders { } return dictionary } - + static func decode(clazz clazz: T.Type, source: AnyObject) -> T { initialize() if T.self is Int32.Type && source is NSNumber { @@ -65,7 +65,7 @@ class Decoders { if source is T { return source as! T } - + let key = "\(T.self)" if let decoder = decoders[key] { return decoder(source) as! T @@ -100,14 +100,15 @@ class Decoders { Decoders.decode(clazz: clazz, source: someSource) } } - + static private func initialize() { dispatch_once(&once) { let formatters = [ "yyyy-MM-dd", "yyyy-MM-dd'T'HH:mm:ssZZZZZ", "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ", - "yyyy-MM-dd'T'HH:mm:ss'Z'" + "yyyy-MM-dd'T'HH:mm:ss'Z'", + "yyyy-MM-dd'T'HH:mm:ss.SSS" ].map { (format: String) -> NSDateFormatter in let formatter = NSDateFormatter() formatter.dateFormat = format @@ -121,7 +122,7 @@ class Decoders { return date } } - + } if let sourceInt = source as? Int { // treat as a java date diff --git a/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/Models.swift b/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/Models.swift index 5a8eade51b3..cad60a236a7 100644 --- a/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/Models.swift +++ b/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/Models.swift @@ -34,17 +34,17 @@ public class Response { private var once = dispatch_once_t() class Decoders { static private var decoders = Dictionary AnyObject)>() - + static func addDecoder(clazz clazz: T.Type, decoder: ((AnyObject) -> T)) { let key = "\(T.self)" decoders[key] = { decoder($0) as! AnyObject } } - + static func decode(clazz clazz: [T].Type, source: AnyObject) -> [T] { let array = source as! [AnyObject] return array.map { Decoders.decode(clazz: T.self, source: $0) } } - + static func decode(clazz clazz: [Key:T].Type, source: AnyObject) -> [Key:T] { let sourceDictionary = source as! [Key: AnyObject] var dictionary = [Key:T]() @@ -53,7 +53,7 @@ class Decoders { } return dictionary } - + static func decode(clazz clazz: T.Type, source: AnyObject) -> T { initialize() if T.self is Int32.Type && source is NSNumber { @@ -65,7 +65,7 @@ class Decoders { if source is T { return source as! T } - + let key = "\(T.self)" if let decoder = decoders[key] { return decoder(source) as! T @@ -100,14 +100,15 @@ class Decoders { Decoders.decode(clazz: clazz, source: someSource) } } - + static private func initialize() { dispatch_once(&once) { let formatters = [ "yyyy-MM-dd", "yyyy-MM-dd'T'HH:mm:ssZZZZZ", "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ", - "yyyy-MM-dd'T'HH:mm:ss'Z'" + "yyyy-MM-dd'T'HH:mm:ss'Z'", + "yyyy-MM-dd'T'HH:mm:ss.SSS" ].map { (format: String) -> NSDateFormatter in let formatter = NSDateFormatter() formatter.dateFormat = format @@ -121,7 +122,7 @@ class Decoders { return date } } - + } if let sourceInt = source as? Int { // treat as a java date diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Podfile.lock b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Podfile.lock index cfeb9499108..fa9ebeb16ef 100644 --- a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Podfile.lock +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Podfile.lock @@ -1,12 +1,12 @@ PODS: - Alamofire (3.1.5) - - OMGHTTPURLRQ (3.1.1): - - OMGHTTPURLRQ/RQ (= 3.1.1) - - OMGHTTPURLRQ/FormURLEncode (3.1.1) - - OMGHTTPURLRQ/RQ (3.1.1): + - OMGHTTPURLRQ (3.1.2): + - OMGHTTPURLRQ/RQ (= 3.1.2) + - OMGHTTPURLRQ/FormURLEncode (3.1.2) + - OMGHTTPURLRQ/RQ (3.1.2): - OMGHTTPURLRQ/FormURLEncode - OMGHTTPURLRQ/UserAgent - - OMGHTTPURLRQ/UserAgent (3.1.1) + - OMGHTTPURLRQ/UserAgent (3.1.2) - PetstoreClient (0.0.1): - Alamofire (~> 3.1.5) - PromiseKit (~> 3.1.1) @@ -32,7 +32,7 @@ EXTERNAL SOURCES: SPEC CHECKSUMS: Alamofire: 5f730ba29fd113b7ddd71c1e65d0c630acf5d7b0 - OMGHTTPURLRQ: 633f98ee745aeda02345935a52eec1784cddb589 + OMGHTTPURLRQ: 38316b56d88125c600bcdb16df8329147da2b0ee PetstoreClient: efd495da2b7a6f3e798752702d59f96e306dbace PromiseKit: 4e8127c22a9b29d1b44958ab2ec762ea6115cbfb diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Manifest.lock b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Manifest.lock index cfeb9499108..fa9ebeb16ef 100644 --- a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Manifest.lock +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Manifest.lock @@ -1,12 +1,12 @@ PODS: - Alamofire (3.1.5) - - OMGHTTPURLRQ (3.1.1): - - OMGHTTPURLRQ/RQ (= 3.1.1) - - OMGHTTPURLRQ/FormURLEncode (3.1.1) - - OMGHTTPURLRQ/RQ (3.1.1): + - OMGHTTPURLRQ (3.1.2): + - OMGHTTPURLRQ/RQ (= 3.1.2) + - OMGHTTPURLRQ/FormURLEncode (3.1.2) + - OMGHTTPURLRQ/RQ (3.1.2): - OMGHTTPURLRQ/FormURLEncode - OMGHTTPURLRQ/UserAgent - - OMGHTTPURLRQ/UserAgent (3.1.1) + - OMGHTTPURLRQ/UserAgent (3.1.2) - PetstoreClient (0.0.1): - Alamofire (~> 3.1.5) - PromiseKit (~> 3.1.1) @@ -32,7 +32,7 @@ EXTERNAL SOURCES: SPEC CHECKSUMS: Alamofire: 5f730ba29fd113b7ddd71c1e65d0c630acf5d7b0 - OMGHTTPURLRQ: 633f98ee745aeda02345935a52eec1784cddb589 + OMGHTTPURLRQ: 38316b56d88125c600bcdb16df8329147da2b0ee PetstoreClient: efd495da2b7a6f3e798752702d59f96e306dbace PromiseKit: 4e8127c22a9b29d1b44958ab2ec762ea6115cbfb diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/OMGHTTPURLRQ/README.markdown b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/OMGHTTPURLRQ/README.markdown index ff905517872..1cd71258ad3 100644 --- a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/OMGHTTPURLRQ/README.markdown +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/OMGHTTPURLRQ/README.markdown @@ -39,7 +39,7 @@ NSData *data2 = UIImagePNGRepresentation(image2); [multipartFormData addFile:data2 parameterName:@"file2" filename:@"myimage2.png" contentType:@"image/png"]; // SUPER Ideally you would not want to re-encode the JPEG as the process -// is lossy. If you image comes from the AssetLibrary you *CAN* get the +// is lossy. If your image comes from the AssetLibrary you *CAN* get the // original `NSData`. See stackoverflow.com. UIImage *image3 = [UIImage imageNamed:@"image3"]; NSData *data3 = UIImageJPEGRepresentation(image3); @@ -97,7 +97,7 @@ your API keys that registering at https://dev.twitter.com will provide you. ```objc -NSMutableURLRequest *rq = [TDOAuth URLRequestForPath:@"/oauth/request_token" POSTParameters:@{@"x_auth_mode" : @"reverse_auth"} host:@"api.twitter.com"consumerKey:APIKey consumerSecret:APISecret accessToken:nil tokenSecret:nil]; +NSMutableURLRequest *rq = [TDOAuth URLRequestForPath:@"/oauth/request_token" POSTParameters:@{@"x_auth_mode" : @"reverse_auth"} host:@"api.twitter.com" consumerKey:APIKey consumerSecret:APISecret accessToken:nil tokenSecret:nil]; [rq addValue:OMGUserAgent() forHTTPHeaderField:@"User-Agent"]; [NSURLConnection sendAsynchronousRequest:rq queue:nil completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) { @@ -142,4 +142,4 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -``` \ No newline at end of file +``` diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/OMGHTTPURLRQ/Sources/OMGHTTPURLRQ.m b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/OMGHTTPURLRQ/Sources/OMGHTTPURLRQ.m index 0854acd0eb7..3f48ace500e 100644 --- a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/OMGHTTPURLRQ/Sources/OMGHTTPURLRQ.m +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/OMGHTTPURLRQ/Sources/OMGHTTPURLRQ.m @@ -71,8 +71,8 @@ static inline NSMutableURLRequest *OMGMutableURLRequest() { @implementation OMGHTTPURLRQ + (NSMutableURLRequest *)GET:(NSString *)urlString :(NSDictionary *)params error:(NSError **)error { - id queryString = OMGFormURLEncode(params); - if (queryString) urlString = [urlString stringByAppendingFormat:@"?%@", queryString]; + NSString *queryString = OMGFormURLEncode(params); + if (queryString.length) urlString = [urlString stringByAppendingFormat:@"?%@", queryString]; id url = [NSURL URLWithString:urlString]; if (!url) { diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/PromiseKit/Info.plist b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/PromiseKit/Info.plist index 793d31a9fdd..c11c2ee42e9 100644 --- a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/PromiseKit/Info.plist +++ b/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/Target Support Files/PromiseKit/Info.plist @@ -15,7 +15,7 @@ CFBundlePackageType FMWK CFBundleShortVersionString - 3.1.1 + 3.1.2 CFBundleSignature ???? CFBundleVersion diff --git a/samples/server/petstore/rails5/LICENSE b/samples/server/petstore/rails5/LICENSE index 309973afd74..8dada3edaf5 100644 --- a/samples/server/petstore/rails5/LICENSE +++ b/samples/server/petstore/rails5/LICENSE @@ -175,27 +175,27 @@ END OF TERMS AND CONDITIONS - APPENDIX: How to apply the Apache License to your work. + APPENDIX: How to apply the Apache License to your work. - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "{}" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. - Copyright {yyyy} {name of copyright owner} + Copyright {yyyy} {name of copyright owner} - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at - http://www.apache.org/licenses/LICENSE-2.0 + http://www.apache.org/licenses/LICENSE-2.0 - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/samples/server/petstore/rails5/README.md b/samples/server/petstore/rails5/README.md index c5cb90075a6..841b82ad656 100644 --- a/samples/server/petstore/rails5/README.md +++ b/samples/server/petstore/rails5/README.md @@ -14,7 +14,7 @@ bundle install This sample was generated with the [swagger-codegen](https://github.com/swagger-api/swagger-codegen) project. ``` -bin/rake db:create +bin/rake db:create db:migrate bin/rails s ``` diff --git a/samples/server/petstore/rails5/app/models/api_response.rb b/samples/server/petstore/rails5/app/models/api_response.rb new file mode 100644 index 00000000000..1ad59e6c792 --- /dev/null +++ b/samples/server/petstore/rails5/app/models/api_response.rb @@ -0,0 +1,27 @@ +=begin +Swagger Petstore + +This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end + + +class ApiResponse < ApplicationRecord + +end diff --git a/samples/server/petstore/rails5/app/models/category.rb b/samples/server/petstore/rails5/app/models/category.rb new file mode 100644 index 00000000000..3adaa488309 --- /dev/null +++ b/samples/server/petstore/rails5/app/models/category.rb @@ -0,0 +1,27 @@ +=begin +Swagger Petstore + +This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end + + +class Category < ApplicationRecord + +end diff --git a/samples/server/petstore/rails5/app/models/order.rb b/samples/server/petstore/rails5/app/models/order.rb new file mode 100644 index 00000000000..963eb8e18ed --- /dev/null +++ b/samples/server/petstore/rails5/app/models/order.rb @@ -0,0 +1,27 @@ +=begin +Swagger Petstore + +This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end + + +class Order < ApplicationRecord + +end diff --git a/samples/server/petstore/rails5/app/models/pet.rb b/samples/server/petstore/rails5/app/models/pet.rb new file mode 100644 index 00000000000..da927b6260e --- /dev/null +++ b/samples/server/petstore/rails5/app/models/pet.rb @@ -0,0 +1,31 @@ +=begin +Swagger Petstore + +This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end + + +class Pet < ApplicationRecord + validate_presence_of :name + validate_presence_of :photo_urls + + serialize :photo_urls, Array + serialize :tags, Array +end diff --git a/samples/server/petstore/rails5/app/models/tag.rb b/samples/server/petstore/rails5/app/models/tag.rb new file mode 100644 index 00000000000..096f132e2c2 --- /dev/null +++ b/samples/server/petstore/rails5/app/models/tag.rb @@ -0,0 +1,27 @@ +=begin +Swagger Petstore + +This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end + + +class Tag < ApplicationRecord + +end diff --git a/samples/server/petstore/rails5/app/models/user.rb b/samples/server/petstore/rails5/app/models/user.rb new file mode 100644 index 00000000000..47f81df1089 --- /dev/null +++ b/samples/server/petstore/rails5/app/models/user.rb @@ -0,0 +1,27 @@ +=begin +Swagger Petstore + +This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end + + +class User < ApplicationRecord + +end diff --git a/samples/server/petstore/rails5/db/migrate/0_init_tables.rb b/samples/server/petstore/rails5/db/migrate/0_init_tables.rb new file mode 100644 index 00000000000..5fa060fb4dc --- /dev/null +++ b/samples/server/petstore/rails5/db/migrate/0_init_tables.rb @@ -0,0 +1,84 @@ +=begin +Swagger Petstore + +This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +=end + +class InitTables < ActiveRecord::Migration + def change + create_table :api_response, id: false do |t| + t.integer :code + t.string :type + t.string :message + + t.timestamps + end + + create_table :category, id: false do |t| + t.integer :id + t.string :name + + t.timestamps + end + + create_table :order, id: false do |t| + t.integer :id + t.integer :pet_id + t.integer :quantity + t.datetime :ship_date + t.string :status + t.boolean :complete + + t.timestamps + end + + create_table :pet, id: false do |t| + t.integer :id + t.string :category + t.string :name + t.string :photo_urls + t.string :tags + t.string :status + + t.timestamps + end + + create_table :tag, id: false do |t| + t.integer :id + t.string :name + + t.timestamps + end + + create_table :user, id: false do |t| + t.integer :id + t.string :username + t.string :first_name + t.string :last_name + t.string :email + t.string :password + t.string :phone + t.integer :user_status + + t.timestamps + end + + end +end diff --git a/samples/server/petstore/springboot/.swagger-codegen-ignore b/samples/server/petstore/springboot/.swagger-codegen-ignore new file mode 100644 index 00000000000..19d3377182e --- /dev/null +++ b/samples/server/petstore/springboot/.swagger-codegen-ignore @@ -0,0 +1,23 @@ +# Swagger Codegen Ignore +# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell Swagger Codgen to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# Thsi matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/server/petstore/springboot/LICENSE b/samples/server/petstore/springboot/LICENSE new file mode 100644 index 00000000000..8dada3edaf5 --- /dev/null +++ b/samples/server/petstore/springboot/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/samples/server/petstore/springboot/README.md b/samples/server/petstore/springboot/README.md index 8f9855eedf9..a2e8a9f7b84 100644 --- a/samples/server/petstore/springboot/README.md +++ b/samples/server/petstore/springboot/README.md @@ -15,4 +15,4 @@ 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 +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 index 139b3da9ab4..0002871db8f 100644 --- a/samples/server/petstore/springboot/pom.xml +++ b/samples/server/petstore/springboot/pom.xml @@ -50,5 +50,14 @@ springfox-swagger-ui ${springfox-version} + + + com.fasterxml.jackson.datatype + jackson-datatype-joda + + + joda-time + joda-time + \ No newline at end of file diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/Swagger2SpringBoot.java b/samples/server/petstore/springboot/src/main/java/io/swagger/Swagger2SpringBoot.java index 2cc65db2b81..4317ba2f1a6 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/Swagger2SpringBoot.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/Swagger2SpringBoot.java @@ -33,4 +33,4 @@ public class Swagger2SpringBoot implements CommandLineRunner { } } -} \ 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 index 1652afba0ad..7fa61c50d24 100644 --- 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 @@ -1,6 +1,6 @@ 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) { 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 index d18415d8e7c..f0f62dc7206 100644 --- 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 @@ -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.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, 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 index a58b9c19e97..33f95878e54 100644 --- 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 @@ -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.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; 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 index 8770f484be1..295109d7fc4 100644 --- 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 @@ -1,6 +1,6 @@ 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) { diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/api/PetApi.java b/samples/server/petstore/springboot/src/main/java/io/swagger/api/PetApi.java index 7f66bdc75f7..bb63b7e11d6 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/api/PetApi.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/api/PetApi.java @@ -3,14 +3,12 @@ package io.swagger.api; import io.swagger.model.*; import io.swagger.model.Pet; -import java.io.File; import io.swagger.model.ModelApiResponse; +import java.io.File; 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; @@ -24,11 +22,9 @@ 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 { +@Api(value = "pet", description = "the pet API") + +public interface PetApi { @ApiOperation(value = "Add a new pet to the store", notes = "", response = Void.class, authorizations = { @Authorization(value = "petstore_auth", scopes = { @@ -38,18 +34,11 @@ public class PetApi { }) @ApiResponses(value = { @ApiResponse(code = 405, message = "Invalid input", response = Void.class) }) - @RequestMapping(value = "", + @RequestMapping(value = "/pet", 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); - } + ResponseEntity addPet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @RequestBody Pet body); @ApiOperation(value = "Deletes a pet", notes = "", response = Void.class, authorizations = { @@ -60,22 +49,11 @@ public class PetApi { }) @ApiResponses(value = { @ApiResponse(code = 400, message = "Invalid pet value", response = Void.class) }) - @RequestMapping(value = "/{petId}", + @RequestMapping(value = "/pet/{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); - } + ResponseEntity deletePet(@ApiParam(value = "Pet id to delete",required=true ) @PathVariable("petId") Long petId, + @ApiParam(value = "" ) @RequestHeader(value="api_key", required=false) String apiKey); @ApiOperation(value = "Finds Pets by status", notes = "Multiple status values can be provided with comma separated strings", response = Pet.class, responseContainer = "List", authorizations = { @@ -87,18 +65,10 @@ public class PetApi { @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Pet.class), @ApiResponse(code = 400, message = "Invalid status value", response = Pet.class) }) - @RequestMapping(value = "/findByStatus", + @RequestMapping(value = "/pet/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); - } + ResponseEntity> findPetsByStatus(@ApiParam(value = "Status values that need to be considered for filter", required = true) @RequestParam(value = "status", required = true) List status); @ApiOperation(value = "Finds Pets by tags", notes = "Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.", response = Pet.class, responseContainer = "List", authorizations = { @@ -110,18 +80,10 @@ public class PetApi { @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Pet.class), @ApiResponse(code = 400, message = "Invalid tag value", response = Pet.class) }) - @RequestMapping(value = "/findByTags", + @RequestMapping(value = "/pet/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); - } + ResponseEntity> findPetsByTags(@ApiParam(value = "Tags to filter by", required = true) @RequestParam(value = "tags", required = true) List tags); @ApiOperation(value = "Find pet by ID", notes = "Returns a single pet", response = Pet.class, authorizations = { @@ -131,18 +93,10 @@ public class PetApi { @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}", + @RequestMapping(value = "/pet/{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); - } + ResponseEntity getPetById(@ApiParam(value = "ID of pet to return",required=true ) @PathVariable("petId") Long petId); @ApiOperation(value = "Update an existing pet", notes = "", response = Void.class, authorizations = { @@ -155,18 +109,11 @@ public class PetApi { @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 = "", + @RequestMapping(value = "/pet", 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); - } + ResponseEntity updatePet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @RequestBody Pet body); @ApiOperation(value = "Updates a pet in the store with form data", notes = "", response = Void.class, authorizations = { @@ -177,28 +124,13 @@ public class PetApi { }) @ApiResponses(value = { @ApiResponse(code = 405, message = "Invalid input", response = Void.class) }) - @RequestMapping(value = "/{petId}", + @RequestMapping(value = "/pet/{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); - } + ResponseEntity updatePetWithForm(@ApiParam(value = "ID of pet that needs to be updated",required=true ) @PathVariable("petId") Long petId, + @ApiParam(value = "Updated name of the pet" ) @RequestPart(value="name", required=false) String name, + @ApiParam(value = "Updated status of the pet" ) @RequestPart(value="status", required=false) String status); @ApiOperation(value = "uploads an image", notes = "", response = ModelApiResponse.class, authorizations = { @@ -209,26 +141,12 @@ public class PetApi { }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = ModelApiResponse.class) }) - @RequestMapping(value = "/{petId}/uploadImage", + @RequestMapping(value = "/pet/{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); - } + ResponseEntity uploadFile(@ApiParam(value = "ID of pet to update",required=true ) @PathVariable("petId") Long petId, + @ApiParam(value = "Additional data to pass to server" ) @RequestPart(value="additionalMetadata", required=false) String additionalMetadata, + @ApiParam(value = "file detail") @RequestPart("file") MultipartFile file); } diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/api/PetApiController.java b/samples/server/petstore/springboot/src/main/java/io/swagger/api/PetApiController.java new file mode 100644 index 00000000000..ec3bbf3e747 --- /dev/null +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/api/PetApiController.java @@ -0,0 +1,71 @@ +package io.swagger.api; + +import io.swagger.model.*; + +import io.swagger.model.Pet; +import io.swagger.model.ModelApiResponse; +import java.io.File; + +import io.swagger.annotations.*; + +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RequestPart; +import org.springframework.web.multipart.MultipartFile; + +import java.util.List; + +@Controller + +public class PetApiController implements PetApi { + public ResponseEntity addPet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @RequestBody Pet body) { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + + public ResponseEntity deletePet(@ApiParam(value = "Pet id to delete",required=true ) @PathVariable("petId") Long petId, + @ApiParam(value = "" ) @RequestHeader(value="api_key", required=false) String apiKey) { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + + public ResponseEntity> findPetsByStatus(@ApiParam(value = "Status values that need to be considered for filter", required = true) @RequestParam(value = "status", required = true) List status) { + // do some magic! + return new ResponseEntity>(HttpStatus.OK); + } + + public ResponseEntity> findPetsByTags(@ApiParam(value = "Tags to filter by", required = true) @RequestParam(value = "tags", required = true) List tags) { + // do some magic! + return new ResponseEntity>(HttpStatus.OK); + } + + public ResponseEntity getPetById(@ApiParam(value = "ID of pet to return",required=true ) @PathVariable("petId") Long petId) { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + + public ResponseEntity updatePet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @RequestBody Pet body) { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + + public ResponseEntity updatePetWithForm(@ApiParam(value = "ID of pet that needs to be updated",required=true ) @PathVariable("petId") Long petId, + @ApiParam(value = "Updated name of the pet" ) @RequestPart(value="name", required=false) String name, + @ApiParam(value = "Updated status of the pet" ) @RequestPart(value="status", required=false) String status) { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + + public ResponseEntity uploadFile(@ApiParam(value = "ID of pet to update",required=true ) @PathVariable("petId") Long petId, + @ApiParam(value = "Additional data to pass to server" ) @RequestPart(value="additionalMetadata", required=false) String additionalMetadata, + @ApiParam(value = "file detail") @RequestPart("file") MultipartFile file) { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + +} diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/api/StoreApi.java b/samples/server/petstore/springboot/src/main/java/io/swagger/api/StoreApi.java index 8cf2283e4fe..2fb7585dbdd 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/api/StoreApi.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/api/StoreApi.java @@ -7,9 +7,7 @@ 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; @@ -23,28 +21,18 @@ 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 { +@Api(value = "store", description = "the store API") + +public interface StoreApi { @ApiOperation(value = "Delete purchase order by ID", notes = "For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors", response = Void.class) @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}", + @RequestMapping(value = "/store/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); - } + ResponseEntity deleteOrder(@ApiParam(value = "ID of the order that needs to be deleted",required=true ) @PathVariable("orderId") String orderId); @ApiOperation(value = "Returns pet inventories by status", notes = "Returns a map of status codes to quantities", response = Integer.class, responseContainer = "Map", authorizations = { @@ -52,15 +40,10 @@ public class StoreApi { }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Integer.class) }) - @RequestMapping(value = "/inventory", + @RequestMapping(value = "/store/inventory", produces = { "application/json" }, - method = RequestMethod.GET) - public ResponseEntity> getInventory() - throws NotFoundException { - // do some magic! - return new ResponseEntity>(HttpStatus.OK); - } + ResponseEntity> getInventory(); @ApiOperation(value = "Find purchase order by ID", notes = "For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions", response = Order.class) @@ -68,35 +51,19 @@ public class StoreApi { @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}", + @RequestMapping(value = "/store/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); - } + ResponseEntity getOrderById(@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathVariable("orderId") Long orderId); @ApiOperation(value = "Place an order for a pet", notes = "", response = Order.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Order.class), @ApiResponse(code = 400, message = "Invalid Order", response = Order.class) }) - @RequestMapping(value = "/order", + @RequestMapping(value = "/store/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); - } + ResponseEntity placeOrder(@ApiParam(value = "order placed for purchasing the pet" ,required=true ) @RequestBody Order body); } diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/api/StoreApiController.java b/samples/server/petstore/springboot/src/main/java/io/swagger/api/StoreApiController.java new file mode 100644 index 00000000000..92de5eb86b4 --- /dev/null +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/api/StoreApiController.java @@ -0,0 +1,45 @@ +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.RequestParam; +import org.springframework.web.bind.annotation.RequestPart; +import org.springframework.web.multipart.MultipartFile; + +import java.util.List; + +@Controller + +public class StoreApiController implements StoreApi { + public ResponseEntity deleteOrder(@ApiParam(value = "ID of the order that needs to be deleted",required=true ) @PathVariable("orderId") String orderId) { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + + public ResponseEntity> getInventory() { + // do some magic! + return new ResponseEntity>(HttpStatus.OK); + } + + public ResponseEntity getOrderById(@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathVariable("orderId") Long orderId) { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + + public ResponseEntity placeOrder(@ApiParam(value = "order placed for purchasing the pet" ,required=true ) @RequestBody Order body) { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + +} diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/api/UserApi.java b/samples/server/petstore/springboot/src/main/java/io/swagger/api/UserApi.java index 36c500faded..3877be4e8ad 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/api/UserApi.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/api/UserApi.java @@ -7,9 +7,7 @@ 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; @@ -23,79 +21,45 @@ 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 { +@Api(value = "user", description = "the user API") + +public interface UserApi { @ApiOperation(value = "Create user", notes = "This can only be done by the logged in user.", response = Void.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Void.class) }) - @RequestMapping(value = "", + @RequestMapping(value = "/user", 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); - } + ResponseEntity createUser(@ApiParam(value = "Created user object" ,required=true ) @RequestBody User body); @ApiOperation(value = "Creates list of users with given input array", notes = "", response = Void.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Void.class) }) - @RequestMapping(value = "/createWithArray", + @RequestMapping(value = "/user/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); - } + ResponseEntity createUsersWithArrayInput(@ApiParam(value = "List of user object" ,required=true ) @RequestBody List body); @ApiOperation(value = "Creates list of users with given input array", notes = "", response = Void.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Void.class) }) - @RequestMapping(value = "/createWithList", + @RequestMapping(value = "/user/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); - } + ResponseEntity createUsersWithListInput(@ApiParam(value = "List of user object" ,required=true ) @RequestBody List body); @ApiOperation(value = "Delete user", notes = "This can only be done by the logged in user.", response = Void.class) @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}", + @RequestMapping(value = "/user/{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); - } + ResponseEntity deleteUser(@ApiParam(value = "The name that needs to be deleted",required=true ) @PathVariable("username") String username); @ApiOperation(value = "Get user by user name", notes = "", response = User.class) @@ -103,75 +67,40 @@ public class UserApi { @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}", + @RequestMapping(value = "/user/{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); - } + ResponseEntity getUserByName(@ApiParam(value = "The name that needs to be fetched. Use user1 for testing. ",required=true ) @PathVariable("username") String username); @ApiOperation(value = "Logs user into the system", notes = "", response = String.class) @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", + @RequestMapping(value = "/user/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); - } + ResponseEntity loginUser(@ApiParam(value = "The user name for login", required = true) @RequestParam(value = "username", required = true) String username, + @ApiParam(value = "The password for login in clear text", required = true) @RequestParam(value = "password", required = true) String password); @ApiOperation(value = "Logs out current logged in user session", notes = "", response = Void.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Void.class) }) - @RequestMapping(value = "/logout", + @RequestMapping(value = "/user/logout", produces = { "application/xml", "application/json" }, - method = RequestMethod.GET) - public ResponseEntity logoutUser() - throws NotFoundException { - // do some magic! - return new ResponseEntity(HttpStatus.OK); - } + ResponseEntity logoutUser(); @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}", + @RequestMapping(value = "/user/{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); - } + ResponseEntity updateUser(@ApiParam(value = "name that need to be deleted",required=true ) @PathVariable("username") String username, + @ApiParam(value = "Updated user object" ,required=true ) @RequestBody User body); } diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/api/UserApiController.java b/samples/server/petstore/springboot/src/main/java/io/swagger/api/UserApiController.java new file mode 100644 index 00000000000..f855d358ea5 --- /dev/null +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/api/UserApiController.java @@ -0,0 +1,67 @@ +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.RequestParam; +import org.springframework.web.bind.annotation.RequestPart; +import org.springframework.web.multipart.MultipartFile; + +import java.util.List; + +@Controller + +public class UserApiController implements UserApi { + public ResponseEntity createUser(@ApiParam(value = "Created user object" ,required=true ) @RequestBody User body) { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + + public ResponseEntity createUsersWithArrayInput(@ApiParam(value = "List of user object" ,required=true ) @RequestBody List body) { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + + public ResponseEntity createUsersWithListInput(@ApiParam(value = "List of user object" ,required=true ) @RequestBody List body) { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + + public ResponseEntity deleteUser(@ApiParam(value = "The name that needs to be deleted",required=true ) @PathVariable("username") String username) { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + + public ResponseEntity getUserByName(@ApiParam(value = "The name that needs to be fetched. Use user1 for testing. ",required=true ) @PathVariable("username") String username) { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + + public ResponseEntity loginUser(@ApiParam(value = "The user name for login", required = true) @RequestParam(value = "username", required = true) String username, + @ApiParam(value = "The password for login in clear text", required = true) @RequestParam(value = "password", required = true) String password) { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + + public ResponseEntity logoutUser() { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + + public ResponseEntity updateUser(@ApiParam(value = "name that need to be deleted",required=true ) @PathVariable("username") String username, + @ApiParam(value = "Updated user object" ,required=true ) @RequestBody User body) { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + +} diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/configuration/SwaggerDocumentationConfig.java b/samples/server/petstore/springboot/src/main/java/io/swagger/configuration/SwaggerDocumentationConfig.java index 185c0e08794..282773a2d30 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/configuration/SwaggerDocumentationConfig.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/configuration/SwaggerDocumentationConfig.java @@ -13,7 +13,7 @@ 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() { @@ -34,6 +34,8 @@ public class SwaggerDocumentationConfig { .select() .apis(RequestHandlerSelectors.basePackage("io.swagger.api")) .build() + .directModelSubstitute(org.joda.time.LocalDate.class, java.sql.Date.class) + .directModelSubstitute(org.joda.time.DateTime.class, java.util.Date.class) .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 index 411a206a7f6..d7aa14a8c75 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/model/Category.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/Category.java @@ -11,7 +11,7 @@ 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; diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/model/ModelApiResponse.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/ModelApiResponse.java index 73a0717d5e5..50163623706 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/model/ModelApiResponse.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/ModelApiResponse.java @@ -11,7 +11,7 @@ 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; diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/model/Order.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/Order.java index 3f8bbd49e37..941bfe67c2f 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/model/Order.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/Order.java @@ -4,7 +4,7 @@ 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 org.joda.time.DateTime; import io.swagger.annotations.*; import com.fasterxml.jackson.annotation.JsonProperty; @@ -13,13 +13,13 @@ 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; + private DateTime shipDate = null; public enum StatusEnum { placed, approved, delivered, }; @@ -64,10 +64,10 @@ public class Order { **/ @ApiModelProperty(value = "") @JsonProperty("shipDate") - public Date getShipDate() { + public DateTime getShipDate() { return shipDate; } - public void setShipDate(Date shipDate) { + public void setShipDate(DateTime shipDate) { this.shipDate = shipDate; } diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/model/Pet.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/Pet.java index 1507c988f3b..aabffb593e4 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/model/Pet.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/Pet.java @@ -16,7 +16,7 @@ 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; diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/model/Tag.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/Tag.java index 665a5c00270..e9ef2ca5704 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/model/Tag.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/Tag.java @@ -11,7 +11,7 @@ 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; diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/model/User.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/User.java index dd8cd876e7b..76ac713c8ee 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/model/User.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/User.java @@ -11,7 +11,7 @@ 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;