diff --git a/.gitignore b/.gitignore index 2aaad73c13f..d84a08f7b94 100644 --- a/.gitignore +++ b/.gitignore @@ -55,6 +55,8 @@ samples/client/petstore/php/SwaggerClient-php/vendor/ samples/client/petstore/silex/SwaggerServer/composer.lock samples/client/petstore/silex/SwaggerServer/venodr/ +samples/client/petstore/perl/deep_module_test/ + samples/client/petstore/python/.projectile samples/client/petstore/python/.venv/ diff --git a/.travis.yml b/.travis.yml index 46286b5e5ca..46bb326da69 100644 --- a/.travis.yml +++ b/.travis.yml @@ -2,6 +2,7 @@ sudo: required language: java jdk: - oraclejdk7 + - oraclejdk8 services: - docker @@ -11,12 +12,10 @@ before_install: - gem install bundler install: - - docker login --email=$DOCKER_HUB_EMAIL --username=$DOCKER_HUB_USERNAME --password=$DOCKER_HUB_PASSWORD script: - mvn verify -Psamples - - docker build -t $DOCKER_IMAGE_NAME ./modules/swagger-generator - - if [ ! -z "$TRAVIS_TAG" ]; then docker tag $DOCKER_IMAGE_NAME:latest $DOCKER_IMAGE_NAME:$TRAVIS_TAG; fi && docker push $DOCKER_IMAGE_NAME + - if [ $DOCKER_HUB_USERNAME ]; then docker login --email=$DOCKER_HUB_EMAIL --username=$DOCKER_HUB_USERNAME --password=$DOCKER_HUB_PASSWORD && docker build -t $DOCKER_IMAGE_NAME ./modules/swagger-generator && if [ ! -z "$TRAVIS_TAG" ]; then docker tag $DOCKER_IMAGE_NAME:latest $DOCKER_IMAGE_NAME:$TRAVIS_TAG; fi && docker push $DOCKER_IMAGE_NAME; fi env: - DOCKER_IMAGE_NAME=swaggerapi/swagger-generator diff --git a/LICENSE b/LICENSE index 542991f9550..ebfd64c4931 100644 --- a/LICENSE +++ b/LICENSE @@ -1,4 +1,4 @@ -Copyright 2015 SmartBear Software +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. diff --git a/README.md b/README.md index 243ae836dbd..e267217ebd0 100644 --- a/README.md +++ b/README.md @@ -23,6 +23,7 @@ Check out [Swagger-Spec](https://github.com/OAI/OpenAPI-Specification) for addit - [Docker](#docker) - [Build and run](#build-and-run-using-docker) - [Build a Node.js server stub](#build-a-nodejs-server-stub) + - [Public Docker image](#public-docker-image) - [Homebrew](#homebrew) - Generators - [To generate a sample client library](#to-generate-a-sample-client-library) @@ -32,7 +33,7 @@ Check out [Swagger-Spec](https://github.com/OAI/OpenAPI-Specification) for addit - [Where is Javascript???](#where-is-javascript) - [Generating a client from local files](#generating-a-client-from-local-files) - [Customizing the generator](#customizing-the-generator) - - [Validating your OpenAPI Spec](#validating-your-swagger-spec) + - [Validating your OpenAPI Spec](#validating-your-openapi-spec) - [Generating dynamic html api documentation](#generating-dynamic-html-api-documentation) - [Generating static html api documentation](#generating-static-html-api-documentation) - [To build a server stub](#to-build-a-server-stub) @@ -56,7 +57,7 @@ The OpenAPI Specification has undergone 3 revisions since initial creation in 20 Swagger Codegen Version | Release Date | OpenAPI Spec compatibility | Notes -------------------------- | ------------ | -------------------------- | ----- 2.1.6-SNAPSHOT | | 1.0, 1.1, 1.2, 2.0 | [master](https://github.com/swagger-api/swagger-codegen) -2.1.5 (**current stable**) | 2015-01-06 | 1.0, 1.1, 1.2, 2.0 | [tag v2.1.5](https://github.com/swagger-api/swagger-codegen/tree/v2.1.4) +2.1.5 (**current stable**) | 2015-01-06 | 1.0, 1.1, 1.2, 2.0 | [tag v2.1.5](https://github.com/swagger-api/swagger-codegen/tree/v2.1.5) 2.0.17 | 2014-08-22 | 1.1, 1.2 | [tag v2.0.17](https://github.com/swagger-api/swagger-codegen/tree/v2.0.17) 1.0.4 | 2012-04-12 | 1.0, 1.1 | [tag v1.0.4](https://github.com/swagger-api/swagger-codegen/tree/swagger-codegen_2.9.1-1.1) @@ -77,16 +78,16 @@ brew install swagger-codegen To build from source, you need the following installed and available in your $PATH: -* [Java 7](http://java.oracle.com) +* [Java 7 or 8](http://java.oracle.com) * [Apache maven 3.0.3 or greater](http://maven.apache.org/) #### OS X Users -Don't forget to install Java 7. You probably have 1.6 or 1.8. +Don't forget to install Java 7 or 8. You probably have 1.6. Export JAVA_HOME in order to use the supported Java version: ``` -export JAVA_HOME=`/usr/libexec/java_home -v 1.7` +export JAVA_HOME=`/usr/libexec/java_home -v 1.8` export PATH=${JAVA_HOME}/bin:$PATH ``` @@ -117,6 +118,10 @@ cd swagger-codegen -o samples/server/petstore/nodejs ``` +#### Public Docker image + +https://hub.docker.com/r/swaggerapi/swagger-generator/ + ### Homebrew To install, run `brew install swagger-codegen` @@ -580,7 +585,7 @@ Please refer to this [page](https://github.com/swagger-api/swagger-codegen/blob/ License ------- -Copyright 2015 SmartBear Software +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. diff --git a/bin/perl-petstore.sh b/bin/perl-petstore.sh index 64d684e9ec8..b2eb1753d67 100755 --- a/bin/perl-petstore.sh +++ b/bin/perl-petstore.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" +# complex module name used for testing ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l perl -o samples/client/petstore/perl" java $JAVA_OPTS -jar $executable $ags + +java $JAVA_OPTS -jar $executable $ags --additional-properties moduleName=Something::Deep -o samples/client/petstore/perl/deep_module_test diff --git a/modules/swagger-codegen-cli/pom.xml b/modules/swagger-codegen-cli/pom.xml index 1f52f4ff663..9100143a236 100644 --- a/modules/swagger-codegen-cli/pom.xml +++ b/modules/swagger-codegen-cli/pom.xml @@ -3,7 +3,7 @@ io.swagger swagger-codegen-project - 2.1.5 + 2.1.6-SNAPSHOT ../.. 4.0.0 diff --git a/modules/swagger-codegen-maven-plugin/pom.xml b/modules/swagger-codegen-maven-plugin/pom.xml index 94508f71527..850ac735534 100644 --- a/modules/swagger-codegen-maven-plugin/pom.xml +++ b/modules/swagger-codegen-maven-plugin/pom.xml @@ -6,7 +6,7 @@ io.swagger swagger-codegen-project - 2.1.5 + 2.1.6-SNAPSHOT ../.. swagger-codegen-maven-plugin diff --git a/modules/swagger-codegen/pom.xml b/modules/swagger-codegen/pom.xml index 901f18b9a1b..29d2dc4e148 100644 --- a/modules/swagger-codegen/pom.xml +++ b/modules/swagger-codegen/pom.xml @@ -3,7 +3,7 @@ io.swagger swagger-codegen-project - 2.1.5 + 2.1.6-SNAPSHOT ../.. 4.0.0 diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConstants.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConstants.java index fc2410fa9de..4a4f9e037ef 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConstants.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConstants.java @@ -46,6 +46,9 @@ public class CodegenConstants { public static final String SORT_PARAMS_BY_REQUIRED_FLAG = "sortParamsByRequiredFlag"; public static final String SORT_PARAMS_BY_REQUIRED_FLAG_DESC = "Sort method arguments to place required parameters before optional parameters."; + public static final String USE_DATETIME_OFFSET = "useDateTimeOffset"; + public static final String USE_DATETIME_OFFSET_DESC = "Use DateTimeOffset to model date-time properties"; + public static final String ENSURE_UNIQUE_PARAMS = "ensureUniqueParams"; public static final String ENSURE_UNIQUE_PARAMS_DESC = "Whether to ensure parameter names are unique in an operation (rename parameters that are not)."; @@ -54,4 +57,9 @@ public class CodegenConstants { public static final String POD_VERSION = "podVersion"; public static final String OPTIONAL_METHOD_ARGUMENT = "optionalMethodArgument"; + public static final String OPTIONAL_METHOD_ARGUMENT_DESC = "Optional method argument, e.g. void square(int x=10) (.net 4.0+ only)."; + + public static final String OPTIONAL_ASSEMBLY_INFO = "optionalAssemblyInfo"; + public static final String OPTIONAL_ASSEMBLY_INFO_DESC = "Generate AssemblyInfo.cs (Default: true)."; + } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AndroidClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AndroidClientCodegen.java index 8137dbb9793..ac84e7c795d 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AndroidClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AndroidClientCodegen.java @@ -42,13 +42,19 @@ public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfi reservedWords = new HashSet( Arrays.asList( - "abstract", "continue", "for", "new", "switch", "assert", - "default", "if", "package", "synchronized", "boolean", "do", "goto", "private", - "this", "break", "double", "implements", "protected", "throw", "byte", "else", - "import", "public", "throws", "case", "enum", "instanceof", "return", "transient", - "catch", "extends", "int", "short", "try", "char", "final", "interface", "static", - "void", "class", "finally", "long", "strictfp", "volatile", "const", "float", - "native", "super", "while") + // local variable names used in API methods (endpoints) + "postBody", "path", "queryParams", "headerParams", "formParams", + "contentTypes", "contentType", "response", "builder", "httpEntity", + "authNames", "basePath", "apiInvoker", + + // android reserved words + "abstract", "continue", "for", "new", "switch", "assert", + "default", "if", "package", "synchronized", "boolean", "do", "goto", "private", + "this", "break", "double", "implements", "protected", "throw", "byte", "else", + "import", "public", "throws", "case", "enum", "instanceof", "return", "transient", + "catch", "extends", "int", "short", "try", "char", "final", "interface", "static", + "void", "class", "finally", "long", "strictfp", "volatile", "const", "float", + "native", "super", "while") ); languageSpecificPrimitives = new HashSet( @@ -281,10 +287,6 @@ public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfi supportingFiles.add(new SupportingFile("manifest.mustache", projectFolder, "AndroidManifest.xml")); supportingFiles.add(new SupportingFile("apiInvoker.mustache", (sourceFolder + File.separator + invokerPackage).replace(".", File.separator), "ApiInvoker.java")); - supportingFiles.add(new SupportingFile("responses.mustache", - (sourceFolder + File.separator + invokerPackage).replace(".", File.separator), "Responses.java")); - // supportingFiles.add(new SupportingFile("httpPatch.mustache", - // (sourceFolder + File.separator + invokerPackage).replace(".", File.separator), "HttpPatch.java")); supportingFiles.add(new SupportingFile("jsonUtil.mustache", (sourceFolder + File.separator + invokerPackage).replace(".", File.separator), "JsonUtil.java")); supportingFiles.add(new SupportingFile("apiException.mustache", diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AsyncScalaClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AsyncScalaClientCodegen.java index 310b4788dd0..bac6efe2aff 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AsyncScalaClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AsyncScalaClientCodegen.java @@ -47,11 +47,16 @@ public class AsyncScalaClientCodegen extends DefaultCodegen implements CodegenCo reservedWords = new HashSet( Arrays.asList( - "abstract", "case", "catch", "class", "def", "do", "else", "extends", - "false", "final", "finally", "for", "forSome", "if", "implicit", - "import", "lazy", "match", "new", "null", "object", "override", "package", - "private", "protected", "return", "sealed", "super", "this", "throw", - "trait", "try", "true", "type", "val", "var", "while", "with", "yield") + // local variable names used in API methods (endpoints) + "config", "path", "contentTypes", "contentType", "queryParams", "headerParams", + "formParams", "postBody", "resFuture", "client", "reader", + + // scala reserved words + "abstract", "case", "catch", "class", "def", "do", "else", "extends", + "false", "final", "finally", "for", "forSome", "if", "implicit", + "import", "lazy", "match", "new", "null", "object", "override", "package", + "private", "protected", "return", "sealed", "super", "this", "throw", + "trait", "try", "true", "type", "val", "var", "while", "with", "yield") ); additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, invokerPackage); 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 aa776731e9c..23c266e618f 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 @@ -23,7 +23,9 @@ import org.slf4j.LoggerFactory; public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig { private static final Logger LOGGER = LoggerFactory.getLogger(CSharpClientCodegen.class); + protected boolean optionalAssemblyInfoFlag = true; protected boolean optionalMethodArgumentFlag = true; + protected boolean useDateTimeOffsetFlag = false; protected String packageTitle = "Swagger Library"; protected String packageProductName = "SwaggerLibrary"; protected String packageDescription = "A library generated from a Swagger doc"; @@ -75,6 +77,7 @@ public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig "List", "Dictionary", "DateTime?", + "DateTimeOffset?", "String", "Boolean", "Double", @@ -89,6 +92,7 @@ public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig typeMapping = new HashMap(); typeMapping.put("string", "string"); + typeMapping.put("binary", "byte[]"); typeMapping.put("boolean", "bool?"); typeMapping.put("integer", "int?"); typeMapping.put("float", "float?"); @@ -111,6 +115,10 @@ public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG_DESC).defaultValue(Boolean.TRUE.toString())); cliOptions.add(CliOption.newBoolean(CodegenConstants.OPTIONAL_METHOD_ARGUMENT, "C# Optional method argument, " + "e.g. void square(int x=10) (.net 4.0+ only).")); + cliOptions.add(CliOption.newBoolean(CodegenConstants.OPTIONAL_ASSEMBLY_INFO, + CodegenConstants.OPTIONAL_ASSEMBLY_INFO_DESC).defaultValue(Boolean.TRUE.toString())); + cliOptions.add(new CliOption(CodegenConstants.SOURCE_FOLDER, CodegenConstants.SOURCE_FOLDER_DESC).defaultValue(sourceFolder)); + cliOptions.add(CliOption.newBoolean(CodegenConstants.USE_DATETIME_OFFSET, CodegenConstants.USE_DATETIME_OFFSET_DESC)); } @Override @@ -123,6 +131,14 @@ public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig additionalProperties.put(CodegenConstants.PACKAGE_VERSION, packageVersion); } + if (additionalProperties.containsKey(CodegenConstants.SOURCE_FOLDER)){ + setSourceFolder((String) additionalProperties.get(CodegenConstants.SOURCE_FOLDER)); + } + else + { + additionalProperties.put(CodegenConstants.SOURCE_FOLDER, this.sourceFolder); + } + if (additionalProperties.containsKey(CodegenConstants.PACKAGE_NAME)) { setPackageName((String) additionalProperties.get(CodegenConstants.PACKAGE_NAME)); apiPackage = packageName + ".Api"; @@ -132,6 +148,13 @@ public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig additionalProperties.put(CodegenConstants.PACKAGE_NAME, packageName); } + // Use DateTimeOffset + if (additionalProperties.containsKey(CodegenConstants.USE_DATETIME_OFFSET)) + { + useDateTimeOffset(Boolean.valueOf(additionalProperties.get(CodegenConstants.USE_DATETIME_OFFSET).toString())); + } + additionalProperties.put(CodegenConstants.USE_DATETIME_OFFSET, useDateTimeOffsetFlag); + additionalProperties.put("clientPackage", clientPackage); // Add properties used by AssemblyInfo.mustache @@ -147,6 +170,11 @@ public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig } additionalProperties.put("optionalMethodArgument", optionalMethodArgumentFlag); + if (additionalProperties.containsKey(CodegenConstants.OPTIONAL_ASSEMBLY_INFO)) { + setOptionalAssemblyInfoFlag(Boolean.valueOf(additionalProperties + .get(CodegenConstants.OPTIONAL_ASSEMBLY_INFO).toString())); + } + supportingFiles.add(new SupportingFile("Configuration.mustache", sourceFolder + File.separator + clientPackage.replace(".", java.io.File.separator), "Configuration.cs")); supportingFiles.add(new SupportingFile("ApiClient.mustache", @@ -158,8 +186,13 @@ public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig supportingFiles.add(new SupportingFile("Newtonsoft.Json.dll", "bin", "Newtonsoft.Json.dll")); supportingFiles.add(new SupportingFile("RestSharp.dll", "bin", "RestSharp.dll")); supportingFiles.add(new SupportingFile("compile.mustache", "", "compile.bat")); + supportingFiles.add(new SupportingFile("compile-mono.sh.mustache", "", "compile-mono.sh")); + supportingFiles.add(new SupportingFile("packages.config.mustache", "vendor" + java.io.File.separator, "packages.config")); supportingFiles.add(new SupportingFile("README.md", "", "README.md")); - supportingFiles.add(new SupportingFile("AssemblyInfo.mustache", "src" + File.separator + "Properties", "AssemblyInfo.cs")); + + if (optionalAssemblyInfoFlag) { + supportingFiles.add(new SupportingFile("AssemblyInfo.mustache", "src" + File.separator + "Properties", "AssemblyInfo.cs")); + } } @@ -301,10 +334,23 @@ public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig return camelize(sanitizeName(operationId)); } + public void setOptionalAssemblyInfoFlag(boolean flag) { + this.optionalAssemblyInfoFlag = flag; + } + public void setOptionalMethodArgumentFlag(boolean flag) { this.optionalMethodArgumentFlag = flag; } + public void useDateTimeOffset(boolean flag) { + this.useDateTimeOffsetFlag = flag; + if (flag) + typeMapping.put("datetime", "DateTimeOffset?"); + else + typeMapping.put("datetime", "DateTime?"); + } + + public void setPackageName(String packageName) { this.packageName = packageName; } @@ -313,6 +359,10 @@ public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig this.packageVersion = packageVersion; } + public void setSourceFolder(String sourceFolder) { + this.sourceFolder = sourceFolder; + } + @Override public Map postProcessModels(Map objs) { List models = (List) objs.get("models"); 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 0658e3ad6f3..8a09eb34ea9 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 @@ -223,12 +223,11 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { final String authFolder = (sourceFolder + '/' + invokerPackage + ".auth").replace(".", "/"); if ("feign".equals(getLibrary())) { supportingFiles.add(new SupportingFile("FormAwareEncoder.mustache", invokerFolder, "FormAwareEncoder.java")); - } else { - supportingFiles.add(new SupportingFile("auth/HttpBasicAuth.mustache", authFolder, "HttpBasicAuth.java")); - supportingFiles.add(new SupportingFile("auth/ApiKeyAuth.mustache", authFolder, "ApiKeyAuth.java")); - supportingFiles.add(new SupportingFile("auth/OAuth.mustache", authFolder, "OAuth.java")); - supportingFiles.add(new SupportingFile("auth/OAuthFlow.mustache", authFolder, "OAuthFlow.java")); } + supportingFiles.add(new SupportingFile("auth/HttpBasicAuth.mustache", authFolder, "HttpBasicAuth.java")); + supportingFiles.add(new SupportingFile("auth/ApiKeyAuth.mustache", authFolder, "ApiKeyAuth.java")); + supportingFiles.add(new SupportingFile("auth/OAuth.mustache", authFolder, "OAuth.java")); + supportingFiles.add(new SupportingFile("auth/OAuthFlow.mustache", authFolder, "OAuthFlow.java")); if (!("feign".equals(getLibrary()) || "retrofit".equals(getLibrary()) || "retrofit2".equals(getLibrary()))) { supportingFiles.add(new SupportingFile("apiException.mustache", invokerFolder, "ApiException.java")); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/NodeJSServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/NodeJSServerCodegen.java index d4bb00bb652..f463fbc473f 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/NodeJSServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/NodeJSServerCodegen.java @@ -11,6 +11,7 @@ import com.google.common.collect.Multimap; import io.swagger.codegen.*; import io.swagger.models.Swagger; +import io.swagger.models.Info; import io.swagger.util.Yaml; import java.io.File; @@ -246,9 +247,6 @@ public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig @Override public void preprocessSwagger(Swagger swagger) { - if ("/".equals(swagger.getBasePath())) { - swagger.setBasePath(""); - } String host = swagger.getHost(); String port = "8080"; @@ -259,6 +257,16 @@ public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig } } this.additionalProperties.put("serverPort", port); + + if (swagger.getInfo() != null) { + Info info = swagger.getInfo(); + if (info.getTitle() != null) { + // when info.title is defined, use it for projectName + // used in package.json + projectName = dashize(info.getTitle()); + this.additionalProperties.put("projectName", projectName); + } + } } @Override diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PerlClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PerlClientCodegen.java index 4f8a1fb2a9f..421c72f80d6 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PerlClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PerlClientCodegen.java @@ -20,7 +20,8 @@ import org.apache.commons.lang.StringUtils; public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig { public static final String MODULE_NAME = "moduleName"; public static final String MODULE_VERSION = "moduleVersion"; - protected String moduleName = "SwaggerClient"; + protected String moduleName = "WWW::SwaggerClient"; + protected String modulePathPart = moduleName.replaceAll("::",String.valueOf(File.separatorChar)); protected String moduleVersion = "1.0.0"; public PerlClientCodegen() { @@ -72,7 +73,7 @@ public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig { typeMapping.put("object", "object"); cliOptions.clear(); - cliOptions.add(new CliOption(MODULE_NAME, "Perl module name (convention: CamelCase).").defaultValue("SwaggerClient")); + cliOptions.add(new CliOption(MODULE_NAME, "Perl module name (convention: CamelCase or Long::Module).").defaultValue("SwaggerClient")); cliOptions.add(new CliOption(MODULE_VERSION, "Perl module version.").defaultValue("1.0.0")); cliOptions.add(CliOption.newBoolean(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG_DESC).defaultValue(Boolean.TRUE.toString())); @@ -94,15 +95,16 @@ public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig { if (additionalProperties.containsKey(MODULE_NAME)) { setModuleName((String) additionalProperties.get(MODULE_NAME)); + setModulePathPart(moduleName.replaceAll("::",String.valueOf(File.separatorChar))); } else { additionalProperties.put(MODULE_NAME, moduleName); } - supportingFiles.add(new SupportingFile("ApiClient.mustache", ("lib/WWW/" + moduleName).replace('/', File.separatorChar), "ApiClient.pm")); - supportingFiles.add(new SupportingFile("Configuration.mustache", ("lib/WWW/" + moduleName).replace('/', File.separatorChar), "Configuration.pm")); - supportingFiles.add(new SupportingFile("ApiFactory.mustache", ("lib/WWW/" + moduleName).replace('/', File.separatorChar), "ApiFactory.pm")); - supportingFiles.add(new SupportingFile("Role.mustache", ("lib/WWW/" + moduleName).replace('/', File.separatorChar), "Role.pm")); - supportingFiles.add(new SupportingFile("AutoDoc.mustache", ("lib/WWW/" + moduleName + "/Role").replace('/', File.separatorChar), "AutoDoc.pm")); + supportingFiles.add(new SupportingFile("ApiClient.mustache", ("lib/" + modulePathPart).replace('/', File.separatorChar), "ApiClient.pm")); + supportingFiles.add(new SupportingFile("Configuration.mustache", ("lib/" + modulePathPart).replace('/', File.separatorChar), "Configuration.pm")); + supportingFiles.add(new SupportingFile("ApiFactory.mustache", ("lib/" + modulePathPart).replace('/', File.separatorChar), "ApiFactory.pm")); + supportingFiles.add(new SupportingFile("Role.mustache", ("lib/" + modulePathPart).replace('/', File.separatorChar), "Role.pm")); + supportingFiles.add(new SupportingFile("AutoDoc.mustache", ("lib/" + modulePathPart + "/Role").replace('/', File.separatorChar), "AutoDoc.pm")); supportingFiles.add(new SupportingFile("autodoc.script.mustache", "bin", "autodoc")); supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); } @@ -129,12 +131,12 @@ public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig { @Override public String apiFileFolder() { - return (outputFolder + "/lib/WWW/" + moduleName + apiPackage()).replace('/', File.separatorChar); + return (outputFolder + "/lib/" + modulePathPart + apiPackage()).replace('/', File.separatorChar); } @Override public String modelFileFolder() { - return (outputFolder + "/lib/WWW/" + moduleName + modelPackage()).replace('/', File.separatorChar); + return (outputFolder + "/lib/" + modulePathPart + modelPackage()).replace('/', File.separatorChar); } @Override @@ -251,6 +253,10 @@ public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig { this.moduleName = moduleName; } + public void setModulePathPart(String modulePathPart) { + this.modulePathPart = modulePathPart; + } + public void setModuleVersion(String moduleVersion) { this.moduleVersion = moduleVersion; } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RubyClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RubyClientCodegen.java index 766e5f74f30..ddc4f35346f 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RubyClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RubyClientCodegen.java @@ -19,10 +19,24 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { public static final String GEM_NAME = "gemName"; public static final String MODULE_NAME = "moduleName"; public static final String GEM_VERSION = "gemVersion"; + public static final String GEM_LICENSE = "gemLicense"; + public static final String GEM_HOMEPAGE = "gemHomepage"; + public static final String GEM_SUMMARY = "gemSummary"; + public static final String GEM_DESCRIPTION = "gemDescription"; + public static final String GEM_AUTHOR = "gemAuthor"; + public static final String GEM_AUTHOR_EMAIL = "gemAuthorEmail"; + protected String gemName; protected String moduleName; protected String gemVersion = "1.0.0"; protected String libFolder = "lib"; + protected String gemLicense = "Apache-2.0"; + protected String gemHomepage = "http://swagger.io"; + protected String gemSummary = "A ruby wrapper for the swagger APIs"; + protected String gemDescription = "This gem maps to a swagger API"; + protected String gemAuthor = ""; + protected String gemAuthorEmail = ""; + public RubyClientCodegen() { super(); @@ -87,6 +101,23 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { cliOptions.add(new CliOption(MODULE_NAME, "top module name (convention: CamelCase, usually corresponding" + " to gem name).").defaultValue("SwaggerClient")); cliOptions.add(new CliOption(GEM_VERSION, "gem version.").defaultValue("1.0.0")); + + cliOptions.add(new CliOption(GEM_LICENSE, "gem license. "). + defaultValue("Apache-2.0")); + + cliOptions.add(new CliOption(GEM_HOMEPAGE, "gem homepage. "). + defaultValue("http://swagger.io")); + + cliOptions.add(new CliOption(GEM_SUMMARY, "gem summary. "). + defaultValue("A ruby wrapper for the swagger APIs")); + + cliOptions.add(new CliOption(GEM_DESCRIPTION, "gem description. "). + defaultValue("This gem maps to a swagger API")); + + cliOptions.add(new CliOption(GEM_AUTHOR, "gem author (only one is supported).")); + + cliOptions.add(new CliOption(GEM_AUTHOR_EMAIL, "gem author email (only one is supported).")); + } @Override @@ -114,11 +145,36 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { if (additionalProperties.containsKey(GEM_VERSION)) { setGemVersion((String) additionalProperties.get(GEM_VERSION)); - } else { + }else { // not set, pass the default value to template additionalProperties.put(GEM_VERSION, gemVersion); } + if (additionalProperties.containsKey(GEM_LICENSE)) { + setGemLicense((String) additionalProperties.get(GEM_LICENSE)); + } + + if (additionalProperties.containsKey(GEM_HOMEPAGE)) { + setGemHomepage((String) additionalProperties.get(GEM_HOMEPAGE)); + } + + if (additionalProperties.containsKey(GEM_SUMMARY)) { + setGemSummary((String) additionalProperties.get(GEM_SUMMARY)); + } + + if (additionalProperties.containsKey(GEM_DESCRIPTION)) { + setGemDescription((String) additionalProperties.get(GEM_DESCRIPTION)); + } + + if (additionalProperties.containsKey(GEM_AUTHOR)) { + setGemAuthor((String) additionalProperties.get(GEM_AUTHOR)); + } + + if (additionalProperties.containsKey(GEM_AUTHOR_EMAIL)) { + setGemAuthorEmail((String) additionalProperties.get(GEM_AUTHOR_EMAIL)); + } + + // use constant model/api package (folder path) setModelPackage("models"); setApiPackage("api"); @@ -133,6 +189,7 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { String modelFolder = gemFolder + File.separator + modelPackage.replace("/", File.separator); } + @Override public CodegenType getTag() { return CodegenType.CLIENT; @@ -354,4 +411,28 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { public void setGemVersion(String gemVersion) { this.gemVersion = gemVersion; } + + public void setGemDescription(String gemDescription) { + this.gemDescription = gemDescription; + } + + public void setGemSummary(String gemSummary) { + this.gemSummary = gemSummary; + } + + public void setGemLicense(String gemLicense) { + this.gemLicense = gemLicense; + } + + public void setGemHomepage(String gemHomepage) { + this.gemHomepage = gemHomepage; + } + + public void setGemAuthor(String gemAuthor) { + this.gemAuthor = gemAuthor; + } + + public void setGemAuthorEmail(String gemAuthorEmail) { + this.gemAuthorEmail = gemAuthorEmail; + } } 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 9469cbb8e81..088d7fdaad8 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 @@ -49,11 +49,16 @@ public class ScalaClientCodegen extends DefaultCodegen implements CodegenConfig reservedWords = new HashSet( Arrays.asList( - "abstract", "case", "catch", "class", "def", "do", "else", "extends", - "false", "final", "finally", "for", "forSome", "if", "implicit", - "import", "lazy", "match", "new", "null", "object", "override", "package", - "private", "protected", "return", "sealed", "super", "this", "throw", - "trait", "try", "true", "type", "val", "var", "while", "with", "yield") + // local variable names used in API methods (endpoints) + "path", "contentTypes", "contentType", "queryParams", "headerParams", + "formParams", "postBody", "mp", "basePath", "apiInvoker", + + // scala reserved words + "abstract", "case", "catch", "class", "def", "do", "else", "extends", + "false", "final", "finally", "for", "forSome", "if", "implicit", + "import", "lazy", "match", "new", "null", "object", "override", "package", + "private", "protected", "return", "sealed", "super", "this", "throw", + "trait", "try", "true", "type", "val", "var", "while", "with", "yield") ); additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, invokerPackage); diff --git a/modules/swagger-codegen/src/main/resources/CsharpDotNet2/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/CsharpDotNet2/ApiClient.mustache index a428cdc3630..ea92989daa4 100644 --- a/modules/swagger-codegen/src/main/resources/CsharpDotNet2/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/CsharpDotNet2/ApiClient.mustache @@ -159,6 +159,7 @@ namespace {{packageName}}.Client /// /// HTTP body (e.g. string, JSON). /// Object type. + /// HTTP headers. /// Object representation of the JSON string. public object Deserialize(string content, Type type, IList headers=null) { diff --git a/modules/swagger-codegen/src/main/resources/CsharpDotNet2/ApiException.mustache b/modules/swagger-codegen/src/main/resources/CsharpDotNet2/ApiException.mustache index 71d0243d729..dd618e0a99c 100644 --- a/modules/swagger-codegen/src/main/resources/CsharpDotNet2/ApiException.mustache +++ b/modules/swagger-codegen/src/main/resources/CsharpDotNet2/ApiException.mustache @@ -20,7 +20,6 @@ namespace {{packageName}}.Client { /// /// Initializes a new instance of the class. /// - /// The base path. public ApiException() {} /// diff --git a/modules/swagger-codegen/src/main/resources/CsharpDotNet2/api.mustache b/modules/swagger-codegen/src/main/resources/CsharpDotNet2/api.mustache index 2e51c913c30..c3fb85acb4f 100644 --- a/modules/swagger-codegen/src/main/resources/CsharpDotNet2/api.mustache +++ b/modules/swagger-codegen/src/main/resources/CsharpDotNet2/api.mustache @@ -9,6 +9,9 @@ using {{packageName}}.Client; namespace {{packageName}}.Api { {{#operations}} + /// + /// Represents a collection of functions to interact with the API endpoints + /// public interface I{{classname}} { {{#operation}} @@ -16,7 +19,7 @@ namespace {{packageName}}.Api /// {{summary}} {{notes}} /// {{#allParams}}/// {{description}} - {{/allParams}}/// {{#returnType}}{{{returnType}}}{{/returnType}} + {{/allParams}}/// {{#returnType}}{{returnType}}{{/returnType}} {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} {{nickname}} ({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); {{/operation}} } @@ -71,7 +74,7 @@ namespace {{packageName}}.Api /// /// Gets or sets the API client. /// - /// An instance of the ApiClient + /// An instance of the ApiClient public ApiClient ApiClient {get; set;} {{#operation}} @@ -79,7 +82,7 @@ namespace {{packageName}}.Api /// {{summary}} {{notes}} /// {{#allParams}}/// {{description}} - {{/allParams}}/// {{#returnType}}{{{returnType}}}{{/returnType}} + {{/allParams}}/// {{#returnType}}{{returnType}}{{/returnType}} public {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} {{nickname}} ({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) { {{#allParams}}{{#required}} diff --git a/modules/swagger-codegen/src/main/resources/CsharpDotNet2/compile-mono.sh.mustache b/modules/swagger-codegen/src/main/resources/CsharpDotNet2/compile-mono.sh.mustache index 73add75a69a..1e4e12b4aee 100644 --- a/modules/swagger-codegen/src/main/resources/CsharpDotNet2/compile-mono.sh.mustache +++ b/modules/swagger-codegen/src/main/resources/CsharpDotNet2/compile-mono.sh.mustache @@ -7,6 +7,6 @@ vendor/RestSharp.Net2.1.1.11/lib/net20/RestSharp.Net2.dll,\ System.Runtime.Serialization.dll \ -target:library \ -out:bin/{{packageName}}.dll \ --recurse:src/*.cs \ +-recurse:'src/*.cs' \ -doc:bin/{{packageName}}.xml \ --platform:anycpu \ No newline at end of file +-platform:anycpu diff --git a/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache index ef31058d561..9f55d5a14d4 100644 --- a/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache @@ -43,10 +43,12 @@ import {{invokerPackage}}.auth.OAuth; {{>generatedAnnotation}} public class ApiClient { - private Map hostMap = new HashMap(); private Map defaultHeaderMap = new HashMap(); - private boolean debugging = false; private String basePath = "{{basePath}}"; + private boolean debugging = false; + private int connectionTimeout = 0; + + private Client httpClient; private ObjectMapper mapper; private Map authentications; @@ -64,7 +66,9 @@ public class ApiClient { mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING); mapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING); mapper.registerModule(new JodaModule()); - + + httpClient = buildHttpClient(debugging); + // Use RFC3339 format for date and datetime. // See http://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14 this.dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); @@ -224,9 +228,29 @@ public class ApiClient { */ public ApiClient setDebugging(boolean debugging) { this.debugging = debugging; + // Rebuild HTTP Client according to the new "debugging" value. + this.httpClient = buildHttpClient(debugging); return this; } + /** + * Connect timeout (in milliseconds). + */ + public int getConnectTimeout() { + return connectionTimeout; + } + + /** + * Set the connect timeout (in milliseconds). + * A value of 0 means no timeout, otherwise values must be between 1 and + * {@link Integer#MAX_VALUE}. + */ + public ApiClient setConnectTimeout(int connectionTimeout) { + this.connectionTimeout = connectionTimeout; + httpClient.setConnectTimeout(connectionTimeout); + return this; + } + /** * Get the date format used to parse/format date parameters. */ @@ -436,8 +460,6 @@ public class ApiClient { updateParamsForAuth(authNames, queryParams, headerParams); - Client client = getClient(); - StringBuilder b = new StringBuilder(); b.append("?"); if (queryParams != null){ @@ -455,9 +477,9 @@ public class ApiClient { Builder builder; if (accept == null) - builder = client.resource(basePath + path + querystring).getRequestBuilder(); + builder = httpClient.resource(basePath + path + querystring).getRequestBuilder(); else - builder = client.resource(basePath + path + querystring).accept(accept); + builder = httpClient.resource(basePath + path + querystring).accept(accept); for (String key : headerParams.keySet()) { builder = builder.header(key, headerParams.get(key)); @@ -571,19 +593,17 @@ public class ApiClient { } /** - * Get an existing client or create a new client to handle HTTP request. + * Build the Client used to make HTTP requests. */ - private Client getClient() { - if(!hostMap.containsKey(basePath)) { - // Add the JSON serialization support to Jersey - JacksonJsonProvider jsonProvider = new JacksonJsonProvider(mapper); - DefaultClientConfig conf = new DefaultClientConfig(); - conf.getSingletons().add(jsonProvider); - Client client = Client.create(conf); - if (debugging) - client.addFilter(new LoggingFilter()); - hostMap.put(basePath, client); + private Client buildHttpClient(boolean debugging) { + // Add the JSON serialization support to Jersey + JacksonJsonProvider jsonProvider = new JacksonJsonProvider(mapper); + DefaultClientConfig conf = new DefaultClientConfig(); + conf.getSingletons().add(jsonProvider); + Client client = Client.create(conf); + if (debugging) { + client.addFilter(new LoggingFilter()); } - return hostMap.get(basePath); + return client; } } 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 3f2bfcebd5b..2d9fa23cf04 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 @@ -1,12 +1,22 @@ package {{invokerPackage}}; +import java.util.LinkedHashMap; +import java.util.Map; + +import org.apache.oltu.oauth2.client.request.OAuthClientRequest.AuthenticationRequestBuilder; +import org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuilder; + import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; + import feign.Feign; +import feign.RequestInterceptor; import feign.jackson.JacksonDecoder; import feign.jackson.JacksonEncoder; import feign.slf4j.Slf4jLogger; +import {{invokerPackage}}.auth.*; +import {{invokerPackage}}.auth.OAuth.AccessTokenListener; {{>generatedAnnotation}} public class ApiClient { @@ -14,11 +24,80 @@ public class ApiClient { private ObjectMapper objectMapper; private String basePath = "{{basePath}}"; + private Map apiAuthorizations; + private Feign.Builder feignBuilder; public ApiClient() { objectMapper = createObjectMapper(); + apiAuthorizations = new LinkedHashMap(); + feignBuilder = Feign.builder() + .encoder(new FormAwareEncoder(new JacksonEncoder(objectMapper))) + .decoder(new JacksonDecoder(objectMapper)) + .logger(new Slf4jLogger()); } + public ApiClient(String[] authNames) { + this(); + for(String authName : authNames) { {{#hasAuthMethods}} + RequestInterceptor auth; + {{#authMethods}}if (authName == "{{name}}") { {{#isBasic}} + auth = new HttpBasicAuth();{{/isBasic}}{{#isApiKey}} + auth = new ApiKeyAuth({{#isKeyInHeader}}"header"{{/isKeyInHeader}}{{^isKeyInHeader}}"query"{{/isKeyInHeader}}, "{{keyParamName}}");{{/isApiKey}}{{#isOAuth}} + auth = new OAuth(OAuthFlow.{{flow}}, "{{authorizationUrl}}", "{{tokenUrl}}", "{{#scopes}}{{scope}}{{#hasMore}}, {{/hasMore}}{{/scopes}}");{{/isOAuth}} + } else {{/authMethods}}{ + throw new RuntimeException("auth name \"" + authName + "\" not found in available auth names"); + } + addAuthorization(authName, auth);{{/hasAuthMethods}}{{^hasAuthMethods}} + throw new RuntimeException("auth name \"" + authName + "\" not found in available auth names");{{/hasAuthMethods}} + } + } + + /** + * Basic constructor for single auth name + * @param authName + */ + public ApiClient(String authName) { + this(new String[]{authName}); + } + + /** + * Helper constructor for single api key + * @param authName + * @param apiKey + */ + public ApiClient(String authName, String apiKey) { + this(authName); + this.setApiKey(apiKey); + } + + /** + * Helper constructor for single basic auth or password oauth2 + * @param authName + * @param username + * @param password + */ + public ApiClient(String authName, String username, String password) { + this(authName); + this.setCredentials(username, password); + } + + /** + * Helper constructor for single password oauth2 + * @param authName + * @param clientId + * @param secret + * @param username + * @param password + */ + public ApiClient(String authName, String clientId, String secret, String username, String password) { + this(authName); + this.getTokenEndPoint() + .setClientId(clientId) + .setClientSecret(secret) + .setUsername(username) + .setPassword(password); + } + public String getBasePath() { return basePath; } @@ -28,6 +107,23 @@ public class ApiClient { return this; } + public Map getApiAuthorizations() { + return apiAuthorizations; + } + + public void setApiAuthorizations(Map apiAuthorizations) { + this.apiAuthorizations = apiAuthorizations; + } + + public Feign.Builder getFeignBuilder() { + return feignBuilder; + } + + public ApiClient setFeignBuilder(Feign.Builder feignBuilder) { + this.feignBuilder = feignBuilder; + return this; + } + private ObjectMapper createObjectMapper() { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING); @@ -45,13 +141,7 @@ public class ApiClient { * XYZResponse response = api.someMethod(...); */ public T buildClient(Class clientClass) { - return Feign.builder() - .encoder(new FormAwareEncoder(new JacksonEncoder(objectMapper))) - .decoder(new JacksonDecoder(objectMapper)) -// enable for basic auth: -// .requestInterceptor(new feign.auth.BasicAuthRequestInterceptor(username, password)) - .logger(new Slf4jLogger()) - .target(clientClass, basePath); + return feignBuilder.target(clientClass, basePath); } /** @@ -83,4 +173,137 @@ public class ApiClient { if (StringUtil.containsIgnoreCase(contentTypes, "application/json")) return "application/json"; return contentTypes[0]; } + + /** + * Helper method to configure the first api key found + * @param apiKey + */ + public void setApiKey(String apiKey) { + for(RequestInterceptor apiAuthorization : apiAuthorizations.values()) { + if (apiAuthorization instanceof ApiKeyAuth) { + ApiKeyAuth keyAuth = (ApiKeyAuth) apiAuthorization; + keyAuth.setApiKey(apiKey); + return ; + } + } + throw new RuntimeException("No API key authentication configured!"); + } + + /** + * Helper method to configure the username/password for basic auth or password OAuth + * @param username + * @param password + */ + public void setCredentials(String username, String password) { + for(RequestInterceptor apiAuthorization : apiAuthorizations.values()) { + if (apiAuthorization instanceof HttpBasicAuth) { + HttpBasicAuth basicAuth = (HttpBasicAuth) apiAuthorization; + basicAuth.setCredentials(username, password); + return; + } + if (apiAuthorization instanceof OAuth) { + OAuth oauth = (OAuth) apiAuthorization; + oauth.getTokenRequestBuilder().setUsername(username).setPassword(password); + return; + } + } + throw new RuntimeException("No Basic authentication or OAuth configured!"); + } + + /** + * Helper method to configure the token endpoint of the first oauth found in the apiAuthorizations (there should be only one) + * @return + */ + public TokenRequestBuilder getTokenEndPoint() { + for(RequestInterceptor apiAuthorization : apiAuthorizations.values()) { + if (apiAuthorization instanceof OAuth) { + OAuth oauth = (OAuth) apiAuthorization; + return oauth.getTokenRequestBuilder(); + } + } + return null; + } + + /** + * Helper method to configure authorization endpoint of the first oauth found in the apiAuthorizations (there should be only one) + * @return + */ + public AuthenticationRequestBuilder getAuthorizationEndPoint() { + for(RequestInterceptor apiAuthorization : apiAuthorizations.values()) { + if (apiAuthorization instanceof OAuth) { + OAuth oauth = (OAuth) apiAuthorization; + return oauth.getAuthenticationRequestBuilder(); + } + } + return null; + } + + /** + * Helper method to pre-set the oauth access token of the first oauth found in the apiAuthorizations (there should be only one) + * @param accessToken + * @param expiresIn : validity period in seconds + */ + public void setAccessToken(String accessToken, Long expiresIn) { + for(RequestInterceptor apiAuthorization : apiAuthorizations.values()) { + if (apiAuthorization instanceof OAuth) { + OAuth oauth = (OAuth) apiAuthorization; + oauth.setAccessToken(accessToken, expiresIn); + return; + } + } + } + + /** + * Helper method to configure the oauth accessCode/implicit flow parameters + * @param clientId + * @param clientSecret + * @param redirectURI + */ + public void configureAuthorizationFlow(String clientId, String clientSecret, String redirectURI) { + for(RequestInterceptor apiAuthorization : apiAuthorizations.values()) { + if (apiAuthorization instanceof OAuth) { + OAuth oauth = (OAuth) apiAuthorization; + oauth.getTokenRequestBuilder() + .setClientId(clientId) + .setClientSecret(clientSecret) + .setRedirectURI(redirectURI); + oauth.getAuthenticationRequestBuilder() + .setClientId(clientId) + .setRedirectURI(redirectURI); + return; + } + } + } + + /** + * Configures a listener which is notified when a new access token is received. + * @param accessTokenListener + */ + public void registerAccessTokenListener(AccessTokenListener accessTokenListener) { + for(RequestInterceptor apiAuthorization : apiAuthorizations.values()) { + if (apiAuthorization instanceof OAuth) { + OAuth oauth = (OAuth) apiAuthorization; + oauth.registerAccessTokenListener(accessTokenListener); + return; + } + } + } + + public RequestInterceptor getAuthorization(String authName) { + return apiAuthorizations.get(authName); + } + + /** + * Adds an authorization to be used by the client + * @param authName + * @param authorization + */ + public void addAuthorization(String authName, RequestInterceptor authorization) { + if (apiAuthorizations.containsKey(authName)) { + throw new RuntimeException("auth name \"" + authName + "\" already in api authorizations"); + } + apiAuthorizations.put(authName, authorization); + feignBuilder.requestInterceptor(authorization); + } + } diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/feign/api.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/api.mustache index 729320bd2e5..4dc48da3111 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/feign/api.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/api.mustache @@ -19,7 +19,7 @@ public interface {{classname}} extends ApiClient.Api { {{#allParams}} * @param {{paramName}} {{description}} {{/allParams}} * @return {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} */ - @RequestLine("{{httpMethod}} {{{path}}}{{#hasQueryParams}}?{{/hasQueryParams}}{{#queryParams}}{{paramName}}={{=<% %>=}}{<%paramName%>}<%={{ }}=%>{{#hasMore}}&{{/hasMore}}{{/queryParams}}") + @RequestLine("{{httpMethod}} {{{path}}}{{#hasQueryParams}}?{{/hasQueryParams}}{{#queryParams}}{{baseName}}={{=<% %>=}}{<%paramName%>}<%={{ }}=%>{{#hasMore}}&{{/hasMore}}{{/queryParams}}") @Headers({ "Content-type: {{vendorExtensions.x-contentType}}", "Accepts: {{vendorExtensions.x-accepts}}",{{#headerParams}} diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/feign/auth/ApiKeyAuth.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/auth/ApiKeyAuth.mustache new file mode 100644 index 00000000000..371b24dbe55 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/auth/ApiKeyAuth.mustache @@ -0,0 +1,41 @@ +package {{invokerPackage}}.auth; + +import feign.RequestInterceptor; +import feign.RequestTemplate; + +public class ApiKeyAuth implements RequestInterceptor { + private final String location; + private final String paramName; + + private String apiKey; + + public ApiKeyAuth(String location, String paramName) { + this.location = location; + this.paramName = paramName; + } + + public String getLocation() { + return location; + } + + public String getParamName() { + return paramName; + } + + public String getApiKey() { + return apiKey; + } + + public void setApiKey(String apiKey) { + this.apiKey = apiKey; + } + + @Override + public void apply(RequestTemplate template) { + if (location == "query") { + template.query(paramName, apiKey); + } else if (location == "header") { + template.header(paramName, apiKey); + } + } +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/feign/auth/HttpBasicAuth.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/auth/HttpBasicAuth.mustache new file mode 100644 index 00000000000..2b1acb8ff74 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/auth/HttpBasicAuth.mustache @@ -0,0 +1,41 @@ +package {{invokerPackage}}.auth; + +import feign.RequestInterceptor; +import feign.RequestTemplate; +import feign.auth.BasicAuthRequestInterceptor; + +/** + * An interceptor that adds the request header needed to use HTTP basic authentication. + */ +public class HttpBasicAuth implements RequestInterceptor { + + 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; + } + + public void setCredentials(String username, String password) { + this.username = username; + this.password = password; + } + + @Override + public void apply(RequestTemplate template) { + RequestInterceptor requestInterceptor = new BasicAuthRequestInterceptor(username, password); + requestInterceptor.apply(template); + } +} diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/feign/auth/OAuth.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/auth/OAuth.mustache new file mode 100644 index 00000000000..74ff86ebd1b --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/auth/OAuth.mustache @@ -0,0 +1,203 @@ +package {{invokerPackage}}.auth; + +import java.io.IOException; +import java.util.Collection; +import java.util.Map; +import java.util.Map.Entry; + +import org.apache.oltu.oauth2.client.HttpClient; +import org.apache.oltu.oauth2.client.OAuthClient; +import org.apache.oltu.oauth2.client.request.OAuthClientRequest; +import org.apache.oltu.oauth2.client.request.OAuthClientRequest.AuthenticationRequestBuilder; +import org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuilder; +import org.apache.oltu.oauth2.client.response.OAuthClientResponse; +import org.apache.oltu.oauth2.client.response.OAuthClientResponseFactory; +import org.apache.oltu.oauth2.client.response.OAuthJSONAccessTokenResponse; +import org.apache.oltu.oauth2.common.exception.OAuthProblemException; +import org.apache.oltu.oauth2.common.exception.OAuthSystemException; +import org.apache.oltu.oauth2.common.message.types.GrantType; +import org.apache.oltu.oauth2.common.token.BasicOAuthToken; + +import feign.Client; +import feign.Request.Options; +import feign.RequestInterceptor; +import feign.RequestTemplate; +import feign.Response; +import feign.Util; +import {{invokerPackage}}.StringUtil; + + +public class OAuth implements RequestInterceptor { + + public interface AccessTokenListener { + public void notify(BasicOAuthToken token); + } + + private volatile String accessToken; + private Long expirationTimeMillis; + private OAuthClient oauthClient; + private TokenRequestBuilder tokenRequestBuilder; + private AuthenticationRequestBuilder authenticationRequestBuilder; + private AccessTokenListener accessTokenListener; + + public OAuth(Client client, TokenRequestBuilder requestBuilder) { + setOauthClient(client); + this.tokenRequestBuilder = requestBuilder; + } + + public OAuth(Client client, OAuthFlow flow, String authorizationUrl, String tokenUrl, String scopes) { + this(client, OAuthClientRequest.tokenLocation(tokenUrl).setScope(scopes)); + setFlow(flow); + authenticationRequestBuilder = OAuthClientRequest.authorizationLocation(authorizationUrl); + } + + public OAuth(OAuthFlow flow, String authorizationUrl, String tokenUrl, String scopes) { + this(new Client.Default(null, null), flow, authorizationUrl, tokenUrl, scopes); + } + + public void setFlow(OAuthFlow flow) { + switch(flow) { + case accessCode: + case implicit: + tokenRequestBuilder.setGrantType(GrantType.AUTHORIZATION_CODE); + break; + case password: + tokenRequestBuilder.setGrantType(GrantType.PASSWORD); + break; + case application: + tokenRequestBuilder.setGrantType(GrantType.CLIENT_CREDENTIALS); + break; + default: + break; + } + } + + @Override + public void apply(RequestTemplate template) { + // If the request already have an authorization (eg. Basic auth), do nothing + if (template.headers().containsKey("Authorization")) { + return; + } + // If first time, get the token + if (expirationTimeMillis == null || System.currentTimeMillis() >= expirationTimeMillis) { + try { + updateAccessToken(); + } catch (OAuthSystemException e) { + e.printStackTrace(); + return; + } catch (OAuthProblemException e) { + e.printStackTrace(); + return; + } + } + if (getAccessToken() != null) { + template.header("Authorization", "Bearer " + getAccessToken()); + } + } + + public synchronized void updateAccessToken() throws OAuthSystemException, OAuthProblemException { + if (getAccessToken() == null) { + OAuthJSONAccessTokenResponse accessTokenResponse = oauthClient.accessToken(tokenRequestBuilder.buildBodyMessage()); + if (accessTokenResponse != null && accessTokenResponse.getAccessToken() != null) { + setAccessToken(accessTokenResponse.getAccessToken(), accessTokenResponse.getExpiresIn()); + if (accessTokenListener != null) { + accessTokenListener.notify((BasicOAuthToken) accessTokenResponse.getOAuthToken()); + } + } + } + } + + public void registerAccessTokenListener(AccessTokenListener accessTokenListener) { + this.accessTokenListener = accessTokenListener; + } + + public synchronized String getAccessToken() { + return accessToken; + } + + public synchronized void setAccessToken(String accessToken, Long expiresIn) { + this.accessToken = accessToken; + this.expirationTimeMillis = System.currentTimeMillis() + expiresIn * 1000; + } + + public TokenRequestBuilder getTokenRequestBuilder() { + return tokenRequestBuilder; + } + + public void setTokenRequestBuilder(TokenRequestBuilder tokenRequestBuilder) { + this.tokenRequestBuilder = tokenRequestBuilder; + } + + public AuthenticationRequestBuilder getAuthenticationRequestBuilder() { + return authenticationRequestBuilder; + } + + public void setAuthenticationRequestBuilder(AuthenticationRequestBuilder authenticationRequestBuilder) { + this.authenticationRequestBuilder = authenticationRequestBuilder; + } + + public OAuthClient getOauthClient() { + return oauthClient; + } + + public void setOauthClient(OAuthClient oauthClient) { + this.oauthClient = oauthClient; + } + + public void setOauthClient(Client client) { + this.oauthClient = new OAuthClient( new OAuthFeignClient(client)); + } + + public class OAuthFeignClient implements HttpClient { + + private Client client; + + public OAuthFeignClient() { + this.client = new Client.Default(null, null); + } + + public OAuthFeignClient(Client client) { + this.client = client; + } + + public T execute(OAuthClientRequest request, Map headers, + String requestMethod, Class responseClass) + throws OAuthSystemException, OAuthProblemException { + + RequestTemplate req = new RequestTemplate() + .append(request.getLocationUri()) + .method(requestMethod) + .body(request.getBody()); + + for (Entry entry : headers.entrySet()) { + req.header(entry.getKey(), entry.getValue()); + } + Response feignResponse; + String body = ""; + try { + feignResponse = client.execute(req.request(), new Options()); + body = Util.toString(feignResponse.body().asReader()); + } catch (IOException e) { + throw new OAuthSystemException(e); + } + + String contentType = null; + Collection contentTypeHeader = feignResponse.headers().get("Content-Type"); + if(contentTypeHeader != null) { + contentType = StringUtil.join(contentTypeHeader.toArray(new String[0]), ";"); + } + + return OAuthClientResponseFactory.createCustomResponse( + body, + contentType, + feignResponse.status(), + responseClass + ); + } + + public void shutdown() { + // Nothing to do here + } + + } +} 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 e8069b82931..d0121e752dc 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 @@ -164,6 +164,12 @@ 2.2 + + org.apache.oltu.oauth2 + org.apache.oltu.oauth2.client + ${oltu-version} + + junit @@ -179,5 +185,6 @@ 2.5 4.12 1.0.0 + 1.0.0 diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/ApiClient.mustache index f482b8c34d4..83e92921a82 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/ApiClient.mustache @@ -12,7 +12,9 @@ import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import org.glassfish.jersey.client.ClientConfig; +import org.glassfish.jersey.client.ClientProperties; import org.glassfish.jersey.filter.LoggingFilter; +import org.glassfish.jersey.jackson.JacksonFeature; import org.glassfish.jersey.media.multipart.FormDataBodyPart; import org.glassfish.jersey.media.multipart.FormDataContentDisposition; import org.glassfish.jersey.media.multipart.MultiPart; @@ -43,12 +45,13 @@ import {{invokerPackage}}.auth.OAuth; {{>generatedAnnotation}} public class ApiClient { - private Client client; - private Map hostMap = new HashMap(); private Map defaultHeaderMap = new HashMap(); - private boolean debugging = false; private String basePath = "{{basePath}}"; - private JSON json = new JSON(); + private boolean debugging = false; + private int connectionTimeout = 0; + + private Client httpClient; + private JSON json; private Map authentications; @@ -58,6 +61,9 @@ public class ApiClient { private DateFormat dateFormat; public ApiClient() { + json = new JSON(); + httpClient = buildHttpClient(debugging); + // Use RFC3339 format for date and datetime. // See http://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14 this.dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); @@ -70,8 +76,6 @@ public class ApiClient { // Set default User-Agent. setUserAgent("Java-Swagger"); - buildClient(); - // Setup authentications (key: authentication name, value: authentication). authentications = new HashMap();{{#authMethods}}{{#isBasic}} authentications.put("{{name}}", new HttpBasicAuth());{{/isBasic}}{{#isApiKey}} @@ -226,10 +230,29 @@ public class ApiClient { */ public ApiClient setDebugging(boolean debugging) { this.debugging = debugging; - buildClient(); + // Rebuild HTTP Client according to the new "debugging" value. + this.httpClient = buildHttpClient(debugging); return this; } + /** + * Connect timeout (in milliseconds). + */ + public int getConnectTimeout() { + return connectionTimeout; + } + + /** + * Set the connect timeout (in milliseconds). + * A value of 0 means no timeout, otherwise values must be between 1 and + * {@link Integer#MAX_VALUE}. + */ + public ApiClient setConnectTimeout(int connectionTimeout) { + this.connectionTimeout = connectionTimeout; + httpClient.property(ClientProperties.CONNECT_TIMEOUT, connectionTimeout); + return this; + } + /** * Get the date format used to parse/format date parameters. */ @@ -472,7 +495,7 @@ public class ApiClient { public T invokeAPI(String path, String method, List queryParams, Object body, Map headerParams, Map formParams, String accept, String contentType, String[] authNames, GenericType returnType) throws ApiException { updateParamsForAuth(authNames, queryParams, headerParams); - WebTarget target = client.target(this.basePath).path(path); + WebTarget target = httpClient.target(this.basePath).path(path); if (queryParams != null) { for (Pair queryParam : queryParams) { @@ -545,15 +568,18 @@ public class ApiClient { } } - private void buildClient() { + /** + * Build the Client used to make HTTP requests. + */ + private Client buildHttpClient(boolean debugging) { final ClientConfig clientConfig = new ClientConfig(); clientConfig.register(MultiPartFeature.class); clientConfig.register(json); - clientConfig.register(org.glassfish.jersey.jackson.JacksonFeature.class); + clientConfig.register(JacksonFeature.class); if (debugging) { clientConfig.register(LoggingFilter.class); } - this.client = ClientBuilder.newClient(clientConfig); + return ClientBuilder.newClient(clientConfig); } private Map> buildResponseHeaders(Response response) { 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 8c0880bf217..c80f45b91a5 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 @@ -11,6 +11,8 @@ import com.squareup.okhttp.MultipartBuilder; import com.squareup.okhttp.MediaType; import com.squareup.okhttp.Headers; import com.squareup.okhttp.internal.http.HttpMethod; +import com.squareup.okhttp.logging.HttpLoggingInterceptor; +import com.squareup.okhttp.logging.HttpLoggingInterceptor.Level; import java.lang.reflect.Type; @@ -116,6 +118,8 @@ public class ApiClient { private OkHttpClient httpClient; private JSON json; + private HttpLoggingInterceptor loggingInterceptor; + public ApiClient() { httpClient = new OkHttpClient(); @@ -452,6 +456,16 @@ public class ApiClient { * @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; } 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 0d7e9015101..982334a3914 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 @@ -117,6 +117,11 @@ okhttp ${okhttp-version} + + com.squareup.okhttp + logging-interceptor + ${okhttp-version} + com.google.code.gson gson @@ -133,7 +138,7 @@ 1.5.0 - 2.4.0 + 2.7.2 2.3.1 1.0.0 4.8.1 diff --git a/modules/swagger-codegen/src/main/resources/Java/pojo.mustache b/modules/swagger-codegen/src/main/resources/Java/pojo.mustache index eea33d346d4..0bc15c0ecb0 100644 --- a/modules/swagger-codegen/src/main/resources/Java/pojo.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/pojo.mustache @@ -27,22 +27,23 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#seriali {{/vars}} @Override - public boolean equals(Object o) { + public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } - {{classname}} {{classVarName}} = ({{classname}}) o;{{#hasVars}} - return {{#vars}}Objects.equals({{name}}, {{classVarName}}.{{name}}){{#hasMore}} && - {{/hasMore}}{{^hasMore}};{{/hasMore}}{{/vars}}{{/hasVars}}{{^hasVars}} - return true;{{/hasVars}} + {{classname}} {{classVarName}} = ({{classname}}) o; + + return true {{#hasVars}}&& {{#vars}}Objects.equals({{name}}, {{classVarName}}.{{name}}){{#hasMore}} && + {{/hasMore}}{{/vars}}{{/hasVars}} + {{#parent}}&& super.equals(o){{/parent}}; } @Override public int hashCode() { - return Objects.hash({{#vars}}{{name}}{{#hasMore}}, {{/hasMore}}{{/vars}}); + return Objects.hash({{#vars}}{{name}}{{#hasMore}}, {{/hasMore}}{{/vars}}{{#parent}}{{#hasVars}},{{/hasVars}} super.hashCode(){{/parent}}); } @Override @@ -59,7 +60,7 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#seriali * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ - private String toIndentedString(Object o) { + private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } diff --git a/modules/swagger-codegen/src/main/resources/android/libraries/volley/api.mustache b/modules/swagger-codegen/src/main/resources/android/libraries/volley/api.mustache index ccd12fd67c5..1d70000c1dc 100644 --- a/modules/swagger-codegen/src/main/resources/android/libraries/volley/api.mustache +++ b/modules/swagger-codegen/src/main/resources/android/libraries/volley/api.mustache @@ -1,6 +1,5 @@ package {{package}}; -import {{invokerPackage}}.Responses; import {{invokerPackage}}.ApiInvoker; import {{invokerPackage}}.ApiException; import {{invokerPackage}}.Pair; @@ -50,7 +49,7 @@ public class {{classname}} { {{#allParams}} * @param {{paramName}} {{description}} {{/allParams}} * @return {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} */ - public void {{nickname}} ({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{^hasMore}}, {{/hasMore}}{{/allParams}}final {{#returnBaseType}}Responses.{{returnBaseType}}{{#isListContainer}}List{{/isListContainer}}Response{{/returnBaseType}}{{^returnBaseType}}Responses.StringResponse{{/returnBaseType}} responseListener, final Response.ErrorListener errorListener) { + public void {{nickname}} ({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{^hasMore}}, {{/hasMore}}{{/allParams}}final Response.Listener<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}String{{/returnType}}> responseListener, final Response.ErrorListener errorListener) { Object postBody = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}}; {{#allParams}}{{#required}} diff --git a/modules/swagger-codegen/src/main/resources/android/libraries/volley/build.mustache b/modules/swagger-codegen/src/main/resources/android/libraries/volley/build.mustache index ec599632fd8..87d7f4a882c 100644 --- a/modules/swagger-codegen/src/main/resources/android/libraries/volley/build.mustache +++ b/modules/swagger-codegen/src/main/resources/android/libraries/volley/build.mustache @@ -28,11 +28,11 @@ apply plugin: 'com.github.dcendents.android-maven' {{/useAndroidMavenGradlePlugin}} android { - compileSdkVersion 22 - buildToolsVersion '22.0.0' + compileSdkVersion 23 + buildToolsVersion '23.0.2' defaultConfig { minSdkVersion 14 - targetSdkVersion 22 + targetSdkVersion 23 } compileOptions { sourceCompatibility JavaVersion.VERSION_1_7 diff --git a/modules/swagger-codegen/src/main/resources/android/libraries/volley/responses.mustache b/modules/swagger-codegen/src/main/resources/android/libraries/volley/responses.mustache deleted file mode 100644 index 7cb955f7239..00000000000 --- a/modules/swagger-codegen/src/main/resources/android/libraries/volley/responses.mustache +++ /dev/null @@ -1,24 +0,0 @@ -package {{invokerPackage}}; - -import java.util.List; -import {{modelPackage}}.*; - -public class Responses { - {{#models}} - {{#model}} - public static interface {{classname}}Response { - public void onResponse({{classname}} {{classVarName}}); - } - public static interface {{classname}}ListResponse { - public void onResponse(List<{{classname}}> {{classVarName}}List); - } - {{/model}} - {{/models}} - public static interface StringResponse { - public void onResponse(String response); - } - - public static interface StringListResponse { - public void onResponse(List stringList); - } -} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/csharp/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/csharp/ApiClient.mustache index 142b2e6bbb9..8a22c2f23f9 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/ApiClient.mustache @@ -77,9 +77,10 @@ namespace {{packageName}}.Client // Creates and sets up a RestRequest prior to a call. private RestRequest PrepareRequest( - String path, RestSharp.Method method, Dictionary queryParams, String postBody, + String path, RestSharp.Method method, Dictionary queryParams, Object postBody, Dictionary headerParams, Dictionary formParams, - Dictionary fileParams, Dictionary pathParams) + Dictionary fileParams, Dictionary pathParams, + String contentType) { var request = new RestRequest(path, method); @@ -103,8 +104,17 @@ namespace {{packageName}}.Client foreach(var param in fileParams) request.AddFile(param.Value.Name, param.Value.Writer, param.Value.FileName, param.Value.ContentType); - if (postBody != null) // http body (model) parameter - request.AddParameter("application/json", postBody, ParameterType.RequestBody); + if (postBody != null) // http body (model or byte[]) parameter + { + if (postBody.GetType() == typeof(String)) + { + request.AddParameter("application/json", postBody, ParameterType.RequestBody); + } + else if (postBody.GetType() == typeof(byte[])) + { + request.AddParameter(contentType, postBody, ParameterType.RequestBody); + } + } return request; } @@ -120,14 +130,18 @@ namespace {{packageName}}.Client /// Form parameters. /// File parameters. /// Path parameters. + /// Content Type of the request /// Object public Object CallApi( - String path, RestSharp.Method method, Dictionary queryParams, String postBody, + String path, RestSharp.Method method, Dictionary queryParams, Object postBody, Dictionary headerParams, Dictionary formParams, - Dictionary fileParams, Dictionary pathParams) + Dictionary fileParams, Dictionary pathParams, + String contentType) { var request = PrepareRequest( - path, method, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + path, method, queryParams, postBody, headerParams, formParams, fileParams, + pathParams, contentType); + var response = RestClient.Execute(request); return (Object) response; } @@ -143,14 +157,17 @@ namespace {{packageName}}.Client /// Form parameters. /// File parameters. /// Path parameters. + /// Content type. /// The Task instance. public async System.Threading.Tasks.Task CallApiAsync( - String path, RestSharp.Method method, Dictionary queryParams, String postBody, + String path, RestSharp.Method method, Dictionary queryParams, Object postBody, Dictionary headerParams, Dictionary formParams, - Dictionary fileParams, Dictionary pathParams) + Dictionary fileParams, Dictionary pathParams, + String contentType) { var request = PrepareRequest( - path, method, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + path, method, queryParams, postBody, headerParams, formParams, fileParams, + pathParams, contentType); var response = await RestClient.ExecuteTaskAsync(request); return (Object)response; } @@ -194,6 +211,12 @@ namespace {{packageName}}.Client // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 // For example: 2009-06-15T13:45:30.0000000 return ((DateTime)obj).ToString (Configuration.DateTimeFormat); + else if (obj is DateTimeOffset) + // Return a formatted date string - Can be customized with Configuration.DateTimeFormat + // Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o") + // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 + // For example: 2009-06-15T13:45:30.0000000 + return ((DateTimeOffset)obj).ToString (Configuration.DateTimeFormat); else if (obj is IList) { var flattenedString = new StringBuilder(); @@ -224,6 +247,10 @@ namespace {{packageName}}.Client { return content; } + else if (type == typeof(byte[])) // return byte array + { + return data; + } if (type == typeof(Stream)) { @@ -270,11 +297,11 @@ namespace {{packageName}}.Client } /// - /// Serialize an object into JSON string. + /// Serialize an input (model) into JSON string /// /// Object. /// JSON string. - public string Serialize(object obj) + public String Serialize(object obj) { try { @@ -286,6 +313,24 @@ namespace {{packageName}}.Client } } + /// + /// Select the Content-Type header's value from the given content-type array: + /// if JSON exists in the given array, use it; + /// otherwise use the first one defined in 'consumes' + /// + /// The Content-Type array to select from. + /// The Content-Type header to use. + public String SelectHeaderContentType(String[] contentTypes) + { + if (contentTypes.Length == 0) + return null; + + if (contentTypes.Contains("application/json", StringComparer.OrdinalIgnoreCase)) + return "application/json"; + + return contentTypes[0]; // use the first content type specified in 'consumes' + } + /// /// Select the Accept header's value from the given accepts array: /// if JSON exists in the given array, use it; diff --git a/modules/swagger-codegen/src/main/resources/csharp/ApiResponse.mustache b/modules/swagger-codegen/src/main/resources/csharp/ApiResponse.mustache index 32816110a1b..c4317c35b65 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/ApiResponse.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/ApiResponse.mustache @@ -27,10 +27,10 @@ namespace {{packageName}}.Client public T Data { get; private set; } /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// /// HTTP status code. - /// Error message. + /// HTTP headers. /// Data (parsed HTTP body) public ApiResponse(int statusCode, IDictionary headers, T data) { diff --git a/modules/swagger-codegen/src/main/resources/csharp/Configuration.mustache b/modules/swagger-codegen/src/main/resources/csharp/Configuration.mustache index 7062a73c1e1..d3ef0c6f731 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/Configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/Configuration.mustache @@ -24,6 +24,7 @@ namespace {{packageName}}.Client /// Dictionary of API key prefix /// Temp folder path /// DateTime format string + /// HTTP connection timeout (in milliseconds) public Configuration(ApiClient apiClient = null, Dictionary defaultHeader = null, string username = null, diff --git a/modules/swagger-codegen/src/main/resources/csharp/api.mustache b/modules/swagger-codegen/src/main/resources/csharp/api.mustache index 51f8b3f9394..28919d6be49 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/api.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/api.mustache @@ -154,7 +154,8 @@ namespace {{packageName}}.Api { {{#allParams}}{{#required}} // verify the required parameter '{{paramName}}' is set - if ({{paramName}} == null) throw new ApiException(400, "Missing required parameter '{{paramName}}' when calling {{operationId}}"); + if ({{paramName}} == null) + throw new ApiException(400, "Missing required parameter '{{paramName}}' when calling {{classname}}->{{operationId}}"); {{/required}}{{/allParams}} var path_ = "{{path}}"; @@ -164,15 +165,21 @@ namespace {{packageName}}.Api var headerParams = new Dictionary(Configuration.DefaultHeader); var formParams = new Dictionary(); var fileParams = new Dictionary(); - String postBody = null; + Object postBody = null; + + // to determine the Content-Type header + String[] httpContentTypes = new String[] { + {{#consumes}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} + }; + String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes); // to determine the Accept header - String[] http_header_accepts = new String[] { + String[] httpHeaderAccepts = new String[] { {{#produces}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }; - String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); - if (http_header_accept != null) - headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); + String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAccept != null) + headerParams.Add("Accept", httpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json @@ -185,11 +192,16 @@ namespace {{packageName}}.Api {{/headerParams}} {{#formParams}}if ({{paramName}} != null) {{#isFile}}fileParams.Add("{{baseName}}", Configuration.ApiClient.ParameterToFile("{{baseName}}", {{paramName}}));{{/isFile}}{{^isFile}}formParams.Add("{{baseName}}", Configuration.ApiClient.ParameterToString({{paramName}})); // form parameter{{/isFile}} {{/formParams}} - {{#bodyParam}}postBody = Configuration.ApiClient.Serialize({{paramName}}); // http body (model) parameter - {{/bodyParam}} + {{#bodyParam}}if ({{paramName}}.GetType() != typeof(byte[])) + { + postBody = Configuration.ApiClient.Serialize({{paramName}}); // http body (model) parameter + } + else + { + postBody = {{paramName}}; // byte array + }{{/bodyParam}} - {{#authMethods}} - // authentication ({{name}}) required + {{#authMethods}}// authentication ({{name}}) required {{#isApiKey}}{{#isKeyInHeader}} var apiKeyValue = Configuration.GetApiKeyWithPrefix("{{keyParamName}}"); if (!String.IsNullOrEmpty(apiKeyValue)) @@ -214,7 +226,9 @@ namespace {{packageName}}.Api {{/authMethods}} // make the HTTP request - IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, Method.{{httpMethod}}, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, + Method.{{httpMethod}}, queryParams, postBody, headerParams, formParams, fileParams, + pathParams, httpContentType); int statusCode = (int) response.StatusCode; @@ -261,15 +275,21 @@ namespace {{packageName}}.Api var headerParams = new Dictionary(); var formParams = new Dictionary(); var fileParams = new Dictionary(); - String postBody = null; + Object postBody = null; + + // to determine the Content-Type header + String[] httpContentTypes = new String[] { + {{#consumes}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} + }; + String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes); // to determine the Accept header - String[] http_header_accepts = new String[] { + String[] httpHeaderAccepts = new String[] { {{#produces}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }; - String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); - if (http_header_accept != null) - headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); + String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAccept != null) + headerParams.Add("Accept", httpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json @@ -311,7 +331,9 @@ namespace {{packageName}}.Api {{/authMethods}} // make the HTTP request - IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, Method.{{httpMethod}}, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, + Method.{{httpMethod}}, queryParams, postBody, headerParams, formParams, fileParams, + pathParams, httpContentType); int statusCode = (int) response.StatusCode; 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 new file mode 100644 index 00000000000..9472dcc8d3d --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/csharp/compile-mono.sh.mustache @@ -0,0 +1,12 @@ +wget -nc https://nuget.org/nuget.exe; +mozroots --import --sync +mono nuget.exe install vendor/packages.config -o vendor; +mkdir -p bin; +mcs -sdk:45 -r:vendor/Newtonsoft.Json.8.0.2/lib/net45/Newtonsoft.Json.dll,\ +vendor/RestSharp.105.2.3/lib/net45/RestSharp.dll,\ +System.Runtime.Serialization.dll \ +-target:library \ +-out:bin/{{packageName}}.dll \ +-recurse:'src/*.cs' \ +-doc:bin/{{packageName}}.xml \ +-platform:anycpu diff --git a/modules/swagger-codegen/src/main/resources/csharp/model.mustache b/modules/swagger-codegen/src/main/resources/csharp/model.mustache index ad942039677..6db39b046a2 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/model.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/model.mustache @@ -74,7 +74,7 @@ namespace {{packageName}}.Model /// /// Returns true if {{classname}} instances are equal /// - /// Instance of {{classname}} to be compared + /// Instance of {{classname}} to be compared /// Boolean public bool Equals({{classname}} other) { diff --git a/modules/swagger-codegen/src/main/resources/csharp/packages.config.mustache b/modules/swagger-codegen/src/main/resources/csharp/packages.config.mustache new file mode 100644 index 00000000000..c87bbb79fa6 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/csharp/packages.config.mustache @@ -0,0 +1,5 @@ + + + + + diff --git a/modules/swagger-codegen/src/main/resources/perl/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/perl/ApiClient.mustache index 4d7d5bb7088..401a33eddad 100644 --- a/modules/swagger-codegen/src/main/resources/perl/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/perl/ApiClient.mustache @@ -1,4 +1,4 @@ -package WWW::{{moduleName}}::ApiClient; +package {{moduleName}}::ApiClient; use strict; use warnings; @@ -18,7 +18,7 @@ use Log::Any qw($log); use Carp; use Module::Runtime qw(use_module); -use WWW::{{moduleName}}::Configuration; +use {{moduleName}}::Configuration; use base 'Class::Singleton'; @@ -34,7 +34,7 @@ sub _new_instance return bless \%args, $class; } -sub _cfg {'WWW::{{moduleName}}::Configuration'} +sub _cfg {'{{moduleName}}::Configuration'} # Set the user agent of the API client # @@ -119,8 +119,8 @@ sub call_api { else { } - $self->{ua}->timeout($self->{http_timeout} || $WWW::{{moduleName}}::Configuration::http_timeout); - $self->{ua}->agent($self->{http_user_agent} || $WWW::{{moduleName}}::Configuration::http_user_agent); + $self->{ua}->timeout($self->{http_timeout} || ${{moduleName}}::Configuration::http_timeout); + $self->{ua}->agent($self->{http_user_agent} || ${{moduleName}}::Configuration::http_user_agent); $log->debugf("REQUEST: %s", $_request->as_string); my $_response = $self->{ua}->request($_request); @@ -243,7 +243,7 @@ sub deserialize } elsif (grep /^$class$/, ('string', 'int', 'float', 'bool', 'object')) { return $data; } else { # model - my $_instance = use_module("WWW::{{moduleName}}::Object::$class")->new; + my $_instance = use_module("{{moduleName}}::Object::$class")->new; if (ref $data eq "HASH") { return $_instance->from_hash($data); } else { # string, need to json decode first @@ -294,11 +294,11 @@ sub get_api_key_with_prefix { my ($self, $key_name) = @_; - my $api_key = $WWW::{{moduleName}}::Configuration::api_key->{$key_name}; + my $api_key = ${{moduleName}}::Configuration::api_key->{$key_name}; return unless $api_key; - my $prefix = $WWW::{{moduleName}}::Configuration::api_key_prefix->{$key_name}; + my $prefix = ${{moduleName}}::Configuration::api_key_prefix->{$key_name}; return $prefix ? "$prefix $api_key" : $api_key; } @@ -329,11 +329,11 @@ sub update_params_for_auth { if ($api_key) { $query_params->{'{{keyParamName}}'} = $api_key; }{{/isKeyInQuery}}{{/isApiKey}}{{#isBasic}} - if ($WWW::{{moduleName}}::Configuration::username || $WWW::{{moduleName}}::Configuration::password) { - $header_params->{'Authorization'} = 'Basic ' . encode_base64($WWW::{{moduleName}}::Configuration::username . ":" . $WWW::{{moduleName}}::Configuration::password); + if (${{moduleName}}::Configuration::username || ${{moduleName}}::Configuration::password) { + $header_params->{'Authorization'} = 'Basic ' . encode_base64(${{moduleName}}::Configuration::username . ":" . ${{moduleName}}::Configuration::password); }{{/isBasic}}{{#isOAuth}} - if ($WWW::{{moduleName}}::Configuration::access_token) { - $header_params->{'Authorization'} = 'Bearer ' . $WWW::{{moduleName}}::Configuration::access_token; + if (${{moduleName}}::Configuration::access_token) { + $header_params->{'Authorization'} = 'Bearer ' . ${{moduleName}}::Configuration::access_token; }{{/isOAuth}} } {{/authMethods}} diff --git a/modules/swagger-codegen/src/main/resources/perl/ApiFactory.mustache b/modules/swagger-codegen/src/main/resources/perl/ApiFactory.mustache index fc119f7a902..ef5f322a014 100644 --- a/modules/swagger-codegen/src/main/resources/perl/ApiFactory.mustache +++ b/modules/swagger-codegen/src/main/resources/perl/ApiFactory.mustache @@ -1,4 +1,4 @@ -package WWW::{{moduleName}}::ApiFactory; +package {{moduleName}}::ApiFactory; use strict; use warnings; @@ -7,26 +7,26 @@ use utf8; use Carp; use Module::Find; -usesub WWW::{{moduleName}}::Object; +usesub {{moduleName}}::Object; -use WWW::{{moduleName}}::ApiClient; +use {{moduleName}}::ApiClient; =head1 Name - WWW::{{moduleName}}::ApiFactory - constructs APIs to retrieve {{moduleName}} objects + {{moduleName}}::ApiFactory - constructs APIs to retrieve {{moduleName}} objects =head1 Synopsis package My::Petstore::App; - use WWW::{{moduleName}}::ApiFactory; + use {{moduleName}}::ApiFactory; - my $api_factory = WWW::{{moduleName}}::ApiFactory->new( ... ); # any args for ApiClient constructor + my $api_factory = {{moduleName}}::ApiFactory->new( ... ); # any args for ApiClient constructor # later... my $pet_api = $api_factory->get_api('Pet'); - # $pet_api isa WWW::{{moduleName}}::PetApi + # $pet_api isa {{moduleName}}::PetApi my $pet = $pet_api->get_pet_by_id(pet_id => $pet_id); @@ -39,9 +39,9 @@ use WWW::{{moduleName}}::ApiClient; =cut # Load all the API classes and construct a lookup table at startup time -my %_apis = map { $_ =~ /^WWW::{{moduleName}}::(.*)$/; $1 => $_ } +my %_apis = map { $_ =~ /^{{moduleName}}::(.*)$/; $1 => $_ } grep {$_ =~ /Api$/} - usesub 'WWW::{{moduleName}}'; + usesub '{{moduleName}}'; =head1 new() @@ -54,7 +54,7 @@ my %_apis = map { $_ =~ /^WWW::{{moduleName}}::(.*)$/; $1 => $_ } sub new { my ($class, %p) = (shift, @_); - $p{api_client} = WWW::{{moduleName}}::ApiClient->instance(%p); + $p{api_client} = {{moduleName}}::ApiClient->instance(%p); return bless \%p, $class; } @@ -64,7 +64,7 @@ sub new { $which is a nickname for the class: - WWW::FooBarClient::BazApi has nickname 'Baz' + FooBarClient::BazApi has nickname 'Baz' =cut diff --git a/modules/swagger-codegen/src/main/resources/perl/AutoDoc.mustache b/modules/swagger-codegen/src/main/resources/perl/AutoDoc.mustache index 76da048b069..3c10c2450fe 100644 --- a/modules/swagger-codegen/src/main/resources/perl/AutoDoc.mustache +++ b/modules/swagger-codegen/src/main/resources/perl/AutoDoc.mustache @@ -1,4 +1,4 @@ -package WWW::{{moduleName}}::Role::AutoDoc; +package {{moduleName}}::Role::AutoDoc; use List::MoreUtils qw(uniq); use Moose::Role; @@ -40,7 +40,7 @@ sub _printisa { foreach my $role (@roles) { $rolepkg = $role->{package} || next; # some are anonymous, or something - next if $rolepkg eq 'WWW::{{moduleName}}::Role::AutoDoc'; + next if $rolepkg eq '{{moduleName}}::Role::AutoDoc'; $role_reqs = join ', ', keys %{$role->{required_methods}}; $role_reqs ||= ''; $~ = $how eq 'pod' ? 'ROLES_POD' : 'ROLES'; @@ -424,4 +424,4 @@ $attrname -1; \ No newline at end of file +1; diff --git a/modules/swagger-codegen/src/main/resources/perl/BaseObject.mustache b/modules/swagger-codegen/src/main/resources/perl/BaseObject.mustache index aed1aec3118..9f262543acd 100644 --- a/modules/swagger-codegen/src/main/resources/perl/BaseObject.mustache +++ b/modules/swagger-codegen/src/main/resources/perl/BaseObject.mustache @@ -68,7 +68,7 @@ sub _deserialize { } elsif ( grep( /^$type$/, ('int', 'double', 'string', 'boolean'))) { return $data; } else { # hash(model) - my $_instance = eval "WWW::{{moduleName}}::Object::$type->new()"; + my $_instance = eval "{{moduleName}}::Object::$type->new()"; return $_instance->from_hash($data); } } diff --git a/modules/swagger-codegen/src/main/resources/perl/Configuration.mustache b/modules/swagger-codegen/src/main/resources/perl/Configuration.mustache index 75a1ba7f61a..e0ed9bf3295 100644 --- a/modules/swagger-codegen/src/main/resources/perl/Configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/perl/Configuration.mustache @@ -1,4 +1,4 @@ -package WWW::{{moduleName}}::Configuration; +package {{moduleName}}::Configuration; use strict; use warnings; diff --git a/modules/swagger-codegen/src/main/resources/perl/README.mustache b/modules/swagger-codegen/src/main/resources/perl/README.mustache index ac94b5b0638..62d57f6b3cf 100644 --- a/modules/swagger-codegen/src/main/resources/perl/README.mustache +++ b/modules/swagger-codegen/src/main/resources/perl/README.mustache @@ -1,6 +1,6 @@ # NAME -WWW::{{moduleName}}::Role - a Moose role for the {{appName}} +{{moduleName}}::Role - a Moose role for the {{appName}} ## {{appName}} version: {{appVersion}} @@ -15,7 +15,7 @@ Automatically generated by the Perl Swagger Codegen project: ## A note on Moose This role is the only component of the library that uses Moose. See -WWW::{{moduleName}}::ApiFactory for non-Moosey usage. +{{moduleName}}::ApiFactory for non-Moosey usage. # SYNOPSIS @@ -29,7 +29,7 @@ role. package MyApp; use Moose; - with 'WWW::{{moduleName}}::Role'; + with '{{moduleName}}::Role'; package main; @@ -88,37 +88,37 @@ you are accessing. Usually `prefix` and `in` will be determined by the code gene the spec and you will not need to set them at run time. If not, `in` will default to 'head' and `prefix` to the empty string. -The tokens will be placed in the `WWW::{{moduleName}}::Configuration` namespace +The tokens will be placed in the `{{moduleName}}::Configuration` namespace as follows, but you don't need to know about this. -- `$WWW::{{moduleName}}::Configuration::username` +- `${{moduleName}}::Configuration::username` String. The username for basic auth. -- `$WWW::{{moduleName}}::Configuration::password` +- `${{moduleName}}::Configuration::password` String. The password for basic auth. -- `$WWW::{{moduleName}}::Configuration::api_key` +- `${{moduleName}}::Configuration::api_key` Hashref. Keyed on the name of each key (there can be multiple tokens). - $WWW::{{moduleName}}::Configuration::api_key = { + ${{moduleName}}::Configuration::api_key = { secretKey => 'aaaabbbbccccdddd', anotherKey => '1111222233334444', }; -- `$WWW::{{moduleName}}::Configuration::api_key_prefix` +- `${{moduleName}}::Configuration::api_key_prefix` Hashref. Keyed on the name of each key (there can be multiple tokens). Note not all api keys require a prefix. - $WWW::{{moduleName}}::Configuration::api_key_prefix = { + ${{moduleName}}::Configuration::api_key_prefix = { secretKey => 'string', anotherKey => 'same or some other string', }; -- `$WWW::{{moduleName}}::Configuration::access_token` +- `${{moduleName}}::Configuration::access_token` String. The OAuth access token. @@ -134,7 +134,7 @@ created yet) the current value of `base_url`. Returns an API factory object. You probably won't need to call this directly. - $self->api_factory('Pet'); # returns a WWW::{{moduleName}}::PetApi instance + $self->api_factory('Pet'); # returns a {{moduleName}}::PetApi instance $self->pet_api; # the same @@ -162,12 +162,12 @@ you could also call them on class names. See the homepage `https://github.com/swagger-api/swagger-codegen` for full details. But briefly, clone the git repository, build the codegen codebase, set up your build -config file, then run the API build script. You will need git, Java 7 and Apache +config file, then run the API build script. You will need git, Java 7 or 8 and Apache maven 3.0.3 or better already installed. The config file should specify the project name for the generated library: - {"moduleName":"MyProjectName"} + {"moduleName":"WWW::MyProjectName"} Your library files will be built under `WWW::MyProjectName`. diff --git a/modules/swagger-codegen/src/main/resources/perl/Role.mustache b/modules/swagger-codegen/src/main/resources/perl/Role.mustache index ac2298a08e9..fb343ccb890 100644 --- a/modules/swagger-codegen/src/main/resources/perl/Role.mustache +++ b/modules/swagger-codegen/src/main/resources/perl/Role.mustache @@ -1,11 +1,11 @@ -package WWW::{{moduleName}}::Role; +package {{moduleName}}::Role; use utf8; use Moose::Role; use namespace::autoclean; use Class::Inspector; use Log::Any qw($log); -use WWW::{{moduleName}}::ApiFactory; +use {{moduleName}}::ApiFactory; has base_url => ( is => 'ro', required => 0, @@ -14,7 +14,7 @@ has base_url => ( is => 'ro', ); has api_factory => ( is => 'ro', - isa => 'WWW::{{moduleName}}::ApiFactory', + isa => '{{moduleName}}::ApiFactory', builder => '_build_af', lazy => 1, documentation => 'Builds an instance of the endpoint API class', @@ -29,7 +29,7 @@ has tokens => ( is => 'ro', has _cfg => ( is => 'ro', isa => 'Str', - default => 'WWW::{{moduleName}}::Configuration', + default => '{{moduleName}}::Configuration', ); has version_info => ( is => 'ro', @@ -88,12 +88,12 @@ sub _build_af { my $self = shift; my %args; $args{base_url} = $self->base_url if $self->base_url; - return WWW::{{moduleName}}::ApiFactory->new(%args); + return {{moduleName}}::ApiFactory->new(%args); } =head1 NAME -WWW::{{moduleName}}::Role - a Moose role for the {{appName}} +{{moduleName}}::Role - a Moose role for the {{appName}} =head2 {{appName}} version: {{appVersion}} @@ -114,7 +114,7 @@ Automatically generated by the Perl Swagger Codegen project: =head2 A note on Moose This role is the only component of the library that uses Moose. See -WWW::{{moduleName}}::ApiFactory for non-Moosey usage. +{{moduleName}}::ApiFactory for non-Moosey usage. =head1 SYNOPSIS @@ -128,7 +128,7 @@ role. package MyApp; use Moose; - with 'WWW::{{moduleName}}::Role'; + with '{{moduleName}}::Role'; package main; @@ -186,39 +186,39 @@ you are accessing. Usually C and C will be determined by the code ge the spec and you will not need to set them at run time. If not, C will default to 'head' and C to the empty string. -The tokens will be placed in the C namespace +The tokens will be placed in the C<{{moduleName}}::Configuration> namespace as follows, but you don't need to know about this. =over 4 -=item C<$WWW::{{moduleName}}::Configuration::username> +=item C<${{moduleName}}::Configuration::username> String. The username for basic auth. -=item C<$WWW::{{moduleName}}::Configuration::password> +=item C<${{moduleName}}::Configuration::password> String. The password for basic auth. -=item C<$WWW::{{moduleName}}::Configuration::api_key> +=item C<${{moduleName}}::Configuration::api_key> Hashref. Keyed on the name of each key (there can be multiple tokens). - $WWW::{{moduleName}}::Configuration::api_key = { + ${{moduleName}}::Configuration::api_key = { secretKey => 'aaaabbbbccccdddd', anotherKey => '1111222233334444', }; -=item C<$WWW::{{moduleName}}::Configuration::api_key_prefix> +=item C<${{moduleName}}::Configuration::api_key_prefix> Hashref. Keyed on the name of each key (there can be multiple tokens). Note not all api keys require a prefix. - $WWW::{{moduleName}}::Configuration::api_key_prefix = { + ${{moduleName}}::Configuration::api_key_prefix = { secretKey => 'string', anotherKey => 'same or some other string', }; -=item C<$WWW::{{moduleName}}::Configuration::access_token> +=item C<${{moduleName}}::Configuration::access_token> String. The OAuth access token. @@ -236,7 +236,7 @@ created yet) the current value of C. Returns an API factory object. You probably won't need to call this directly. - $self->api_factory('Pet'); # returns a WWW::{{moduleName}}::PetApi instance + $self->api_factory('Pet'); # returns a {{moduleName}}::PetApi instance $self->pet_api; # the same @@ -264,12 +264,12 @@ you could also call them on class names. See the homepage C for full details. But briefly, clone the git repository, build the codegen codebase, set up your build -config file, then run the API build script. You will need git, Java 7 and Apache +config file, then run the API build script. You will need git, Java 7 or 8 and Apache maven 3.0.3 or better already installed. The config file should specify the project name for the generated library: - {"moduleName":"MyProjectName"} + {"moduleName":"WWW::MyProjectName"} Your library files will be built under C. diff --git a/modules/swagger-codegen/src/main/resources/perl/api.mustache b/modules/swagger-codegen/src/main/resources/perl/api.mustache index f25c63a528c..dcebb0bb518 100644 --- a/modules/swagger-codegen/src/main/resources/perl/api.mustache +++ b/modules/swagger-codegen/src/main/resources/perl/api.mustache @@ -1,5 +1,5 @@ # -# Copyright 2015 SmartBear Software +# 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. @@ -17,7 +17,7 @@ # NOTE: This class is auto generated by the swagger code generator program. # Do not edit the class manually. # -package WWW::{{moduleName}}::{{classname}}; +package {{moduleName}}::{{classname}}; require 5.6.0; use strict; @@ -27,8 +27,8 @@ use Exporter; use Carp qw( croak ); use Log::Any qw($log); -use WWW::{{moduleName}}::ApiClient; -use WWW::{{moduleName}}::Configuration; +use {{moduleName}}::ApiClient; +use {{moduleName}}::Configuration; use base "Class::Data::Inheritable"; @@ -37,7 +37,7 @@ __PACKAGE__->mk_classdata('method_documentation' => {}); sub new { my $class = shift; my (%self) = ( - 'api_client' => WWW::{{moduleName}}::ApiClient->instance, + 'api_client' => {{moduleName}}::ApiClient->instance, @_ ); diff --git a/modules/swagger-codegen/src/main/resources/perl/autodoc.script.mustache b/modules/swagger-codegen/src/main/resources/perl/autodoc.script.mustache index 240936d9b51..35f8f65fc9f 100644 --- a/modules/swagger-codegen/src/main/resources/perl/autodoc.script.mustache +++ b/modules/swagger-codegen/src/main/resources/perl/autodoc.script.mustache @@ -15,14 +15,14 @@ my $my_app = $options{c} || 'My::App'; if ($options{c}) { eval <getTempFolderPath().$match[1]; + if (array_key_exists('Content-Disposition', $httpHeaders) && preg_match('/inline; filename=[\'"]?([^\'"\s]+)[\'"]?$/i', $httpHeaders['Content-Disposition'], $match)) { + $filename = Configuration::getDefaultConfiguration()->getTempFolderPath() . sanitizeFilename($match[1]); } else { $filename = tempnam(Configuration::getDefaultConfiguration()->getTempFolderPath(), ''); } diff --git a/modules/swagger-codegen/src/main/resources/php/api.mustache b/modules/swagger-codegen/src/main/resources/php/api.mustache index 2521cc61cff..c0c497ff418 100644 --- a/modules/swagger-codegen/src/main/resources/php/api.mustache +++ b/modules/swagger-codegen/src/main/resources/php/api.mustache @@ -10,7 +10,7 @@ * @link https://github.com/swagger-api/swagger-codegen */ /** - * Copyright 2015 SmartBear Software + * 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. @@ -126,8 +126,6 @@ use \{{invokerPackage}}\ObjectSerializer; // parse inputs $resourcePath = "{{path}}"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "{{httpMethod}}"; $httpBody = ''; $queryParams = array(); $headerParams = array(); @@ -169,6 +167,9 @@ use \{{invokerPackage}}\ObjectSerializer; $resourcePath ); }{{/pathParams}} + // default format to json + $resourcePath = str_replace("{format}", "json", $resourcePath); + {{#formParams}}// form params if (${{paramName}} !== null) { {{#isFile}} @@ -213,7 +214,7 @@ use \{{invokerPackage}}\ObjectSerializer; // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, $method, + $resourcePath, '{{httpMethod}}', $queryParams, $httpBody, $headerParams{{#returnType}}, '{{returnType}}'{{/returnType}} ); diff --git a/modules/swagger-codegen/src/main/resources/php/configuration.mustache b/modules/swagger-codegen/src/main/resources/php/configuration.mustache index 161affb1c9d..8fa5e1cb1f0 100644 --- a/modules/swagger-codegen/src/main/resources/php/configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/php/configuration.mustache @@ -11,7 +11,7 @@ */ /** - * Copyright 2015 SmartBear Software + * 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. diff --git a/modules/swagger-codegen/src/main/resources/php/model.mustache b/modules/swagger-codegen/src/main/resources/php/model.mustache index 66cabf0122b..5b486c7fa62 100644 --- a/modules/swagger-codegen/src/main/resources/php/model.mustache +++ b/modules/swagger-codegen/src/main/resources/php/model.mustache @@ -13,7 +13,7 @@ * @link https://github.com/swagger-api/swagger-codegen */ /** - * Copyright 2015 SmartBear Software + * 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. diff --git a/modules/swagger-codegen/src/main/resources/python/api.mustache b/modules/swagger-codegen/src/main/resources/python/api.mustache index 474cf84f356..77ece14d44b 100644 --- a/modules/swagger-codegen/src/main/resources/python/api.mustache +++ b/modules/swagger-codegen/src/main/resources/python/api.mustache @@ -2,7 +2,7 @@ """ {{classname}}.py -Copyright 2015 SmartBear Software +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. 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 f6e34f041e3..57ada23fb32 100644 --- a/modules/swagger-codegen/src/main/resources/python/api_client.mustache +++ b/modules/swagger-codegen/src/main/resources/python/api_client.mustache @@ -1,7 +1,7 @@ # coding: utf-8 """ -Copyright 2015 SmartBear Software +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. diff --git a/modules/swagger-codegen/src/main/resources/python/configuration.mustache b/modules/swagger-codegen/src/main/resources/python/configuration.mustache index bab1d09d761..8f878f82318 100644 --- a/modules/swagger-codegen/src/main/resources/python/configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/python/configuration.mustache @@ -1,7 +1,7 @@ # coding: utf-8 """ -Copyright 2015 SmartBear Software +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. diff --git a/modules/swagger-codegen/src/main/resources/python/model.mustache b/modules/swagger-codegen/src/main/resources/python/model.mustache index aae43175a2e..105eefec095 100644 --- a/modules/swagger-codegen/src/main/resources/python/model.mustache +++ b/modules/swagger-codegen/src/main/resources/python/model.mustache @@ -1,7 +1,7 @@ # coding: utf-8 """ -Copyright 2015 SmartBear Software +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. diff --git a/modules/swagger-codegen/src/main/resources/python/rest.mustache b/modules/swagger-codegen/src/main/resources/python/rest.mustache index 0d1f4ce1da8..c5b9a4e6f91 100644 --- a/modules/swagger-codegen/src/main/resources/python/rest.mustache +++ b/modules/swagger-codegen/src/main/resources/python/rest.mustache @@ -1,7 +1,7 @@ # coding: utf-8 """ -Copyright 2015 SmartBear Software +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. diff --git a/modules/swagger-codegen/src/main/resources/ruby/gemspec.mustache b/modules/swagger-codegen/src/main/resources/ruby/gemspec.mustache index 5c9c1c1a497..7ab8a9e73d7 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/gemspec.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/gemspec.mustache @@ -6,12 +6,13 @@ Gem::Specification.new do |s| s.name = "{{gemName}}" s.version = {{moduleName}}::VERSION s.platform = Gem::Platform::RUBY - s.authors = ["Zeke Sikelianos", "Tony Tam"] - s.email = ["zeke@wordnik.com", "fehguy@gmail.com"] - s.homepage = "http://swagger.io" - s.summary = %q{A ruby wrapper for the swagger APIs} - s.description = %q{This gem maps to a swagger API} - s.license = "Apache-2.0" + s.authors = ["{{gemAuthor}}"] + s.email = ["{{gemAuthorEmail}}"] + s.homepage = "{{gemHomepage}}" + s.summary = "{{gemSummary}}" + s.description = "{{gemDescription}}" + s.license = "{{gemLicense}}" + s.add_runtime_dependency 'typhoeus', '~> 0.2', '>= 0.2.1' s.add_runtime_dependency 'json', '~> 1.4', '>= 1.4.6' @@ -22,7 +23,7 @@ Gem::Specification.new do |s| s.add_development_dependency 'autotest', '~> 4.4', '>= 4.4.6' s.add_development_dependency 'autotest-rails-pure', '~> 4.1', '>= 4.1.2' s.add_development_dependency 'autotest-growl', '~> 0.2', '>= 0.2.16' - s.add_development_dependency 'autotest-fsevent', '~> 0.2', '>= 0.2.10' + s.add_development_dependency 'autotest-fsevent', '~> 0.2', '>= 0.2.11' s.files = `find *`.split("\n").uniq.sort.select{|f| !f.empty? } s.test_files = `find spec/*`.split("\n") diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/csharp/CSharpClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/csharp/CSharpClientOptionsTest.java index ec5246f7723..367977e2b05 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/csharp/CSharpClientOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/csharp/CSharpClientOptionsTest.java @@ -31,6 +31,12 @@ public class CSharpClientOptionsTest extends AbstractOptionsTest { times = 1; clientCodegen.setPackageVersion(CSharpClientOptionsProvider.PACKAGE_VERSION_VALUE); times = 1; + clientCodegen.setOptionalAssemblyInfoFlag(true); + times = 1; + clientCodegen.setSourceFolder(CSharpClientOptionsProvider.SOURCE_FOLDER_VALUE); + times = 1; + clientCodegen.useDateTimeOffset(true); + times = 1; }}; } } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/CSharpClientOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/CSharpClientOptionsProvider.java index 94440db97c0..0c2da1f3fa2 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/CSharpClientOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/CSharpClientOptionsProvider.java @@ -9,7 +9,8 @@ import java.util.Map; public class CSharpClientOptionsProvider implements OptionsProvider { public static final String PACKAGE_NAME_VALUE = "swagger_client_csharp"; public static final String PACKAGE_VERSION_VALUE = "1.0.0-SNAPSHOT"; - + public static final String SOURCE_FOLDER_VALUE = "src_csharp"; + @Override public String getLanguage() { return "csharp"; @@ -22,6 +23,9 @@ public class CSharpClientOptionsProvider implements OptionsProvider { .put(CodegenConstants.PACKAGE_VERSION, PACKAGE_VERSION_VALUE) .put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, "true") .put(CodegenConstants.OPTIONAL_METHOD_ARGUMENT, "true") + .put(CodegenConstants.OPTIONAL_ASSEMBLY_INFO, "true") + .put(CodegenConstants.USE_DATETIME_OFFSET, "true") + .put(CodegenConstants.SOURCE_FOLDER, SOURCE_FOLDER_VALUE) .build(); } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/RubyClientOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/RubyClientOptionsProvider.java index d80341f0200..64e388d38ef 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/RubyClientOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/RubyClientOptionsProvider.java @@ -13,6 +13,12 @@ public class RubyClientOptionsProvider implements OptionsProvider { public static final String GEM_VERSION_VALUE = "1.0.0-SNAPSHOT"; public static final String SORT_PARAMS_VALUE = "false"; public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; + public static final String GEM_LICENSE_VALUE = "MIT"; + public static final String GEM_HOMEPAGE_VALUE = "homepage"; + public static final String GEM_SUMMARY_VALUE = "summary"; + public static final String GEM_DESCRIPTION_VALUE = "description"; + public static final String GEM_AUTHOR_VALUE = "foo"; + public static final String GEM_AUTHOR_EMAIL_VALUE = "foo"; @Override public String getLanguage() { @@ -25,6 +31,12 @@ public class RubyClientOptionsProvider implements OptionsProvider { return builder.put(RubyClientCodegen.GEM_NAME, GEM_NAME_VALUE) .put(RubyClientCodegen.MODULE_NAME, MODULE_NAME_VALUE) .put(RubyClientCodegen.GEM_VERSION, GEM_VERSION_VALUE) + .put(RubyClientCodegen.GEM_LICENSE, GEM_LICENSE_VALUE) + .put(RubyClientCodegen.GEM_DESCRIPTION, GEM_DESCRIPTION_VALUE) + .put(RubyClientCodegen.GEM_HOMEPAGE, GEM_HOMEPAGE_VALUE) + .put(RubyClientCodegen.GEM_SUMMARY, GEM_SUMMARY_VALUE) + .put(RubyClientCodegen.GEM_AUTHOR, GEM_AUTHOR_VALUE) + .put(RubyClientCodegen.GEM_AUTHOR_EMAIL, GEM_AUTHOR_EMAIL_VALUE) .put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) .build(); diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/ruby/RubyClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/ruby/RubyClientOptionsTest.java index b679de923c8..40494161973 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/ruby/RubyClientOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/ruby/RubyClientOptionsTest.java @@ -31,6 +31,19 @@ public class RubyClientOptionsTest extends AbstractOptionsTest { times = 1; clientCodegen.setGemVersion(RubyClientOptionsProvider.GEM_VERSION_VALUE); times = 1; + clientCodegen.setGemLicense(RubyClientOptionsProvider.GEM_LICENSE_VALUE); + times = 1; + clientCodegen.setGemHomepage(RubyClientOptionsProvider.GEM_HOMEPAGE_VALUE); + times = 1; + clientCodegen.setGemDescription(RubyClientOptionsProvider.GEM_DESCRIPTION_VALUE); + times = 1; + clientCodegen.setGemSummary(RubyClientOptionsProvider.GEM_SUMMARY_VALUE); + times = 1; + clientCodegen.setGemAuthor(RubyClientOptionsProvider.GEM_AUTHOR_VALUE); + times = 1; + clientCodegen.setGemAuthorEmail(RubyClientOptionsProvider.GEM_AUTHOR_EMAIL_VALUE); + times = 1; + }}; } } diff --git a/modules/swagger-codegen/src/test/resources/2_0/petstore.json b/modules/swagger-codegen/src/test/resources/2_0/petstore.json index 66762d74b2b..703b920db21 100644 --- a/modules/swagger-codegen/src/test/resources/2_0/petstore.json +++ b/modules/swagger-codegen/src/test/resources/2_0/petstore.json @@ -19,6 +19,49 @@ "http" ], "paths": { + "/pet?testing_byte_array=true": { + "post": { + "tags": [ + "pet" + ], + "summary": "Fake endpoint to test byte array in body parameter for adding a new pet to the store", + "description": "", + "operationId": "addPetUsingByteArray", + "consumes": [ + "application/json", + "application/xml" + ], + "produces": [ + "application/json", + "application/xml" + ], + "parameters": [ + { + "in": "body", + "name": "body", + "description": "Pet object in the form of byte array", + "required": false, + "schema": { + "type": "string", + "format": "binary" + } + } + ], + "responses": { + "405": { + "description": "Invalid input" + } + }, + "security": [ + { + "petstore_auth": [ + "write:pets", + "read:pets" + ] + } + ] + } + }, "/pet": { "post": { "tags": [ @@ -206,6 +249,56 @@ ] } }, + "/pet/{petId}?testing_byte_array=true": { + "get": { + "tags": [ + "pet" + ], + "summary": "Fake endpoint to test byte array return by 'Find pet by ID'", + "description": "Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions", + "operationId": "getPetByIdWithByteArray", + "produces": [ + "application/json", + "application/xml" + ], + "parameters": [ + { + "name": "petId", + "in": "path", + "description": "ID of pet that needs to be fetched", + "required": true, + "type": "integer", + "format": "int64" + } + ], + "responses": { + "404": { + "description": "Pet not found" + }, + "200": { + "description": "successful operation", + "schema": { + "type": "string", + "format": "binary" + } + }, + "400": { + "description": "Invalid ID supplied" + } + }, + "security": [ + { + "api_key": [] + }, + { + "petstore_auth": [ + "write:pets", + "read:pets" + ] + } + ] + } + }, "/pet/{petId}": { "get": { "tags": [ diff --git a/modules/swagger-generator/pom.xml b/modules/swagger-generator/pom.xml index e893fed1ba3..6210ed77f37 100644 --- a/modules/swagger-generator/pom.xml +++ b/modules/swagger-generator/pom.xml @@ -4,7 +4,7 @@ io.swagger swagger-codegen-project - 2.1.5 + 2.1.6-SNAPSHOT ../.. swagger-generator @@ -218,6 +218,6 @@ 2.5 1.3.2 9.2.9.v20150224 - 2.4.1 + 2.6 diff --git a/modules/swagger-generator/src/main/java/io/swagger/generator/Bootstrap.java b/modules/swagger-generator/src/main/java/io/swagger/generator/Bootstrap.java index 7d1c46c4362..995fc8c80e7 100644 --- a/modules/swagger-generator/src/main/java/io/swagger/generator/Bootstrap.java +++ b/modules/swagger-generator/src/main/java/io/swagger/generator/Bootstrap.java @@ -1,5 +1,5 @@ /** - * Copyright 2015 SmartBear Software + * 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. diff --git a/modules/swagger-generator/src/main/java/io/swagger/generator/exception/ApiException.java b/modules/swagger-generator/src/main/java/io/swagger/generator/exception/ApiException.java index fe8b455ecb0..4ffc2348c27 100644 --- a/modules/swagger-generator/src/main/java/io/swagger/generator/exception/ApiException.java +++ b/modules/swagger-generator/src/main/java/io/swagger/generator/exception/ApiException.java @@ -1,5 +1,5 @@ /** - * Copyright 2015 SmartBear Software + * 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. diff --git a/modules/swagger-generator/src/main/java/io/swagger/generator/exception/BadRequestException.java b/modules/swagger-generator/src/main/java/io/swagger/generator/exception/BadRequestException.java index 7cab512b58c..14093f536d2 100644 --- a/modules/swagger-generator/src/main/java/io/swagger/generator/exception/BadRequestException.java +++ b/modules/swagger-generator/src/main/java/io/swagger/generator/exception/BadRequestException.java @@ -1,5 +1,5 @@ /** - * Copyright 2015 SmartBear Software + * 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. diff --git a/modules/swagger-generator/src/main/java/io/swagger/generator/exception/NotFoundException.java b/modules/swagger-generator/src/main/java/io/swagger/generator/exception/NotFoundException.java index b84985d51e1..cdae50ce9b6 100644 --- a/modules/swagger-generator/src/main/java/io/swagger/generator/exception/NotFoundException.java +++ b/modules/swagger-generator/src/main/java/io/swagger/generator/exception/NotFoundException.java @@ -1,5 +1,5 @@ /** - * Copyright 2015 SmartBear Software + * 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. diff --git a/modules/swagger-generator/src/main/java/io/swagger/generator/model/ApiResponse.java b/modules/swagger-generator/src/main/java/io/swagger/generator/model/ApiResponse.java index 8fe9d41fb7e..424b9dd2b0a 100644 --- a/modules/swagger-generator/src/main/java/io/swagger/generator/model/ApiResponse.java +++ b/modules/swagger-generator/src/main/java/io/swagger/generator/model/ApiResponse.java @@ -1,5 +1,5 @@ /** - * Copyright 2015 SmartBear Software + * 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. diff --git a/modules/swagger-generator/src/main/java/io/swagger/generator/model/Generated.java b/modules/swagger-generator/src/main/java/io/swagger/generator/model/Generated.java index 614adcc61bc..f48be6a77da 100644 --- a/modules/swagger-generator/src/main/java/io/swagger/generator/model/Generated.java +++ b/modules/swagger-generator/src/main/java/io/swagger/generator/model/Generated.java @@ -1,5 +1,5 @@ /** - * Copyright 2015 SmartBear Software + * 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. diff --git a/modules/swagger-generator/src/main/java/io/swagger/generator/model/InputOption.java b/modules/swagger-generator/src/main/java/io/swagger/generator/model/InputOption.java index 45b3b7b7bbf..33df1bc5071 100644 --- a/modules/swagger-generator/src/main/java/io/swagger/generator/model/InputOption.java +++ b/modules/swagger-generator/src/main/java/io/swagger/generator/model/InputOption.java @@ -1,5 +1,5 @@ /** - * Copyright 2015 SmartBear Software + * 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. diff --git a/modules/swagger-generator/src/main/java/io/swagger/generator/util/ApiOriginFilter.java b/modules/swagger-generator/src/main/java/io/swagger/generator/util/ApiOriginFilter.java index 07ee795f588..aca470bd89b 100644 --- a/modules/swagger-generator/src/main/java/io/swagger/generator/util/ApiOriginFilter.java +++ b/modules/swagger-generator/src/main/java/io/swagger/generator/util/ApiOriginFilter.java @@ -1,5 +1,5 @@ /** - * Copyright 2015 SmartBear Software + * 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. diff --git a/modules/swagger-generator/src/main/java/io/swagger/generator/util/ZipUtil.java b/modules/swagger-generator/src/main/java/io/swagger/generator/util/ZipUtil.java index ca0a0e62018..c63f161b702 100644 --- a/modules/swagger-generator/src/main/java/io/swagger/generator/util/ZipUtil.java +++ b/modules/swagger-generator/src/main/java/io/swagger/generator/util/ZipUtil.java @@ -1,5 +1,5 @@ /** - * Copyright 2015 SmartBear Software + * 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. diff --git a/pom.xml b/pom.xml index 0f0e35a38c3..a47757a3597 100644 --- a/pom.xml +++ b/pom.xml @@ -10,7 +10,7 @@ swagger-codegen-project pom swagger-codegen-project - 2.1.5 + 2.1.6-SNAPSHOT https://github.com/swagger-api/swagger-codegen scm:git:git@github.com:swagger-api/swagger-codegen.git @@ -151,54 +151,43 @@ maven-release-plugin 2.1 + + + org.apache.maven.plugins + maven-javadoc-plugin + 2.10.3 + + true + 1.7 + UTF-8 + 1g + ${javadoc.package.exclude} + + + + attach-javadocs + verify + + jar + + + + + + org.apache.maven.plugins + maven-source-plugin + 2.1.2 + + + attach-sources + verify + + jar-no-fork + + + + - - - - net.alchim31.maven - scala-maven-plugin - ${scala-maven-plugin-version} - - - org.apache.maven.plugins - maven-javadoc-plugin - 2.9 - - true - 1.6 - UTF-8 - 1g - - http://java.sun.com/javase/6/docs/api/ - - ${javadoc.package.exclude} - - - - attach-javadocs - verify - - jar - - - - - - org.apache.maven.plugins - maven-source-plugin - 2.1.2 - - - attach-sources - verify - - jar-no-fork - - - - - - @@ -530,10 +519,10 @@ - 1.0.15-SNAPSHOT + 1.0.17-SNAPSHOT 2.11.1 2.3.4 - 1.5.5 + 1.5.6 2.4 1.2 4.8.1 diff --git a/samples/client/petstore/android/default/src/test/java/io/swagger/petstore/test/PetApiTest.java b/samples/client/petstore/android/default/src/test/java/io/swagger/petstore/test/PetApiTest.java index ca868d2ea22..75039a9fa39 100644 --- a/samples/client/petstore/android/default/src/test/java/io/swagger/petstore/test/PetApiTest.java +++ b/samples/client/petstore/android/default/src/test/java/io/swagger/petstore/test/PetApiTest.java @@ -72,6 +72,11 @@ public class PetApiTest { } @Test + @Ignore + /* ignoring the findPetByTags test below as it's very similar to + * testFindPetsByStatus and testFindPetsByTags sometimes got 500 + * due to server issue, which makes the test unstable. + */ public void testFindPetsByTags() throws Exception { Pet pet = createRandomPet(); pet.setName("monster"); diff --git a/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/compile-mono.sh b/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/compile-mono.sh index bc4e0989945..352274186d2 100644 --- a/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/compile-mono.sh +++ b/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/compile-mono.sh @@ -7,6 +7,6 @@ vendor/RestSharp.Net2.1.1.11/lib/net20/RestSharp.Net2.dll,\ System.Runtime.Serialization.dll \ -target:library \ -out:bin/IO.Swagger.dll \ --recurse:src/*.cs \ +-recurse:'src/*.cs' \ -doc:bin/IO.Swagger.xml \ --platform:anycpu \ No newline at end of file +-platform:anycpu diff --git a/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/src/main/CsharpDotNet2/IO/Swagger/Api/PetApi.cs b/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/src/main/CsharpDotNet2/IO/Swagger/Api/PetApi.cs index 7db0f993846..b09b31264c3 100644 --- a/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/src/main/CsharpDotNet2/IO/Swagger/Api/PetApi.cs +++ b/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/src/main/CsharpDotNet2/IO/Swagger/Api/PetApi.cs @@ -8,6 +8,9 @@ using IO.Swagger.Model; namespace IO.Swagger.Api { + ///

+ /// Represents a collection of functions to interact with the API endpoints + /// public interface IPetApi { @@ -29,14 +32,14 @@ namespace IO.Swagger.Api /// Finds Pets by status Multiple status values can be provided with comma seperated strings ///
/// Status values that need to be considered for filter - /// List + /// List<Pet> List FindPetsByStatus (List status); /// /// Finds Pets by tags Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. /// /// Tags to filter by - /// List + /// List<Pet> List FindPetsByTags (List tags); /// @@ -124,7 +127,7 @@ namespace IO.Swagger.Api /// /// Gets or sets the API client. /// - /// An instance of the ApiClient + /// An instance of the ApiClient public ApiClient ApiClient {get; set;} @@ -212,7 +215,7 @@ namespace IO.Swagger.Api /// Finds Pets by status Multiple status values can be provided with comma seperated strings /// /// Status values that need to be considered for filter - /// List + /// List<Pet> public List FindPetsByStatus (List status) { @@ -252,7 +255,7 @@ namespace IO.Swagger.Api /// Finds Pets by tags Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. /// /// Tags to filter by - /// List + /// List<Pet> public List FindPetsByTags (List tags) { diff --git a/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/src/main/CsharpDotNet2/IO/Swagger/Api/StoreApi.cs b/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/src/main/CsharpDotNet2/IO/Swagger/Api/StoreApi.cs index c6c90631bef..ba269cc2b0c 100644 --- a/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/src/main/CsharpDotNet2/IO/Swagger/Api/StoreApi.cs +++ b/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/src/main/CsharpDotNet2/IO/Swagger/Api/StoreApi.cs @@ -8,13 +8,16 @@ using IO.Swagger.Model; namespace IO.Swagger.Api { + /// + /// Represents a collection of functions to interact with the API endpoints + /// public interface IStoreApi { /// /// Returns pet inventories by status Returns a map of status codes to quantities /// - /// Dictionary + /// Dictionary<String, int?> Dictionary GetInventory (); /// @@ -90,14 +93,14 @@ namespace IO.Swagger.Api /// /// Gets or sets the API client. /// - /// An instance of the ApiClient + /// An instance of the ApiClient public ApiClient ApiClient {get; set;} /// /// Returns pet inventories by status Returns a map of status codes to quantities /// - /// Dictionary + /// Dictionary<String, int?> public Dictionary GetInventory () { diff --git a/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/src/main/CsharpDotNet2/IO/Swagger/Api/UserApi.cs b/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/src/main/CsharpDotNet2/IO/Swagger/Api/UserApi.cs index 3e3c8869d04..1374556698e 100644 --- a/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/src/main/CsharpDotNet2/IO/Swagger/Api/UserApi.cs +++ b/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/src/main/CsharpDotNet2/IO/Swagger/Api/UserApi.cs @@ -8,6 +8,9 @@ using IO.Swagger.Model; namespace IO.Swagger.Api { + /// + /// Represents a collection of functions to interact with the API endpoints + /// public interface IUserApi { @@ -120,7 +123,7 @@ namespace IO.Swagger.Api /// /// Gets or sets the API client. /// - /// An instance of the ApiClient + /// An instance of the ApiClient public ApiClient ApiClient {get; set;} diff --git a/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/src/main/CsharpDotNet2/IO/Swagger/Client/ApiClient.cs b/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/src/main/CsharpDotNet2/IO/Swagger/Client/ApiClient.cs index 56331e606a9..3041cde567e 100644 --- a/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/src/main/CsharpDotNet2/IO/Swagger/Client/ApiClient.cs +++ b/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/src/main/CsharpDotNet2/IO/Swagger/Client/ApiClient.cs @@ -159,6 +159,7 @@ namespace IO.Swagger.Client /// /// HTTP body (e.g. string, JSON). /// Object type. + /// HTTP headers. /// Object representation of the JSON string. public object Deserialize(string content, Type type, IList headers=null) { diff --git a/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/src/main/CsharpDotNet2/IO/Swagger/Client/ApiException.cs b/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/src/main/CsharpDotNet2/IO/Swagger/Client/ApiException.cs index ff0b4be791e..dfc5fd9fc03 100644 --- a/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/src/main/CsharpDotNet2/IO/Swagger/Client/ApiException.cs +++ b/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/src/main/CsharpDotNet2/IO/Swagger/Client/ApiException.cs @@ -20,7 +20,6 @@ namespace IO.Swagger.Client { /// /// Initializes a new instance of the class. /// - /// The base path. public ApiException() {} /// diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/Properties/AssemblyInfo.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/Properties/AssemblyInfo.cs new file mode 100644 index 00000000000..1de9edb2a81 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/Properties/AssemblyInfo.cs @@ -0,0 +1,33 @@ +using System.Reflection; +using System.Runtime.InteropServices; +using System.Windows; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("Swagger Library")] +[assembly: AssemblyDescription("A library generated from a Swagger doc")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("Swagger")] +[assembly: AssemblyProduct("SwaggerLibrary")] +[assembly: AssemblyCopyright("No Copyright")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0")] +[assembly: AssemblyFileVersion("1.0.0")] diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/PetApi.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/PetApi.cs index ba58eeac9e0..892412e5b3e 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/PetApi.cs +++ b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/PetApi.cs @@ -355,6 +355,86 @@ namespace IO.Swagger.Api /// Task of ApiResponse System.Threading.Tasks.Task> UploadFileAsyncWithHttpInfo (long? petId, string additionalMetadata = null, Stream file = null); + /// + /// 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 + /// + /// ID of pet that needs to be fetched + /// byte[] + byte[] GetPetByIdWithByteArray (long? petId); + + /// + /// Fake endpoint to test byte array return by 'Find pet by ID' + /// + /// + /// Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + /// + /// ID of pet that needs to be fetched + /// ApiResponse of byte[] + ApiResponse GetPetByIdWithByteArrayWithHttpInfo (long? petId); + + /// + /// Fake endpoint to test byte array return by 'Find pet by ID' + /// + /// + /// Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + /// + /// ID of pet that needs to be fetched + /// Task of byte[] + System.Threading.Tasks.Task GetPetByIdWithByteArrayAsync (long? petId); + + /// + /// Fake endpoint to test byte array return by 'Find pet by ID' + /// + /// + /// Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + /// + /// ID of pet that needs to be fetched + /// Task of ApiResponse (byte[]) + System.Threading.Tasks.Task> GetPetByIdWithByteArrayAsyncWithHttpInfo (long? petId); + + /// + /// Fake endpoint to test byte array in body parameter for adding a new pet to the store + /// + /// + /// + /// + /// Pet object in the form of byte array + /// + void AddPetUsingByteArray (byte[] body = null); + + /// + /// Fake endpoint to test byte array in body parameter for adding a new pet to the store + /// + /// + /// + /// + /// Pet object in the form of byte array + /// ApiResponse of Object(void) + ApiResponse AddPetUsingByteArrayWithHttpInfo (byte[] body = null); + + /// + /// Fake endpoint to test byte array in body parameter for adding a new pet to the store + /// + /// + /// + /// + /// Pet object in the form of byte array + /// Task of void + System.Threading.Tasks.Task AddPetUsingByteArrayAsync (byte[] body = null); + + /// + /// Fake endpoint to test byte array in body parameter for adding a new pet to the store + /// + /// + /// + /// + /// Pet object in the form of byte array + /// Task of ApiResponse + System.Threading.Tasks.Task> AddPetUsingByteArrayAsyncWithHttpInfo (byte[] body = null); + } /// @@ -459,15 +539,21 @@ namespace IO.Swagger.Api var headerParams = new Dictionary(Configuration.DefaultHeader); var formParams = new Dictionary(); var fileParams = new Dictionary(); - String postBody = null; + Object postBody = null; - // to determine the Accept header - String[] http_header_accepts = new String[] { + // to determine the Content-Type header + String[] httpContentTypes = new String[] { "application/json", "application/xml" }; - String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); - if (http_header_accept != null) - headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); + String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes); + + // to determine the Accept header + String[] httpHeaderAccepts = new String[] { + "application/json", "application/xml" + }; + String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAccept != null) + headerParams.Add("Accept", httpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json @@ -476,10 +562,15 @@ namespace IO.Swagger.Api - postBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter - + if (body.GetType() != typeof(byte[])) + { + postBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter + } + else + { + postBody = body; // byte array + } - // authentication (petstore_auth) required // oauth required @@ -490,7 +581,9 @@ namespace IO.Swagger.Api // make the HTTP request - IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, Method.PUT, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, + Method.PUT, queryParams, postBody, headerParams, formParams, fileParams, + pathParams, httpContentType); int statusCode = (int) response.StatusCode; @@ -532,15 +625,21 @@ namespace IO.Swagger.Api var headerParams = new Dictionary(); var formParams = new Dictionary(); var fileParams = new Dictionary(); - String postBody = null; + Object postBody = null; - // to determine the Accept header - String[] http_header_accepts = new String[] { + // to determine the Content-Type header + String[] httpContentTypes = new String[] { "application/json", "application/xml" }; - String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); - if (http_header_accept != null) - headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); + String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes); + + // to determine the Accept header + String[] httpHeaderAccepts = new String[] { + "application/json", "application/xml" + }; + String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAccept != null) + headerParams.Add("Accept", httpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json @@ -563,7 +662,9 @@ namespace IO.Swagger.Api // make the HTTP request - IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, Method.PUT, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, + Method.PUT, queryParams, postBody, headerParams, formParams, fileParams, + pathParams, httpContentType); int statusCode = (int) response.StatusCode; @@ -604,15 +705,21 @@ namespace IO.Swagger.Api var headerParams = new Dictionary(Configuration.DefaultHeader); var formParams = new Dictionary(); var fileParams = new Dictionary(); - String postBody = null; + Object postBody = null; - // to determine the Accept header - String[] http_header_accepts = new String[] { + // to determine the Content-Type header + String[] httpContentTypes = new String[] { "application/json", "application/xml" }; - String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); - if (http_header_accept != null) - headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); + String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes); + + // to determine the Accept header + String[] httpHeaderAccepts = new String[] { + "application/json", "application/xml" + }; + String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAccept != null) + headerParams.Add("Accept", httpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json @@ -621,10 +728,15 @@ namespace IO.Swagger.Api - postBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter - + if (body.GetType() != typeof(byte[])) + { + postBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter + } + else + { + postBody = body; // byte array + } - // authentication (petstore_auth) required // oauth required @@ -635,7 +747,9 @@ namespace IO.Swagger.Api // make the HTTP request - IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, + Method.POST, queryParams, postBody, headerParams, formParams, fileParams, + pathParams, httpContentType); int statusCode = (int) response.StatusCode; @@ -677,15 +791,21 @@ namespace IO.Swagger.Api var headerParams = new Dictionary(); var formParams = new Dictionary(); var fileParams = new Dictionary(); - String postBody = null; + Object postBody = null; - // to determine the Accept header - String[] http_header_accepts = new String[] { + // to determine the Content-Type header + String[] httpContentTypes = new String[] { "application/json", "application/xml" }; - String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); - if (http_header_accept != null) - headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); + String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes); + + // to determine the Accept header + String[] httpHeaderAccepts = new String[] { + "application/json", "application/xml" + }; + String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAccept != null) + headerParams.Add("Accept", httpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json @@ -708,7 +828,9 @@ namespace IO.Swagger.Api // make the HTTP request - IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, + Method.POST, queryParams, postBody, headerParams, formParams, fileParams, + pathParams, httpContentType); int statusCode = (int) response.StatusCode; @@ -750,15 +872,21 @@ namespace IO.Swagger.Api var headerParams = new Dictionary(Configuration.DefaultHeader); var formParams = new Dictionary(); var fileParams = new Dictionary(); - String postBody = null; + Object postBody = null; + + // to determine the Content-Type header + String[] httpContentTypes = new String[] { + + }; + String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes); // to determine the Accept header - String[] http_header_accepts = new String[] { + String[] httpHeaderAccepts = new String[] { "application/json", "application/xml" }; - String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); - if (http_header_accept != null) - headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); + String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAccept != null) + headerParams.Add("Accept", httpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json @@ -770,7 +898,6 @@ namespace IO.Swagger.Api - // authentication (petstore_auth) required // oauth required @@ -781,7 +908,9 @@ namespace IO.Swagger.Api // make the HTTP request - IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, + Method.GET, queryParams, postBody, headerParams, formParams, fileParams, + pathParams, httpContentType); int statusCode = (int) response.StatusCode; @@ -824,15 +953,21 @@ namespace IO.Swagger.Api var headerParams = new Dictionary(); var formParams = new Dictionary(); var fileParams = new Dictionary(); - String postBody = null; + Object postBody = null; + + // to determine the Content-Type header + String[] httpContentTypes = new String[] { + + }; + String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes); // to determine the Accept header - String[] http_header_accepts = new String[] { + String[] httpHeaderAccepts = new String[] { "application/json", "application/xml" }; - String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); - if (http_header_accept != null) - headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); + String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAccept != null) + headerParams.Add("Accept", httpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json @@ -855,7 +990,9 @@ namespace IO.Swagger.Api // make the HTTP request - IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, + Method.GET, queryParams, postBody, headerParams, formParams, fileParams, + pathParams, httpContentType); int statusCode = (int) response.StatusCode; @@ -897,15 +1034,21 @@ namespace IO.Swagger.Api var headerParams = new Dictionary(Configuration.DefaultHeader); var formParams = new Dictionary(); var fileParams = new Dictionary(); - String postBody = null; + Object postBody = null; + + // to determine the Content-Type header + String[] httpContentTypes = new String[] { + + }; + String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes); // to determine the Accept header - String[] http_header_accepts = new String[] { + String[] httpHeaderAccepts = new String[] { "application/json", "application/xml" }; - String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); - if (http_header_accept != null) - headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); + String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAccept != null) + headerParams.Add("Accept", httpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json @@ -917,7 +1060,6 @@ namespace IO.Swagger.Api - // authentication (petstore_auth) required // oauth required @@ -928,7 +1070,9 @@ namespace IO.Swagger.Api // make the HTTP request - IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, + Method.GET, queryParams, postBody, headerParams, formParams, fileParams, + pathParams, httpContentType); int statusCode = (int) response.StatusCode; @@ -971,15 +1115,21 @@ namespace IO.Swagger.Api var headerParams = new Dictionary(); var formParams = new Dictionary(); var fileParams = new Dictionary(); - String postBody = null; + Object postBody = null; + + // to determine the Content-Type header + String[] httpContentTypes = new String[] { + + }; + String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes); // to determine the Accept header - String[] http_header_accepts = new String[] { + String[] httpHeaderAccepts = new String[] { "application/json", "application/xml" }; - String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); - if (http_header_accept != null) - headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); + String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAccept != null) + headerParams.Add("Accept", httpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json @@ -1002,7 +1152,9 @@ namespace IO.Swagger.Api // make the HTTP request - IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, + Method.GET, queryParams, postBody, headerParams, formParams, fileParams, + pathParams, httpContentType); int statusCode = (int) response.StatusCode; @@ -1037,7 +1189,8 @@ namespace IO.Swagger.Api { // verify the required parameter 'petId' is set - if (petId == null) throw new ApiException(400, "Missing required parameter 'petId' when calling GetPetById"); + if (petId == null) + throw new ApiException(400, "Missing required parameter 'petId' when calling PetApi->GetPetById"); var path_ = "/pet/{petId}"; @@ -1047,15 +1200,21 @@ namespace IO.Swagger.Api var headerParams = new Dictionary(Configuration.DefaultHeader); var formParams = new Dictionary(); var fileParams = new Dictionary(); - String postBody = null; + Object postBody = null; + + // to determine the Content-Type header + String[] httpContentTypes = new String[] { + + }; + String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes); // to determine the Accept header - String[] http_header_accepts = new String[] { + String[] httpHeaderAccepts = new String[] { "application/json", "application/xml" }; - String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); - if (http_header_accept != null) - headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); + String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAccept != null) + headerParams.Add("Accept", httpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json @@ -1067,7 +1226,6 @@ namespace IO.Swagger.Api - // authentication (api_key) required var apiKeyValue = Configuration.GetApiKeyWithPrefix("api_key"); @@ -1078,7 +1236,9 @@ namespace IO.Swagger.Api // make the HTTP request - IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, + Method.GET, queryParams, postBody, headerParams, formParams, fileParams, + pathParams, httpContentType); int statusCode = (int) response.StatusCode; @@ -1123,15 +1283,21 @@ namespace IO.Swagger.Api var headerParams = new Dictionary(); var formParams = new Dictionary(); var fileParams = new Dictionary(); - String postBody = null; + Object postBody = null; + + // to determine the Content-Type header + String[] httpContentTypes = new String[] { + + }; + String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes); // to determine the Accept header - String[] http_header_accepts = new String[] { + String[] httpHeaderAccepts = new String[] { "application/json", "application/xml" }; - String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); - if (http_header_accept != null) - headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); + String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAccept != null) + headerParams.Add("Accept", httpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json @@ -1154,7 +1320,9 @@ namespace IO.Swagger.Api // make the HTTP request - IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, + Method.GET, queryParams, postBody, headerParams, formParams, fileParams, + pathParams, httpContentType); int statusCode = (int) response.StatusCode; @@ -1192,7 +1360,8 @@ namespace IO.Swagger.Api { // verify the required parameter 'petId' is set - if (petId == null) throw new ApiException(400, "Missing required parameter 'petId' when calling UpdatePetWithForm"); + if (petId == null) + throw new ApiException(400, "Missing required parameter 'petId' when calling PetApi->UpdatePetWithForm"); var path_ = "/pet/{petId}"; @@ -1202,15 +1371,21 @@ namespace IO.Swagger.Api var headerParams = new Dictionary(Configuration.DefaultHeader); var formParams = new Dictionary(); var fileParams = new Dictionary(); - String postBody = null; + Object postBody = null; + + // to determine the Content-Type header + String[] httpContentTypes = new String[] { + "application/x-www-form-urlencoded" + }; + String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes); // to determine the Accept header - String[] http_header_accepts = new String[] { + String[] httpHeaderAccepts = new String[] { "application/json", "application/xml" }; - String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); - if (http_header_accept != null) - headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); + String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAccept != null) + headerParams.Add("Accept", httpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json @@ -1224,7 +1399,6 @@ namespace IO.Swagger.Api - // authentication (petstore_auth) required // oauth required @@ -1235,7 +1409,9 @@ namespace IO.Swagger.Api // make the HTTP request - IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, + Method.POST, queryParams, postBody, headerParams, formParams, fileParams, + pathParams, httpContentType); int statusCode = (int) response.StatusCode; @@ -1283,15 +1459,21 @@ namespace IO.Swagger.Api var headerParams = new Dictionary(); var formParams = new Dictionary(); var fileParams = new Dictionary(); - String postBody = null; + Object postBody = null; + + // to determine the Content-Type header + String[] httpContentTypes = new String[] { + "application/x-www-form-urlencoded" + }; + String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes); // to determine the Accept header - String[] http_header_accepts = new String[] { + String[] httpHeaderAccepts = new String[] { "application/json", "application/xml" }; - String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); - if (http_header_accept != null) - headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); + String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAccept != null) + headerParams.Add("Accept", httpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json @@ -1316,7 +1498,9 @@ namespace IO.Swagger.Api // make the HTTP request - IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, + Method.POST, queryParams, postBody, headerParams, formParams, fileParams, + pathParams, httpContentType); int statusCode = (int) response.StatusCode; @@ -1352,7 +1536,8 @@ namespace IO.Swagger.Api { // verify the required parameter 'petId' is set - if (petId == null) throw new ApiException(400, "Missing required parameter 'petId' when calling DeletePet"); + if (petId == null) + throw new ApiException(400, "Missing required parameter 'petId' when calling PetApi->DeletePet"); var path_ = "/pet/{petId}"; @@ -1362,15 +1547,21 @@ namespace IO.Swagger.Api var headerParams = new Dictionary(Configuration.DefaultHeader); var formParams = new Dictionary(); var fileParams = new Dictionary(); - String postBody = null; + Object postBody = null; + + // to determine the Content-Type header + String[] httpContentTypes = new String[] { + + }; + String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes); // to determine the Accept header - String[] http_header_accepts = new String[] { + String[] httpHeaderAccepts = new String[] { "application/json", "application/xml" }; - String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); - if (http_header_accept != null) - headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); + String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAccept != null) + headerParams.Add("Accept", httpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json @@ -1383,7 +1574,6 @@ namespace IO.Swagger.Api - // authentication (petstore_auth) required // oauth required @@ -1394,7 +1584,9 @@ namespace IO.Swagger.Api // make the HTTP request - IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, Method.DELETE, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, + Method.DELETE, queryParams, postBody, headerParams, formParams, fileParams, + pathParams, httpContentType); int statusCode = (int) response.StatusCode; @@ -1440,15 +1632,21 @@ namespace IO.Swagger.Api var headerParams = new Dictionary(); var formParams = new Dictionary(); var fileParams = new Dictionary(); - String postBody = null; + Object postBody = null; + + // to determine the Content-Type header + String[] httpContentTypes = new String[] { + + }; + String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes); // to determine the Accept header - String[] http_header_accepts = new String[] { + String[] httpHeaderAccepts = new String[] { "application/json", "application/xml" }; - String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); - if (http_header_accept != null) - headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); + String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAccept != null) + headerParams.Add("Accept", httpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json @@ -1472,7 +1670,9 @@ namespace IO.Swagger.Api // make the HTTP request - IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, Method.DELETE, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, + Method.DELETE, queryParams, postBody, headerParams, formParams, fileParams, + pathParams, httpContentType); int statusCode = (int) response.StatusCode; @@ -1510,7 +1710,8 @@ namespace IO.Swagger.Api { // verify the required parameter 'petId' is set - if (petId == null) throw new ApiException(400, "Missing required parameter 'petId' when calling UploadFile"); + if (petId == null) + throw new ApiException(400, "Missing required parameter 'petId' when calling PetApi->UploadFile"); var path_ = "/pet/{petId}/uploadImage"; @@ -1520,15 +1721,21 @@ namespace IO.Swagger.Api var headerParams = new Dictionary(Configuration.DefaultHeader); var formParams = new Dictionary(); var fileParams = new Dictionary(); - String postBody = null; + Object postBody = null; + + // to determine the Content-Type header + String[] httpContentTypes = new String[] { + "multipart/form-data" + }; + String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes); // to determine the Accept header - String[] http_header_accepts = new String[] { + String[] httpHeaderAccepts = new String[] { "application/json", "application/xml" }; - String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); - if (http_header_accept != null) - headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); + String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAccept != null) + headerParams.Add("Accept", httpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json @@ -1542,7 +1749,6 @@ namespace IO.Swagger.Api - // authentication (petstore_auth) required // oauth required @@ -1553,7 +1759,9 @@ namespace IO.Swagger.Api // make the HTTP request - IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, + Method.POST, queryParams, postBody, headerParams, formParams, fileParams, + pathParams, httpContentType); int statusCode = (int) response.StatusCode; @@ -1601,15 +1809,21 @@ namespace IO.Swagger.Api var headerParams = new Dictionary(); var formParams = new Dictionary(); var fileParams = new Dictionary(); - String postBody = null; + Object postBody = null; + + // to determine the Content-Type header + String[] httpContentTypes = new String[] { + "multipart/form-data" + }; + String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes); // to determine the Accept header - String[] http_header_accepts = new String[] { + String[] httpHeaderAccepts = new String[] { "application/json", "application/xml" }; - String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); - if (http_header_accept != null) - headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); + String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAccept != null) + headerParams.Add("Accept", httpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json @@ -1634,7 +1848,9 @@ namespace IO.Swagger.Api // make the HTTP request - IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, + Method.POST, queryParams, postBody, headerParams, formParams, fileParams, + pathParams, httpContentType); int statusCode = (int) response.StatusCode; @@ -1649,6 +1865,340 @@ namespace IO.Swagger.Api null); } + /// + /// 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 + /// + /// ID of pet that needs to be fetched + /// byte[] + public byte[] GetPetByIdWithByteArray (long? petId) + { + ApiResponse response = GetPetByIdWithByteArrayWithHttpInfo(petId); + return response.Data; + } + + /// + /// 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 + /// + /// ID of pet that needs to be fetched + /// ApiResponse of byte[] + public ApiResponse< byte[] > GetPetByIdWithByteArrayWithHttpInfo (long? petId) + { + + // verify the required parameter 'petId' is set + if (petId == null) + throw new ApiException(400, "Missing required parameter 'petId' when calling PetApi->GetPetByIdWithByteArray"); + + + var path_ = "/pet/{petId}?testing_byte_array=true"; + + var pathParams = new Dictionary(); + var queryParams = new Dictionary(); + var headerParams = new Dictionary(Configuration.DefaultHeader); + var formParams = new Dictionary(); + var fileParams = new Dictionary(); + Object postBody = null; + + // to determine the Content-Type header + String[] httpContentTypes = new String[] { + + }; + String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes); + + // to determine the Accept header + String[] httpHeaderAccepts = new String[] { + "application/json", "application/xml" + }; + String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAccept != null) + headerParams.Add("Accept", httpHeaderAccept); + + // set "format" to json by default + // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json + pathParams.Add("format", "json"); + if (petId != null) pathParams.Add("petId", Configuration.ApiClient.ParameterToString(petId)); // path parameter + + + + + + + // authentication (api_key) required + + var apiKeyValue = Configuration.GetApiKeyWithPrefix("api_key"); + if (!String.IsNullOrEmpty(apiKeyValue)) + { + headerParams["api_key"] = apiKeyValue; + } + + + // make the HTTP request + IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, + Method.GET, queryParams, postBody, headerParams, formParams, fileParams, + pathParams, httpContentType); + + int statusCode = (int) response.StatusCode; + + if (statusCode >= 400) + throw new ApiException (statusCode, "Error calling GetPetByIdWithByteArray: " + response.Content, response.Content); + else if (statusCode == 0) + throw new ApiException (statusCode, "Error calling GetPetByIdWithByteArray: " + response.ErrorMessage, response.ErrorMessage); + + return new ApiResponse(statusCode, + response.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), + (byte[]) Configuration.ApiClient.Deserialize(response, typeof(byte[]))); + + } + + /// + /// Fake endpoint to test byte array return by 'Find pet by ID' Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + /// + /// ID of pet that needs to be fetched + /// Task of byte[] + public async System.Threading.Tasks.Task GetPetByIdWithByteArrayAsync (long? petId) + { + ApiResponse response = await GetPetByIdWithByteArrayAsyncWithHttpInfo(petId); + return response.Data; + + } + + /// + /// 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 + /// + /// ID of pet that needs to be fetched + /// Task of ApiResponse (byte[]) + public async System.Threading.Tasks.Task> GetPetByIdWithByteArrayAsyncWithHttpInfo (long? petId) + { + // verify the required parameter 'petId' is set + if (petId == null) throw new ApiException(400, "Missing required parameter 'petId' when calling GetPetByIdWithByteArray"); + + + var path_ = "/pet/{petId}?testing_byte_array=true"; + + var pathParams = new Dictionary(); + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + var fileParams = new Dictionary(); + Object postBody = null; + + // to determine the Content-Type header + String[] httpContentTypes = new String[] { + + }; + String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes); + + // to determine the Accept header + String[] httpHeaderAccepts = new String[] { + "application/json", "application/xml" + }; + String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAccept != null) + headerParams.Add("Accept", httpHeaderAccept); + + // set "format" to json by default + // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json + pathParams.Add("format", "json"); + if (petId != null) pathParams.Add("petId", Configuration.ApiClient.ParameterToString(petId)); // path parameter + + + + + + + + // authentication (api_key) required + + var apiKeyValue = Configuration.GetApiKeyWithPrefix("api_key"); + if (!String.IsNullOrEmpty(apiKeyValue)) + { + headerParams["api_key"] = apiKeyValue; + } + + + // make the HTTP request + IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, + Method.GET, queryParams, postBody, headerParams, formParams, fileParams, + pathParams, httpContentType); + + int statusCode = (int) response.StatusCode; + + if (statusCode >= 400) + throw new ApiException (statusCode, "Error calling GetPetByIdWithByteArray: " + response.Content, response.Content); + else if (statusCode == 0) + throw new ApiException (statusCode, "Error calling GetPetByIdWithByteArray: " + response.ErrorMessage, response.ErrorMessage); + + return new ApiResponse(statusCode, + response.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), + (byte[]) Configuration.ApiClient.Deserialize(response, typeof(byte[]))); + + } + + /// + /// Fake endpoint to test byte array in body parameter for adding a new pet to the store + /// + /// Pet object in the form of byte array + /// + public void AddPetUsingByteArray (byte[] body = null) + { + AddPetUsingByteArrayWithHttpInfo(body); + } + + /// + /// Fake endpoint to test byte array in body parameter for adding a new pet to the store + /// + /// Pet object in the form of byte array + /// ApiResponse of Object(void) + public ApiResponse AddPetUsingByteArrayWithHttpInfo (byte[] body = null) + { + + + var path_ = "/pet?testing_byte_array=true"; + + var pathParams = new Dictionary(); + var queryParams = new Dictionary(); + var headerParams = new Dictionary(Configuration.DefaultHeader); + var formParams = new Dictionary(); + var fileParams = new Dictionary(); + Object postBody = null; + + // to determine the Content-Type header + String[] httpContentTypes = new String[] { + "application/json", "application/xml" + }; + String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes); + + // to determine the Accept header + String[] httpHeaderAccepts = new String[] { + "application/json", "application/xml" + }; + String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAccept != null) + headerParams.Add("Accept", httpHeaderAccept); + + // set "format" to json by default + // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json + pathParams.Add("format", "json"); + + + + + if (body.GetType() != typeof(byte[])) + { + postBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter + } + else + { + postBody = body; // byte array + } + + // authentication (petstore_auth) required + + // oauth required + if (!String.IsNullOrEmpty(Configuration.AccessToken)) + { + headerParams["Authorization"] = "Bearer " + Configuration.AccessToken; + } + + + // make the HTTP request + IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, + Method.POST, queryParams, postBody, headerParams, formParams, fileParams, + pathParams, httpContentType); + + int statusCode = (int) response.StatusCode; + + if (statusCode >= 400) + throw new ApiException (statusCode, "Error calling AddPetUsingByteArray: " + response.Content, response.Content); + else if (statusCode == 0) + throw new ApiException (statusCode, "Error calling AddPetUsingByteArray: " + response.ErrorMessage, response.ErrorMessage); + + + return new ApiResponse(statusCode, + response.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), + null); + } + + /// + /// Fake endpoint to test byte array in body parameter for adding a new pet to the store + /// + /// Pet object in the form of byte array + /// Task of void + public async System.Threading.Tasks.Task AddPetUsingByteArrayAsync (byte[] body = null) + { + await AddPetUsingByteArrayAsyncWithHttpInfo(body); + + } + + /// + /// Fake endpoint to test byte array in body parameter for adding a new pet to the store + /// + /// Pet object in the form of byte array + /// Task of ApiResponse + public async System.Threading.Tasks.Task> AddPetUsingByteArrayAsyncWithHttpInfo (byte[] body = null) + { + + + var path_ = "/pet?testing_byte_array=true"; + + var pathParams = new Dictionary(); + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + var fileParams = new Dictionary(); + Object postBody = null; + + // to determine the Content-Type header + String[] httpContentTypes = new String[] { + "application/json", "application/xml" + }; + String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes); + + // to determine the Accept header + String[] httpHeaderAccepts = new String[] { + "application/json", "application/xml" + }; + String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAccept != null) + headerParams.Add("Accept", httpHeaderAccept); + + // set "format" to json by default + // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json + pathParams.Add("format", "json"); + + + + + postBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter + + + + // authentication (petstore_auth) required + + // oauth required + if (!String.IsNullOrEmpty(Configuration.AccessToken)) + { + headerParams["Authorization"] = "Bearer " + Configuration.AccessToken; + } + + + // make the HTTP request + IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, + Method.POST, queryParams, postBody, headerParams, formParams, fileParams, + pathParams, httpContentType); + + int statusCode = (int) response.StatusCode; + + if (statusCode >= 400) + throw new ApiException (statusCode, "Error calling AddPetUsingByteArray: " + response.Content, response.Content); + else if (statusCode == 0) + throw new ApiException (statusCode, "Error calling AddPetUsingByteArray: " + response.ErrorMessage, response.ErrorMessage); + + + return new ApiResponse(statusCode, + response.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), + null); + } + } } diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/StoreApi.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/StoreApi.cs index a9e9d6e9b74..a92876f1a53 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/StoreApi.cs +++ b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/StoreApi.cs @@ -274,15 +274,21 @@ namespace IO.Swagger.Api var headerParams = new Dictionary(Configuration.DefaultHeader); var formParams = new Dictionary(); var fileParams = new Dictionary(); - String postBody = null; + Object postBody = null; + + // to determine the Content-Type header + String[] httpContentTypes = new String[] { + + }; + String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes); // to determine the Accept header - String[] http_header_accepts = new String[] { + String[] httpHeaderAccepts = new String[] { "application/json", "application/xml" }; - String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); - if (http_header_accept != null) - headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); + String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAccept != null) + headerParams.Add("Accept", httpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json @@ -293,7 +299,6 @@ namespace IO.Swagger.Api - // authentication (api_key) required var apiKeyValue = Configuration.GetApiKeyWithPrefix("api_key"); @@ -304,7 +309,9 @@ namespace IO.Swagger.Api // make the HTTP request - IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, + Method.GET, queryParams, postBody, headerParams, formParams, fileParams, + pathParams, httpContentType); int statusCode = (int) response.StatusCode; @@ -345,15 +352,21 @@ namespace IO.Swagger.Api var headerParams = new Dictionary(); var formParams = new Dictionary(); var fileParams = new Dictionary(); - String postBody = null; + Object postBody = null; + + // to determine the Content-Type header + String[] httpContentTypes = new String[] { + + }; + String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes); // to determine the Accept header - String[] http_header_accepts = new String[] { + String[] httpHeaderAccepts = new String[] { "application/json", "application/xml" }; - String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); - if (http_header_accept != null) - headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); + String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAccept != null) + headerParams.Add("Accept", httpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json @@ -375,7 +388,9 @@ namespace IO.Swagger.Api // make the HTTP request - IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, + Method.GET, queryParams, postBody, headerParams, formParams, fileParams, + pathParams, httpContentType); int statusCode = (int) response.StatusCode; @@ -417,15 +432,21 @@ namespace IO.Swagger.Api var headerParams = new Dictionary(Configuration.DefaultHeader); var formParams = new Dictionary(); var fileParams = new Dictionary(); - String postBody = null; + Object postBody = null; + + // to determine the Content-Type header + String[] httpContentTypes = new String[] { + + }; + String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes); // to determine the Accept header - String[] http_header_accepts = new String[] { + String[] httpHeaderAccepts = new String[] { "application/json", "application/xml" }; - String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); - if (http_header_accept != null) - headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); + String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAccept != null) + headerParams.Add("Accept", httpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json @@ -434,13 +455,21 @@ namespace IO.Swagger.Api - postBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter - + if (body.GetType() != typeof(byte[])) + { + postBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter + } + else + { + postBody = body; // byte array + } // make the HTTP request - IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, + Method.POST, queryParams, postBody, headerParams, formParams, fileParams, + pathParams, httpContentType); int statusCode = (int) response.StatusCode; @@ -483,15 +512,21 @@ namespace IO.Swagger.Api var headerParams = new Dictionary(); var formParams = new Dictionary(); var fileParams = new Dictionary(); - String postBody = null; + Object postBody = null; + + // to determine the Content-Type header + String[] httpContentTypes = new String[] { + + }; + String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes); // to determine the Accept header - String[] http_header_accepts = new String[] { + String[] httpHeaderAccepts = new String[] { "application/json", "application/xml" }; - String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); - if (http_header_accept != null) - headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); + String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAccept != null) + headerParams.Add("Accept", httpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json @@ -506,7 +541,9 @@ namespace IO.Swagger.Api // make the HTTP request - IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, + Method.POST, queryParams, postBody, headerParams, formParams, fileParams, + pathParams, httpContentType); int statusCode = (int) response.StatusCode; @@ -541,7 +578,8 @@ namespace IO.Swagger.Api { // verify the required parameter 'orderId' is set - if (orderId == null) throw new ApiException(400, "Missing required parameter 'orderId' when calling GetOrderById"); + if (orderId == null) + throw new ApiException(400, "Missing required parameter 'orderId' when calling StoreApi->GetOrderById"); var path_ = "/store/order/{orderId}"; @@ -551,15 +589,21 @@ namespace IO.Swagger.Api var headerParams = new Dictionary(Configuration.DefaultHeader); var formParams = new Dictionary(); var fileParams = new Dictionary(); - String postBody = null; + Object postBody = null; + + // to determine the Content-Type header + String[] httpContentTypes = new String[] { + + }; + String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes); // to determine the Accept header - String[] http_header_accepts = new String[] { + String[] httpHeaderAccepts = new String[] { "application/json", "application/xml" }; - String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); - if (http_header_accept != null) - headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); + String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAccept != null) + headerParams.Add("Accept", httpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json @@ -574,7 +618,9 @@ namespace IO.Swagger.Api // make the HTTP request - IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, + Method.GET, queryParams, postBody, headerParams, formParams, fileParams, + pathParams, httpContentType); int statusCode = (int) response.StatusCode; @@ -619,15 +665,21 @@ namespace IO.Swagger.Api var headerParams = new Dictionary(); var formParams = new Dictionary(); var fileParams = new Dictionary(); - String postBody = null; + Object postBody = null; + + // to determine the Content-Type header + String[] httpContentTypes = new String[] { + + }; + String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes); // to determine the Accept header - String[] http_header_accepts = new String[] { + String[] httpHeaderAccepts = new String[] { "application/json", "application/xml" }; - String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); - if (http_header_accept != null) - headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); + String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAccept != null) + headerParams.Add("Accept", httpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json @@ -642,7 +694,9 @@ namespace IO.Swagger.Api // make the HTTP request - IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, + Method.GET, queryParams, postBody, headerParams, formParams, fileParams, + pathParams, httpContentType); int statusCode = (int) response.StatusCode; @@ -676,7 +730,8 @@ namespace IO.Swagger.Api { // verify the required parameter 'orderId' is set - if (orderId == null) throw new ApiException(400, "Missing required parameter 'orderId' when calling DeleteOrder"); + if (orderId == null) + throw new ApiException(400, "Missing required parameter 'orderId' when calling StoreApi->DeleteOrder"); var path_ = "/store/order/{orderId}"; @@ -686,15 +741,21 @@ namespace IO.Swagger.Api var headerParams = new Dictionary(Configuration.DefaultHeader); var formParams = new Dictionary(); var fileParams = new Dictionary(); - String postBody = null; + Object postBody = null; + + // to determine the Content-Type header + String[] httpContentTypes = new String[] { + + }; + String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes); // to determine the Accept header - String[] http_header_accepts = new String[] { + String[] httpHeaderAccepts = new String[] { "application/json", "application/xml" }; - String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); - if (http_header_accept != null) - headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); + String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAccept != null) + headerParams.Add("Accept", httpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json @@ -709,7 +770,9 @@ namespace IO.Swagger.Api // make the HTTP request - IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, Method.DELETE, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, + Method.DELETE, queryParams, postBody, headerParams, formParams, fileParams, + pathParams, httpContentType); int statusCode = (int) response.StatusCode; @@ -753,15 +816,21 @@ namespace IO.Swagger.Api var headerParams = new Dictionary(); var formParams = new Dictionary(); var fileParams = new Dictionary(); - String postBody = null; + Object postBody = null; + + // to determine the Content-Type header + String[] httpContentTypes = new String[] { + + }; + String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes); // to determine the Accept header - String[] http_header_accepts = new String[] { + String[] httpHeaderAccepts = new String[] { "application/json", "application/xml" }; - String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); - if (http_header_accept != null) - headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); + String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAccept != null) + headerParams.Add("Accept", httpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json @@ -776,7 +845,9 @@ namespace IO.Swagger.Api // make the HTTP request - IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, Method.DELETE, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, + Method.DELETE, queryParams, postBody, headerParams, formParams, fileParams, + pathParams, httpContentType); int statusCode = (int) response.StatusCode; diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/UserApi.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/UserApi.cs index 5502fe15da1..0b9e633c5f3 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/UserApi.cs +++ b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/UserApi.cs @@ -443,15 +443,21 @@ namespace IO.Swagger.Api var headerParams = new Dictionary(Configuration.DefaultHeader); var formParams = new Dictionary(); var fileParams = new Dictionary(); - String postBody = null; + Object postBody = null; + + // to determine the Content-Type header + String[] httpContentTypes = new String[] { + + }; + String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes); // to determine the Accept header - String[] http_header_accepts = new String[] { + String[] httpHeaderAccepts = new String[] { "application/json", "application/xml" }; - String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); - if (http_header_accept != null) - headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); + String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAccept != null) + headerParams.Add("Accept", httpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json @@ -460,13 +466,21 @@ namespace IO.Swagger.Api - postBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter - + if (body.GetType() != typeof(byte[])) + { + postBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter + } + else + { + postBody = body; // byte array + } // make the HTTP request - IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, + Method.POST, queryParams, postBody, headerParams, formParams, fileParams, + pathParams, httpContentType); int statusCode = (int) response.StatusCode; @@ -508,15 +522,21 @@ namespace IO.Swagger.Api var headerParams = new Dictionary(); var formParams = new Dictionary(); var fileParams = new Dictionary(); - String postBody = null; + Object postBody = null; + + // to determine the Content-Type header + String[] httpContentTypes = new String[] { + + }; + String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes); // to determine the Accept header - String[] http_header_accepts = new String[] { + String[] httpHeaderAccepts = new String[] { "application/json", "application/xml" }; - String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); - if (http_header_accept != null) - headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); + String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAccept != null) + headerParams.Add("Accept", httpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json @@ -531,7 +551,9 @@ namespace IO.Swagger.Api // make the HTTP request - IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, + Method.POST, queryParams, postBody, headerParams, formParams, fileParams, + pathParams, httpContentType); int statusCode = (int) response.StatusCode; @@ -572,15 +594,21 @@ namespace IO.Swagger.Api var headerParams = new Dictionary(Configuration.DefaultHeader); var formParams = new Dictionary(); var fileParams = new Dictionary(); - String postBody = null; + Object postBody = null; + + // to determine the Content-Type header + String[] httpContentTypes = new String[] { + + }; + String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes); // to determine the Accept header - String[] http_header_accepts = new String[] { + String[] httpHeaderAccepts = new String[] { "application/json", "application/xml" }; - String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); - if (http_header_accept != null) - headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); + String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAccept != null) + headerParams.Add("Accept", httpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json @@ -589,13 +617,21 @@ namespace IO.Swagger.Api - postBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter - + if (body.GetType() != typeof(byte[])) + { + postBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter + } + else + { + postBody = body; // byte array + } // make the HTTP request - IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, + Method.POST, queryParams, postBody, headerParams, formParams, fileParams, + pathParams, httpContentType); int statusCode = (int) response.StatusCode; @@ -637,15 +673,21 @@ namespace IO.Swagger.Api var headerParams = new Dictionary(); var formParams = new Dictionary(); var fileParams = new Dictionary(); - String postBody = null; + Object postBody = null; + + // to determine the Content-Type header + String[] httpContentTypes = new String[] { + + }; + String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes); // to determine the Accept header - String[] http_header_accepts = new String[] { + String[] httpHeaderAccepts = new String[] { "application/json", "application/xml" }; - String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); - if (http_header_accept != null) - headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); + String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAccept != null) + headerParams.Add("Accept", httpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json @@ -660,7 +702,9 @@ namespace IO.Swagger.Api // make the HTTP request - IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, + Method.POST, queryParams, postBody, headerParams, formParams, fileParams, + pathParams, httpContentType); int statusCode = (int) response.StatusCode; @@ -701,15 +745,21 @@ namespace IO.Swagger.Api var headerParams = new Dictionary(Configuration.DefaultHeader); var formParams = new Dictionary(); var fileParams = new Dictionary(); - String postBody = null; + Object postBody = null; + + // to determine the Content-Type header + String[] httpContentTypes = new String[] { + + }; + String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes); // to determine the Accept header - String[] http_header_accepts = new String[] { + String[] httpHeaderAccepts = new String[] { "application/json", "application/xml" }; - String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); - if (http_header_accept != null) - headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); + String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAccept != null) + headerParams.Add("Accept", httpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json @@ -718,13 +768,21 @@ namespace IO.Swagger.Api - postBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter - + if (body.GetType() != typeof(byte[])) + { + postBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter + } + else + { + postBody = body; // byte array + } // make the HTTP request - IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, + Method.POST, queryParams, postBody, headerParams, formParams, fileParams, + pathParams, httpContentType); int statusCode = (int) response.StatusCode; @@ -766,15 +824,21 @@ namespace IO.Swagger.Api var headerParams = new Dictionary(); var formParams = new Dictionary(); var fileParams = new Dictionary(); - String postBody = null; + Object postBody = null; + + // to determine the Content-Type header + String[] httpContentTypes = new String[] { + + }; + String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes); // to determine the Accept header - String[] http_header_accepts = new String[] { + String[] httpHeaderAccepts = new String[] { "application/json", "application/xml" }; - String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); - if (http_header_accept != null) - headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); + String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAccept != null) + headerParams.Add("Accept", httpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json @@ -789,7 +853,9 @@ namespace IO.Swagger.Api // make the HTTP request - IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, + Method.POST, queryParams, postBody, headerParams, formParams, fileParams, + pathParams, httpContentType); int statusCode = (int) response.StatusCode; @@ -833,15 +899,21 @@ namespace IO.Swagger.Api var headerParams = new Dictionary(Configuration.DefaultHeader); var formParams = new Dictionary(); var fileParams = new Dictionary(); - String postBody = null; + Object postBody = null; + + // to determine the Content-Type header + String[] httpContentTypes = new String[] { + + }; + String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes); // to determine the Accept header - String[] http_header_accepts = new String[] { + String[] httpHeaderAccepts = new String[] { "application/json", "application/xml" }; - String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); - if (http_header_accept != null) - headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); + String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAccept != null) + headerParams.Add("Accept", httpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json @@ -857,7 +929,9 @@ namespace IO.Swagger.Api // make the HTTP request - IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, + Method.GET, queryParams, postBody, headerParams, formParams, fileParams, + pathParams, httpContentType); int statusCode = (int) response.StatusCode; @@ -902,15 +976,21 @@ namespace IO.Swagger.Api var headerParams = new Dictionary(); var formParams = new Dictionary(); var fileParams = new Dictionary(); - String postBody = null; + Object postBody = null; + + // to determine the Content-Type header + String[] httpContentTypes = new String[] { + + }; + String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes); // to determine the Accept header - String[] http_header_accepts = new String[] { + String[] httpHeaderAccepts = new String[] { "application/json", "application/xml" }; - String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); - if (http_header_accept != null) - headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); + String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAccept != null) + headerParams.Add("Accept", httpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json @@ -926,7 +1006,9 @@ namespace IO.Swagger.Api // make the HTTP request - IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, + Method.GET, queryParams, postBody, headerParams, formParams, fileParams, + pathParams, httpContentType); int statusCode = (int) response.StatusCode; @@ -965,15 +1047,21 @@ namespace IO.Swagger.Api var headerParams = new Dictionary(Configuration.DefaultHeader); var formParams = new Dictionary(); var fileParams = new Dictionary(); - String postBody = null; + Object postBody = null; + + // to determine the Content-Type header + String[] httpContentTypes = new String[] { + + }; + String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes); // to determine the Accept header - String[] http_header_accepts = new String[] { + String[] httpHeaderAccepts = new String[] { "application/json", "application/xml" }; - String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); - if (http_header_accept != null) - headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); + String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAccept != null) + headerParams.Add("Accept", httpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json @@ -987,7 +1075,9 @@ namespace IO.Swagger.Api // make the HTTP request - IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, + Method.GET, queryParams, postBody, headerParams, formParams, fileParams, + pathParams, httpContentType); int statusCode = (int) response.StatusCode; @@ -1027,15 +1117,21 @@ namespace IO.Swagger.Api var headerParams = new Dictionary(); var formParams = new Dictionary(); var fileParams = new Dictionary(); - String postBody = null; + Object postBody = null; + + // to determine the Content-Type header + String[] httpContentTypes = new String[] { + + }; + String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes); // to determine the Accept header - String[] http_header_accepts = new String[] { + String[] httpHeaderAccepts = new String[] { "application/json", "application/xml" }; - String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); - if (http_header_accept != null) - headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); + String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAccept != null) + headerParams.Add("Accept", httpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json @@ -1049,7 +1145,9 @@ namespace IO.Swagger.Api // make the HTTP request - IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, + Method.GET, queryParams, postBody, headerParams, formParams, fileParams, + pathParams, httpContentType); int statusCode = (int) response.StatusCode; @@ -1084,7 +1182,8 @@ namespace IO.Swagger.Api { // verify the required parameter 'username' is set - if (username == null) throw new ApiException(400, "Missing required parameter 'username' when calling GetUserByName"); + if (username == null) + throw new ApiException(400, "Missing required parameter 'username' when calling UserApi->GetUserByName"); var path_ = "/user/{username}"; @@ -1094,15 +1193,21 @@ namespace IO.Swagger.Api var headerParams = new Dictionary(Configuration.DefaultHeader); var formParams = new Dictionary(); var fileParams = new Dictionary(); - String postBody = null; + Object postBody = null; + + // to determine the Content-Type header + String[] httpContentTypes = new String[] { + + }; + String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes); // to determine the Accept header - String[] http_header_accepts = new String[] { + String[] httpHeaderAccepts = new String[] { "application/json", "application/xml" }; - String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); - if (http_header_accept != null) - headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); + String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAccept != null) + headerParams.Add("Accept", httpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json @@ -1117,7 +1222,9 @@ namespace IO.Swagger.Api // make the HTTP request - IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, + Method.GET, queryParams, postBody, headerParams, formParams, fileParams, + pathParams, httpContentType); int statusCode = (int) response.StatusCode; @@ -1162,15 +1269,21 @@ namespace IO.Swagger.Api var headerParams = new Dictionary(); var formParams = new Dictionary(); var fileParams = new Dictionary(); - String postBody = null; + Object postBody = null; + + // to determine the Content-Type header + String[] httpContentTypes = new String[] { + + }; + String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes); // to determine the Accept header - String[] http_header_accepts = new String[] { + String[] httpHeaderAccepts = new String[] { "application/json", "application/xml" }; - String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); - if (http_header_accept != null) - headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); + String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAccept != null) + headerParams.Add("Accept", httpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json @@ -1185,7 +1298,9 @@ namespace IO.Swagger.Api // make the HTTP request - IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, + Method.GET, queryParams, postBody, headerParams, formParams, fileParams, + pathParams, httpContentType); int statusCode = (int) response.StatusCode; @@ -1221,7 +1336,8 @@ namespace IO.Swagger.Api { // verify the required parameter 'username' is set - if (username == null) throw new ApiException(400, "Missing required parameter 'username' when calling UpdateUser"); + if (username == null) + throw new ApiException(400, "Missing required parameter 'username' when calling UserApi->UpdateUser"); var path_ = "/user/{username}"; @@ -1231,15 +1347,21 @@ namespace IO.Swagger.Api var headerParams = new Dictionary(Configuration.DefaultHeader); var formParams = new Dictionary(); var fileParams = new Dictionary(); - String postBody = null; + Object postBody = null; + + // to determine the Content-Type header + String[] httpContentTypes = new String[] { + + }; + String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes); // to determine the Accept header - String[] http_header_accepts = new String[] { + String[] httpHeaderAccepts = new String[] { "application/json", "application/xml" }; - String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); - if (http_header_accept != null) - headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); + String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAccept != null) + headerParams.Add("Accept", httpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json @@ -1249,13 +1371,21 @@ namespace IO.Swagger.Api - postBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter - + if (body.GetType() != typeof(byte[])) + { + postBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter + } + else + { + postBody = body; // byte array + } // make the HTTP request - IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, Method.PUT, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, + Method.PUT, queryParams, postBody, headerParams, formParams, fileParams, + pathParams, httpContentType); int statusCode = (int) response.StatusCode; @@ -1301,15 +1431,21 @@ namespace IO.Swagger.Api var headerParams = new Dictionary(); var formParams = new Dictionary(); var fileParams = new Dictionary(); - String postBody = null; + Object postBody = null; + + // to determine the Content-Type header + String[] httpContentTypes = new String[] { + + }; + String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes); // to determine the Accept header - String[] http_header_accepts = new String[] { + String[] httpHeaderAccepts = new String[] { "application/json", "application/xml" }; - String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); - if (http_header_accept != null) - headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); + String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAccept != null) + headerParams.Add("Accept", httpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json @@ -1325,7 +1461,9 @@ namespace IO.Swagger.Api // make the HTTP request - IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, Method.PUT, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, + Method.PUT, queryParams, postBody, headerParams, formParams, fileParams, + pathParams, httpContentType); int statusCode = (int) response.StatusCode; @@ -1359,7 +1497,8 @@ namespace IO.Swagger.Api { // verify the required parameter 'username' is set - if (username == null) throw new ApiException(400, "Missing required parameter 'username' when calling DeleteUser"); + if (username == null) + throw new ApiException(400, "Missing required parameter 'username' when calling UserApi->DeleteUser"); var path_ = "/user/{username}"; @@ -1369,15 +1508,21 @@ namespace IO.Swagger.Api var headerParams = new Dictionary(Configuration.DefaultHeader); var formParams = new Dictionary(); var fileParams = new Dictionary(); - String postBody = null; + Object postBody = null; + + // to determine the Content-Type header + String[] httpContentTypes = new String[] { + + }; + String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes); // to determine the Accept header - String[] http_header_accepts = new String[] { + String[] httpHeaderAccepts = new String[] { "application/json", "application/xml" }; - String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); - if (http_header_accept != null) - headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); + String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAccept != null) + headerParams.Add("Accept", httpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json @@ -1392,7 +1537,9 @@ namespace IO.Swagger.Api // make the HTTP request - IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, Method.DELETE, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, + Method.DELETE, queryParams, postBody, headerParams, formParams, fileParams, + pathParams, httpContentType); int statusCode = (int) response.StatusCode; @@ -1436,15 +1583,21 @@ namespace IO.Swagger.Api var headerParams = new Dictionary(); var formParams = new Dictionary(); var fileParams = new Dictionary(); - String postBody = null; + Object postBody = null; + + // to determine the Content-Type header + String[] httpContentTypes = new String[] { + + }; + String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes); // to determine the Accept header - String[] http_header_accepts = new String[] { + String[] httpHeaderAccepts = new String[] { "application/json", "application/xml" }; - String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); - if (http_header_accept != null) - headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); + String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAccept != null) + headerParams.Add("Accept", httpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json @@ -1459,7 +1612,9 @@ namespace IO.Swagger.Api // make the HTTP request - IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, Method.DELETE, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, + Method.DELETE, queryParams, postBody, headerParams, formParams, fileParams, + pathParams, httpContentType); int statusCode = (int) response.StatusCode; diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Client/ApiClient.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Client/ApiClient.cs index 7e6807f16a4..ab115aba980 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Client/ApiClient.cs +++ b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Client/ApiClient.cs @@ -77,9 +77,10 @@ namespace IO.Swagger.Client // Creates and sets up a RestRequest prior to a call. private RestRequest PrepareRequest( - String path, RestSharp.Method method, Dictionary queryParams, String postBody, + String path, RestSharp.Method method, Dictionary queryParams, Object postBody, Dictionary headerParams, Dictionary formParams, - Dictionary fileParams, Dictionary pathParams) + Dictionary fileParams, Dictionary pathParams, + String contentType) { var request = new RestRequest(path, method); @@ -103,8 +104,17 @@ namespace IO.Swagger.Client foreach(var param in fileParams) request.AddFile(param.Value.Name, param.Value.Writer, param.Value.FileName, param.Value.ContentType); - if (postBody != null) // http body (model) parameter - request.AddParameter("application/json", postBody, ParameterType.RequestBody); + if (postBody != null) // http body (model or byte[]) parameter + { + if (postBody.GetType() == typeof(String)) + { + request.AddParameter("application/json", postBody, ParameterType.RequestBody); + } + else if (postBody.GetType() == typeof(byte[])) + { + request.AddParameter(contentType, postBody, ParameterType.RequestBody); + } + } return request; } @@ -120,14 +130,18 @@ namespace IO.Swagger.Client /// Form parameters. /// File parameters. /// Path parameters. + /// Content Type of the request /// Object public Object CallApi( - String path, RestSharp.Method method, Dictionary queryParams, String postBody, + String path, RestSharp.Method method, Dictionary queryParams, Object postBody, Dictionary headerParams, Dictionary formParams, - Dictionary fileParams, Dictionary pathParams) + Dictionary fileParams, Dictionary pathParams, + String contentType) { var request = PrepareRequest( - path, method, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + path, method, queryParams, postBody, headerParams, formParams, fileParams, + pathParams, contentType); + var response = RestClient.Execute(request); return (Object) response; } @@ -143,14 +157,17 @@ namespace IO.Swagger.Client /// Form parameters. /// File parameters. /// Path parameters. + /// Content type. /// The Task instance. public async System.Threading.Tasks.Task CallApiAsync( - String path, RestSharp.Method method, Dictionary queryParams, String postBody, + String path, RestSharp.Method method, Dictionary queryParams, Object postBody, Dictionary headerParams, Dictionary formParams, - Dictionary fileParams, Dictionary pathParams) + Dictionary fileParams, Dictionary pathParams, + String contentType) { var request = PrepareRequest( - path, method, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + path, method, queryParams, postBody, headerParams, formParams, fileParams, + pathParams, contentType); var response = await RestClient.ExecuteTaskAsync(request); return (Object)response; } @@ -194,6 +211,12 @@ namespace IO.Swagger.Client // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 // For example: 2009-06-15T13:45:30.0000000 return ((DateTime)obj).ToString (Configuration.DateTimeFormat); + else if (obj is DateTimeOffset) + // Return a formatted date string - Can be customized with Configuration.DateTimeFormat + // Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o") + // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 + // For example: 2009-06-15T13:45:30.0000000 + return ((DateTimeOffset)obj).ToString (Configuration.DateTimeFormat); else if (obj is IList) { var flattenedString = new StringBuilder(); @@ -224,6 +247,10 @@ namespace IO.Swagger.Client { return content; } + else if (type == typeof(byte[])) // return byte array + { + return data; + } if (type == typeof(Stream)) { @@ -270,11 +297,11 @@ namespace IO.Swagger.Client } /// - /// Serialize an object into JSON string. + /// Serialize an input (model) into JSON string /// /// Object. /// JSON string. - public string Serialize(object obj) + public String Serialize(object obj) { try { @@ -286,6 +313,24 @@ namespace IO.Swagger.Client } } + /// + /// Select the Content-Type header's value from the given content-type array: + /// if JSON exists in the given array, use it; + /// otherwise use the first one defined in 'consumes' + /// + /// The Content-Type array to select from. + /// The Content-Type header to use. + public String SelectHeaderContentType(String[] contentTypes) + { + if (contentTypes.Length == 0) + return null; + + if (contentTypes.Contains("application/json", StringComparer.OrdinalIgnoreCase)) + return "application/json"; + + return contentTypes[0]; // use the first content type specified in 'consumes' + } + /// /// Select the Accept header's value from the given accepts array: /// if JSON exists in the given array, use it; diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Client/ApiResponse.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Client/ApiResponse.cs index 15735711656..651d3609c22 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Client/ApiResponse.cs +++ b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Client/ApiResponse.cs @@ -27,10 +27,10 @@ namespace IO.Swagger.Client public T Data { get; private set; } /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// /// HTTP status code. - /// Error message. + /// HTTP headers. /// Data (parsed HTTP body) public ApiResponse(int statusCode, IDictionary headers, T data) { diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Client/Configuration.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Client/Configuration.cs index 000b8893cdf..7ea30009c9c 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Client/Configuration.cs +++ b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Client/Configuration.cs @@ -24,6 +24,7 @@ namespace IO.Swagger.Client /// Dictionary of API key prefix /// Temp folder path /// DateTime format string + /// HTTP connection timeout (in milliseconds) public Configuration(ApiClient apiClient = null, Dictionary defaultHeader = null, string username = null, diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Category.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Category.cs index 6ad53e05257..85694bc93c8 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Category.cs +++ b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Category.cs @@ -78,7 +78,7 @@ namespace IO.Swagger.Model /// /// Returns true if Category instances are equal /// - /// Instance of Category to be compared + /// Instance of Category to be compared /// Boolean public bool Equals(Category other) { diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Order.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Order.cs index eb649ccf587..5a110929b20 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Order.cs +++ b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Order.cs @@ -111,7 +111,7 @@ namespace IO.Swagger.Model /// /// Returns true if Order instances are equal /// - /// Instance of Order to be compared + /// Instance of Order to be compared /// Boolean public bool Equals(Order other) { diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Pet.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Pet.cs index 202a171c219..ec3b3d5ca13 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Pet.cs +++ b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Pet.cs @@ -111,7 +111,7 @@ namespace IO.Swagger.Model /// /// Returns true if Pet instances are equal /// - /// Instance of Pet to be compared + /// Instance of Pet to be compared /// Boolean public bool Equals(Pet other) { diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Tag.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Tag.cs index 4aa4a9c97f0..078a53ad1ea 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Tag.cs +++ b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Tag.cs @@ -78,7 +78,7 @@ namespace IO.Swagger.Model /// /// Returns true if Tag instances are equal /// - /// Instance of Tag to be compared + /// Instance of Tag to be compared /// Boolean public bool Equals(Tag other) { diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/User.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/User.cs index 5785a3d3509..7f0b3b858aa 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/User.cs +++ b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/User.cs @@ -127,7 +127,7 @@ namespace IO.Swagger.Model /// /// Returns true if User instances are equal /// - /// Instance of User to be compared + /// Instance of User to be compared /// Boolean public bool Equals(User other) { diff --git a/samples/client/petstore/csharp/SwaggerClientTest/SwaggerClientTest.userprefs b/samples/client/petstore/csharp/SwaggerClientTest/SwaggerClientTest.userprefs index a5ad5d531bd..34b1a516f28 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/SwaggerClientTest.userprefs +++ b/samples/client/petstore/csharp/SwaggerClientTest/SwaggerClientTest.userprefs @@ -1,14 +1,25 @@  - + - - - + + + + + + + + + + + + + + - \ No newline at end of file + diff --git a/samples/client/petstore/csharp/SwaggerClientTest/TestApiClient.cs b/samples/client/petstore/csharp/SwaggerClientTest/TestApiClient.cs index f0232c330f0..6eb32a38442 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/TestApiClient.cs +++ b/samples/client/petstore/csharp/SwaggerClientTest/TestApiClient.cs @@ -14,6 +14,26 @@ namespace SwaggerClientTest.TestApiClient Configuration.Default.DateTimeFormat = "o"; } + /// + /// Test SelectHeaderContentType + /// + [Test ()] + public void TestSelectHeaderContentType () + { + ApiClient api = new ApiClient (); + String[] contentTypes = new String[] { "application/json", "application/xml" }; + Assert.AreEqual("application/json", api.SelectHeaderContentType (contentTypes)); + + contentTypes = new String[] { "application/xml" }; + Assert.AreEqual("application/xml", api.SelectHeaderContentType (contentTypes)); + + contentTypes = new String[] {}; + Assert.IsNull(api.SelectHeaderContentType (contentTypes)); + } + + /// + /// Test ParameterToString + /// [Test ()] public void TestParameterToString () { @@ -48,7 +68,7 @@ namespace SwaggerClientTest.TestApiClient { ApiClient api = new ApiClient (); // test datetime with a time zone - DateTime dateWithTz = DateTime.Parse("2008-04-10T13:30:00.0000000-04:00", null, System.Globalization.DateTimeStyles.RoundtripKind); + DateTimeOffset dateWithTz = DateTimeOffset.Parse("2008-04-10T13:30:00.0000000-04:00", null, System.Globalization.DateTimeStyles.RoundtripKind); Assert.AreEqual("2008-04-10T13:30:00.0000000-04:00", api.ParameterToString(dateWithTz)); } diff --git a/samples/client/petstore/csharp/SwaggerClientTest/TestPet.cs b/samples/client/petstore/csharp/SwaggerClientTest/TestPet.cs index fbbf4494951..001b052bf76 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/TestPet.cs +++ b/samples/client/petstore/csharp/SwaggerClientTest/TestPet.cs @@ -15,7 +15,10 @@ namespace SwaggerClientTest.TestPet { public long petId = 11088; - [SetUp] public void Init() + /// + /// Create a Pet object + /// + private Pet createPet() { // create pet Pet p = new Pet(); @@ -36,6 +39,24 @@ namespace SwaggerClientTest.TestPet p.Category = category; p.PhotoUrls = photoUrls; + return p; + } + + /// + /// Convert string to byte array + /// + private byte[] GetBytes(string str) + { + byte[] bytes = new byte[str.Length * sizeof(char)]; + System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length); + return bytes; + } + + [SetUp] public void Init() + { + // create pet + Pet p = createPet(); + // add pet before testing PetApi petApi = new PetApi("http://petstore.swagger.io/v2/"); petApi.AddPet (p); @@ -137,6 +158,35 @@ namespace SwaggerClientTest.TestPet } + /// + /// Test GetPetByIdWithByteArray + /// + [Test ()] + public void TestGetPetByIdWithByteArray () + { + // set timeout to 10 seconds + Configuration c1 = new Configuration (timeout: 10000); + + PetApi petApi = new PetApi (c1); + byte[] response = petApi.GetPetByIdWithByteArray (petId); + Assert.IsInstanceOf (response, "Response is byte array"); + } + + /// + /// Test AddPetUsingByteArray + /// + [Test ()] + public void TestAddPetUsingByteArray () + { + // set timeout to 10 seconds + Configuration c1 = new Configuration (timeout: 10000); + + PetApi petApi = new PetApi (c1); + Pet p = createPet (); + byte[] petByteArray = GetBytes ((string)petApi.Configuration.ApiClient.Serialize (p)); + petApi.AddPetUsingByteArray (petByteArray); + } + /// /// Test UpdatePetWithForm /// diff --git a/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.dll.mdb b/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.dll.mdb deleted file mode 100644 index d4c01b5c42a..00000000000 Binary files a/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.dll.mdb and /dev/null differ 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 057dcd7d72d..581eafa51ca 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,12 +41,14 @@ 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-01-05T14:39:16.440+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-08T18:50:38.131+08:00") public class ApiClient { - private Map hostMap = new HashMap(); private Map defaultHeaderMap = new HashMap(); - private boolean debugging = false; private String basePath = "http://petstore.swagger.io/v2"; + private boolean debugging = false; + private int connectionTimeout = 0; + + private Client httpClient; private ObjectMapper mapper; private Map authentications; @@ -64,7 +66,9 @@ public class ApiClient { mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING); mapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING); mapper.registerModule(new JodaModule()); - + + httpClient = buildHttpClient(debugging); + // Use RFC3339 format for date and datetime. // See http://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14 this.dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); @@ -79,8 +83,8 @@ public class ApiClient { // Setup authentications (key: authentication name, value: authentication). authentications = new HashMap(); - authentications.put("api_key", new ApiKeyAuth("header", "api_key")); authentications.put("petstore_auth", new OAuth()); + authentications.put("api_key", new ApiKeyAuth("header", "api_key")); // Prevent the authentications from being modified. authentications = Collections.unmodifiableMap(authentications); } @@ -223,9 +227,29 @@ public class ApiClient { */ public ApiClient setDebugging(boolean debugging) { this.debugging = debugging; + // Rebuild HTTP Client according to the new "debugging" value. + this.httpClient = buildHttpClient(debugging); return this; } + /** + * Connect timeout (in milliseconds). + */ + public int getConnectTimeout() { + return connectionTimeout; + } + + /** + * Set the connect timeout (in milliseconds). + * A value of 0 means no timeout, otherwise values must be between 1 and + * {@link Integer#MAX_VALUE}. + */ + public ApiClient setConnectTimeout(int connectionTimeout) { + this.connectionTimeout = connectionTimeout; + httpClient.setConnectTimeout(connectionTimeout); + return this; + } + /** * Get the date format used to parse/format date parameters. */ @@ -435,8 +459,6 @@ public class ApiClient { updateParamsForAuth(authNames, queryParams, headerParams); - Client client = getClient(); - StringBuilder b = new StringBuilder(); b.append("?"); if (queryParams != null){ @@ -454,9 +476,9 @@ public class ApiClient { Builder builder; if (accept == null) - builder = client.resource(basePath + path + querystring).getRequestBuilder(); + builder = httpClient.resource(basePath + path + querystring).getRequestBuilder(); else - builder = client.resource(basePath + path + querystring).accept(accept); + builder = httpClient.resource(basePath + path + querystring).accept(accept); for (String key : headerParams.keySet()) { builder = builder.header(key, headerParams.get(key)); @@ -570,19 +592,17 @@ public class ApiClient { } /** - * Get an existing client or create a new client to handle HTTP request. + * Build the Client used to make HTTP requests. */ - private Client getClient() { - if(!hostMap.containsKey(basePath)) { - // Add the JSON serialization support to Jersey - JacksonJsonProvider jsonProvider = new JacksonJsonProvider(mapper); - DefaultClientConfig conf = new DefaultClientConfig(); - conf.getSingletons().add(jsonProvider); - Client client = Client.create(conf); - if (debugging) - client.addFilter(new LoggingFilter()); - hostMap.put(basePath, client); + private Client buildHttpClient(boolean debugging) { + // Add the JSON serialization support to Jersey + JacksonJsonProvider jsonProvider = new JacksonJsonProvider(mapper); + DefaultClientConfig conf = new DefaultClientConfig(); + conf.getSingletons().add(jsonProvider); + Client client = Client.create(conf); + if (debugging) { + client.addFilter(new LoggingFilter()); } - return hostMap.get(basePath); + return client; } } diff --git a/samples/client/petstore/java/feign/pom.xml b/samples/client/petstore/java/feign/pom.xml index 5f7e9551862..d7ad6ee49b9 100644 --- a/samples/client/petstore/java/feign/pom.xml +++ b/samples/client/petstore/java/feign/pom.xml @@ -164,6 +164,12 @@ 2.2 + + org.apache.oltu.oauth2 + org.apache.oltu.oauth2.client + ${oltu-version} + + junit @@ -179,5 +185,6 @@ 2.5 4.12 1.0.0 + 1.0.0 diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/ApiClient.java index a2959f6ef9f..2e032a9d1d1 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 @@ -1,24 +1,102 @@ package io.swagger.client; +import java.util.LinkedHashMap; +import java.util.Map; + +import org.apache.oltu.oauth2.client.request.OAuthClientRequest.AuthenticationRequestBuilder; +import org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuilder; + import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; + import feign.Feign; +import feign.RequestInterceptor; import feign.jackson.JacksonDecoder; import feign.jackson.JacksonEncoder; 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-01-05T14:39:18.888+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-11T21:48:33.457Z") public class ApiClient { public interface Api {} private ObjectMapper objectMapper; private String basePath = "http://petstore.swagger.io/v2"; + private Map apiAuthorizations; + private Feign.Builder feignBuilder; public ApiClient() { objectMapper = createObjectMapper(); + apiAuthorizations = new LinkedHashMap(); + feignBuilder = Feign.builder() + .encoder(new FormAwareEncoder(new JacksonEncoder(objectMapper))) + .decoder(new JacksonDecoder(objectMapper)) + .logger(new Slf4jLogger()); } + public ApiClient(String[] authNames) { + this(); + for(String authName : authNames) { + RequestInterceptor auth; + if (authName == "petstore_auth") { + auth = new OAuth(OAuthFlow.implicit, "http://petstore.swagger.io/api/oauth/dialog", "", "write:pets, read:pets"); + } else if (authName == "api_key") { + auth = new ApiKeyAuth("header", "api_key"); + } else { + throw new RuntimeException("auth name \"" + authName + "\" not found in available auth names"); + } + addAuthorization(authName, auth); + } + } + + /** + * Basic constructor for single auth name + * @param authName + */ + public ApiClient(String authName) { + this(new String[]{authName}); + } + + /** + * Helper constructor for single api key + * @param authName + * @param apiKey + */ + public ApiClient(String authName, String apiKey) { + this(authName); + this.setApiKey(apiKey); + } + + /** + * Helper constructor for single basic auth or password oauth2 + * @param authName + * @param username + * @param password + */ + public ApiClient(String authName, String username, String password) { + this(authName); + this.setCredentials(username, password); + } + + /** + * Helper constructor for single password oauth2 + * @param authName + * @param clientId + * @param secret + * @param username + * @param password + */ + public ApiClient(String authName, String clientId, String secret, String username, String password) { + this(authName); + this.getTokenEndPoint() + .setClientId(clientId) + .setClientSecret(secret) + .setUsername(username) + .setPassword(password); + } + public String getBasePath() { return basePath; } @@ -28,6 +106,23 @@ public class ApiClient { return this; } + public Map getApiAuthorizations() { + return apiAuthorizations; + } + + public void setApiAuthorizations(Map apiAuthorizations) { + this.apiAuthorizations = apiAuthorizations; + } + + public Feign.Builder getFeignBuilder() { + return feignBuilder; + } + + public ApiClient setFeignBuilder(Feign.Builder feignBuilder) { + this.feignBuilder = feignBuilder; + return this; + } + private ObjectMapper createObjectMapper() { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING); @@ -45,13 +140,7 @@ public class ApiClient { * XYZResponse response = api.someMethod(...); */ public T buildClient(Class clientClass) { - return Feign.builder() - .encoder(new FormAwareEncoder(new JacksonEncoder(objectMapper))) - .decoder(new JacksonDecoder(objectMapper)) -// enable for basic auth: -// .requestInterceptor(new feign.auth.BasicAuthRequestInterceptor(username, password)) - .logger(new Slf4jLogger()) - .target(clientClass, basePath); + return feignBuilder.target(clientClass, basePath); } /** @@ -83,4 +172,137 @@ public class ApiClient { if (StringUtil.containsIgnoreCase(contentTypes, "application/json")) return "application/json"; return contentTypes[0]; } + + /** + * Helper method to configure the first api key found + * @param apiKey + */ + public void setApiKey(String apiKey) { + for(RequestInterceptor apiAuthorization : apiAuthorizations.values()) { + if (apiAuthorization instanceof ApiKeyAuth) { + ApiKeyAuth keyAuth = (ApiKeyAuth) apiAuthorization; + keyAuth.setApiKey(apiKey); + return ; + } + } + throw new RuntimeException("No API key authentication configured!"); + } + + /** + * Helper method to configure the username/password for basic auth or password OAuth + * @param username + * @param password + */ + public void setCredentials(String username, String password) { + for(RequestInterceptor apiAuthorization : apiAuthorizations.values()) { + if (apiAuthorization instanceof HttpBasicAuth) { + HttpBasicAuth basicAuth = (HttpBasicAuth) apiAuthorization; + basicAuth.setCredentials(username, password); + return; + } + if (apiAuthorization instanceof OAuth) { + OAuth oauth = (OAuth) apiAuthorization; + oauth.getTokenRequestBuilder().setUsername(username).setPassword(password); + return; + } + } + throw new RuntimeException("No Basic authentication or OAuth configured!"); + } + + /** + * Helper method to configure the token endpoint of the first oauth found in the apiAuthorizations (there should be only one) + * @return + */ + public TokenRequestBuilder getTokenEndPoint() { + for(RequestInterceptor apiAuthorization : apiAuthorizations.values()) { + if (apiAuthorization instanceof OAuth) { + OAuth oauth = (OAuth) apiAuthorization; + return oauth.getTokenRequestBuilder(); + } + } + return null; + } + + /** + * Helper method to configure authorization endpoint of the first oauth found in the apiAuthorizations (there should be only one) + * @return + */ + public AuthenticationRequestBuilder getAuthorizationEndPoint() { + for(RequestInterceptor apiAuthorization : apiAuthorizations.values()) { + if (apiAuthorization instanceof OAuth) { + OAuth oauth = (OAuth) apiAuthorization; + return oauth.getAuthenticationRequestBuilder(); + } + } + return null; + } + + /** + * Helper method to pre-set the oauth access token of the first oauth found in the apiAuthorizations (there should be only one) + * @param accessToken + * @param expiresIn : validity period in seconds + */ + public void setAccessToken(String accessToken, Long expiresIn) { + for(RequestInterceptor apiAuthorization : apiAuthorizations.values()) { + if (apiAuthorization instanceof OAuth) { + OAuth oauth = (OAuth) apiAuthorization; + oauth.setAccessToken(accessToken, expiresIn); + return; + } + } + } + + /** + * Helper method to configure the oauth accessCode/implicit flow parameters + * @param clientId + * @param clientSecret + * @param redirectURI + */ + public void configureAuthorizationFlow(String clientId, String clientSecret, String redirectURI) { + for(RequestInterceptor apiAuthorization : apiAuthorizations.values()) { + if (apiAuthorization instanceof OAuth) { + OAuth oauth = (OAuth) apiAuthorization; + oauth.getTokenRequestBuilder() + .setClientId(clientId) + .setClientSecret(clientSecret) + .setRedirectURI(redirectURI); + oauth.getAuthenticationRequestBuilder() + .setClientId(clientId) + .setRedirectURI(redirectURI); + return; + } + } + } + + /** + * Configures a listener which is notified when a new access token is received. + * @param accessTokenListener + */ + public void registerAccessTokenListener(AccessTokenListener accessTokenListener) { + for(RequestInterceptor apiAuthorization : apiAuthorizations.values()) { + if (apiAuthorization instanceof OAuth) { + OAuth oauth = (OAuth) apiAuthorization; + oauth.registerAccessTokenListener(accessTokenListener); + return; + } + } + } + + public RequestInterceptor getAuthorization(String authName) { + return apiAuthorizations.get(authName); + } + + /** + * Adds an authorization to be used by the client + * @param authName + * @param authorization + */ + public void addAuthorization(String authName, RequestInterceptor authorization) { + if (apiAuthorizations.containsKey(authName)) { + throw new RuntimeException("auth name \"" + authName + "\" already in api authorizations"); + } + apiAuthorizations.put(authName, authorization); + feignBuilder.requestInterceptor(authorization); + } + } 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 eab17f660ef..40f6af65150 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/FormAwareEncoder.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/FormAwareEncoder.java @@ -14,7 +14,7 @@ import feign.codec.EncodeException; import feign.codec.Encoder; import feign.RequestTemplate; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-05T14:39:18.888+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-11T21:48:33.457Z") 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 9a27c73e12f..a7299767d3f 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/StringUtil.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/StringUtil.java @@ -1,6 +1,6 @@ package io.swagger.client; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-05T14:39:18.888+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-11T21:48:33.457Z") public class StringUtil { /** * Check if the given array contains the given value (with case-insensitive comparison). diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/PetApi.java index f53ac745037..02a44b271f0 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 @@ -8,7 +8,7 @@ import java.io.File; import java.util.*; import feign.*; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-05T14:39:18.888+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-11T21:48:33.457Z") 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 66644ad9469..7a460f718a4 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 @@ -8,7 +8,7 @@ import io.swagger.client.model.Order; import java.util.*; import feign.*; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-05T14:39:18.888+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-11T21:48:33.457Z") 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 5400f5cace4..cf7ccd97497 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 @@ -8,7 +8,7 @@ import java.util.*; import java.util.*; import feign.*; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-05T14:39:18.888+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-11T21:48:33.457Z") public interface UserApi extends ApiClient.Api { diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/auth/ApiKeyAuth.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/auth/ApiKeyAuth.java new file mode 100644 index 00000000000..067672104a9 --- /dev/null +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/auth/ApiKeyAuth.java @@ -0,0 +1,41 @@ +package io.swagger.client.auth; + +import feign.RequestInterceptor; +import feign.RequestTemplate; + +public class ApiKeyAuth implements RequestInterceptor { + private final String location; + private final String paramName; + + private String apiKey; + + public ApiKeyAuth(String location, String paramName) { + this.location = location; + this.paramName = paramName; + } + + public String getLocation() { + return location; + } + + public String getParamName() { + return paramName; + } + + public String getApiKey() { + return apiKey; + } + + public void setApiKey(String apiKey) { + this.apiKey = apiKey; + } + + @Override + public void apply(RequestTemplate template) { + if (location == "query") { + template.query(paramName, apiKey); + } else if (location == "header") { + template.header(paramName, apiKey); + } + } +} \ No newline at end of file diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/auth/HttpBasicAuth.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/auth/HttpBasicAuth.java new file mode 100644 index 00000000000..26a97039879 --- /dev/null +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/auth/HttpBasicAuth.java @@ -0,0 +1,41 @@ +package io.swagger.client.auth; + +import feign.RequestInterceptor; +import feign.RequestTemplate; +import feign.auth.BasicAuthRequestInterceptor; + +/** + * An interceptor that adds the request header needed to use HTTP basic authentication. + */ +public class HttpBasicAuth implements RequestInterceptor { + + 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; + } + + public void setCredentials(String username, String password) { + this.username = username; + this.password = password; + } + + @Override + public void apply(RequestTemplate template) { + RequestInterceptor requestInterceptor = new BasicAuthRequestInterceptor(username, password); + requestInterceptor.apply(template); + } +} diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/auth/OAuth.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/auth/OAuth.java new file mode 100644 index 00000000000..5aafbf81a2f --- /dev/null +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/auth/OAuth.java @@ -0,0 +1,203 @@ +package io.swagger.client.auth; + +import java.io.IOException; +import java.util.Collection; +import java.util.Map; +import java.util.Map.Entry; + +import org.apache.oltu.oauth2.client.HttpClient; +import org.apache.oltu.oauth2.client.OAuthClient; +import org.apache.oltu.oauth2.client.request.OAuthClientRequest; +import org.apache.oltu.oauth2.client.request.OAuthClientRequest.AuthenticationRequestBuilder; +import org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuilder; +import org.apache.oltu.oauth2.client.response.OAuthClientResponse; +import org.apache.oltu.oauth2.client.response.OAuthClientResponseFactory; +import org.apache.oltu.oauth2.client.response.OAuthJSONAccessTokenResponse; +import org.apache.oltu.oauth2.common.exception.OAuthProblemException; +import org.apache.oltu.oauth2.common.exception.OAuthSystemException; +import org.apache.oltu.oauth2.common.message.types.GrantType; +import org.apache.oltu.oauth2.common.token.BasicOAuthToken; + +import feign.Client; +import feign.Request.Options; +import feign.RequestInterceptor; +import feign.RequestTemplate; +import feign.Response; +import feign.Util; +import io.swagger.client.StringUtil; + + +public class OAuth implements RequestInterceptor { + + public interface AccessTokenListener { + public void notify(BasicOAuthToken token); + } + + private volatile String accessToken; + private Long expirationTimeMillis; + private OAuthClient oauthClient; + private TokenRequestBuilder tokenRequestBuilder; + private AuthenticationRequestBuilder authenticationRequestBuilder; + private AccessTokenListener accessTokenListener; + + public OAuth(Client client, TokenRequestBuilder requestBuilder) { + setOauthClient(client); + this.tokenRequestBuilder = requestBuilder; + } + + public OAuth(Client client, OAuthFlow flow, String authorizationUrl, String tokenUrl, String scopes) { + this(client, OAuthClientRequest.tokenLocation(tokenUrl).setScope(scopes)); + setFlow(flow); + authenticationRequestBuilder = OAuthClientRequest.authorizationLocation(authorizationUrl); + } + + public OAuth(OAuthFlow flow, String authorizationUrl, String tokenUrl, String scopes) { + this(new Client.Default(null, null), flow, authorizationUrl, tokenUrl, scopes); + } + + public void setFlow(OAuthFlow flow) { + switch(flow) { + case accessCode: + case implicit: + tokenRequestBuilder.setGrantType(GrantType.AUTHORIZATION_CODE); + break; + case password: + tokenRequestBuilder.setGrantType(GrantType.PASSWORD); + break; + case application: + tokenRequestBuilder.setGrantType(GrantType.CLIENT_CREDENTIALS); + break; + default: + break; + } + } + + @Override + public void apply(RequestTemplate template) { + // If the request already have an authorization (eg. Basic auth), do nothing + if (template.headers().containsKey("Authorization")) { + return; + } + // If first time, get the token + if (expirationTimeMillis == null || System.currentTimeMillis() >= expirationTimeMillis) { + try { + updateAccessToken(); + } catch (OAuthSystemException e) { + e.printStackTrace(); + return; + } catch (OAuthProblemException e) { + e.printStackTrace(); + return; + } + } + if (getAccessToken() != null) { + template.header("Authorization", "Bearer " + getAccessToken()); + } + } + + public synchronized void updateAccessToken() throws OAuthSystemException, OAuthProblemException { + if (getAccessToken() == null) { + OAuthJSONAccessTokenResponse accessTokenResponse = oauthClient.accessToken(tokenRequestBuilder.buildBodyMessage()); + if (accessTokenResponse != null && accessTokenResponse.getAccessToken() != null) { + setAccessToken(accessTokenResponse.getAccessToken(), accessTokenResponse.getExpiresIn()); + if (accessTokenListener != null) { + accessTokenListener.notify((BasicOAuthToken) accessTokenResponse.getOAuthToken()); + } + } + } + } + + public void registerAccessTokenListener(AccessTokenListener accessTokenListener) { + this.accessTokenListener = accessTokenListener; + } + + public synchronized String getAccessToken() { + return accessToken; + } + + public synchronized void setAccessToken(String accessToken, Long expiresIn) { + this.accessToken = accessToken; + this.expirationTimeMillis = System.currentTimeMillis() + expiresIn * 1000; + } + + public TokenRequestBuilder getTokenRequestBuilder() { + return tokenRequestBuilder; + } + + public void setTokenRequestBuilder(TokenRequestBuilder tokenRequestBuilder) { + this.tokenRequestBuilder = tokenRequestBuilder; + } + + public AuthenticationRequestBuilder getAuthenticationRequestBuilder() { + return authenticationRequestBuilder; + } + + public void setAuthenticationRequestBuilder(AuthenticationRequestBuilder authenticationRequestBuilder) { + this.authenticationRequestBuilder = authenticationRequestBuilder; + } + + public OAuthClient getOauthClient() { + return oauthClient; + } + + public void setOauthClient(OAuthClient oauthClient) { + this.oauthClient = oauthClient; + } + + public void setOauthClient(Client client) { + this.oauthClient = new OAuthClient( new OAuthFeignClient(client)); + } + + public class OAuthFeignClient implements HttpClient { + + private Client client; + + public OAuthFeignClient() { + this.client = new Client.Default(null, null); + } + + public OAuthFeignClient(Client client) { + this.client = client; + } + + public T execute(OAuthClientRequest request, Map headers, + String requestMethod, Class responseClass) + throws OAuthSystemException, OAuthProblemException { + + RequestTemplate req = new RequestTemplate() + .append(request.getLocationUri()) + .method(requestMethod) + .body(request.getBody()); + + for (Entry entry : headers.entrySet()) { + req.header(entry.getKey(), entry.getValue()); + } + Response feignResponse; + String body = ""; + try { + feignResponse = client.execute(req.request(), new Options()); + body = Util.toString(feignResponse.body().asReader()); + } catch (IOException e) { + throw new OAuthSystemException(e); + } + + String contentType = null; + Collection contentTypeHeader = feignResponse.headers().get("Content-Type"); + if(contentTypeHeader != null) { + contentType = StringUtil.join(contentTypeHeader.toArray(new String[0]), ";"); + } + + return OAuthClientResponseFactory.createCustomResponse( + body, + contentType, + feignResponse.status(), + responseClass + ); + } + + public void shutdown() { + // Nothing to do here + } + + } +} diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/auth/OAuthFlow.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/auth/OAuthFlow.java new file mode 100644 index 00000000000..597ec99b48b --- /dev/null +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/auth/OAuthFlow.java @@ -0,0 +1,5 @@ +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/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 52bff46824c..92e69c4d407 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; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-05T14:39:18.888+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-11T21:48:33.457Z") public class Category { private Long id = null; @@ -53,8 +53,10 @@ public class Category { return false; } Category category = (Category) o; - return Objects.equals(id, category.id) && - Objects.equals(name, category.name); + + return true && Objects.equals(id, category.id) && + Objects.equals(name, category.name) + ; } @Override 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 8c5d349d105..3dc9168d926 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Order.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Order.java @@ -11,7 +11,7 @@ import java.util.Date; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-05T14:39:18.888+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-11T21:48:33.457Z") public class Order { private Long id = null; @@ -131,12 +131,14 @@ public class Order { return false; } Order order = (Order) o; - return Objects.equals(id, order.id) && + + return true && 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); + Objects.equals(complete, order.complete) + ; } @Override 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 df7d37173fb..908d654679a 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 @@ -13,7 +13,7 @@ import java.util.*; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-05T14:39:18.888+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-11T21:48:33.457Z") public class Pet { private Long id = null; @@ -133,12 +133,14 @@ public class Pet { return false; } Pet pet = (Pet) o; - return Objects.equals(id, pet.id) && + + return true && 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); + Objects.equals(status, pet.status) + ; } @Override 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 5f6b24d052c..337c84211a4 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; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-05T14:39:18.888+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-11T21:48:33.457Z") public class Tag { private Long id = null; @@ -53,8 +53,10 @@ public class Tag { return false; } Tag tag = (Tag) o; - return Objects.equals(id, tag.id) && - Objects.equals(name, tag.name); + + return true && Objects.equals(id, tag.id) && + Objects.equals(name, tag.name) + ; } @Override 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 7ebd78e6ea8..b05d8a58a81 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; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-05T14:39:18.888+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-11T21:48:33.457Z") public class User { private Long id = null; @@ -138,14 +138,16 @@ public class User { return false; } User user = (User) o; - return Objects.equals(id, user.id) && + + return true && 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); + Objects.equals(userStatus, user.userStatus) + ; } @Override 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 73deed7fad8..7f06e36633f 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 @@ -12,7 +12,9 @@ import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import org.glassfish.jersey.client.ClientConfig; +import org.glassfish.jersey.client.ClientProperties; import org.glassfish.jersey.filter.LoggingFilter; +import org.glassfish.jersey.jackson.JacksonFeature; import org.glassfish.jersey.media.multipart.FormDataBodyPart; import org.glassfish.jersey.media.multipart.FormDataContentDisposition; import org.glassfish.jersey.media.multipart.MultiPart; @@ -41,14 +43,15 @@ 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-01-05T14:39:17.660+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-08T18:51:26.068+08:00") public class ApiClient { - private Client client; - private Map hostMap = new HashMap(); private Map defaultHeaderMap = new HashMap(); - private boolean debugging = false; private String basePath = "http://petstore.swagger.io/v2"; - private JSON json = new JSON(); + private boolean debugging = false; + private int connectionTimeout = 0; + + private Client httpClient; + private JSON json; private Map authentications; @@ -58,6 +61,9 @@ public class ApiClient { private DateFormat dateFormat; public ApiClient() { + json = new JSON(); + httpClient = buildHttpClient(debugging); + // Use RFC3339 format for date and datetime. // See http://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14 this.dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); @@ -70,12 +76,10 @@ public class ApiClient { // Set default User-Agent. setUserAgent("Java-Swagger"); - buildClient(); - // Setup authentications (key: authentication name, value: authentication). authentications = new HashMap(); - authentications.put("api_key", new ApiKeyAuth("header", "api_key")); authentications.put("petstore_auth", new OAuth()); + authentications.put("api_key", new ApiKeyAuth("header", "api_key")); // Prevent the authentications from being modified. authentications = Collections.unmodifiableMap(authentications); } @@ -225,10 +229,29 @@ public class ApiClient { */ public ApiClient setDebugging(boolean debugging) { this.debugging = debugging; - buildClient(); + // Rebuild HTTP Client according to the new "debugging" value. + this.httpClient = buildHttpClient(debugging); return this; } + /** + * Connect timeout (in milliseconds). + */ + public int getConnectTimeout() { + return connectionTimeout; + } + + /** + * Set the connect timeout (in milliseconds). + * A value of 0 means no timeout, otherwise values must be between 1 and + * {@link Integer#MAX_VALUE}. + */ + public ApiClient setConnectTimeout(int connectionTimeout) { + this.connectionTimeout = connectionTimeout; + httpClient.property(ClientProperties.CONNECT_TIMEOUT, connectionTimeout); + return this; + } + /** * Get the date format used to parse/format date parameters. */ @@ -471,7 +494,7 @@ public class ApiClient { public T invokeAPI(String path, String method, List queryParams, Object body, Map headerParams, Map formParams, String accept, String contentType, String[] authNames, GenericType returnType) throws ApiException { updateParamsForAuth(authNames, queryParams, headerParams); - WebTarget target = client.target(this.basePath).path(path); + WebTarget target = httpClient.target(this.basePath).path(path); if (queryParams != null) { for (Pair queryParam : queryParams) { @@ -544,15 +567,18 @@ public class ApiClient { } } - private void buildClient() { + /** + * Build the Client used to make HTTP requests. + */ + private Client buildHttpClient(boolean debugging) { final ClientConfig clientConfig = new ClientConfig(); clientConfig.register(MultiPartFeature.class); clientConfig.register(json); - clientConfig.register(org.glassfish.jersey.jackson.JacksonFeature.class); + clientConfig.register(JacksonFeature.class); if (debugging) { clientConfig.register(LoggingFilter.class); } - this.client = ClientBuilder.newClient(clientConfig); + return ClientBuilder.newClient(clientConfig); } private Map> buildResponseHeaders(Response response) { diff --git a/samples/client/petstore/java/okhttp-gson/pom.xml b/samples/client/petstore/java/okhttp-gson/pom.xml index 9fa057be939..4eaf536b2c8 100644 --- a/samples/client/petstore/java/okhttp-gson/pom.xml +++ b/samples/client/petstore/java/okhttp-gson/pom.xml @@ -117,6 +117,11 @@ okhttp ${okhttp-version} + + com.squareup.okhttp + logging-interceptor + ${okhttp-version} + com.google.code.gson gson @@ -133,7 +138,7 @@ 1.5.0 - 2.4.0 + 2.7.2 2.3.1 1.0.0 4.8.1 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 7fb4cc49bf3..782f3b239c5 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 @@ -11,6 +11,8 @@ import com.squareup.okhttp.MultipartBuilder; import com.squareup.okhttp.MediaType; import com.squareup.okhttp.Headers; import com.squareup.okhttp.internal.http.HttpMethod; +import com.squareup.okhttp.logging.HttpLoggingInterceptor; +import com.squareup.okhttp.logging.HttpLoggingInterceptor.Level; import java.lang.reflect.Type; @@ -116,6 +118,8 @@ public class ApiClient { private OkHttpClient httpClient; private JSON json; + private HttpLoggingInterceptor loggingInterceptor; + public ApiClient() { httpClient = new OkHttpClient(); @@ -141,8 +145,8 @@ public class ApiClient { // Setup authentications (key: authentication name, value: authentication). authentications = new HashMap(); - authentications.put("api_key", new ApiKeyAuth("header", "api_key")); authentications.put("petstore_auth", new OAuth()); + authentications.put("api_key", new ApiKeyAuth("header", "api_key")); // Prevent the authentications from being modified. authentications = Collections.unmodifiableMap(authentications); } @@ -451,6 +455,16 @@ public class ApiClient { * @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; } diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/ApiClientTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/ApiClientTest.java index ba143470c9a..43c5ee2b86a 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/ApiClientTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/ApiClientTest.java @@ -186,14 +186,15 @@ public class ApiClientTest { @Test public void testGetAndSetConnectTimeout() { - assertEquals(0, apiClient.getConnectTimeout()); - assertEquals(0, apiClient.getHttpClient().getConnectTimeout()); - - apiClient.setConnectTimeout(10000); + // connect timeout defaults to 10 seconds assertEquals(10000, apiClient.getConnectTimeout()); assertEquals(10000, apiClient.getHttpClient().getConnectTimeout()); apiClient.setConnectTimeout(0); + assertEquals(0, apiClient.getConnectTimeout()); + assertEquals(0, apiClient.getHttpClient().getConnectTimeout()); + + apiClient.setConnectTimeout(10000); } @Test diff --git a/samples/client/petstore/perl/README.md b/samples/client/petstore/perl/README.md index e50a07a5418..576fadf5900 100644 --- a/samples/client/petstore/perl/README.md +++ b/samples/client/petstore/perl/README.md @@ -8,7 +8,7 @@ WWW::SwaggerClient::Role - a Moose role for the Swagger Petstore Automatically generated by the Perl Swagger Codegen project: -- Build date: 2015-12-29T16:27:28.775+08:00 +- Build date: 2016-01-04T20:36:07.450-08:00 - Build package: class io.swagger.codegen.languages.PerlClientCodegen - Codegen version: @@ -167,7 +167,7 @@ maven 3.0.3 or better already installed. The config file should specify the project name for the generated library: - {"moduleName":"MyProjectName"} + {"moduleName":"WWW::MyProjectName"} Your library files will be built under `WWW::MyProjectName`. diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/ApiClient.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/ApiClient.pm index 11f2ab3f236..cf596a9918d 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/ApiClient.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/ApiClient.pm @@ -319,6 +319,12 @@ sub update_params_for_auth { if (!defined($auth)) { # TODO show warning about auth setting not defined } + elsif ($auth eq 'petstore_auth') { + + if ($WWW::SwaggerClient::Configuration::access_token) { + $header_params->{'Authorization'} = 'Bearer ' . $WWW::SwaggerClient::Configuration::access_token; + } + } elsif ($auth eq 'api_key') { my $api_key = $self->get_api_key_with_prefix('api_key'); @@ -326,12 +332,6 @@ sub update_params_for_auth { $header_params->{'api_key'} = $api_key; } } - elsif ($auth eq 'petstore_auth') { - - if ($WWW::SwaggerClient::Configuration::access_token) { - $header_params->{'Authorization'} = 'Bearer ' . $WWW::SwaggerClient::Configuration::access_token; - } - } else { # TODO show warning about security definition not found @@ -341,7 +341,7 @@ sub update_params_for_auth { # The endpoint API class has not found any settings for auth. This may be deliberate, # in which case update_params_for_auth() will be a no-op. But it may also be that the -# swagger spec does not describe the intended authorization. So we check in the config for any +# OpenAPI Spec does not describe the intended authorization. So we check in the config for any # auth tokens and if we find any, we use them for all endpoints; sub _global_auth_setup { my ($self, $header_params, $query_params) = @_; diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/ApiFactory.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/ApiFactory.pm index f0846a9b594..0ffd5498420 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/ApiFactory.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/ApiFactory.pm @@ -13,7 +13,7 @@ use WWW::SwaggerClient::ApiClient; =head1 Name - WWW::SwaggerClient::ApiFactory - constructs APIs to retrieve SwaggerClient objects + WWW::SwaggerClient::ApiFactory - constructs APIs to retrieve WWW::SwaggerClient objects =head1 Synopsis @@ -64,7 +64,7 @@ sub new { $which is a nickname for the class: - WWW::FooBarClient::BazApi has nickname 'Baz' + FooBarClient::BazApi has nickname 'Baz' =cut diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/PetApi.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/PetApi.pm index 06ccfca98e8..e6182c4e952 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/PetApi.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/PetApi.pm @@ -1,5 +1,5 @@ # -# Copyright 2015 SmartBear Software +# 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. diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Role.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Role.pm index 8c9e85ed506..8ad294d399d 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Role.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Role.pm @@ -37,7 +37,7 @@ has version_info => ( is => 'ro', default => sub { { app_name => 'Swagger Petstore', app_version => '1.0.0', - generated_date => '2015-12-29T16:27:28.775+08:00', + generated_date => '2016-01-04T20:36:07.450-08:00', generator_class => 'class io.swagger.codegen.languages.PerlClientCodegen', } }, documentation => 'Information about the application version and the codegen codebase version' @@ -103,7 +103,7 @@ Automatically generated by the Perl Swagger Codegen project: =over 4 -=item Build date: 2015-12-29T16:27:28.775+08:00 +=item Build date: 2016-01-04T20:36:07.450-08:00 =item Build package: class io.swagger.codegen.languages.PerlClientCodegen @@ -119,7 +119,7 @@ WWW::SwaggerClient::ApiFactory for non-Moosey usage. =head1 SYNOPSIS The Perl Swagger Codegen project builds a library of Perl modules to interact with -a web service defined by a Swagger specification. See below for how to build the +a web service defined by a OpenAPI Specification. See below for how to build the library. This module provides an interface to the generated library. All the classes, @@ -154,7 +154,7 @@ For documentation of all these methods, see AUTOMATIC DOCUMENTATION below. =head2 Configuring authentication -In the normal case, the Swagger spec will describe what parameters are +In the normal case, the OpenAPI Spec will describe what parameters are required and where to put them. You just need to supply the tokens. my $tokens = { @@ -269,7 +269,7 @@ maven 3.0.3 or better already installed. The config file should specify the project name for the generated library: - {"moduleName":"MyProjectName"} + {"moduleName":"WWW::MyProjectName"} Your library files will be built under C. @@ -304,7 +304,7 @@ output formats are supported: The C<-c> option allows you to load and inspect your own application. A dummy namespace is used if you don't supply your own class. -=head1 DOCUMENTATION FROM THE SWAGGER SPEC +=head1 DOCUMENTATION FROM THE OpenAPI Spec Additional documentation for each class and method may be provided by the Swagger spec. If so, this is available via the C and 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 0dc30dbfb90..d57c96c1798 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Role/AutoDoc.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Role/AutoDoc.pm @@ -424,4 +424,4 @@ $attrname -1; \ No newline at end of file +1; diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/StoreApi.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/StoreApi.pm index abe936573e7..e28f8a6b260 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/StoreApi.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/StoreApi.pm @@ -1,5 +1,5 @@ # -# Copyright 2015 SmartBear Software +# 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. diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/UserApi.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/UserApi.pm index 9ba45815c8c..5e983e1aa7c 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/UserApi.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/UserApi.pm @@ -1,5 +1,5 @@ # -# Copyright 2015 SmartBear Software +# 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. diff --git a/samples/client/petstore/perl/t/05_long_module_name.t b/samples/client/petstore/perl/t/05_long_module_name.t new file mode 100644 index 00000000000..5663e15e5ff --- /dev/null +++ b/samples/client/petstore/perl/t/05_long_module_name.t @@ -0,0 +1,96 @@ +use Test::More; +use Test::Exception; + +use lib 'deep_module_test/lib'; +use strict; +use warnings; + +if (! -d 'deep_module_test/lib' ) { + plan skip_all => 'bin/perl-petstore.sh needs to be run first'; +} +else { + plan tests => 38; +} + +use_ok('Something::Deep::PetApi'); +use_ok('Something::Deep::ApiClient'); +use_ok('Something::Deep::Object::Pet'); +use_ok('Something::Deep::Object::Tag'); +use_ok('Something::Deep::Object::Category'); + +my $api_client = Something::Deep::ApiClient->instance('base_url' => 'http://testing'); +my $pet_api = Something::Deep::PetApi->new('api_client' => $api_client); +is $pet_api->{api_client}->{base_url}, 'http://testing', 'get the proper base URL from api client'; + +my $api = Something::Deep::PetApi->new(); + +is $api->{api_client}->{base_url}, 'http://testing', 'we still get the original base URL from api client, because it\'s a singleton'; + +# reset the base_url - no direct access because an application shouldn't be changing +# its base URL halfway through +$api->{api_client}->{base_url} = 'http://petstore.swagger.io/v2'; + +is $api->{api_client}->{base_url}, 'http://petstore.swagger.io/v2', 'get the default base URL from api client'; + +# test select_header_content_type +is $api->{api_client}->select_header_content_type('application/xml', 'Application/JSON'), 'application/json', 'get the proper content type application/json but not application/xml'; +is $api->{api_client}->select_header_content_type('application/xml'), 'application/xml', 'get the proper content type application/json'; +is $api->{api_client}->select_header_content_type(''), 'application/json', 'get the proper content type application/json (default)'; + +# test select_header_accept +is $api->{api_client}->select_header_accept('application/xml', 'Application/JSON'), 'application/json', 'get the proper accept application/json but not application/xml'; +is $api->{api_client}->select_header_content_type('application/xml'), 'application/xml', 'get the proper accept application/json'; +is $api->{api_client}->select_header_accept(''), undef, 'get the proper accept "undef" (default)'; + +my $pet_id = 10008; + +my $category = Something::Deep::Object::Category->new('id' => '22', 'name' => 'perl'); +my $tag = Something::Deep::Object::Tag->new('id' => '11', 'name' => 'just kidding'); +my $pet = Something::Deep::Object::Pet->new('id' => $pet_id, 'name' => 'perl test', + "photoUrls" => ['123', 'oop'], 'tags' => [$tag], 'status' => 'pending', 'category' => $category); + +isa_ok($api, 'Something::Deep::PetApi'); +isa_ok($category, 'Something::Deep::Object::Category'); +isa_ok($tag, 'Something::Deep::Object::Tag'); +isa_ok($pet, 'Something::Deep::Object::Pet'); + +my $pet_hash = $pet->to_hash; + +is $pet_hash->{category}->{id}, '22', 'get the proper category id'; +is $pet_hash->{category}->{name}, 'perl', 'get the proper category name'; +is $pet_hash->{tags}[0]->{name}, 'just kidding', 'get the proper tag name'; +is $pet_hash->{tags}[0]->{id}, '11', 'get the proper tag id'; + +my $add_pet = $api->add_pet(body => $pet); + +my $get_pet = $api->get_pet_by_id(pet_id => $pet_id); +my $get_pet_hash = $get_pet->to_hash; +is $get_pet_hash->{name}, 'perl test', 'get the proper pet name from get_pet_by_id'; +is $get_pet_hash->{id}, '10008', 'get the proper pet id from get_pet_by_id'; +is $get_pet_hash->{category}->{name}, 'perl', 'get the proper category name from get_pet_by_id'; +is $get_pet_hash->{category}->{id}, '22', 'get the proper category id from get_pet_by_id'; +is $get_pet_hash->{category}->{name}, 'perl', 'get the proper category from get_pet_by_id'; +is $get_pet_hash->{tags}[0]->{name}, 'just kidding', 'get the proper tag from get_pet_by_id'; +is $get_pet_hash->{tags}[0]->{id}, '11', 'get the proper tag id from get_pet_by_id'; +is $get_pet_hash->{photoUrls}->[0], '123', 'get the proper photoUrl from get_pet_by_id'; +is $get_pet_hash->{photoUrls}->[1], 'oop', 'get the proper photoUrl from get_pet_by_id'; + + +my $update_pet_with_form = $api->update_pet_with_form(pet_id => $pet_id, name => 'test_name', status => 'sold'); +is $update_pet_with_form, undef, 'get the null response from update_pet_wth_form'; + +my $get_pet_after_update = $api->get_pet_by_id(pet_id => $pet_id); +is $get_pet_after_update->{status}, 'sold', 'get the updated status after update_pet_with_form'; + +my $upload_pet = $api->upload_file(pet_id => $pet_id, additional_metadata => 'testabc', file => 'test.pl'); +is $upload_pet, undef, 'get the null response from upload_pet'; + +my $delete_pet = $api->delete_pet(pet_id => $pet_id); +is $delete_pet, undef, 'get the null response from delete_pet'; +throws_ok{$api->get_pet_by_id(pet_id => $pet_id)} qr/API Exception\(404\): Not Found/, "throw 404 error about pet not found after delete"; +#is $get_pet_after_delete->{status}, undef, 'get the updated status after update_pet_with_form'; + +my $pets; +lives_ok {$pets = $api->find_pets_by_status(status => [qw(sold available)])} 'array query param processed correctly'; +isa_ok($pets->[0], 'Something::Deep::Object::Pet'); + diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php index a2ce3cac04b..c853583d0eb 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php @@ -10,7 +10,7 @@ * @link https://github.com/swagger-api/swagger-codegen */ /** - * Copyright 2015 SmartBear Software + * 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. @@ -122,8 +122,6 @@ class PetApi // parse inputs $resourcePath = "/pet"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "PUT"; $httpBody = ''; $queryParams = array(); $headerParams = array(); @@ -137,6 +135,9 @@ class PetApi + // default format to json + $resourcePath = str_replace("{format}", "json", $resourcePath); + // body params $_tempBody = null; @@ -159,7 +160,7 @@ class PetApi // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, $method, + $resourcePath, 'PUT', $queryParams, $httpBody, $headerParams ); @@ -205,8 +206,6 @@ class PetApi // parse inputs $resourcePath = "/pet"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "POST"; $httpBody = ''; $queryParams = array(); $headerParams = array(); @@ -220,6 +219,9 @@ class PetApi + // default format to json + $resourcePath = str_replace("{format}", "json", $resourcePath); + // body params $_tempBody = null; @@ -242,7 +244,7 @@ class PetApi // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, $method, + $resourcePath, 'POST', $queryParams, $httpBody, $headerParams ); @@ -288,8 +290,6 @@ class PetApi // parse inputs $resourcePath = "/pet/findByStatus"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "GET"; $httpBody = ''; $queryParams = array(); $headerParams = array(); @@ -311,6 +311,9 @@ class PetApi } + // default format to json + $resourcePath = str_replace("{format}", "json", $resourcePath); + @@ -329,7 +332,7 @@ class PetApi // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, $method, + $resourcePath, 'GET', $queryParams, $httpBody, $headerParams, '\Swagger\Client\Model\Pet[]' ); @@ -383,8 +386,6 @@ class PetApi // parse inputs $resourcePath = "/pet/findByTags"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "GET"; $httpBody = ''; $queryParams = array(); $headerParams = array(); @@ -406,6 +407,9 @@ class PetApi } + // default format to json + $resourcePath = str_replace("{format}", "json", $resourcePath); + @@ -424,7 +428,7 @@ class PetApi // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, $method, + $resourcePath, 'GET', $queryParams, $httpBody, $headerParams, '\Swagger\Client\Model\Pet[]' ); @@ -482,8 +486,6 @@ class PetApi // parse inputs $resourcePath = "/pet/{petId}"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "GET"; $httpBody = ''; $queryParams = array(); $headerParams = array(); @@ -505,6 +507,9 @@ class PetApi $resourcePath ); } + // default format to json + $resourcePath = str_replace("{format}", "json", $resourcePath); + @@ -525,7 +530,7 @@ class PetApi // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, $method, + $resourcePath, 'GET', $queryParams, $httpBody, $headerParams, '\Swagger\Client\Model\Pet' ); @@ -587,8 +592,6 @@ class PetApi // parse inputs $resourcePath = "/pet/{petId}"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "POST"; $httpBody = ''; $queryParams = array(); $headerParams = array(); @@ -610,6 +613,9 @@ class PetApi $resourcePath ); } + // default format to json + $resourcePath = str_replace("{format}", "json", $resourcePath); + // form params if ($name !== null) { @@ -640,7 +646,7 @@ class PetApi // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, $method, + $resourcePath, 'POST', $queryParams, $httpBody, $headerParams ); @@ -692,8 +698,6 @@ class PetApi // parse inputs $resourcePath = "/pet/{petId}"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "DELETE"; $httpBody = ''; $queryParams = array(); $headerParams = array(); @@ -719,6 +723,9 @@ class PetApi $resourcePath ); } + // default format to json + $resourcePath = str_replace("{format}", "json", $resourcePath); + @@ -737,7 +744,7 @@ class PetApi // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, $method, + $resourcePath, 'DELETE', $queryParams, $httpBody, $headerParams ); @@ -791,8 +798,6 @@ class PetApi // parse inputs $resourcePath = "/pet/{petId}/uploadImage"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "POST"; $httpBody = ''; $queryParams = array(); $headerParams = array(); @@ -814,6 +819,9 @@ class PetApi $resourcePath ); } + // default format to json + $resourcePath = str_replace("{format}", "json", $resourcePath); + // form params if ($additional_metadata !== null) { @@ -850,7 +858,7 @@ class PetApi // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, $method, + $resourcePath, 'POST', $queryParams, $httpBody, $headerParams ); diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php index 6a03542dfb0..2874d8f47ac 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php @@ -10,7 +10,7 @@ * @link https://github.com/swagger-api/swagger-codegen */ /** - * Copyright 2015 SmartBear Software + * 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. @@ -120,8 +120,6 @@ class StoreApi // parse inputs $resourcePath = "/store/inventory"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "GET"; $httpBody = ''; $queryParams = array(); $headerParams = array(); @@ -135,6 +133,9 @@ class StoreApi + // default format to json + $resourcePath = str_replace("{format}", "json", $resourcePath); + @@ -155,7 +156,7 @@ class StoreApi // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, $method, + $resourcePath, 'GET', $queryParams, $httpBody, $headerParams, 'map[string,int]' ); @@ -209,8 +210,6 @@ class StoreApi // parse inputs $resourcePath = "/store/order"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "POST"; $httpBody = ''; $queryParams = array(); $headerParams = array(); @@ -224,6 +223,9 @@ class StoreApi + // default format to json + $resourcePath = str_replace("{format}", "json", $resourcePath); + // body params $_tempBody = null; @@ -241,7 +243,7 @@ class StoreApi // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, $method, + $resourcePath, 'POST', $queryParams, $httpBody, $headerParams, '\Swagger\Client\Model\Order' ); @@ -299,8 +301,6 @@ class StoreApi // parse inputs $resourcePath = "/store/order/{orderId}"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "GET"; $httpBody = ''; $queryParams = array(); $headerParams = array(); @@ -322,6 +322,9 @@ class StoreApi $resourcePath ); } + // default format to json + $resourcePath = str_replace("{format}", "json", $resourcePath); + @@ -335,7 +338,7 @@ class StoreApi // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, $method, + $resourcePath, 'GET', $queryParams, $httpBody, $headerParams, '\Swagger\Client\Model\Order' ); @@ -393,8 +396,6 @@ class StoreApi // parse inputs $resourcePath = "/store/order/{orderId}"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "DELETE"; $httpBody = ''; $queryParams = array(); $headerParams = array(); @@ -416,6 +417,9 @@ class StoreApi $resourcePath ); } + // default format to json + $resourcePath = str_replace("{format}", "json", $resourcePath); + @@ -429,7 +433,7 @@ class StoreApi // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, $method, + $resourcePath, 'DELETE', $queryParams, $httpBody, $headerParams ); diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php index 18d39efea28..b63b679aba1 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php @@ -10,7 +10,7 @@ * @link https://github.com/swagger-api/swagger-codegen */ /** - * Copyright 2015 SmartBear Software + * 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. @@ -122,8 +122,6 @@ class UserApi // parse inputs $resourcePath = "/user"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "POST"; $httpBody = ''; $queryParams = array(); $headerParams = array(); @@ -137,6 +135,9 @@ class UserApi + // default format to json + $resourcePath = str_replace("{format}", "json", $resourcePath); + // body params $_tempBody = null; @@ -154,7 +155,7 @@ class UserApi // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, $method, + $resourcePath, 'POST', $queryParams, $httpBody, $headerParams ); @@ -200,8 +201,6 @@ class UserApi // parse inputs $resourcePath = "/user/createWithArray"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "POST"; $httpBody = ''; $queryParams = array(); $headerParams = array(); @@ -215,6 +214,9 @@ class UserApi + // default format to json + $resourcePath = str_replace("{format}", "json", $resourcePath); + // body params $_tempBody = null; @@ -232,7 +234,7 @@ class UserApi // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, $method, + $resourcePath, 'POST', $queryParams, $httpBody, $headerParams ); @@ -278,8 +280,6 @@ class UserApi // parse inputs $resourcePath = "/user/createWithList"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "POST"; $httpBody = ''; $queryParams = array(); $headerParams = array(); @@ -293,6 +293,9 @@ class UserApi + // default format to json + $resourcePath = str_replace("{format}", "json", $resourcePath); + // body params $_tempBody = null; @@ -310,7 +313,7 @@ class UserApi // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, $method, + $resourcePath, 'POST', $queryParams, $httpBody, $headerParams ); @@ -358,8 +361,6 @@ class UserApi // parse inputs $resourcePath = "/user/login"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "GET"; $httpBody = ''; $queryParams = array(); $headerParams = array(); @@ -381,6 +382,9 @@ class UserApi } + // default format to json + $resourcePath = str_replace("{format}", "json", $resourcePath); + @@ -394,7 +398,7 @@ class UserApi // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, $method, + $resourcePath, 'GET', $queryParams, $httpBody, $headerParams, 'string' ); @@ -446,8 +450,6 @@ class UserApi // parse inputs $resourcePath = "/user/logout"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "GET"; $httpBody = ''; $queryParams = array(); $headerParams = array(); @@ -461,6 +463,9 @@ class UserApi + // default format to json + $resourcePath = str_replace("{format}", "json", $resourcePath); + @@ -474,7 +479,7 @@ class UserApi // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, $method, + $resourcePath, 'GET', $queryParams, $httpBody, $headerParams ); @@ -524,8 +529,6 @@ class UserApi // parse inputs $resourcePath = "/user/{username}"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "GET"; $httpBody = ''; $queryParams = array(); $headerParams = array(); @@ -547,6 +550,9 @@ class UserApi $resourcePath ); } + // default format to json + $resourcePath = str_replace("{format}", "json", $resourcePath); + @@ -560,7 +566,7 @@ class UserApi // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, $method, + $resourcePath, 'GET', $queryParams, $httpBody, $headerParams, '\Swagger\Client\Model\User' ); @@ -620,8 +626,6 @@ class UserApi // parse inputs $resourcePath = "/user/{username}"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "PUT"; $httpBody = ''; $queryParams = array(); $headerParams = array(); @@ -643,6 +647,9 @@ class UserApi $resourcePath ); } + // default format to json + $resourcePath = str_replace("{format}", "json", $resourcePath); + // body params $_tempBody = null; @@ -660,7 +667,7 @@ class UserApi // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, $method, + $resourcePath, 'PUT', $queryParams, $httpBody, $headerParams ); @@ -710,8 +717,6 @@ class UserApi // parse inputs $resourcePath = "/user/{username}"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "DELETE"; $httpBody = ''; $queryParams = array(); $headerParams = array(); @@ -733,6 +738,9 @@ class UserApi $resourcePath ); } + // default format to json + $resourcePath = str_replace("{format}", "json", $resourcePath); + @@ -746,7 +754,7 @@ class UserApi // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, $method, + $resourcePath, 'DELETE', $queryParams, $httpBody, $headerParams ); diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/ApiClient.php b/samples/client/petstore/php/SwaggerClient-php/lib/ApiClient.php index 8730a8c0601..97c82f0051e 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/ApiClient.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/ApiClient.php @@ -11,7 +11,7 @@ * @link https://github.com/swagger-api/swagger-codegen */ /** - * Copyright 2015 SmartBear Software + * 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. diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/ApiException.php b/samples/client/petstore/php/SwaggerClient-php/lib/ApiException.php index 0b8f5892a35..d6040a0ff20 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/ApiException.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/ApiException.php @@ -10,7 +10,7 @@ * @link https://github.com/swagger-api/swagger-codegen */ /** - * Copyright 2015 SmartBear Software + * 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. diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php b/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php index 7281f729985..108092f91b1 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php @@ -11,7 +11,7 @@ */ /** - * Copyright 2015 SmartBear Software + * 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. diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Category.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Category.php index 444c3c1ed7e..ae4d3e39db0 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Category.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Category.php @@ -11,7 +11,7 @@ * @link https://github.com/swagger-api/swagger-codegen */ /** - * Copyright 2015 SmartBear Software + * 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. diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Order.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Order.php index b803bd7325e..c9f2629e31b 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Order.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Order.php @@ -11,7 +11,7 @@ * @link https://github.com/swagger-api/swagger-codegen */ /** - * Copyright 2015 SmartBear Software + * 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. diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Pet.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Pet.php index 6871ea9d9be..543041b0115 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Pet.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Pet.php @@ -11,7 +11,7 @@ * @link https://github.com/swagger-api/swagger-codegen */ /** - * Copyright 2015 SmartBear Software + * 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. diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Tag.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Tag.php index bcecb32fa7e..91bfa6aece9 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Tag.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Tag.php @@ -11,7 +11,7 @@ * @link https://github.com/swagger-api/swagger-codegen */ /** - * Copyright 2015 SmartBear Software + * 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. diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/User.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/User.php index 1650635d8ce..8268f6da2b1 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/User.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/User.php @@ -11,7 +11,7 @@ * @link https://github.com/swagger-api/swagger-codegen */ /** - * Copyright 2015 SmartBear Software + * 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. diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php b/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php index 04b5cd0861b..e7417fc42f2 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php @@ -11,7 +11,7 @@ * @link https://github.com/swagger-api/swagger-codegen */ /** - * Copyright 2015 SmartBear Software + * 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. @@ -79,6 +79,23 @@ class ObjectSerializer return $sanitized; } + /** + * Sanitize filename by removing path. + * e.g. ../../sun.gif becomes sun.gif + * + * @param string $filename filename to be sanitized + * + * @return string the sanitized filename + */ + public function sanitizeFilename($filename) + { + if (preg_match("/.*[\/\\\\](.*)$/", $filename, $match)) { + return $match[1]; + } else { + return $filename; + } + } + /** * Take value and turn it into a string suitable for inclusion in * the path, by url-encoding. @@ -199,11 +216,11 @@ class ObjectSerializer * * @param mixed $data object or primitive to be deserialized * @param string $class class name is passed as a string - * @param string $httpHeader HTTP headers + * @param string $httpHeaders HTTP headers * * @return object an instance of $class */ - public function deserialize($data, $class, $httpHeader=null) + public function deserialize($data, $class, $httpHeaders=null) { if (null === $data) { $deserialized = null; @@ -231,8 +248,8 @@ class ObjectSerializer $deserialized = $data; } elseif ($class === '\SplFileObject') { // determine file name - if (array_key_exists('Content-Disposition', $httpHeaders) && preg_match('/inline; filename=[\'"]?([^\'"\s]+)[\'"]?$/i', $httpHeader['Content-Disposition'], $match)) { - $filename = Configuration::getDefaultConfiguration()->getTempFolderPath().$match[1]; + if (array_key_exists('Content-Disposition', $httpHeaders) && preg_match('/inline; filename=[\'"]?([^\'"\s]+)[\'"]?$/i', $httpHeaders['Content-Disposition'], $match)) { + $filename = Configuration::getDefaultConfiguration()->getTempFolderPath() . sanitizeFilename($match[1]); } else { $filename = tempnam(Configuration::getDefaultConfiguration()->getTempFolderPath(), ''); } diff --git a/samples/client/petstore/php/SwaggerClient-php/tests/ObjectSerializerTest.php b/samples/client/petstore/php/SwaggerClient-php/tests/ObjectSerializerTest.php new file mode 100644 index 00000000000..14bbc0de913 --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/tests/ObjectSerializerTest.php @@ -0,0 +1,29 @@ +assertSame("sun.gif", $s->sanitizeFilename("sun.gif")); + $this->assertSame("sun.gif", $s->sanitizeFilename("../sun.gif")); + $this->assertSame("sun.gif", $s->sanitizeFilename("/var/tmp/sun.gif")); + $this->assertSame("sun.gif", $s->sanitizeFilename("./sun.gif")); + + $this->assertSame("sun", $s->sanitizeFilename("sun")); + $this->assertSame("sun.gif", $s->sanitizeFilename("..\sun.gif")); + $this->assertSame("sun.gif", $s->sanitizeFilename("\var\tmp\sun.gif")); + $this->assertSame("sun.gif", $s->sanitizeFilename("c:\var\tmp\sun.gif")); + $this->assertSame("sun.gif", $s->sanitizeFilename(".\sun.gif")); + } + +} + +?> + diff --git a/samples/client/petstore/php/SwaggerClient-php/tests/OrderApiTest.php b/samples/client/petstore/php/SwaggerClient-php/tests/OrderApiTest.php index 3eb0d11a9b2..f92cc83c693 100644 --- a/samples/client/petstore/php/SwaggerClient-php/tests/OrderApiTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/tests/OrderApiTest.php @@ -57,6 +57,66 @@ ORDER; $this->assertSame(false, $order->getComplete()); } + // test deseralization of array of array of order + public function testDeserializationOfArrayOfArrayOfOrder() + { + $order_json = <<deserialize(json_decode($order_json), 'Swagger\Client\Model\Order[][]'); + + $this->assertArrayHasKey(0, $order); + $this->assertArrayHasKey(0, $order[0]); + $_order = $order[0][0]; + $this->assertInstanceOf('Swagger\Client\Model\Order', $_order); + $this->assertSame(10, $_order->getId()); + $this->assertSame(20, $_order->getPetId()); + $this->assertSame(30, $_order->getQuantity()); + $this->assertTrue(new DateTime("2015-08-22T07:13:36.613Z") == $_order->getShipDate()); + $this->assertSame("placed", $_order->getStatus()); + $this->assertSame(false, $_order->getComplete()); + } + + // test deseralization of map of map of order + public function testDeserializationOfMapOfMapOfOrder() + { + $order_json = <<deserialize(json_decode($order_json), 'map[string,map[string,\Swagger\Client\Model\Order]]'); + + $this->assertArrayHasKey('test', $order); + $this->assertArrayHasKey('test2', $order['test']); + $_order = $order['test']['test2']; + $this->assertInstanceOf('Swagger\Client\Model\Order', $_order); + $this->assertSame(10, $_order->getId()); + $this->assertSame(20, $_order->getPetId()); + $this->assertSame(30, $_order->getQuantity()); + $this->assertTrue(new DateTime("2015-08-22T07:13:36.613Z") == $_order->getShipDate()); + $this->assertSame("placed", $_order->getStatus()); + $this->assertSame(false, $_order->getComplete()); + } + } ?> diff --git a/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php b/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php index c81b07b38fd..a7f53d5c5ba 100644 --- a/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php @@ -5,257 +5,256 @@ require_once('autoload.php'); class PetApiTest extends \PHPUnit_Framework_TestCase { - // add a new pet (id 10005) to ensure the pet object is available for all the tests - public static function setUpBeforeClass() { - // for error reporting (need to run with php5.3 to get no warning) - //ini_set('display_errors', 1); - //error_reporting(~0); - // when running with php5.5, comment out below to skip the warning about - // using @ to handle file upload - //ini_set('display_startup_errors',1); - //ini_set('display_errors',1); - //error_reporting(-1); - - // enable debugging - //Swagger\Client\Configuration::$debug = true; - - // skip initializing the API client as it should be automatic - //$api_client = new Swagger\Client\ApiClient('http://petstore.swagger.io/v2'); - // new pet - $new_pet_id = 10005; - $new_pet = new Swagger\Client\Model\Pet; - $new_pet->setId($new_pet_id); - $new_pet->setName("PHP Unit Test"); - // new tag - $tag= new Swagger\Client\Model\Tag; - $tag->setId($new_pet_id); // use the same id as pet - $tag->setName("test php tag"); - // new category - $category = new Swagger\Client\Model\Category; - $category->setId($new_pet_id); // use the same id as pet - $category->setName("test php category"); - - $new_pet->setTags(array($tag)); - $new_pet->setCategory($category); - - $pet_api = new Swagger\Client\Api\PetAPI(); - // add a new pet (model) - $add_response = $pet_api->addPet($new_pet); - } - - // test static functions defined in ApiClient - public function testApiClient() - { - // test selectHeaderAccept - $api_client = new Swagger\Client\ApiClient(); - $this->assertSame('application/json', $api_client->selectHeaderAccept(array('application/xml','application/json'))); - $this->assertSame(NULL, $api_client->selectHeaderAccept(array())); - $this->assertSame('application/yaml,application/xml', $api_client->selectHeaderAccept(array('application/yaml','application/xml'))); - - // test selectHeaderContentType - $this->assertSame('application/json', $api_client->selectHeaderContentType(array('application/xml','application/json'))); - $this->assertSame('application/json', $api_client->selectHeaderContentType(array())); - $this->assertSame('application/yaml,application/xml', $api_client->selectHeaderContentType(array('application/yaml','application/xml'))); - - // test addDefaultHeader and getDefaultHeader - $api_client->getConfig()->addDefaultHeader('test1', 'value1'); - $api_client->getConfig()->addDefaultHeader('test2', 200); - $defaultHeader = $api_client->getConfig()->getDefaultHeaders(); - $this->assertSame('value1', $defaultHeader['test1']); - $this->assertSame(200, $defaultHeader['test2']); - - // test deleteDefaultHeader - $api_client->getConfig()->deleteDefaultHeader('test2'); - $defaultHeader = $api_client->getConfig()->getDefaultHeaders(); - $this->assertFalse(isset($defaultHeader['test2'])); - - $pet_api2 = new Swagger\Client\Api\PetAPI(); - $config3 = new Swagger\Client\Configuration(); - $apiClient3 = new Swagger\Client\ApiClient($config3); - $apiClient3->getConfig()->setUserAgent('api client 3'); - $config4 = new Swagger\Client\Configuration(); - $apiClient4 = new Swagger\Client\ApiClient($config4); - $apiClient4->getConfig()->setUserAgent('api client 4'); - $pet_api3 = new Swagger\Client\Api\PetAPI($apiClient3); - - // 2 different api clients are not the same - $this->assertNotEquals($apiClient3, $apiClient4); - // customied pet api not using the old pet api's api client - $this->assertNotEquals($pet_api2->getApiClient(), $pet_api3->getApiClient()); - - // test access token - $api_client->getConfig()->setAccessToken("testing_only"); - $this->assertSame('testing_only', $api_client->getConfig()->getAccessToken()); - } - - // test getPetById with a Pet object (id 10005) - public function testGetPetById() - { - // initialize the API client without host - $pet_id = 10005; // ID of pet that needs to be fetched - $pet_api = new Swagger\Client\Api\PetAPI(); - $pet_api->getApiClient()->getConfig()->setApiKey('api_key', '111222333444555'); - // return Pet (model) - $response = $pet_api->getPetById($pet_id); - $this->assertSame($response->getId(), $pet_id); - $this->assertSame($response->getName(), 'PHP Unit Test'); - $this->assertSame($response->getCategory()->getId(), $pet_id); - $this->assertSame($response->getCategory()->getName(), 'test php category'); - $this->assertSame($response->getTags()[0]->getId(), $pet_id); - $this->assertSame($response->getTags()[0]->getName(), 'test php tag'); - } - - // test getPetById with a Pet object (id 10005) - public function testGetPetByIdWithHttpInfo() - { - // initialize the API client without host - $pet_id = 10005; // ID of pet that needs to be fetched - $pet_api = new Swagger\Client\Api\PetAPI(); - $pet_api->getApiClient()->getConfig()->setApiKey('api_key', '111222333444555'); - // return Pet (model) - list($response, $status_code, $response_headers) = $pet_api->getPetByIdWithHttpInfo($pet_id); - $this->assertSame($response->getId(), $pet_id); - $this->assertSame($response->getName(), 'PHP Unit Test'); - $this->assertSame($response->getCategory()->getId(), $pet_id); - $this->assertSame($response->getCategory()->getName(), 'test php category'); - $this->assertSame($response->getTags()[0]->getId(), $pet_id); - $this->assertSame($response->getTags()[0]->getName(), 'test php tag'); - $this->assertSame($status_code, 200); - $this->assertSame($response_headers['Content-Type'], 'application/json'); - } - - // test getPetByStatus and verify by the "id" of the response - public function testFindPetByStatus() - { - // initialize the API client - $config = (new Swagger\Client\Configuration())->setHost('http://petstore.swagger.io/v2'); - $api_client = new Swagger\Client\ApiClient($config); - $pet_api = new Swagger\Client\Api\PetAPI($api_client); - // return Pet (model) - $response = $pet_api->findPetsByStatus("available"); - $this->assertGreaterThan(0, count($response)); // at least one object returned - $this->assertSame(get_class($response[0]), "Swagger\\Client\\Model\\Pet"); // verify the object is Pet - // loop through result to ensure status is "available" - foreach ($response as $_pet) { - $this->assertSame($_pet['status'], "available"); + // add a new pet (id 10005) to ensure the pet object is available for all the tests + public static function setUpBeforeClass() { + // for error reporting (need to run with php5.3 to get no warning) + //ini_set('display_errors', 1); + //error_reporting(~0); + // when running with php5.5, comment out below to skip the warning about + // using @ to handle file upload + //ini_set('display_startup_errors',1); + //ini_set('display_errors',1); + //error_reporting(-1); + + // enable debugging + //Swagger\Client\Configuration::$debug = true; + + // skip initializing the API client as it should be automatic + //$api_client = new Swagger\Client\ApiClient('http://petstore.swagger.io/v2'); + // new pet + $new_pet_id = 10005; + $new_pet = new Swagger\Client\Model\Pet; + $new_pet->setId($new_pet_id); + $new_pet->setName("PHP Unit Test"); + // new tag + $tag= new Swagger\Client\Model\Tag; + $tag->setId($new_pet_id); // use the same id as pet + $tag->setName("test php tag"); + // new category + $category = new Swagger\Client\Model\Category; + $category->setId($new_pet_id); // use the same id as pet + $category->setName("test php category"); + + $new_pet->setTags(array($tag)); + $new_pet->setCategory($category); + + $pet_api = new Swagger\Client\Api\PetAPI(); + // add a new pet (model) + $add_response = $pet_api->addPet($new_pet); } - // test invalid status - $response = $pet_api->findPetsByStatus("unknown_and_incorrect_status"); - $this->assertSame(count($response), 0); // confirm no object returned - } - - // test updatePet (model/json)and verify by the "id" of the response - public function testUpdatePet() - { - // initialize the API client - $config = (new Swagger\Client\Configuration())->setHost('http://petstore.swagger.io/v2'); - $api_client = new Swagger\Client\ApiClient($config); - $pet_id = 10001; // ID of pet that needs to be fetched - $pet_api = new Swagger\Client\Api\PetAPI($api_client); - // create updated pet object - $updated_pet = new Swagger\Client\Model\Pet; - $updated_pet->setId($pet_id); - $updated_pet->setName('updatePet'); // new name - $updated_pet->setStatus('pending'); // new status - // update Pet (model/json) - $update_response = $pet_api->updatePet($updated_pet); - // return nothing (void) - $this->assertSame($update_response, NULL); - // verify updated Pet - $response = $pet_api->getPetById($pet_id); - $this->assertSame($response->getId(), $pet_id); - $this->assertSame($response->getStatus(), 'pending'); - $this->assertSame($response->getName(), 'updatePet'); - } - - // test updatePetWithFormWithHttpInfo and verify by the "name" of the response - public function testUpdatePetWithFormWithHttpInfo() - { - // initialize the API client - $config = (new Swagger\Client\Configuration())->setHost('http://petstore.swagger.io/v2'); - $api_client = new Swagger\Client\ApiClient($config); - $pet_id = 10001; // ID of pet that needs to be fetched - $pet_api = new Swagger\Client\Api\PetAPI($api_client); - // update Pet (form) - list($update_response, $status_code, $http_headers) = $pet_api->updatePetWithFormWithHttpInfo($pet_id, 'update pet with form with http info'); - // return nothing (void) - $this->assertNull($update_response); - $this->assertSame($status_code, 200); - $this->assertSame($http_headers['Content-Type'], 'application/json'); - $response = $pet_api->getPetById($pet_id); - $this->assertSame($response->getId(), $pet_id); - $this->assertSame($response->getName(), 'update pet with form with http info'); - } - - // test updatePetWithForm and verify by the "name" and "status" of the response - public function testUpdatePetWithForm() - { - // initialize the API client - $config = (new Swagger\Client\Configuration())->setHost('http://petstore.swagger.io/v2'); - $api_client = new Swagger\Client\ApiClient($config); - $pet_id = 10001; // ID of pet that needs to be fetched - $pet_api = new Swagger\Client\Api\PetAPI($api_client); - // update Pet (form) - $update_response = $pet_api->updatePetWithForm($pet_id, 'update pet with form', 'sold'); - // return nothing (void) - $this->assertSame($update_response, NULL); - $response = $pet_api->getPetById($pet_id); - $this->assertSame($response->getId(), $pet_id); - $this->assertSame($response->getName(), 'update pet with form'); - $this->assertSame($response->getStatus(), 'sold'); - } - - // test addPet and verify by the "id" and "name" of the response - public function testAddPet() - { - // initialize the API client - $config = (new Swagger\Client\Configuration())->setHost('http://petstore.swagger.io/v2'); - $api_client = new Swagger\Client\ApiClient($config); - $new_pet_id = 10001; - $new_pet = new Swagger\Client\Model\Pet; - $new_pet->setId($new_pet_id); - $new_pet->setName("PHP Unit Test"); - $pet_api = new Swagger\Client\Api\PetAPI($api_client); - // add a new pet (model) - $add_response = $pet_api->addPet($new_pet); - // return nothing (void) - $this->assertSame($add_response, NULL); - // verify added Pet - $response = $pet_api->getPetById($new_pet_id); - $this->assertSame($response->getId(), $new_pet_id); - $this->assertSame($response->getName(), 'PHP Unit Test'); - } - - // test upload file - public function testUploadFile() - { - // initialize the API client - $config = (new Swagger\Client\Configuration())->setHost('http://petstore.swagger.io/v2'); - $api_client = new Swagger\Client\ApiClient($config); - $pet_api = new Swagger\Client\Api\PetAPI($api_client); - // upload file - $pet_id = 10001; - $add_response = $pet_api->uploadFile($pet_id, "test meta", "./composer.json"); - // return nothing (void) - $this->assertSame($add_response, NULL); - } - - // test get inventory - public function testGetInventory() - { - // initialize the API client - $config = new Swagger\Client\Configuration(); - $config->setHost('http://petstore.swagger.io/v2'); - $api_client = new Swagger\Client\APIClient($config); - $store_api = new Swagger\Client\Api\StoreAPI($api_client); - // get inventory - $get_response = $store_api->getInventory(); - - $this->assertInternalType("int", $get_response['sold']); - $this->assertInternalType("int", $get_response['pending']); - - } - + + // test static functions defined in ApiClient + public function testApiClient() + { + // test selectHeaderAccept + $api_client = new Swagger\Client\ApiClient(); + $this->assertSame('application/json', $api_client->selectHeaderAccept(array('application/xml','application/json'))); + $this->assertSame(NULL, $api_client->selectHeaderAccept(array())); + $this->assertSame('application/yaml,application/xml', $api_client->selectHeaderAccept(array('application/yaml','application/xml'))); + + // test selectHeaderContentType + $this->assertSame('application/json', $api_client->selectHeaderContentType(array('application/xml','application/json'))); + $this->assertSame('application/json', $api_client->selectHeaderContentType(array())); + $this->assertSame('application/yaml,application/xml', $api_client->selectHeaderContentType(array('application/yaml','application/xml'))); + + // test addDefaultHeader and getDefaultHeader + $api_client->getConfig()->addDefaultHeader('test1', 'value1'); + $api_client->getConfig()->addDefaultHeader('test2', 200); + $defaultHeader = $api_client->getConfig()->getDefaultHeaders(); + $this->assertSame('value1', $defaultHeader['test1']); + $this->assertSame(200, $defaultHeader['test2']); + + // test deleteDefaultHeader + $api_client->getConfig()->deleteDefaultHeader('test2'); + $defaultHeader = $api_client->getConfig()->getDefaultHeaders(); + $this->assertFalse(isset($defaultHeader['test2'])); + + $pet_api2 = new Swagger\Client\Api\PetAPI(); + $config3 = new Swagger\Client\Configuration(); + $apiClient3 = new Swagger\Client\ApiClient($config3); + $apiClient3->getConfig()->setUserAgent('api client 3'); + $config4 = new Swagger\Client\Configuration(); + $apiClient4 = new Swagger\Client\ApiClient($config4); + $apiClient4->getConfig()->setUserAgent('api client 4'); + $pet_api3 = new Swagger\Client\Api\PetAPI($apiClient3); + + // 2 different api clients are not the same + $this->assertNotEquals($apiClient3, $apiClient4); + // customied pet api not using the old pet api's api client + $this->assertNotEquals($pet_api2->getApiClient(), $pet_api3->getApiClient()); + + // test access token + $api_client->getConfig()->setAccessToken("testing_only"); + $this->assertSame('testing_only', $api_client->getConfig()->getAccessToken()); + } + + // test getPetById with a Pet object (id 10005) + public function testGetPetById() + { + // initialize the API client without host + $pet_id = 10005; // ID of pet that needs to be fetched + $pet_api = new Swagger\Client\Api\PetAPI(); + $pet_api->getApiClient()->getConfig()->setApiKey('api_key', '111222333444555'); + // return Pet (model) + $response = $pet_api->getPetById($pet_id); + $this->assertSame($response->getId(), $pet_id); + $this->assertSame($response->getName(), 'PHP Unit Test'); + $this->assertSame($response->getCategory()->getId(), $pet_id); + $this->assertSame($response->getCategory()->getName(), 'test php category'); + $this->assertSame($response->getTags()[0]->getId(), $pet_id); + $this->assertSame($response->getTags()[0]->getName(), 'test php tag'); + } + + // test getPetById with a Pet object (id 10005) + public function testGetPetByIdWithHttpInfo() + { + // initialize the API client without host + $pet_id = 10005; // ID of pet that needs to be fetched + $pet_api = new Swagger\Client\Api\PetAPI(); + $pet_api->getApiClient()->getConfig()->setApiKey('api_key', '111222333444555'); + // return Pet (model) + list($response, $status_code, $response_headers) = $pet_api->getPetByIdWithHttpInfo($pet_id); + $this->assertSame($response->getId(), $pet_id); + $this->assertSame($response->getName(), 'PHP Unit Test'); + $this->assertSame($response->getCategory()->getId(), $pet_id); + $this->assertSame($response->getCategory()->getName(), 'test php category'); + $this->assertSame($response->getTags()[0]->getId(), $pet_id); + $this->assertSame($response->getTags()[0]->getName(), 'test php tag'); + $this->assertSame($status_code, 200); + $this->assertSame($response_headers['Content-Type'], 'application/json'); + } + + // test getPetByStatus and verify by the "id" of the response + public function testFindPetByStatus() + { + // initialize the API client + $config = (new Swagger\Client\Configuration())->setHost('http://petstore.swagger.io/v2'); + $api_client = new Swagger\Client\ApiClient($config); + $pet_api = new Swagger\Client\Api\PetAPI($api_client); + // return Pet (model) + $response = $pet_api->findPetsByStatus("available"); + $this->assertGreaterThan(0, count($response)); // at least one object returned + $this->assertSame(get_class($response[0]), "Swagger\\Client\\Model\\Pet"); // verify the object is Pet + // loop through result to ensure status is "available" + foreach ($response as $_pet) { + $this->assertSame($_pet['status'], "available"); + } + // test invalid status + $response = $pet_api->findPetsByStatus("unknown_and_incorrect_status"); + $this->assertSame(count($response), 0); // confirm no object returned + } + + // test updatePet (model/json)and verify by the "id" of the response + public function testUpdatePet() + { + // initialize the API client + $config = (new Swagger\Client\Configuration())->setHost('http://petstore.swagger.io/v2'); + $api_client = new Swagger\Client\ApiClient($config); + $pet_id = 10001; // ID of pet that needs to be fetched + $pet_api = new Swagger\Client\Api\PetAPI($api_client); + // create updated pet object + $updated_pet = new Swagger\Client\Model\Pet; + $updated_pet->setId($pet_id); + $updated_pet->setName('updatePet'); // new name + $updated_pet->setStatus('pending'); // new status + // update Pet (model/json) + $update_response = $pet_api->updatePet($updated_pet); + // return nothing (void) + $this->assertSame($update_response, NULL); + // verify updated Pet + $response = $pet_api->getPetById($pet_id); + $this->assertSame($response->getId(), $pet_id); + $this->assertSame($response->getStatus(), 'pending'); + $this->assertSame($response->getName(), 'updatePet'); + } + + // test updatePetWithFormWithHttpInfo and verify by the "name" of the response + public function testUpdatePetWithFormWithHttpInfo() + { + // initialize the API client + $config = (new Swagger\Client\Configuration())->setHost('http://petstore.swagger.io/v2'); + $api_client = new Swagger\Client\ApiClient($config); + $pet_id = 10001; // ID of pet that needs to be fetched + $pet_api = new Swagger\Client\Api\PetAPI($api_client); + // update Pet (form) + list($update_response, $status_code, $http_headers) = $pet_api->updatePetWithFormWithHttpInfo($pet_id, 'update pet with form with http info'); + // return nothing (void) + $this->assertNull($update_response); + $this->assertSame($status_code, 200); + $this->assertSame($http_headers['Content-Type'], 'application/json'); + $response = $pet_api->getPetById($pet_id); + $this->assertSame($response->getId(), $pet_id); + $this->assertSame($response->getName(), 'update pet with form with http info'); + } + + // test updatePetWithForm and verify by the "name" and "status" of the response + public function testUpdatePetWithForm() + { + // initialize the API client + $config = (new Swagger\Client\Configuration())->setHost('http://petstore.swagger.io/v2'); + $api_client = new Swagger\Client\ApiClient($config); + $pet_id = 10001; // ID of pet that needs to be fetched + $pet_api = new Swagger\Client\Api\PetAPI($api_client); + // update Pet (form) + $update_response = $pet_api->updatePetWithForm($pet_id, 'update pet with form', 'sold'); + // return nothing (void) + $this->assertSame($update_response, NULL); + $response = $pet_api->getPetById($pet_id); + $this->assertSame($response->getId(), $pet_id); + $this->assertSame($response->getName(), 'update pet with form'); + $this->assertSame($response->getStatus(), 'sold'); + } + + // test addPet and verify by the "id" and "name" of the response + public function testAddPet() + { + // initialize the API client + $config = (new Swagger\Client\Configuration())->setHost('http://petstore.swagger.io/v2'); + $api_client = new Swagger\Client\ApiClient($config); + $new_pet_id = 10001; + $new_pet = new Swagger\Client\Model\Pet; + $new_pet->setId($new_pet_id); + $new_pet->setName("PHP Unit Test"); + $pet_api = new Swagger\Client\Api\PetAPI($api_client); + // add a new pet (model) + $add_response = $pet_api->addPet($new_pet); + // return nothing (void) + $this->assertSame($add_response, NULL); + // verify added Pet + $response = $pet_api->getPetById($new_pet_id); + $this->assertSame($response->getId(), $new_pet_id); + $this->assertSame($response->getName(), 'PHP Unit Test'); + } + + // test upload file + public function testUploadFile() + { + // initialize the API client + $config = (new Swagger\Client\Configuration())->setHost('http://petstore.swagger.io/v2'); + $api_client = new Swagger\Client\ApiClient($config); + $pet_api = new Swagger\Client\Api\PetAPI($api_client); + // upload file + $pet_id = 10001; + $add_response = $pet_api->uploadFile($pet_id, "test meta", "./composer.json"); + // return nothing (void) + $this->assertSame($add_response, NULL); + } + + // test get inventory + public function testGetInventory() + { + // initialize the API client + $config = new Swagger\Client\Configuration(); + $config->setHost('http://petstore.swagger.io/v2'); + $api_client = new Swagger\Client\APIClient($config); + $store_api = new Swagger\Client\Api\StoreAPI($api_client); + // get inventory + $get_response = $store_api->getInventory(); + + $this->assertInternalType("int", $get_response['sold']); + $this->assertInternalType("int", $get_response['pending']); + } + } ?> diff --git a/samples/client/petstore/python/swagger_client/api_client.py b/samples/client/petstore/python/swagger_client/api_client.py index 63740a08745..00b901f3c4a 100644 --- a/samples/client/petstore/python/swagger_client/api_client.py +++ b/samples/client/petstore/python/swagger_client/api_client.py @@ -1,7 +1,7 @@ # coding: utf-8 """ -Copyright 2015 SmartBear Software +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. diff --git a/samples/client/petstore/python/swagger_client/apis/pet_api.py b/samples/client/petstore/python/swagger_client/apis/pet_api.py index d7bc11daaaf..8e50474658c 100644 --- a/samples/client/petstore/python/swagger_client/apis/pet_api.py +++ b/samples/client/petstore/python/swagger_client/apis/pet_api.py @@ -2,7 +2,7 @@ """ PetApi.py -Copyright 2015 SmartBear Software +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. diff --git a/samples/client/petstore/python/swagger_client/apis/store_api.py b/samples/client/petstore/python/swagger_client/apis/store_api.py index e3835990a30..af6e56d6928 100644 --- a/samples/client/petstore/python/swagger_client/apis/store_api.py +++ b/samples/client/petstore/python/swagger_client/apis/store_api.py @@ -2,7 +2,7 @@ """ StoreApi.py -Copyright 2015 SmartBear Software +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. diff --git a/samples/client/petstore/python/swagger_client/apis/user_api.py b/samples/client/petstore/python/swagger_client/apis/user_api.py index 4394941b1d5..98111a84d9d 100644 --- a/samples/client/petstore/python/swagger_client/apis/user_api.py +++ b/samples/client/petstore/python/swagger_client/apis/user_api.py @@ -2,7 +2,7 @@ """ UserApi.py -Copyright 2015 SmartBear Software +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. diff --git a/samples/client/petstore/python/swagger_client/configuration.py b/samples/client/petstore/python/swagger_client/configuration.py index ecbecf7e9f9..fe38630927e 100644 --- a/samples/client/petstore/python/swagger_client/configuration.py +++ b/samples/client/petstore/python/swagger_client/configuration.py @@ -1,7 +1,7 @@ # coding: utf-8 """ -Copyright 2015 SmartBear Software +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. diff --git a/samples/client/petstore/python/swagger_client/models/category.py b/samples/client/petstore/python/swagger_client/models/category.py index 7c36ea3ec47..d5156eee4ff 100644 --- a/samples/client/petstore/python/swagger_client/models/category.py +++ b/samples/client/petstore/python/swagger_client/models/category.py @@ -1,7 +1,7 @@ # coding: utf-8 """ -Copyright 2015 SmartBear Software +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. diff --git a/samples/client/petstore/python/swagger_client/models/order.py b/samples/client/petstore/python/swagger_client/models/order.py index 39081233b11..93126d98a86 100644 --- a/samples/client/petstore/python/swagger_client/models/order.py +++ b/samples/client/petstore/python/swagger_client/models/order.py @@ -1,7 +1,7 @@ # coding: utf-8 """ -Copyright 2015 SmartBear Software +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. diff --git a/samples/client/petstore/python/swagger_client/models/pet.py b/samples/client/petstore/python/swagger_client/models/pet.py index eafb352f2d0..d7c425e3e0e 100644 --- a/samples/client/petstore/python/swagger_client/models/pet.py +++ b/samples/client/petstore/python/swagger_client/models/pet.py @@ -1,7 +1,7 @@ # coding: utf-8 """ -Copyright 2015 SmartBear Software +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. diff --git a/samples/client/petstore/python/swagger_client/models/tag.py b/samples/client/petstore/python/swagger_client/models/tag.py index 2041940dadf..81d27fa5e63 100644 --- a/samples/client/petstore/python/swagger_client/models/tag.py +++ b/samples/client/petstore/python/swagger_client/models/tag.py @@ -1,7 +1,7 @@ # coding: utf-8 """ -Copyright 2015 SmartBear Software +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. diff --git a/samples/client/petstore/python/swagger_client/models/user.py b/samples/client/petstore/python/swagger_client/models/user.py index a3ad99fa4c5..6af36592c02 100644 --- a/samples/client/petstore/python/swagger_client/models/user.py +++ b/samples/client/petstore/python/swagger_client/models/user.py @@ -1,7 +1,7 @@ # coding: utf-8 """ -Copyright 2015 SmartBear Software +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. diff --git a/samples/client/petstore/python/swagger_client/rest.py b/samples/client/petstore/python/swagger_client/rest.py index 0d1f4ce1da8..c5b9a4e6f91 100644 --- a/samples/client/petstore/python/swagger_client/rest.py +++ b/samples/client/petstore/python/swagger_client/rest.py @@ -1,7 +1,7 @@ # coding: utf-8 """ -Copyright 2015 SmartBear Software +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. diff --git a/samples/client/petstore/ruby/Gemfile.lock b/samples/client/petstore/ruby/Gemfile.lock index 05a6aa23790..e7812e45845 100644 --- a/samples/client/petstore/ruby/Gemfile.lock +++ b/samples/client/petstore/ruby/Gemfile.lock @@ -12,7 +12,7 @@ GEM addressable (2.3.8) autotest (4.4.6) ZenTest (>= 4.4.1) - autotest-fsevent (0.2.10) + autotest-fsevent (0.2.11) sys-uname autotest-growl (0.2.16) autotest-rails-pure (4.1.2) @@ -51,7 +51,7 @@ PLATFORMS DEPENDENCIES autotest (~> 4.4, >= 4.4.6) - autotest-fsevent (~> 0.2, >= 0.2.10) + autotest-fsevent (~> 0.2, >= 0.2.11) autotest-growl (~> 0.2, >= 0.2.16) autotest-rails-pure (~> 4.1, >= 4.1.2) petstore! diff --git a/samples/client/petstore/ruby/petstore.gemspec b/samples/client/petstore/ruby/petstore.gemspec index 6e41479fe46..df8a6df24d0 100644 --- a/samples/client/petstore/ruby/petstore.gemspec +++ b/samples/client/petstore/ruby/petstore.gemspec @@ -22,7 +22,7 @@ Gem::Specification.new do |s| s.add_development_dependency 'autotest', '~> 4.4', '>= 4.4.6' s.add_development_dependency 'autotest-rails-pure', '~> 4.1', '>= 4.1.2' s.add_development_dependency 'autotest-growl', '~> 0.2', '>= 0.2.16' - s.add_development_dependency 'autotest-fsevent', '~> 0.2', '>= 0.2.10' + s.add_development_dependency 'autotest-fsevent', '~> 0.2', '>= 0.2.11' s.files = `find *`.split("\n").uniq.sort.select{|f| !f.empty? } s.test_files = `find spec/*`.split("\n") diff --git a/samples/client/petstore/ruby/spec/api_client_spec.rb b/samples/client/petstore/ruby/spec/api_client_spec.rb index aeb4eefad51..347b9876cf7 100644 --- a/samples/client/petstore/ruby/spec/api_client_spec.rb +++ b/samples/client/petstore/ruby/spec/api_client_spec.rb @@ -112,6 +112,24 @@ describe Petstore::ApiClient do end describe "#deserialize" do + it "handles Array" do + api_client = Petstore::ApiClient.new + headers = {'Content-Type' => 'application/json'} + response = double('response', headers: headers, body: '[12, 34]') + data = api_client.deserialize(response, 'Array') + data.should be_a(Array) + data.should == [12, 34] + end + + it "handles Array>" do + api_client = Petstore::ApiClient.new + headers = {'Content-Type' => 'application/json'} + response = double('response', headers: headers, body: '[[12, 34], [56]]') + data = api_client.deserialize(response, 'Array>') + data.should be_a(Array) + data.should == [[12, 34], [56]] + end + it "handles Hash" do api_client = Petstore::ApiClient.new headers = {'Content-Type' => 'application/json'} @@ -132,6 +150,21 @@ describe Petstore::ApiClient do pet.should be_a(Petstore::Pet) pet.id.should == 1 end + + it "handles Hash>" do + api_client = Petstore::ApiClient.new + headers = {'Content-Type' => 'application/json'} + response = double('response', headers: headers, body: '{"data": {"pet": {"id": 1}}}') + result = api_client.deserialize(response, 'Hash>') + result.should be_a(Hash) + result.keys.should == [:data] + data = result[:data] + data.should be_a(Hash) + data.keys.should == [:pet] + pet = data[:pet] + pet.should be_a(Petstore::Pet) + pet.id.should == 1 + end end describe "#object_to_hash" do diff --git a/samples/client/petstore/ruby/spec/spec_helper.rb b/samples/client/petstore/ruby/spec/spec_helper.rb index 26da98f9c42..5eff37b134a 100644 --- a/samples/client/petstore/ruby/spec/spec_helper.rb +++ b/samples/client/petstore/ruby/spec/spec_helper.rb @@ -40,8 +40,13 @@ API_CLIENT = Petstore::ApiClient.new(Petstore::Configuration.new) # always delete and then re-create the pet object with 10002 def prepare_pet(pet_api) - # remove the pet - pet_api.delete_pet(10002) + begin + # remove the pet + pet_api.delete_pet(10002) + rescue Petstore::ApiError => e + # ignore ApiError 404 (Not Found) + raise e if e.code != 404 + end # recreate the pet category = Petstore::Category.new('id' => 20002, 'name' => 'category test') tag = Petstore::Tag.new('id' => 30002, 'name' => 'tag test')