diff --git a/.gitignore b/.gitignore index d55a8014a342..db34c76636c6 100644 --- a/.gitignore +++ b/.gitignore @@ -13,6 +13,7 @@ generated-sources/* generated-code/* *.swp *.swo +*.csproj.user /target /generated-files @@ -36,6 +37,9 @@ samples/client/petstore/objc/SwaggerClientTests/Pods samples/client/petstore/objc/SwaggerClientTests/SwaggerClient.xcworkspace samples/client/petstore/objc/SwaggerClientTests/Podfile.lock samples/server/petstore/nodejs/node_modules +samples/client/petstore/csharp/SwaggerClientTest/.vs +samples/client/petstore/csharp/SwaggerClientTest/obj +samples/client/petstore/csharp/SwaggerClientTest/bin target .idea .lib @@ -60,4 +64,4 @@ samples/client/petstore/python/.venv/ *.java~ *.pm~ *.xml~ -*.t~ \ No newline at end of file +*.t~ diff --git a/README.md b/README.md index e1015f0fef8a..3f1691144b9a 100644 --- a/README.md +++ b/README.md @@ -299,6 +299,7 @@ JavaClientCodegen.java JavaInflectorServerCodegen.java JavascriptClientCodegen.java JaxRSServerCodegen.java +JMeterCodegen.java NodeJSServerCodegen.java ObjcClientCodegen.java PerlClientCodegen.java @@ -376,9 +377,10 @@ CONFIG OPTIONS library template (sub-template) to use: - HTTP client: Jersey client 1.18. JSON processing: Jackson 2.4.2 jersey2 - HTTP client: Jersey client 2.6 + feign - HTTP client: Netflix Feign 8.1.1. JSON processing: Jackson 2.6.3 okhttp-gson - HTTP client: OkHttp 2.4.0. JSON processing: Gson 2.3.1 retrofit - HTTP client: OkHttp 2.4.0. JSON processing: Gson 2.3.1 (Retrofit 1.9.0) - retrofit2 - HTTP client: OkHttp 2.5.0. JSON processing: Gson 2.4 (Retrofit 2.0.0-beta2) + retrofit2 - HTTP client: OkHttp 2.5.0. JSON processing: Gson 2.4 (Retrofit 2.0.0-beta2) ``` Your config file for java can look like @@ -387,7 +389,8 @@ Your config file for java can look like { "groupId":"com.my.company", "artifactId":"MyClent", - "artifactVersion":"1.2.0" + "artifactVersion":"1.2.0", + "library":"feign" } ``` diff --git a/bin/java-petstore-feign.json b/bin/java-petstore-feign.json new file mode 100644 index 000000000000..5502ee3bbad2 --- /dev/null +++ b/bin/java-petstore-feign.json @@ -0,0 +1,4 @@ +{ + "library": "feign", + "artifactId": "swagger-petstore-feign" +} diff --git a/bin/java-petstore-feign.sh b/bin/java-petstore-feign.sh new file mode 100755 index 000000000000..6f0a5fdf8ff5 --- /dev/null +++ b/bin/java-petstore-feign.sh @@ -0,0 +1,31 @@ +#!/bin/sh + +SCRIPT="$0" + +while [ -h "$SCRIPT" ] ; do + ls=`ls -ld "$SCRIPT"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + SCRIPT="$link" + else + SCRIPT=`dirname "$SCRIPT"`/"$link" + fi +done + +if [ ! -d "${APP_DIR}" ]; then + APP_DIR=`dirname "$SCRIPT"`/.. + APP_DIR=`cd "${APP_DIR}"; pwd` +fi + +executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar" + +if [ ! -f "$executable" ] +then + mvn clean package +fi + +# if you've executed sbt assembly previously it will use that instead. +export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" +ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l java -c bin/java-petstore-feign.json -o samples/client/petstore/java/feign" + +java $JAVA_OPTS -jar $executable $ags diff --git a/config-feign.json b/config-feign.json new file mode 100644 index 000000000000..3b8c48c3caa0 --- /dev/null +++ b/config-feign.json @@ -0,0 +1 @@ +{"library":"feign"} \ No newline at end of file diff --git a/modules/swagger-codegen/pom.xml b/modules/swagger-codegen/pom.xml index fc51a41fcdf9..656223ff42b9 100644 --- a/modules/swagger-codegen/pom.xml +++ b/modules/swagger-codegen/pom.xml @@ -154,6 +154,7 @@ target/site + org.apache.maven.plugins maven-javadoc-plugin diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConstants.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConstants.java index 74464397120e..9c2711f8cad8 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConstants.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConstants.java @@ -41,7 +41,7 @@ public class CodegenConstants { public static final String SORT_PARAMS_BY_REQUIRED_FLAG_DESC = "Sort method arguments to place required parameters before optional parameters."; public static final String ENSURE_UNIQUE_PARAMS = "ensureUniqueParams"; - public static final String ENSURE_UNIQUE_PARAMS_DESC = "Whether to ensure parameter names are unique in an operation (rename parameters that are not). Default: true"; + public static final String ENSURE_UNIQUE_PARAMS_DESC = "Whether to ensure parameter names are unique in an operation (rename parameters that are not)."; public static final String PACKAGE_NAME = "packageName"; public static final String PACKAGE_VERSION = "packageVersion"; diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java index e11e38691ef7..b2894e8b2e9c 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java @@ -448,7 +448,8 @@ public class DefaultCodegen { cliOptions.add(new CliOption(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG_DESC).defaultValue("true")); - cliOptions.add(new CliOption(CodegenConstants.ENSURE_UNIQUE_PARAMS, CodegenConstants.ENSURE_UNIQUE_PARAMS_DESC)); + cliOptions.add(new CliOption(CodegenConstants.ENSURE_UNIQUE_PARAMS, CodegenConstants.ENSURE_UNIQUE_PARAMS_DESC) + .defaultValue("true")); } /** @@ -1826,6 +1827,16 @@ public class DefaultCodegen { return word; } + /** + * Dashize the given word. + * + * @param word The word + * @return The dashized version of the word, e.g. "my-name" + */ + protected String dashize(String word) { + return underscore(word).replaceAll("[_ ]", "-"); + } + /** * Generate the next name for the given name, i.e. append "2" to the base name if not ending with a number, * otherwise increase the number by 1. For example: diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ClojureClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ClojureClientCodegen.java index a850785a7dbb..c8b581b3d3a4 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ClojureClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ClojureClientCodegen.java @@ -199,8 +199,4 @@ public class ClojureClientCodegen extends DefaultCodegen implements CodegenConfi protected String namespaceToFolder(String ns) { return ns.replace(".", File.separator).replace("-", "_"); } - - protected String dashize(String s) { - return underscore(s).replaceAll("[_ ]", "-"); - } } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JMeterCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JMeterCodegen.java new file mode 100644 index 000000000000..fb1674772146 --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JMeterCodegen.java @@ -0,0 +1,183 @@ +package io.swagger.codegen.languages; + +import io.swagger.codegen.*; +import io.swagger.models.Operation; +import io.swagger.models.Path; +import io.swagger.models.Swagger; +import io.swagger.models.properties.*; +import org.apache.commons.lang.StringUtils; + +import java.util.*; +import java.io.File; + +public class JMeterCodegen extends DefaultCodegen implements CodegenConfig { + + // source folder where to write the files + protected String sourceFolder = ""; + protected String apiVersion = "1.0.0"; + + /** + * Configures the type of generator. + * + * @return the CodegenType for this generator + * @see io.swagger.codegen.CodegenType + */ + public CodegenType getTag() { + return CodegenType.CLIENT; + } + + /** + * Configures a friendly name for the generator. This will be used by the generator + * to select the library with the -l flag. + * + * @return the friendly name for the generator + */ + public String getName() { + return "jmeter"; + } + + /** + * Returns human-friendly help for the generator. Provide the consumer with help + * tips, parameters here + * + * @return A string value for the help message + */ + public String getHelp() { + return "Generates a JMeter .jmx file."; + } + + public JMeterCodegen() { + super(); + + // set the output folder here + outputFolder = "generated-code/JMeterCodegen"; + + /** + * Api classes. You can write classes for each Api file with the apiTemplateFiles map. + * as with models, add multiple entries with different extensions for multiple files per + * class + */ + apiTemplateFiles.put( + "api.mustache", // the template to use + ".jmx"); // the extension for each file to write + + apiTemplateFiles.put("testdata-localhost.mustache", ".csv"); + + /** + * Template Location. This is the location which templates will be read from. The generator + * will use the resource stream to attempt to read the templates. + */ + templateDir = "JMeter"; + + /** + * Api Package. Optional, if needed, this can be used in templates + */ + apiPackage = ""; + + /** + * Model Package. Optional, if needed, this can be used in templates + */ + modelPackage = ""; + + /** + * Reserved words. Override this with reserved words specific to your language + */ + reservedWords = new HashSet ( + Arrays.asList( + "sample1", // replace with static values + "sample2") + ); + + /** + * Additional Properties. These values can be passed to the templates and + * are available in models, apis, and supporting files + */ + additionalProperties.put("apiVersion", apiVersion); + +// supportingFiles.add(new SupportingFile("testdata-localhost.mustache", "input", "testdata-localhost.csv")); + } + + public void preprocessSwagger(Swagger swagger) { + if (swagger != null && swagger.getPaths() != null) { + for (String pathname : swagger.getPaths().keySet()) { + Path path = swagger.getPath(pathname); + if (path.getOperations() != null) { + for (Operation operation : path.getOperations()) { + String pathWithDollars = pathname.replaceAll("\\{", "\\$\\{"); + operation.setVendorExtension("x-path", pathWithDollars); + } + } + } + } + } + + /** + * Escapes a reserved word as defined in the `reservedWords` array. Handle escaping + * those terms here. This logic is only called if a variable matches the reseved words + * + * @return the escaped term + */ + @Override + public String escapeReservedWord(String name) { + return "_" + name; // add an underscore to the name + } + + /** + * Location to write model files. You can use the modelPackage() as defined when the class is + * instantiated + */ + public String modelFileFolder() { + return outputFolder + "/" + sourceFolder + "/" + modelPackage().replace('.', File.separatorChar); + } + + /** + * Location to write api files. You can use the apiPackage() as defined when the class is + * instantiated + */ + @Override + public String apiFileFolder() { + return outputFolder + "/" + sourceFolder + "/" + apiPackage().replace('.', File.separatorChar); + } + + /** + * Optional - type declaration. This is a String which is used by the templates to instantiate your + * types. There is typically special handling for different property types + * + * @return a string value used as the `dataType` field for model templates, `returnType` for api templates + */ + @Override + public String getTypeDeclaration(Property p) { + if(p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + Property inner = ap.getItems(); + return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]"; + } + else if (p instanceof MapProperty) { + MapProperty mp = (MapProperty) p; + Property inner = mp.getAdditionalProperties(); + return getSwaggerType(p) + "[String, " + getTypeDeclaration(inner) + "]"; + } + return super.getTypeDeclaration(p); + } + + /** + * Optional - swagger type conversion. This is used to map swagger types in a `Property` into + * either language specific types via `typeMapping` or into complex models if there is not a mapping. + * + * @return a string value of the type or complex model for this property + * @see io.swagger.models.properties.Property + */ + @Override + public String getSwaggerType(Property p) { + String swaggerType = super.getSwaggerType(p); + String type = null; + if(typeMapping.containsKey(swaggerType)) { + type = typeMapping.get(swaggerType); + if(languageSpecificPrimitives.contains(type)) + return toModelName(type); + } + else + type = swaggerType; + return toModelName(type); + } +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaClientCodegen.java index 67a746d4afbc..1c03e6c9e6fd 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaClientCodegen.java @@ -11,6 +11,12 @@ import io.swagger.codegen.CodegenType; import io.swagger.codegen.DefaultCodegen; import io.swagger.codegen.SupportingFile; import io.swagger.models.Model; +import io.swagger.models.Operation; +import io.swagger.models.Path; +import io.swagger.models.Swagger; +import io.swagger.models.parameters.BodyParameter; +import io.swagger.models.parameters.FormParameter; +import io.swagger.models.parameters.Parameter; import io.swagger.models.properties.ArrayProperty; import io.swagger.models.properties.BooleanProperty; import io.swagger.models.properties.DoubleProperty; @@ -98,6 +104,7 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { .defaultValue("false")); supportedLibraries.put(DEFAULT_LIBRARY, "HTTP client: Jersey client 1.18. JSON processing: Jackson 2.4.2"); + supportedLibraries.put("feign", "HTTP client: Netflix Feign 8.1.1"); supportedLibraries.put("jersey2", "HTTP client: Jersey client 2.6"); supportedLibraries.put("okhttp-gson", "HTTP client: OkHttp 2.4.0. JSON processing: Gson 2.3.1"); supportedLibraries.put("retrofit", "HTTP client: OkHttp 2.4.0. JSON processing: Gson 2.3.1 (Retrofit 1.9.0)"); @@ -215,15 +222,18 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { supportingFiles.add(new SupportingFile("StringUtil.mustache", invokerFolder, "StringUtil.java")); final String authFolder = (sourceFolder + '/' + invokerPackage + ".auth").replace(".", "/"); - supportingFiles.add(new SupportingFile("auth/HttpBasicAuth.mustache", authFolder, "HttpBasicAuth.java")); - supportingFiles.add(new SupportingFile("auth/ApiKeyAuth.mustache", authFolder, "ApiKeyAuth.java")); - supportingFiles.add(new SupportingFile("auth/OAuth.mustache", authFolder, "OAuth.java")); - supportingFiles.add(new SupportingFile("auth/OAuthFlow.mustache", authFolder, "OAuthFlow.java")); + if ("feign".equals(getLibrary())) { + supportingFiles.add(new SupportingFile("FormAwareEncoder.mustache", invokerFolder, "FormAwareEncoder.java")); + } else { + supportingFiles.add(new SupportingFile("auth/HttpBasicAuth.mustache", authFolder, "HttpBasicAuth.java")); + supportingFiles.add(new SupportingFile("auth/ApiKeyAuth.mustache", authFolder, "ApiKeyAuth.java")); + supportingFiles.add(new SupportingFile("auth/OAuth.mustache", authFolder, "OAuth.java")); + supportingFiles.add(new SupportingFile("auth/OAuthFlow.mustache", authFolder, "OAuthFlow.java")); + } - if (!("retrofit".equals(getLibrary()) || "retrofit2".equals(getLibrary()))) { + if (!("feign".equals(getLibrary()) || "retrofit".equals(getLibrary()) || "retrofit2".equals(getLibrary()))) { supportingFiles.add(new SupportingFile("apiException.mustache", invokerFolder, "ApiException.java")); supportingFiles.add(new SupportingFile("Configuration.mustache", invokerFolder, "Configuration.java")); - supportingFiles.add(new SupportingFile("JSON.mustache", invokerFolder, "JSON.java")); supportingFiles.add(new SupportingFile("Pair.mustache", invokerFolder, "Pair.java")); supportingFiles.add(new SupportingFile("auth/Authentication.mustache", authFolder, "Authentication.java")); } @@ -233,6 +243,7 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { // the "okhttp-gson" library template requires "ApiCallback.mustache" for async call supportingFiles.add(new SupportingFile("ApiCallback.mustache", invokerFolder, "ApiCallback.java")); supportingFiles.add(new SupportingFile("ApiResponse.mustache", invokerFolder, "ApiResponse.java")); + supportingFiles.add(new SupportingFile("JSON.mustache", invokerFolder, "JSON.java")); supportingFiles.add(new SupportingFile("ProgressRequestBody.mustache", invokerFolder, "ProgressRequestBody.java")); supportingFiles.add(new SupportingFile("ProgressResponseBody.mustache", invokerFolder, "ProgressResponseBody.java")); // "build.sbt" is for development with SBT @@ -240,8 +251,8 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { } else if ("retrofit".equals(getLibrary()) || "retrofit2".equals(getLibrary())) { supportingFiles.add(new SupportingFile("auth/OAuthOkHttpClient.mustache", authFolder, "OAuthOkHttpClient.java")); supportingFiles.add(new SupportingFile("CollectionFormats.mustache", invokerFolder, "CollectionFormats.java")); - } else { - supportingFiles.add(new SupportingFile("TypeRef.mustache", invokerFolder, "TypeRef.java")); + } else if("jersey2".equals(getLibrary())) { + supportingFiles.add(new SupportingFile("JSON.mustache", invokerFolder, "JSON.java")); } } @@ -544,6 +555,57 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { return objs; } + public void preprocessSwagger(Swagger swagger) { + if (swagger != null && swagger.getPaths() != null) { + for (String pathname : swagger.getPaths().keySet()) { + Path path = swagger.getPath(pathname); + if (path.getOperations() != null) { + for (Operation operation : path.getOperations()) { + boolean hasFormParameters = false; + for (Parameter parameter : operation.getParameters()) { + if (parameter instanceof FormParameter) { + hasFormParameters = true; + } + } + + String defaultContentType = hasFormParameters ? "application/x-www-form-urlencoded" : "application/json"; + String contentType = operation.getConsumes() == null || operation.getConsumes().isEmpty() + ? defaultContentType : operation.getConsumes().get(0); + String accepts = getAccept(operation); + operation.setVendorExtension("x-contentType", contentType); + operation.setVendorExtension("x-accepts", accepts); + } + } + } + } + } + + private String getAccept(Operation operation) { + String accepts = null; + String defaultContentType = "application/json"; + if (operation.getProduces() != null && !operation.getProduces().isEmpty()) { + StringBuilder sb = new StringBuilder(); + for (String produces : operation.getProduces()) { + if (defaultContentType.equalsIgnoreCase(produces)) { + accepts = defaultContentType; + break; + } else { + if (sb.length() > 0) { + sb.append(","); + } + sb.append(produces); + } + } + if (accepts == null) { + accepts = sb.toString(); + } + } else { + accepts = defaultContentType; + } + + return accepts; + } + protected boolean needToImport(String type) { return super.needToImport(type) && type.indexOf(".") < 0; } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavascriptClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavascriptClientCodegen.java index 51ef135ae0dc..55b847668c0b 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavascriptClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavascriptClientCodegen.java @@ -11,7 +11,7 @@ import io.swagger.codegen.CodegenProperty; import io.swagger.codegen.CodegenType; import io.swagger.codegen.DefaultCodegen; import io.swagger.codegen.SupportingFile; -import io.swagger.models.Model; +import io.swagger.models.*; import io.swagger.models.properties.ArrayProperty; import io.swagger.models.properties.LongProperty; import io.swagger.models.properties.MapProperty; @@ -34,15 +34,19 @@ import org.slf4j.LoggerFactory; public class JavascriptClientCodegen extends DefaultCodegen implements CodegenConfig { private static final Logger LOGGER = LoggerFactory.getLogger(JavascriptClientCodegen.class); - protected String invokerPackage = "io.swagger.client"; - protected String groupId = "io.swagger"; - protected String artifactId = "swagger-java-client"; - protected String artifactVersion = "1.0.0"; + private static final String PROJECT_NAME = "projectName"; + private static final String MODULE_NAME = "moduleName"; + private static final String PROJECT_DESCRIPTION = "projectDescription"; + private static final String PROJECT_VERSION = "projectVersion"; + private static final String PROJECT_LICENSE_NAME = "projectLicenseName"; + + protected String projectName = null; + protected String moduleName = null; + protected String projectDescription = null; + protected String projectVersion = null; + protected String sourceFolder = "src"; protected String localVariablePrefix = ""; - protected boolean fullJavaUtil = false; - protected String javaUtilPrefix = ""; - protected Boolean serializableModel = false; public JavascriptClientCodegen() { super(); @@ -50,44 +54,48 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo modelTemplateFiles.put("model.mustache", ".js"); apiTemplateFiles.put("api.mustache", ".js"); templateDir = "Javascript"; - apiPackage = "scripts/rest/api"; - modelPackage = "scripts/rest/model"; + apiPackage = "api"; + modelPackage = "model"; + // reference: http://www.w3schools.com/js/js_reserved.asp 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") + "abstract", "arguments", "boolean", "break", "byte", + "case", "catch", "char", "class", "const", + "continue", "debugger", "default", "delete", "do", + "double", "else", "enum", "eval", "export", + "extends", "false", "final", "finally", "float", + "for", "function", "goto", "if", "implements", + "import", "in", "instanceof", "int", "interface", + "let", "long", "native", "new", "null", + "package", "private", "protected", "public", "return", + "short", "static", "super", "switch", "synchronized", + "this", "throw", "throws", "transient", "true", + "try", "typeof", "var", "void", "volatile", + "while", "with", "yield", + "Array", "Date", "eval", "function", "hasOwnProperty", + "Infinity", "isFinite", "isNaN", "isPrototypeOf", + "Math", "NaN", "Number", "Object", + "prototype", "String", "toString", "undefined", "valueOf") ); languageSpecificPrimitives = new HashSet( - Arrays.asList( - "String", - "boolean", - "Boolean", - "Double", - "Integer", - "Long", - "Float", - "Object", - "byte[]") + Arrays.asList("String", "Boolean", "Integer", "Number", "Array", "Object", "Date", "File") ); - instantiationTypes.put("array", "Array"); - instantiationTypes.put("map", "HashMap"); + defaultIncludes = new HashSet(languageSpecificPrimitives); - cliOptions.add(new CliOption(CodegenConstants.INVOKER_PACKAGE, CodegenConstants.INVOKER_PACKAGE_DESC)); - cliOptions.add(new CliOption(CodegenConstants.GROUP_ID, CodegenConstants.GROUP_ID_DESC)); - cliOptions.add(new CliOption(CodegenConstants.ARTIFACT_ID, CodegenConstants.ARTIFACT_ID_DESC)); - cliOptions.add(new CliOption(CodegenConstants.ARTIFACT_VERSION, CodegenConstants.ARTIFACT_VERSION_DESC)); - cliOptions.add(new CliOption(CodegenConstants.SOURCE_FOLDER, CodegenConstants.SOURCE_FOLDER_DESC)); + cliOptions.add(new CliOption(CodegenConstants.SOURCE_FOLDER, CodegenConstants.SOURCE_FOLDER_DESC).defaultValue("src")); cliOptions.add(new CliOption(CodegenConstants.LOCAL_VARIABLE_PREFIX, CodegenConstants.LOCAL_VARIABLE_PREFIX_DESC)); - cliOptions.add(new CliOption(CodegenConstants.SERIALIZABLE_MODEL, CodegenConstants.SERIALIZABLE_MODEL_DESC)); - cliOptions.add(new CliOption("fullJavaUtil", "whether to use fully qualified name for classes under java.util (default to false)")); - + cliOptions.add(new CliOption(PROJECT_NAME, + "name of the project (Default: generated from info.title or \"swagger-js-client\")")); + cliOptions.add(new CliOption(MODULE_NAME, + "module name for AMD, Node or globals (Default: generated from )")); + cliOptions.add(new CliOption(PROJECT_DESCRIPTION, + "description of the project (Default: using info.description or \"Client library of \")")); + cliOptions.add(new CliOption(PROJECT_VERSION, + "version of the project (Default: using info.version or \"1.0.0\")")); + cliOptions.add(new CliOption(PROJECT_LICENSE_NAME, + "name of the license the project uses (Default: using info.license.name)")); } @Override @@ -109,8 +117,94 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo public void processOpts() { super.processOpts(); - typeMapping.put("array", "Array"); - + typeMapping = new HashMap(); + typeMapping.put("array", "Array"); + typeMapping.put("List", "Array"); + typeMapping.put("map", "Object"); + typeMapping.put("object", "Object"); + typeMapping.put("boolean", "Boolean"); + typeMapping.put("char", "String"); + typeMapping.put("string", "String"); + typeMapping.put("short", "Integer"); + typeMapping.put("int", "Integer"); + typeMapping.put("integer", "Integer"); + typeMapping.put("long", "Integer"); + typeMapping.put("float", "Number"); + typeMapping.put("double", "Number"); + typeMapping.put("number", "Number"); + typeMapping.put("DateTime", "Date"); + + importMapping.clear(); + } + + @Override + public void preprocessSwagger(Swagger swagger) { + super.preprocessSwagger(swagger); + + if (additionalProperties.containsKey(PROJECT_NAME)) { + projectName = ((String) additionalProperties.get(PROJECT_NAME)); + } + if (additionalProperties.containsKey(MODULE_NAME)) { + moduleName = ((String) additionalProperties.get(MODULE_NAME)); + } + if (additionalProperties.containsKey(PROJECT_DESCRIPTION)) { + projectDescription = ((String) additionalProperties.get(PROJECT_DESCRIPTION)); + } + if (additionalProperties.containsKey(PROJECT_VERSION)) { + projectVersion = ((String) additionalProperties.get(PROJECT_VERSION)); + } + if (additionalProperties.containsKey(CodegenConstants.LOCAL_VARIABLE_PREFIX)) { + localVariablePrefix = (String) additionalProperties.get(CodegenConstants.LOCAL_VARIABLE_PREFIX); + } + if (additionalProperties.containsKey(CodegenConstants.SOURCE_FOLDER)) { + sourceFolder = (String) additionalProperties.get(CodegenConstants.SOURCE_FOLDER); + } + + if (swagger.getInfo() != null) { + Info info = swagger.getInfo(); + if (projectName == null && info.getTitle() != null) { + // when projectName is not specified, generate it from info.title + projectName = dashize(info.getTitle()); + } + if (projectVersion == null) { + // when projectVersion is not specified, use info.version + projectVersion = info.getVersion(); + } + if (projectDescription == null) { + // when projectDescription is not specified, use info.description + projectDescription = info.getDescription(); + } + if (info.getLicense() != null) { + License license = info.getLicense(); + if (additionalProperties.get(PROJECT_LICENSE_NAME) == null) { + additionalProperties.put(PROJECT_LICENSE_NAME, license.getName()); + } + } + } + + // default values + if (projectName == null) { + projectName = "swagger-js-client"; + } + if (moduleName == null) { + moduleName = camelize(underscore(projectName)); + } + if (projectVersion == null) { + projectVersion = "1.0.0"; + } + if (projectDescription == null) { + projectDescription = "Client library of " + projectName; + } + + additionalProperties.put(PROJECT_NAME, projectName); + additionalProperties.put(MODULE_NAME, moduleName); + additionalProperties.put(PROJECT_DESCRIPTION, escapeText(projectDescription)); + additionalProperties.put(PROJECT_VERSION, projectVersion); + additionalProperties.put(CodegenConstants.LOCAL_VARIABLE_PREFIX, localVariablePrefix); + additionalProperties.put(CodegenConstants.SOURCE_FOLDER, sourceFolder); + + supportingFiles.add(new SupportingFile("package.mustache", "", "package.json")); + supportingFiles.add(new SupportingFile("index.mustache", sourceFolder, "index.js")); } @Override @@ -180,6 +274,16 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo return toModelName(name); } + @Override + public String toModelImport(String name) { + return name; + } + + @Override + public String toApiImport(String name) { + return toApiName(name); + } + @Override public String getTypeDeclaration(Property p) { if (p instanceof ArrayProperty) { @@ -198,84 +302,42 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo @Override public String toDefaultValue(Property p) { if (p instanceof ArrayProperty) { - final ArrayProperty ap = (ArrayProperty) p; - final String pattern; - //if (fullJavaUtil) { - // pattern = "new ArrayList()"; - //} else { - // pattern = "new ArrayList<%s>()"; - //} - - pattern = "new Array()"; - return String.format(pattern, getTypeDeclaration(ap.getItems())); + return "[]"; } else if (p instanceof MapProperty) { - final MapProperty ap = (MapProperty) p; - final String pattern; - if (fullJavaUtil) { - pattern = "new java.util.HashMap()"; - } else { - pattern = "new HashMap()"; - } - return String.format(pattern, getTypeDeclaration(ap.getAdditionalProperties())); - + return "{}"; } else if (p instanceof LongProperty) { LongProperty dp = (LongProperty) p; if (dp.getDefault() != null) { return dp.getDefault().toString()+"l"; } return "null"; - + // added for Javascript } else if (p instanceof RefProperty) { - RefProperty rp = (RefProperty)p; - System.out.println("rp: " + rp.getName() + rp.getAccess() + rp.getDescription() + rp.getExample() + rp.getFormat() + rp.getSimpleRef() + rp.getTitle() + rp.getType()); - - return "new " +rp.getSimpleRef() + "()"; + RefProperty rp = (RefProperty)p; + return "new " +rp.getSimpleRef() + "()"; } - - System.out.println("property: " + p); - + return super.toDefaultValue(p); } - + @Override public String toDefaultValueWithParam(String name, Property p) { if (p instanceof ArrayProperty) { - final ArrayProperty ap = (ArrayProperty) p; - final String pattern; -// if (fullJavaUtil) { -// pattern = "new java.util.ArrayList<%s>()"; -// } else { -// pattern = "new ArrayList<%s>()" ; -// } - pattern = " = new Array()" ; - - return String.format(pattern, getTypeDeclaration(ap.getItems()))+ ";"; + return " = new Array();"; } else if (p instanceof MapProperty) { - final MapProperty ap = (MapProperty) p; - final String pattern; - if (fullJavaUtil) { - pattern = " = new java.util.HashMap()"; - } else { - pattern = "new HashMap()"; - } - return String.format(pattern, getTypeDeclaration(ap.getAdditionalProperties()))+ ";"; - + return " = {}"; } else if (p instanceof LongProperty) { LongProperty dp = (LongProperty) p; return " = data." + name + ";"; - + // added for Javascript } else if (p instanceof RefProperty) { - RefProperty rp = (RefProperty)p; - System.out.println("rp: " + rp.getName() + rp.getAccess() + rp.getDescription() + rp.getExample() + rp.getFormat() + rp.getSimpleRef() + rp.getTitle() + rp.getType()); - - return ".constructFromObject(data." + name + ");"; + RefProperty rp = (RefProperty)p; + return ".constructFromObject(data." + name + ");"; } - - System.out.println("property: " + p); - + return super.toDefaultValueWithParam(name, p); } @@ -286,7 +348,7 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo String type = null; if (typeMapping.containsKey(swaggerType)) { type = typeMapping.get(swaggerType); - if (languageSpecificPrimitives.contains(type) || type.indexOf(".") >= 0) { + if (!needToImport(type)) { return type; } } else { @@ -397,7 +459,8 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo } protected boolean needToImport(String type) { - return super.needToImport(type) && type.indexOf(".") < 0; + return !defaultIncludes.contains(type) + && !languageSpecificPrimitives.contains(type); } private String findCommonPrefixOfVars(List vars) { @@ -449,7 +512,7 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo } } } - + if(removedChildEnum) { // If we removed an entry from this model's vars, we need to ensure hasMore is updated int count = 0, numVars = codegenProperties.size(); @@ -464,39 +527,6 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo return codegenModel; } - public void setInvokerPackage(String invokerPackage) { - this.invokerPackage = invokerPackage; - } - - public void setGroupId(String groupId) { - this.groupId = groupId; - } - - public void setArtifactId(String artifactId) { - this.artifactId = artifactId; - } - - public void setArtifactVersion(String artifactVersion) { - this.artifactVersion = artifactVersion; - } - - public void setSourceFolder(String sourceFolder) { - this.sourceFolder = sourceFolder; - } - - public void setLocalVariablePrefix(String localVariablePrefix) { - this.localVariablePrefix = localVariablePrefix; - } - - - public Boolean getSerializableModel() { - return serializableModel; - } - - public void setSerializableModel(Boolean serializableModel) { - this.serializableModel = serializableModel; - } - private String sanitizePackageName(String packageName) { packageName = packageName.trim(); packageName = packageName.replaceAll("[^a-zA-Z0-9_\\.]", "_"); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ObjcClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ObjcClientCodegen.java index 7037ee06f9b3..9c488db1254a 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ObjcClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ObjcClientCodegen.java @@ -7,9 +7,7 @@ import io.swagger.codegen.CodegenProperty; import io.swagger.codegen.CodegenType; import io.swagger.codegen.DefaultCodegen; import io.swagger.codegen.SupportingFile; -import io.swagger.models.properties.ArrayProperty; -import io.swagger.models.properties.MapProperty; -import io.swagger.models.properties.Property; +import io.swagger.models.properties.*; import java.io.File; import java.util.Arrays; @@ -343,11 +341,6 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { return name; } - @Override - public String toDefaultValue(Property p) { - return null; - } - @Override public String apiFileFolder() { return outputFolder + File.separatorChar + apiPackage(); @@ -452,4 +445,55 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { public void setLicense(String license) { this.license = license; } + + /** + * Return the default value of the property + * + * @param p Swagger property object + * @return string presentation of the default value of the property + */ + @Override + public String toDefaultValue(Property p) { + if (p instanceof StringProperty) { + StringProperty dp = (StringProperty) p; + if (dp.getDefault() != null) { + return "@\"" + dp.getDefault().toString() + "\""; + } + } else if (p instanceof BooleanProperty) { + BooleanProperty dp = (BooleanProperty) p; + if (dp.getDefault() != null) { + if (dp.getDefault().toString().equalsIgnoreCase("false")) + return "@0"; + else + return "@1"; + } + } else if (p instanceof DateProperty) { + // TODO + } else if (p instanceof DateTimeProperty) { + // TODO + } else if (p instanceof DoubleProperty) { + DoubleProperty dp = (DoubleProperty) p; + if (dp.getDefault() != null) { + return "@" + dp.getDefault().toString(); + } + } else if (p instanceof FloatProperty) { + FloatProperty dp = (FloatProperty) p; + if (dp.getDefault() != null) { + return "@" + dp.getDefault().toString(); + } + } else if (p instanceof IntegerProperty) { + IntegerProperty dp = (IntegerProperty) p; + if (dp.getDefault() != null) { + return "@" + dp.getDefault().toString(); + } + } else if (p instanceof LongProperty) { + LongProperty dp = (LongProperty) p; + if (dp.getDefault() != null) { + return "@" + dp.getDefault().toString(); + } + } + + return null; + } + } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java index 56df40219f5c..c712374f4241 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java @@ -6,10 +6,7 @@ import io.swagger.codegen.CodegenConstants; import io.swagger.codegen.CodegenType; import io.swagger.codegen.DefaultCodegen; import io.swagger.codegen.SupportingFile; -import io.swagger.models.properties.ArrayProperty; -import io.swagger.models.properties.MapProperty; -import io.swagger.models.properties.Property; -import io.swagger.models.properties.RefProperty; +import io.swagger.models.properties.*; import java.io.File; import java.util.Arrays; @@ -276,10 +273,6 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { return toModelName(type); } - public String toDefaultValue(Property p) { - return "null"; - } - public void setInvokerPackage(String invokerPackage) { this.invokerPackage = invokerPackage; } @@ -377,4 +370,51 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { return camelize(sanitizeName(operationId), true); } + /** + * Return the default value of the property + * + * @param p Swagger property object + * @return string presentation of the default value of the property + */ + @Override + public String toDefaultValue(Property p) { + if (p instanceof StringProperty) { + StringProperty dp = (StringProperty) p; + if (dp.getDefault() != null) { + return "'" + dp.getDefault().toString() + "'"; + } + } else if (p instanceof BooleanProperty) { + BooleanProperty dp = (BooleanProperty) p; + if (dp.getDefault() != null) { + return dp.getDefault().toString(); + } + } else if (p instanceof DateProperty) { + // TODO + } else if (p instanceof DateTimeProperty) { + // TODO + } else if (p instanceof DoubleProperty) { + DoubleProperty dp = (DoubleProperty) p; + if (dp.getDefault() != null) { + return dp.getDefault().toString(); + } + } else if (p instanceof FloatProperty) { + FloatProperty dp = (FloatProperty) p; + if (dp.getDefault() != null) { + return dp.getDefault().toString(); + } + } else if (p instanceof IntegerProperty) { + IntegerProperty dp = (IntegerProperty) p; + if (dp.getDefault() != null) { + return dp.getDefault().toString(); + } + } else if (p instanceof LongProperty) { + LongProperty dp = (LongProperty) p; + if (dp.getDefault() != null) { + return dp.getDefault().toString(); + } + } + + return null; + } + } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PythonClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PythonClientCodegen.java index 1759e5152581..b5aa56aa2c46 100755 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PythonClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PythonClientCodegen.java @@ -6,9 +6,7 @@ import io.swagger.codegen.CodegenConstants; import io.swagger.codegen.CodegenType; import io.swagger.codegen.DefaultCodegen; import io.swagger.codegen.SupportingFile; -import io.swagger.models.properties.ArrayProperty; -import io.swagger.models.properties.MapProperty; -import io.swagger.models.properties.Property; +import io.swagger.models.properties.*; import java.io.File; import java.util.Arrays; @@ -166,10 +164,6 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig return type; } - public String toDefaultValue(Property p) { - return "None"; - } - @Override public String toVarName(String name) { // sanitize name @@ -291,4 +285,55 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig public String generatePackageName(String packageName) { return underscore(packageName.replaceAll("[^\\w]+", "")); } + + /** + * Return the default value of the property + * + * @param p Swagger property object + * @return string presentation of the default value of the property + */ + @Override + public String toDefaultValue(Property p) { + if (p instanceof StringProperty) { + StringProperty dp = (StringProperty) p; + if (dp.getDefault() != null) { + return "'" + dp.getDefault().toString() + "'"; + } + } else if (p instanceof BooleanProperty) { + BooleanProperty dp = (BooleanProperty) p; + if (dp.getDefault() != null) { + if (dp.getDefault().toString().equalsIgnoreCase("false")) + return "False"; + else + return "True"; + } + } else if (p instanceof DateProperty) { + // TODO + } else if (p instanceof DateTimeProperty) { + // TODO + } else if (p instanceof DoubleProperty) { + DoubleProperty dp = (DoubleProperty) p; + if (dp.getDefault() != null) { + return dp.getDefault().toString(); + } + } else if (p instanceof FloatProperty) { + FloatProperty dp = (FloatProperty) p; + if (dp.getDefault() != null) { + return dp.getDefault().toString(); + } + } else if (p instanceof IntegerProperty) { + IntegerProperty dp = (IntegerProperty) p; + if (dp.getDefault() != null) { + return dp.getDefault().toString(); + } + } else if (p instanceof LongProperty) { + LongProperty dp = (LongProperty) p; + if (dp.getDefault() != null) { + return dp.getDefault().toString(); + } + } + + return null; + } + } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RubyClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RubyClientCodegen.java index f30b2ef8b85a..2fd6d8d8bc09 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RubyClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RubyClientCodegen.java @@ -6,9 +6,7 @@ import io.swagger.codegen.CodegenConstants; import io.swagger.codegen.CodegenType; import io.swagger.codegen.DefaultCodegen; import io.swagger.codegen.SupportingFile; -import io.swagger.models.properties.ArrayProperty; -import io.swagger.models.properties.MapProperty; -import io.swagger.models.properties.Property; +import io.swagger.models.properties.*; import java.io.File; import java.util.Arrays; @@ -186,6 +184,43 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { return super.getTypeDeclaration(p); } + @Override + public String toDefaultValue(Property p) { + if (p instanceof IntegerProperty) { + IntegerProperty dp = (IntegerProperty) p; + if (dp.getDefault() != null) { + return dp.getDefault().toString(); + } + } else if (p instanceof LongProperty) { + LongProperty dp = (LongProperty) p; + if (dp.getDefault() != null) { + return dp.getDefault().toString(); + } + } else if (p instanceof DoubleProperty) { + DoubleProperty dp = (DoubleProperty) p; + if (dp.getDefault() != null) { + return dp.getDefault().toString(); + } + } else if (p instanceof FloatProperty) { + FloatProperty dp = (FloatProperty) p; + if (dp.getDefault() != null) { + return dp.getDefault().toString(); + } + } else if (p instanceof BooleanProperty) { + BooleanProperty bp = (BooleanProperty) p; + if (bp.getDefault() != null) { + return bp.getDefault().toString(); + } + } else if (p instanceof StringProperty) { + StringProperty sp = (StringProperty) p; + if (sp.getDefault() != null) { + return "\"" + escapeText(sp.getDefault()) + "\""; + } + } + + return null; + } + @Override public String getSwaggerType(Property p) { String swaggerType = super.getSwaggerType(p); @@ -204,10 +239,6 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { return type; } - public String toDefaultValue(Property p) { - return "null"; - } - @Override public String toVarName(String name) { // sanitize name diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SinatraServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SinatraServerCodegen.java index 9bcece874299..1c31b45664e6 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SinatraServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SinatraServerCodegen.java @@ -1,5 +1,7 @@ package io.swagger.codegen.languages; +import com.fasterxml.jackson.core.JsonProcessingException; + import io.swagger.codegen.CliOption; import io.swagger.codegen.CodegenConfig; import io.swagger.codegen.CodegenType; @@ -8,10 +10,13 @@ import io.swagger.codegen.SupportingFile; import io.swagger.models.properties.ArrayProperty; import io.swagger.models.properties.MapProperty; import io.swagger.models.properties.Property; +import io.swagger.models.Swagger; +import io.swagger.util.Yaml; import java.io.File; import java.util.Arrays; import java.util.HashSet; +import java.util.Map; import org.apache.commons.lang.StringUtils; @@ -73,6 +78,7 @@ public class SinatraServerCodegen extends DefaultCodegen implements CodegenConfi supportingFiles.add(new SupportingFile("config.ru", "", "config.ru")); supportingFiles.add(new SupportingFile("Gemfile", "", "Gemfile")); supportingFiles.add(new SupportingFile("README.md", "", "README.md")); + supportingFiles.add(new SupportingFile("swagger.mustache","","swagger.yaml")); } public CodegenType getTag() { @@ -213,5 +219,17 @@ public class SinatraServerCodegen extends DefaultCodegen implements CodegenConfi return underscore(operationId); } + @Override + public Map postProcessSupportingFileData(Map objs) { + Swagger swagger = (Swagger)objs.get("swagger"); + if(swagger != null) { + try { + objs.put("swagger-yaml", Yaml.mapper().writeValueAsString(swagger)); + } catch (JsonProcessingException e) { + e.printStackTrace(); + } + } + return super.postProcessSupportingFileData(objs); + } } diff --git a/modules/swagger-codegen/src/main/resources/CsharpDotNet2/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/CsharpDotNet2/ApiClient.mustache index 8e64db5af313..a428cdc3630f 100644 --- a/modules/swagger-codegen/src/main/resources/CsharpDotNet2/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/CsharpDotNet2/ApiClient.mustache @@ -134,7 +134,7 @@ namespace {{packageName}}.Client } /// - /// If parameter is DateTime, output in ISO8601 format. + /// If parameter is DateTime, output in a formatted string (default ISO 8601), customizable with Configuration.DateTime. /// If parameter is a list of string, join the list with ",". /// Otherwise just return the string. /// @@ -143,7 +143,11 @@ namespace {{packageName}}.Client public string ParameterToString(object obj) { if (obj is DateTime) - return ((DateTime)obj).ToString ("u"); + // Return a formatted date string - Can be customized with Configuration.DateTimeFormat + // Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o") + // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 + // For example: 2009-06-15T13:45:30.0000000 + return ((DateTime)obj).ToString (Configuration.DateTimeFormat); else if (obj is List) return String.Join(",", (obj as List).ToArray()); else diff --git a/modules/swagger-codegen/src/main/resources/CsharpDotNet2/Configuration.mustache b/modules/swagger-codegen/src/main/resources/CsharpDotNet2/Configuration.mustache index 67b07069e2f6..56f4e617556b 100644 --- a/modules/swagger-codegen/src/main/resources/CsharpDotNet2/Configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/CsharpDotNet2/Configuration.mustache @@ -78,7 +78,40 @@ namespace {{packageName}}.Client _tempFolderPath = value + Path.DirectorySeparatorChar; } } - + + private const string ISO8601_DATETIME_FORMAT = "o"; + + private static string _dateTimeFormat = ISO8601_DATETIME_FORMAT; + + /// + /// Gets or sets the the date time format used when serializing in the ApiClient + /// By default, it's set to ISO 8601 - "o", for others see: + /// https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx + /// and https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx + /// No validation is done to ensure that the string you're providing is valid + /// + /// The DateTimeFormat string + public static String DateTimeFormat + { + get + { + return _dateTimeFormat; + } + set + { + if (string.IsNullOrEmpty(value)) + { + // Never allow a blank or null string, go back to the default + _dateTimeFormat = ISO8601_DATETIME_FORMAT; + return; + } + + // Caution, no validation when you choose date time format other than ISO 8601 + // Take a look at the above links + _dateTimeFormat = value; + } + } + /// /// Returns a string with essential information for debugging. /// diff --git a/modules/swagger-codegen/src/main/resources/JMeter/api.mustache b/modules/swagger-codegen/src/main/resources/JMeter/api.mustache new file mode 100644 index 000000000000..1af63c2d66dd --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JMeter/api.mustache @@ -0,0 +1,178 @@ + + + + + + false + false + + + + host + localhost + = + + + port + 8080 + = + + + + + + + + + + testCases + ${__P(host,10)} + = + + + host + ${__P(host,localhost)} + = + + + port + ${__P(port,8080)} + = + {{#operations}}{{#operation}} + + testData.{{operationId}}File + ${__P(testData.{{operationId}}File,{{classname}}.csv)} + = + {{/operation}}{{/operations}} + + + + + + + + ${host} + ${port} + + + + + + 4 + + + {{#operations}}{{#operation}} + continue + + false + ${testCases} + + 1 + 1 + 1448391617000 + 1448391617000 + false + + + + + + {{#headerParams}} + + {{paramName}} + ${__RandomString(10,qwertyuiopasdfghjklzxcvbnm)} + {{/headerParams}} + + + + + + {{#queryParams}} + + false + 0 + = + true + {{paramName}} + {{/queryParams}} + + + + + + + + + {{vendorExtensions.x-path}} + {{httpMethod}} + true + false + true + false + HttpClient3.1 + false + + {{summary}} {{notes}} + + + + , + + ${testData.{{operationId}}File} + true + true + shareMode.all + false + + + + + + + ${httpStatusCode} + + Assertion.response_code + false + 8 + + + + {{/operation}} + {{/operations}} + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + false + false + false + false + false + false + 0 + true + true + + + + + + + + diff --git a/modules/swagger-codegen/src/main/resources/JMeter/testdata-localhost.mustache b/modules/swagger-codegen/src/main/resources/JMeter/testdata-localhost.mustache new file mode 100644 index 000000000000..48708a1d0fa4 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JMeter/testdata-localhost.mustache @@ -0,0 +1,2 @@ +testCase,httpStatusCode{{#operations}}{{#operation}}{{#hasParams}},{{/hasParams}}{{#allParams}}{{paramName}}{{#hasMore}},{{/hasMore}}{{/allParams}}{{/operation}}{{/operations}} +Success,200{{#operations}}{{#operation}}{{#hasParams}},{{/hasParams}}{{#allParams}}0{{#hasMore}},{{/hasMore}}{{/allParams}}{{/operation}}{{/operations}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache index 2e73cd702e90..ef31058d5619 100644 --- a/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache @@ -1,8 +1,13 @@ package {{invokerPackage}}; +import com.fasterxml.jackson.annotation.*; +import com.fasterxml.jackson.databind.*; +import com.fasterxml.jackson.datatype.joda.*; +import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider; + import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.ClientResponse; -import com.sun.jersey.api.client.config.ClientConfig; +import com.sun.jersey.api.client.GenericType; import com.sun.jersey.api.client.config.DefaultClientConfig; import com.sun.jersey.api.client.filter.LoggingFilter; import com.sun.jersey.api.client.WebResource.Builder; @@ -25,14 +30,11 @@ import java.util.TimeZone; import java.net.URLEncoder; -import java.io.IOException; import java.io.File; import java.io.UnsupportedEncodingException; -import java.io.DataInputStream; import java.text.DateFormat; import java.text.SimpleDateFormat; -import java.text.ParseException; import {{invokerPackage}}.auth.Authentication; import {{invokerPackage}}.auth.HttpBasicAuth; @@ -45,7 +47,7 @@ public class ApiClient { private Map defaultHeaderMap = new HashMap(); private boolean debugging = false; private String basePath = "{{basePath}}"; - private JSON json = new JSON(); + private ObjectMapper mapper; private Map authentications; @@ -55,6 +57,14 @@ public class ApiClient { private DateFormat dateFormat; public ApiClient() { + mapper = new ObjectMapper(); + mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); + mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING); + mapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING); + mapper.registerModule(new JodaModule()); + // Use RFC3339 format for date and datetime. // See http://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14 this.dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); @@ -62,7 +72,7 @@ public class ApiClient { // Use UTC as the default time zone. this.dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); - this.json.setDateFormat((DateFormat) dateFormat.clone()); + this.mapper.setDateFormat((DateFormat) dateFormat.clone()); // Set default User-Agent. setUserAgent("Java-Swagger"); @@ -76,13 +86,6 @@ public class ApiClient { authentications = Collections.unmodifiableMap(authentications); } - /** - * Gets the JSON instance to do JSON serialization and deserialization. - */ - public JSON getJSON() { - return json; - } - public String getBasePath() { return basePath; } @@ -237,7 +240,7 @@ public class ApiClient { public ApiClient setDateFormat(DateFormat dateFormat) { this.dateFormat = dateFormat; // also set the date format for model (de)serialization with Date properties - this.json.setDateFormat((DateFormat) dateFormat.clone()); + this.mapper.setDateFormat((DateFormat) dateFormat.clone()); return this; } @@ -269,7 +272,7 @@ public class ApiClient { return formatDate((Date) param); } else if (param instanceof Collection) { StringBuilder b = new StringBuilder(); - for(Object o : (Collection)param) { + for(Object o : (Collection)param) { if(b.length() > 0) { b.append(","); } @@ -290,9 +293,9 @@ public class ApiClient { // preconditions if (name == null || name.isEmpty() || value == null) return params; - Collection valueCollection = null; - if (value instanceof Collection) { - valueCollection = (Collection) value; + Collection valueCollection = null; + if (value instanceof Collection) { + valueCollection = (Collection) value; } else { params.add(new Pair(name, parameterToString(value))); return params; @@ -337,6 +340,17 @@ public class ApiClient { return params; } + /** + * Check if the given MIME is a JSON MIME. + * JSON MIME examples: + * application/json + * application/json; charset=UTF8 + * APPLICATION/JSON + */ + public boolean isJsonMime(String mime) { + return mime != null && mime.matches("(?i)application\\/json(;.*)?"); + } + /** * Select the Accept header's value from the given accepts array: * if JSON exists in the given array, use it; @@ -347,8 +361,14 @@ public class ApiClient { * null will be returned (not to set the Accept header explicitly). */ public String selectHeaderAccept(String[] accepts) { - if (accepts.length == 0) return null; - if (StringUtil.containsIgnoreCase(accepts, "application/json")) return "application/json"; + if (accepts.length == 0) { + return null; + } + for (String accept : accepts) { + if (isJsonMime(accept)) { + return accept; + } + } return StringUtil.join(accepts, ","); } @@ -362,8 +382,14 @@ public class ApiClient { * JSON will be used. */ public String selectHeaderContentType(String[] contentTypes) { - if (contentTypes.length == 0) return "application/json"; - if (StringUtil.containsIgnoreCase(contentTypes, "application/json")) return "application/json"; + if (contentTypes.length == 0) { + return "application/json"; + } + for (String contentType : contentTypes) { + if (isJsonMime(contentType)) { + return contentType; + } + } return contentTypes[0]; } @@ -382,49 +408,30 @@ public class ApiClient { * Serialize the given Java object into string according the given * Content-Type (only JSON is supported for now). */ - public String serialize(Object obj, String contentType) throws ApiException { - if (contentType.startsWith("application/json")) { - return json.serialize(obj); + public Object serialize(Object obj, String contentType, Map formParams) throws ApiException { + if (contentType.startsWith("multipart/form-data")) { + FormDataMultiPart mp = new FormDataMultiPart(); + for (Entry param: formParams.entrySet()) { + if (param.getValue() instanceof File) { + File file = (File) param.getValue(); + mp.bodyPart(new FileDataBodyPart(param.getKey(), file, MediaType.MULTIPART_FORM_DATA_TYPE)); + } else { + mp.field(param.getKey(), parameterToString(param.getValue()), MediaType.MULTIPART_FORM_DATA_TYPE); + } + } + return mp; + } else if (contentType.startsWith("application/x-www-form-urlencoded")) { + return this.getXWWWFormUrlencodedParams(formParams); } else { - throw new ApiException(400, "can not serialize object into Content-Type: " + contentType); + // We let Jersey attempt to serialize the body + return obj; } } - /** - * Deserialize response body to Java object according to the Content-Type. - */ - public T deserialize(ClientResponse response, TypeRef returnType) throws ApiException { - String contentType = null; - List contentTypes = response.getHeaders().get("Content-Type"); - if (contentTypes != null && !contentTypes.isEmpty()) - contentType = contentTypes.get(0); - if (contentType == null) - throw new ApiException(500, "missing Content-Type in response"); + private ClientResponse getAPIResponse(String path, String method, List queryParams, Object body, Map headerParams, Map formParams, String accept, String contentType, String[] authNames) throws ApiException { - String body; - if (response.hasEntity()) - body = (String) response.getEntity(String.class); - else - body = ""; - - if (contentType.startsWith("application/json")) { - return json.deserialize(body, returnType); - } else if (returnType.getType().equals(String.class)) { - // Expecting string, return the raw response body. - return (T) body; - } else { - throw new ApiException( - 500, - "Content type \"" + contentType + "\" is not supported for type: " - + returnType.getType() - ); - } - } - - private ClientResponse getAPIResponse(String path, String method, List queryParams, Object body, byte[] binaryBody, Map headerParams, Map formParams, String accept, String contentType, String[] authNames) throws ApiException { - - if (body != null && binaryBody != null){ - throw new ApiException(500, "either body or binaryBody must be null"); + if (body != null && !formParams.isEmpty()){ + throw new ApiException(500, "Cannot have body and form params"); } updateParamsForAuth(authNames, queryParams, headerParams); @@ -461,61 +468,16 @@ public class ApiClient { } } - String encodedFormParams = null; - if (contentType.startsWith("multipart/form-data")) { - FormDataMultiPart mp = new FormDataMultiPart(); - for (Entry param: formParams.entrySet()) { - if (param.getValue() instanceof File) { - File file = (File) param.getValue(); - mp.bodyPart(new FileDataBodyPart(param.getKey(), file, MediaType.MULTIPART_FORM_DATA_TYPE)); - } else { - mp.field(param.getKey(), parameterToString(param.getValue()), MediaType.MULTIPART_FORM_DATA_TYPE); - } - } - body = mp; - } else if (contentType.startsWith("application/x-www-form-urlencoded")) { - encodedFormParams = this.getXWWWFormUrlencodedParams(formParams); - } - ClientResponse response = null; if ("GET".equals(method)) { response = (ClientResponse) builder.get(ClientResponse.class); } else if ("POST".equals(method)) { - if (encodedFormParams != null) { - response = builder.type(contentType).post(ClientResponse.class, encodedFormParams); - } else if (body == null) { - if(binaryBody == null) - response = builder.post(ClientResponse.class, null); - else - response = builder.type(contentType).post(ClientResponse.class, binaryBody); - } else if (body instanceof FormDataMultiPart) { - response = builder.type(contentType).post(ClientResponse.class, body); - } else { - response = builder.type(contentType).post(ClientResponse.class, serialize(body, contentType)); - } + response = builder.type(contentType).post(ClientResponse.class, serialize(body, contentType, formParams)); } else if ("PUT".equals(method)) { - if (encodedFormParams != null) { - response = builder.type(contentType).put(ClientResponse.class, encodedFormParams); - } else if(body == null) { - if(binaryBody == null) - response = builder.put(ClientResponse.class, null); - else - response = builder.type(contentType).put(ClientResponse.class, binaryBody); - } else { - response = builder.type(contentType).put(ClientResponse.class, serialize(body, contentType)); - } + response = builder.type(contentType).put(ClientResponse.class, serialize(body, contentType, formParams)); } else if ("DELETE".equals(method)) { - if (encodedFormParams != null) { - response = builder.type(contentType).delete(ClientResponse.class, encodedFormParams); - } else if(body == null) { - if(binaryBody == null) - response = builder.delete(ClientResponse.class); - else - response = builder.type(contentType).delete(ClientResponse.class, binaryBody); - } else { - response = builder.type(contentType).delete(ClientResponse.class, serialize(body, contentType)); - } + response = builder.type(contentType).delete(ClientResponse.class, serialize(body, contentType, formParams)); } else { throw new ApiException(500, "unknown method type " + method); } @@ -529,7 +491,6 @@ public class ApiClient { * @param method The request method, one of "GET", "POST", "PUT", and "DELETE" * @param queryParams The query parameters * @param body The request body object - if it is not binary, otherwise null - * @param binaryBody The request body object - if it is binary, otherwise null * @param headerParams The header parameters * @param formParams The form parameters * @param accept The request's Accept header @@ -537,9 +498,9 @@ public class ApiClient { * @param authNames The authentications to apply * @return The response body in type of string */ - public T invokeAPI(String path, String method, List queryParams, Object body, byte[] binaryBody, Map headerParams, Map formParams, String accept, String contentType, String[] authNames, TypeRef returnType) throws ApiException { + public T invokeAPI(String path, String method, List queryParams, Object body, Map headerParams, Map formParams, String accept, String contentType, String[] authNames, GenericType returnType) throws ApiException { - ClientResponse response = getAPIResponse(path, method, queryParams, body, binaryBody, headerParams, formParams, accept, contentType, authNames); + ClientResponse response = getAPIResponse(path, method, queryParams, body, headerParams, formParams, accept, contentType, authNames); statusCode = response.getStatusInfo().getStatusCode(); responseHeaders = response.getHeaders(); @@ -550,13 +511,13 @@ public class ApiClient { if (returnType == null) return null; else - return deserialize(response, returnType); + return response.getEntity(returnType); } else { String message = "error"; String respBody = null; if (response.hasEntity()) { try { - respBody = String.valueOf(response.getEntity(String.class)); + respBody = response.getEntity(String.class); message = respBody; } catch (RuntimeException e) { // e.printStackTrace(); @@ -569,58 +530,6 @@ public class ApiClient { respBody); } } - /** - * Invoke API by sending HTTP request with the given options - return binary result - * - * @param path The sub-path of the HTTP URL - * @param method The request method, one of "GET", "POST", "PUT", and "DELETE" - * @param queryParams The query parameters - * @param body The request body object - if it is not binary, otherwise null - * @param binaryBody The request body object - if it is binary, otherwise null - * @param headerParams The header parameters - * @param formParams The form parameters - * @param accept The request's Accept header - * @param contentType The request's Content-Type header - * @param authNames The authentications to apply - * @return The response body in type of string - */ - public byte[] invokeBinaryAPI(String path, String method, List queryParams, Object body, byte[] binaryBody, Map headerParams, Map formParams, String accept, String contentType, String[]authNames) throws ApiException { - - ClientResponse response = getAPIResponse(path, method, queryParams, body, binaryBody, headerParams, formParams, accept, contentType, authNames); - - if(response.getStatusInfo() == ClientResponse.Status.NO_CONTENT) { - return null; - } - else if(response.getStatusInfo().getFamily() == Family.SUCCESSFUL) { - if(response.hasEntity()) { - DataInputStream stream = new DataInputStream(response.getEntityInputStream()); - byte[] data = new byte[response.getLength()]; - try { - stream.readFully(data); - } catch (IOException ex) { - throw new ApiException(500, "Error obtaining binary response data"); - } - return data; - } - else { - return new byte[0]; - } - } - else { - String message = "error"; - if(response.hasEntity()) { - try{ - message = String.valueOf(response.getEntity(String.class)); - } - catch (RuntimeException e) { - // e.printStackTrace(); - } - } - throw new ApiException( - response.getStatusInfo().getStatusCode(), - message); - } - } /** * Update query and header parameters based on authentication settings. @@ -642,7 +551,6 @@ public class ApiClient { StringBuilder formParamBuilder = new StringBuilder(); for (Entry param : formParams.entrySet()) { - String keyStr = param.getKey(); String valueStr = parameterToString(param.getValue()); try { formParamBuilder.append(URLEncoder.encode(param.getKey(), "utf8")) @@ -667,7 +575,11 @@ public class ApiClient { */ private Client getClient() { if(!hostMap.containsKey(basePath)) { - Client client = Client.create(); + // Add the JSON serialization support to Jersey + JacksonJsonProvider jsonProvider = new JacksonJsonProvider(mapper); + DefaultClientConfig conf = new DefaultClientConfig(); + conf.getSingletons().add(jsonProvider); + Client client = Client.create(conf); if (debugging) client.addFilter(new LoggingFilter()); hostMap.put(basePath, client); diff --git a/modules/swagger-codegen/src/main/resources/Java/JSON.mustache b/modules/swagger-codegen/src/main/resources/Java/JSON.mustache deleted file mode 100644 index 54faed8dcb38..000000000000 --- a/modules/swagger-codegen/src/main/resources/Java/JSON.mustache +++ /dev/null @@ -1,64 +0,0 @@ -package {{invokerPackage}}; - -import com.fasterxml.jackson.annotation.*; -import com.fasterxml.jackson.databind.*; -import com.fasterxml.jackson.datatype.joda.*; - -import java.text.DateFormat; - -import java.io.IOException; - -{{>generatedAnnotation}} -public class JSON { - private ObjectMapper mapper; - - public JSON() { - mapper = new ObjectMapper(); - mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); - mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING); - mapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING); - mapper.registerModule(new JodaModule()); - } - - /** - * Set the date format for JSON (de)serialization with Date properties. - */ - public void setDateFormat(DateFormat dateFormat) { - mapper.setDateFormat(dateFormat); - } - - /** - * Serialize the given Java object into JSON string. - */ - public String serialize(Object obj) throws ApiException { - try { - if (obj != null) - return mapper.writeValueAsString(obj); - else - return null; - } catch (Exception e) { - throw new ApiException(400, e.getMessage()); - } - } - - /** - * Deserialize the given JSON string to Java object. - * - * @param body The JSON string - * @param returnType The type to deserialize inot - * @return The deserialized Java object - */ - public T deserialize(String body, TypeRef returnType) throws ApiException { - JavaType javaType = mapper.constructType(returnType.getType()); - try { - return mapper.readValue(body, javaType); - } catch (IOException e) { - if (returnType.getType().equals(String.class)) - return (T) body; - else - throw new ApiException(500, e.getMessage(), null, body); - } - } -} diff --git a/modules/swagger-codegen/src/main/resources/Java/TypeRef.mustache b/modules/swagger-codegen/src/main/resources/Java/TypeRef.mustache deleted file mode 100644 index 9e9ba5f88956..000000000000 --- a/modules/swagger-codegen/src/main/resources/Java/TypeRef.mustache +++ /dev/null @@ -1,26 +0,0 @@ -package {{invokerPackage}}; - -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.Type; - -{{>generatedAnnotation}} -public class TypeRef { - private final Type type; - - public TypeRef() { - this.type = getGenericType(getClass()); - } - - private static Type getGenericType(Class klass) { - Type superclass = klass.getGenericSuperclass(); - if (superclass instanceof Class) { - throw new RuntimeException("No type parameter provided"); - } - ParameterizedType parameterized = (ParameterizedType) superclass; - return parameterized.getActualTypeArguments()[0]; - } - - public Type getType() { - return type; - } -} diff --git a/modules/swagger-codegen/src/main/resources/Java/api.mustache b/modules/swagger-codegen/src/main/resources/Java/api.mustache index 5f617a253f14..fc441df954a7 100644 --- a/modules/swagger-codegen/src/main/resources/Java/api.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/api.mustache @@ -1,10 +1,11 @@ package {{package}}; +import com.sun.jersey.api.client.GenericType; + import {{invokerPackage}}.ApiException; import {{invokerPackage}}.ApiClient; import {{invokerPackage}}.Configuration; import {{invokerPackage}}.Pair; -import {{invokerPackage}}.TypeRef; {{#imports}}import {{import}}; {{/imports}} @@ -42,8 +43,7 @@ public class {{classname}} { {{/allParams}} * @return {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} */ public {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}}{{operationId}}({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) throws ApiException { - Object {{localVariablePrefix}}postBody = {{#bodyParam}}{{^isBinary}}{{paramName}}{{/isBinary}}{{#isBinary}}null{{/isBinary}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}}; - byte[] {{localVariablePrefix}}postBinaryBody = {{#bodyParam}}{{#isBinary}}{{paramName}}{{/isBinary}}{{^isBinary}}null{{/isBinary}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}}; + Object {{localVariablePrefix}}postBody = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}}; {{#allParams}}{{#required}} // verify the required parameter '{{paramName}}' is set if ({{paramName}} == null) { @@ -83,22 +83,12 @@ public class {{classname}} { String[] {{localVariablePrefix}}authNames = new String[] { {{#authMethods}}"{{name}}"{{#hasMore}}, {{/hasMore}}{{/authMethods}} }; - {{#isResponseBinary}} - byte[] {{localVariablePrefix}}response = null; - {{localVariablePrefix}}response = {{localVariablePrefix}}apiClient.invokeBinaryAPI({{localVariablePrefix}}path, "{{httpMethod}}", {{localVariablePrefix}}queryParams,{{localVariablePrefix}} postBody, {{localVariablePrefix}}postBinaryBody, {{localVariablePrefix}}headerParams, {{localVariablePrefix}}formParams, {{localVariablePrefix}}accept, {{localVariablePrefix}}contentType, {{localVariablePrefix}}authNames); - return {{localVariablePrefix}}response; - {{/isResponseBinary}} - - {{^isResponseBinary}} {{#returnType}} - TypeRef {{localVariablePrefix}}returnType = new TypeRef<{{{returnType}}}>() {}; - return {{localVariablePrefix}}apiClient.invokeAPI({{localVariablePrefix}}path, "{{httpMethod}}", {{localVariablePrefix}}queryParams, {{localVariablePrefix}}postBody, {{localVariablePrefix}}postBinaryBody, {{localVariablePrefix}}headerParams, {{localVariablePrefix}}formParams, {{localVariablePrefix}}accept, {{localVariablePrefix}}contentType, {{localVariablePrefix}}authNames, {{localVariablePrefix}}returnType); + GenericType<{{{returnType}}}> {{localVariablePrefix}}returnType = new GenericType<{{{returnType}}}>() {}; + return {{localVariablePrefix}}apiClient.invokeAPI({{localVariablePrefix}}path, "{{httpMethod}}", {{localVariablePrefix}}queryParams, {{localVariablePrefix}}postBody, {{localVariablePrefix}}headerParams, {{localVariablePrefix}}formParams, {{localVariablePrefix}}accept, {{localVariablePrefix}}contentType, {{localVariablePrefix}}authNames, {{localVariablePrefix}}returnType); {{/returnType}}{{^returnType}} - {{localVariablePrefix}}apiClient.invokeAPI({{localVariablePrefix}}path, "{{httpMethod}}", {{localVariablePrefix}}queryParams, {{localVariablePrefix}}postBody, {{localVariablePrefix}}postBinaryBody, {{localVariablePrefix}}headerParams, {{localVariablePrefix}}formParams, {{localVariablePrefix}}accept, {{localVariablePrefix}}contentType, {{localVariablePrefix}}authNames, null); + {{localVariablePrefix}}apiClient.invokeAPI({{localVariablePrefix}}path, "{{httpMethod}}", {{localVariablePrefix}}queryParams, {{localVariablePrefix}}postBody, {{localVariablePrefix}}headerParams, {{localVariablePrefix}}formParams, {{localVariablePrefix}}accept, {{localVariablePrefix}}contentType, {{localVariablePrefix}}authNames, null); {{/returnType}} - {{/isResponseBinary}} - - } {{/operation}} } diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/feign/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/ApiClient.mustache new file mode 100644 index 000000000000..3f2bfcebd5b5 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/ApiClient.mustache @@ -0,0 +1,86 @@ +package {{invokerPackage}}; + +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; +import feign.Feign; +import feign.jackson.JacksonDecoder; +import feign.jackson.JacksonEncoder; +import feign.slf4j.Slf4jLogger; + +{{>generatedAnnotation}} +public class ApiClient { + public interface Api {} + + private ObjectMapper objectMapper; + private String basePath = "{{basePath}}"; + + public ApiClient() { + objectMapper = createObjectMapper(); + } + + public String getBasePath() { + return basePath; + } + + public ApiClient setBasePath(String basePath) { + this.basePath = basePath; + return this; + } + + private ObjectMapper createObjectMapper() { + ObjectMapper objectMapper = new ObjectMapper(); + objectMapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING); + objectMapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING); + return objectMapper; + } + + /** + * Creates a feign client for given API interface. + * + * Usage: + * ApiClient apiClient = new ApiClient(); + * apiClient.setBasePath("http://localhost:8080"); + * XYZApi api = apiClient.buildClient(XYZApi.class); + * XYZResponse response = api.someMethod(...); + */ + public T buildClient(Class clientClass) { + return Feign.builder() + .encoder(new FormAwareEncoder(new JacksonEncoder(objectMapper))) + .decoder(new JacksonDecoder(objectMapper)) +// enable for basic auth: +// .requestInterceptor(new feign.auth.BasicAuthRequestInterceptor(username, password)) + .logger(new Slf4jLogger()) + .target(clientClass, basePath); + } + + /** + * Select the Accept header's value from the given accepts array: + * if JSON exists in the given array, use it; + * otherwise use all of them (joining into a string) + * + * @param accepts The accepts array to select from + * @return The Accept header to use. If the given array is empty, + * null will be returned (not to set the Accept header explicitly). + */ + public String selectHeaderAccept(String[] accepts) { + if (accepts.length == 0) return null; + if (StringUtil.containsIgnoreCase(accepts, "application/json")) return "application/json"; + return StringUtil.join(accepts, ","); + } + + /** + * Select the Content-Type header's value from the given array: + * if JSON exists in the given array, use it; + * otherwise use the first one of the array. + * + * @param contentTypes The Content-Type array to select from + * @return The Content-Type header to use. If the given array is empty, + * JSON will be used. + */ + public String selectHeaderContentType(String[] contentTypes) { + if (contentTypes.length == 0) return "application/json"; + if (StringUtil.containsIgnoreCase(contentTypes, "application/json")) return "application/json"; + return contentTypes[0]; + } +} diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/feign/FormAwareEncoder.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/FormAwareEncoder.mustache new file mode 100644 index 000000000000..822aad582d49 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/FormAwareEncoder.mustache @@ -0,0 +1,197 @@ +package {{invokerPackage}}; + +import java.io.*; +import java.lang.reflect.Type; +import java.net.URLEncoder; +import java.net.URLConnection; +import java.nio.charset.Charset; +import java.util.*; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; + +import feign.codec.EncodeException; +import feign.codec.Encoder; +import feign.RequestTemplate; + +{{>generatedAnnotation}} +public class FormAwareEncoder implements Encoder { + public static final String UTF_8 = "utf-8"; + private static final String LINE_FEED = "\r\n"; + private static final String TWO_DASH = "--"; + private static final String BOUNDARY = "----------------314159265358979323846"; + + private byte[] lineFeedBytes; + private byte[] boundaryBytes; + private byte[] twoDashBytes; + private byte[] atBytes; + private byte[] eqBytes; + + private final Encoder delegate; + private final DateFormat dateFormat; + + public FormAwareEncoder(Encoder delegate) { + this.delegate = delegate; + // Use RFC3339 format for date and datetime. + // See http://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14 + this.dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); + + // Use UTC as the default time zone. + this.dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); + try { + this.lineFeedBytes = LINE_FEED.getBytes(UTF_8); + this.boundaryBytes = BOUNDARY.getBytes(UTF_8); + this.twoDashBytes = TWO_DASH.getBytes(UTF_8); + this.atBytes = "&".getBytes(UTF_8); + this.eqBytes = "=".getBytes(UTF_8); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + } + } + + public void encode(Object object, Type bodyType, RequestTemplate template) throws EncodeException { + if (object instanceof Map) { + try { + encodeFormParams(template, (Map) object); + } catch (IOException e) { + throw new EncodeException("Failed to create request", e); + } + } else { + delegate.encode(object, bodyType, template); + } + } + + private void encodeFormParams(RequestTemplate template, Map formParams) throws IOException { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + + boolean isMultiPart = isMultiPart(formParams); + boolean isFirstField = true; + for (Map.Entry param : formParams.entrySet()) { + String keyStr = param.getKey(); + if (param.getValue() instanceof File) { + addFilePart(baos, keyStr, (File) param.getValue()); + } else { + String valueStr = parameterToString(param.getValue()); + if (isMultiPart) { + addMultiPartFormField(baos, keyStr, valueStr); + } else { + addEncodedFormField(baos, keyStr, valueStr, isFirstField); + isFirstField = false; + } + } + } + + if (isMultiPart) { + baos.write(lineFeedBytes); + baos.write(twoDashBytes); + baos.write(boundaryBytes); + baos.write(twoDashBytes); + baos.write(lineFeedBytes); + } + + String contentType = isMultiPart ? "multipart/form-data; boundary=" + BOUNDARY : "application/x-www-form-urlencoded"; + template.header("Content-type"); + template.header("Content-type", contentType); + template.header("MIME-Version", "1.0"); + template.body(baos.toByteArray(), Charset.forName(UTF_8)); + } + + /* + * Currently only supports text files + */ + private void addFilePart(ByteArrayOutputStream baos, String fieldName, File uploadFile) throws IOException { + String fileName = uploadFile.getName(); + baos.write(twoDashBytes); + baos.write(boundaryBytes); + baos.write(lineFeedBytes); + + String contentDisposition = "Content-Disposition: form-data; name=\"" + fieldName + + "\"; filename=\"" + fileName + "\""; + baos.write(contentDisposition.getBytes(UTF_8)); + baos.write(lineFeedBytes); + String contentType = "Content-Type: " + URLConnection.guessContentTypeFromName(fileName); + baos.write(contentType.getBytes(UTF_8)); + baos.write(lineFeedBytes); + baos.write(lineFeedBytes); + + BufferedReader reader = new BufferedReader(new FileReader(uploadFile)); + InputStream input = new FileInputStream(uploadFile); + byte[] bytes = new byte[4096]; + int len = bytes.length; + while ((len = input.read(bytes)) != -1) { + baos.write(bytes, 0, len); + baos.write(lineFeedBytes); + } + + baos.write(lineFeedBytes); + } + + private void addEncodedFormField(ByteArrayOutputStream baos, String name, String value, boolean isFirstField) throws IOException { + if (!isFirstField) { + baos.write(atBytes); + } + + String encodedName = URLEncoder.encode(name, UTF_8); + String encodedValue = URLEncoder.encode(value, UTF_8); + baos.write(encodedName.getBytes(UTF_8)); + baos.write("=".getBytes(UTF_8)); + baos.write(encodedValue.getBytes(UTF_8)); + } + + private void addMultiPartFormField(ByteArrayOutputStream baos, String name, String value) throws IOException { + baos.write(twoDashBytes); + baos.write(boundaryBytes); + baos.write(lineFeedBytes); + + String contentDisposition = "Content-Disposition: form-data; name=\"" + name + "\""; + String contentType = "Content-Type: text/plain; charset=utf-8"; + + baos.write(contentDisposition.getBytes(UTF_8)); + baos.write(lineFeedBytes); + baos.write(contentType.getBytes(UTF_8)); + baos.write(lineFeedBytes); + baos.write(lineFeedBytes); + baos.write(value.getBytes(UTF_8)); + baos.write(lineFeedBytes); + } + + private boolean isMultiPart(Map formParams) { + boolean isMultiPart = false; + for (Map.Entry entry : formParams.entrySet()) { + if (entry.getValue() instanceof File) { + isMultiPart = true; + break; + } + } + return isMultiPart; + } + + /** + * Format the given parameter object into string. + */ + public String parameterToString(Object param) { + if (param == null) { + return ""; + } else if (param instanceof Date) { + return formatDate((Date) param); + } else if (param instanceof Collection) { + StringBuilder b = new StringBuilder(); + for(Object o : (Collection)param) { + if(b.length() > 0) { + b.append(","); + } + b.append(String.valueOf(o)); + } + return b.toString(); + } else { + return String.valueOf(param); + } + } + + /** + * Format the given Date object into string. + */ + public String formatDate(Date date) { + return dateFormat.format(date); + } +} diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/feign/api.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/api.mustache new file mode 100644 index 000000000000..729320bd2e5c --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/api.mustache @@ -0,0 +1,32 @@ +package {{package}}; + +import {{invokerPackage}}.ApiClient; + +{{#imports}}import {{import}}; +{{/imports}} + +{{^fullJavaUtil}}import java.util.*; +{{/fullJavaUtil}} +import feign.*; + +{{>generatedAnnotation}} +public interface {{classname}} extends ApiClient.Api { + +{{#operations}}{{#operation}} + /** + * {{summary}} + * {{notes}} +{{#allParams}} * @param {{paramName}} {{description}} +{{/allParams}} * @return {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} + */ + @RequestLine("{{httpMethod}} {{{path}}}{{#hasQueryParams}}?{{/hasQueryParams}}{{#queryParams}}{{paramName}}={{=<% %>=}}{<%paramName%>}<%={{ }}=%>{{#hasMore}}&{{/hasMore}}{{/queryParams}}") + @Headers({ + "Content-type: {{vendorExtensions.x-contentType}}", + "Accepts: {{vendorExtensions.x-accepts}}",{{#headerParams}} + "{{paramName}}: {{=<% %>=}}{<%paramName%>}<%={{ }}=%>"{{#hasMore}}, + {{/hasMore}}{{/headerParams}} + }) + {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}}{{nickname}}({{#allParams}}{{^isBodyParam}}@Param("{{paramName}}") {{/isBodyParam}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); + {{/operation}} +{{/operations}} +} diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/feign/build.gradle.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/build.gradle.mustache new file mode 100644 index 000000000000..a528180df282 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/build.gradle.mustache @@ -0,0 +1,113 @@ +group = '{{groupId}}' +version = '{{artifactVersion}}' + +buildscript { + repositories { + jcenter() + } + dependencies { + classpath 'com.android.tools.build:gradle:1.2.2' + classpath 'com.github.dcendents:android-maven-plugin:1.2' + } +} + +repositories { + jcenter() +} + + +if(hasProperty('target') && target == 'android') { + + apply plugin: 'com.android.library' + apply plugin: 'com.github.dcendents.android-maven' + + android { + compileSdkVersion 22 + buildToolsVersion '22.0.0' + defaultConfig { + minSdkVersion 14 + targetSdkVersion 22 + } + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_7 + targetCompatibility JavaVersion.VERSION_1_7 + } + + // Rename the aar correctly + libraryVariants.all { variant -> + variant.outputs.each { output -> + def outputFile = output.outputFile + if (outputFile != null && outputFile.name.endsWith('.aar')) { + def fileName = "${project.name}-${variant.baseName}-${version}.aar" + output.outputFile = new File(outputFile.parent, fileName) + } + } + } + + dependencies { + provided 'javax.annotation:jsr250-api:1.0' + } + } + + afterEvaluate { + android.libraryVariants.all { variant -> + def task = project.tasks.create "jar${variant.name.capitalize()}", Jar + task.description = "Create jar artifact for ${variant.name}" + task.dependsOn variant.javaCompile + task.from variant.javaCompile.destinationDir + task.destinationDir = project.file("${project.buildDir}/outputs/jar") + task.archiveName = "${project.name}-${variant.baseName}-${version}.jar" + artifacts.add('archives', task); + } + } + + task sourcesJar(type: Jar) { + from android.sourceSets.main.java.srcDirs + classifier = 'sources' + } + + artifacts { + archives sourcesJar + } + +} else { + + apply plugin: 'java' + apply plugin: 'maven' + + sourceCompatibility = JavaVersion.VERSION_1_7 + targetCompatibility = JavaVersion.VERSION_1_7 + + install { + repositories.mavenInstaller { + pom.artifactId = '{{artifactId}}' + } + } + + task execute(type:JavaExec) { + main = System.getProperty('mainClass') + classpath = sourceSets.main.runtimeClasspath + } +} + +ext { + swagger_annotations_version = "1.5.0" + jackson_version = "2.6.3" + feign_version = "8.1.1" + jodatime_version = "2.5" + junit_version = "4.12" +} + +dependencies { + compile "io.swagger:swagger-annotations:$swagger_annotations_version" + compile "com.netflix.feign:feign-core:$feign_version" + compile "com.netflix.feign:feign-jackson:$feign_version" + compile "com.netflix.feign:feign-slf4j:$feign_version" + compile "com.fasterxml.jackson.core:jackson-core:$jackson_version" + compile "com.fasterxml.jackson.core:jackson-annotations:$jackson_version" + compile "com.fasterxml.jackson.core:jackson-databind:$jackson_version" + compile "com.fasterxml.jackson.datatype:jackson-datatype-joda:2.1.5" + compile "joda-time:joda-time:$jodatime_version" + compile "com.brsanthu:migbase64:2.2" + testCompile "junit:junit:$junit_version" +} diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/feign/pom.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/pom.mustache new file mode 100644 index 000000000000..e8069b829310 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/pom.mustache @@ -0,0 +1,183 @@ + + 4.0.0 + {{groupId}} + {{artifactId}} + jar + {{artifactId}} + {{artifactVersion}} + + scm:git:git@github.com:swagger-api/swagger-mustache.git + scm:git:git@github.com:swagger-api/swagger-codegen.git + https://github.com/swagger-api/swagger-codegen + + + 2.2.0 + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.12 + + + + loggerPath + conf/log4j.properties + + + -Xms512m -Xmx1500m + methods + pertest + + + + maven-dependency-plugin + + + package + + copy-dependencies + + + ${project.build.directory}/lib + + + + + + + + org.apache.maven.plugins + maven-jar-plugin + 2.2 + + + + jar + test-jar + + + + + + + + + org.codehaus.mojo + build-helper-maven-plugin + + + add_sources + generate-sources + + add-source + + + + src/main/java + + + + + add_test_sources + generate-test-sources + + add-test-source + + + + src/test/java + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 2.3.2 + + 1.6 + 1.6 + + + + + + + io.swagger + swagger-annotations + ${swagger-annotations-version} + + + + + com.netflix.feign + feign-core + ${feign-version} + + + com.netflix.feign + feign-jackson + ${feign-version} + + + com.netflix.feign + feign-slf4j + ${feign-version} + + + + + com.fasterxml.jackson.core + jackson-core + ${jackson-version} + + + com.fasterxml.jackson.core + jackson-annotations + ${jackson-version} + + + com.fasterxml.jackson.core + jackson-databind + ${jackson-version} + + + com.fasterxml.jackson.datatype + jackson-datatype-joda + 2.1.5 + + + joda-time + joda-time + ${jodatime-version} + + + + + com.brsanthu + migbase64 + 2.2 + + + + + junit + junit + ${junit-version} + test + + + + 1.5.0 + 8.1.1 + 2.6.3 + 2.5 + 4.12 + 1.0.0 + + diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/ApiClient.mustache index d29beeea34cc..f482b8c34d4d 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/ApiClient.mustache @@ -6,6 +6,7 @@ import javax.ws.rs.client.Entity; import javax.ws.rs.client.Invocation; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.Form; +import javax.ws.rs.core.GenericType; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; @@ -29,13 +30,11 @@ import java.util.TimeZone; import java.net.URLEncoder; -import java.io.IOException; import java.io.File; import java.io.UnsupportedEncodingException; import java.text.DateFormat; import java.text.SimpleDateFormat; -import java.text.ParseException; import {{invokerPackage}}.auth.Authentication; import {{invokerPackage}}.auth.HttpBasicAuth; @@ -344,6 +343,17 @@ public class ApiClient { return params; } + /** + * Check if the given MIME is a JSON MIME. + * JSON MIME examples: + * application/json + * application/json; charset=UTF8 + * APPLICATION/JSON + */ + public boolean isJsonMime(String mime) { + return mime != null && mime.matches("(?i)application\\/json(;.*)?"); + } + /** * Select the Accept header's value from the given accepts array: * if JSON exists in the given array, use it; @@ -354,8 +364,14 @@ public class ApiClient { * null will be returned (not to set the Accept header explicitly). */ public String selectHeaderAccept(String[] accepts) { - if (accepts.length == 0) return null; - if (StringUtil.containsIgnoreCase(accepts, "application/json")) return "application/json"; + if (accepts.length == 0) { + return null; + } + for (String accept : accepts) { + if (isJsonMime(accept)) { + return accept; + } + } return StringUtil.join(accepts, ","); } @@ -369,8 +385,14 @@ public class ApiClient { * JSON will be used. */ public String selectHeaderContentType(String[] contentTypes) { - if (contentTypes.length == 0) return "application/json"; - if (StringUtil.containsIgnoreCase(contentTypes, "application/json")) return "application/json"; + if (contentTypes.length == 0) { + return "application/json"; + } + for (String contentType : contentTypes) { + if (isJsonMime(contentType)) { + return contentType; + } + } return contentTypes[0]; } @@ -389,18 +411,39 @@ public class ApiClient { * Serialize the given Java object into string entity according the given * Content-Type (only JSON is supported for now). */ - public Entity serialize(Object obj, String contentType) throws ApiException { - if (contentType.startsWith("application/json")) { - return Entity.json(json.serialize(obj)); + public Entity serialize(Object obj, Map formParams, String contentType) throws ApiException { + Entity entity = null; + if (contentType.startsWith("multipart/form-data")) { + MultiPart multiPart = new MultiPart(); + for (Entry param: formParams.entrySet()) { + if (param.getValue() instanceof File) { + File file = (File) param.getValue(); + FormDataContentDisposition contentDisp = FormDataContentDisposition.name(param.getKey()) + .fileName(file.getName()).size(file.length()).build(); + multiPart.bodyPart(new FormDataBodyPart(contentDisp, file, MediaType.APPLICATION_OCTET_STREAM_TYPE)); + } else { + FormDataContentDisposition contentDisp = FormDataContentDisposition.name(param.getKey()).build(); + multiPart.bodyPart(new FormDataBodyPart(contentDisp, parameterToString(param.getValue()))); + } + } + entity = Entity.entity(multiPart, MediaType.MULTIPART_FORM_DATA_TYPE); + } else if (contentType.startsWith("application/x-www-form-urlencoded")) { + Form form = new Form(); + for (Entry param: formParams.entrySet()) { + form.param(param.getKey(), parameterToString(param.getValue())); + } + entity = Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE); } else { - throw new ApiException(400, "can not serialize object into Content-Type: " + contentType); + // We let jersey handle the serialization + entity = Entity.entity(obj, contentType); } + return entity; } /** * Deserialize response body to Java object according to the Content-Type. */ - public T deserialize(Response response, TypeRef returnType) throws ApiException { + public T deserialize(Response response, GenericType returnType) throws ApiException { String contentType = null; List contentTypes = response.getHeaders().get("Content-Type"); if (contentTypes != null && !contentTypes.isEmpty()) @@ -408,24 +451,7 @@ public class ApiClient { if (contentType == null) throw new ApiException(500, "missing Content-Type in response"); - String body; - if (response.hasEntity()) - body = (String) response.readEntity(String.class); - else - body = ""; - - if (contentType.startsWith("application/json")) { - return json.deserialize(body, returnType); - } else if (returnType.getType().equals(String.class)) { - // Expecting string, return the raw response body. - return (T) body; - } else { - throw new ApiException( - 500, - "Content type \"" + contentType + "\" is not supported for type: " - + returnType.getType() - ); - } + return response.readEntity(returnType); } /** @@ -443,7 +469,7 @@ public class ApiClient { * @param returnType The return type into which to deserialize the response * @return The response body in type of string */ - public T invokeAPI(String path, String method, List queryParams, Object body, Map headerParams, Map formParams, String accept, String contentType, String[] authNames, TypeRef returnType) throws ApiException { + public T invokeAPI(String path, String method, List queryParams, Object body, Map headerParams, Map formParams, String accept, String contentType, String[] authNames, GenericType returnType) throws ApiException { updateParamsForAuth(authNames, queryParams, headerParams); WebTarget target = client.target(this.basePath).path(path); @@ -474,50 +500,16 @@ public class ApiClient { } } - Entity formEntity = null; - - if (contentType.startsWith("multipart/form-data")) { - MultiPart multiPart = new MultiPart(); - for (Entry param: formParams.entrySet()) { - if (param.getValue() instanceof File) { - File file = (File) param.getValue(); - FormDataContentDisposition contentDisp = FormDataContentDisposition.name(param.getKey()) - .fileName(file.getName()).size(file.length()).build(); - multiPart.bodyPart(new FormDataBodyPart(contentDisp, file, MediaType.APPLICATION_OCTET_STREAM_TYPE)); - } else { - FormDataContentDisposition contentDisp = FormDataContentDisposition.name(param.getKey()).build(); - multiPart.bodyPart(new FormDataBodyPart(contentDisp, parameterToString(param.getValue()))); - } - } - formEntity = Entity.entity(multiPart, MediaType.MULTIPART_FORM_DATA_TYPE); - } else if (contentType.startsWith("application/x-www-form-urlencoded")) { - Form form = new Form(); - for (Entry param: formParams.entrySet()) { - form.param(param.getKey(), parameterToString(param.getValue())); - } - formEntity = Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE); - } + Entity entity = serialize(body, formParams, contentType); Response response = null; if ("GET".equals(method)) { response = invocationBuilder.get(); } else if ("POST".equals(method)) { - if (formEntity != null) { - response = invocationBuilder.post(formEntity); - } else if (body == null) { - response = invocationBuilder.post(null); - } else { - response = invocationBuilder.post(serialize(body, contentType)); - } + response = invocationBuilder.post(entity); } else if ("PUT".equals(method)) { - if (formEntity != null) { - response = invocationBuilder.put(formEntity); - } else if (body == null) { - response = invocationBuilder.put(null); - } else { - response = invocationBuilder.put(serialize(body, contentType)); - } + response = invocationBuilder.put(entity); } else if ("DELETE".equals(method)) { response = invocationBuilder.delete(); } else { @@ -556,6 +548,8 @@ public class ApiClient { private void buildClient() { final ClientConfig clientConfig = new ClientConfig(); clientConfig.register(MultiPartFeature.class); + clientConfig.register(json); + clientConfig.register(org.glassfish.jersey.jackson.JacksonFeature.class); if (debugging) { clientConfig.register(LoggingFilter.class); } diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/JSON.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/JSON.mustache new file mode 100644 index 000000000000..cc3f1baba140 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/JSON.mustache @@ -0,0 +1,36 @@ +package {{invokerPackage}}; + +import com.fasterxml.jackson.annotation.*; +import com.fasterxml.jackson.databind.*; +import com.fasterxml.jackson.datatype.joda.*; + +import java.text.DateFormat; + +import javax.ws.rs.ext.ContextResolver; + +{{>generatedAnnotation}} +public class JSON implements ContextResolver { + private ObjectMapper mapper; + + public JSON() { + mapper = new ObjectMapper(); + mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); + mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING); + mapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING); + mapper.registerModule(new JodaModule()); + } + + /** + * Set the date format for JSON (de)serialization with Date properties. + */ + public void setDateFormat(DateFormat dateFormat) { + mapper.setDateFormat(dateFormat); + } + + @Override + public ObjectMapper getContext(Class type) { + return mapper; + } +} diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/api.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/api.mustache index 0d5c3bcf7f0b..f9572359ded9 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/api.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/api.mustache @@ -4,7 +4,8 @@ import {{invokerPackage}}.ApiException; import {{invokerPackage}}.ApiClient; import {{invokerPackage}}.Configuration; import {{invokerPackage}}.Pair; -import {{invokerPackage}}.TypeRef; + +import javax.ws.rs.core.GenericType; {{#imports}}import {{import}}; {{/imports}} @@ -83,7 +84,7 @@ public class {{classname}} { String[] {{localVariablePrefix}}authNames = new String[] { {{#authMethods}}"{{name}}"{{#hasMore}}, {{/hasMore}}{{/authMethods}} }; {{#returnType}} - TypeRef {{localVariablePrefix}}returnType = new TypeRef<{{{returnType}}}>() {}; + GenericType<{{{returnType}}}> {{localVariablePrefix}}returnType = new GenericType<{{{returnType}}}>() {}; return {{localVariablePrefix}}apiClient.invokeAPI({{localVariablePrefix}}path, "{{httpMethod}}", {{localVariablePrefix}}queryParams, {{localVariablePrefix}}postBody, {{localVariablePrefix}}headerParams, {{localVariablePrefix}}formParams, {{localVariablePrefix}}accept, {{localVariablePrefix}}contentType, {{localVariablePrefix}}authNames, {{localVariablePrefix}}returnType); {{/returnType}}{{^returnType}} {{localVariablePrefix}}apiClient.invokeAPI({{localVariablePrefix}}path, "{{httpMethod}}", {{localVariablePrefix}}queryParams, {{localVariablePrefix}}postBody, {{localVariablePrefix}}headerParams, {{localVariablePrefix}}formParams, {{localVariablePrefix}}accept, {{localVariablePrefix}}contentType, {{localVariablePrefix}}authNames, null); diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/pom.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/pom.mustache index dbe0138aa54b..76f2164a1add 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/pom.mustache @@ -124,7 +124,12 @@ jersey-media-multipart ${jersey-version} - + + org.glassfish.jersey.media + jersey-media-json-jackson + 2.22.1 + + com.fasterxml.jackson.core diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ApiClient.mustache index e97e4c7f97d8..99dcdb517805 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 @@ -549,6 +549,17 @@ public class ApiClient { return params; } + /** + * Check if the given MIME is a JSON MIME. + * JSON MIME examples: + * application/json + * application/json; charset=UTF8 + * APPLICATION/JSON + */ + public boolean isJsonMime(String mime) { + return mime != null && mime.matches("(?i)application\\/json(;.*)?"); + } + /** * Select the Accept header's value from the given accepts array: * if JSON exists in the given array, use it; @@ -559,8 +570,14 @@ public class ApiClient { * null will be returned (not to set the Accept header explicitly). */ public String selectHeaderAccept(String[] accepts) { - if (accepts.length == 0) return null; - if (StringUtil.containsIgnoreCase(accepts, "application/json")) return "application/json"; + if (accepts.length == 0) { + return null; + } + for (String accept : accepts) { + if (isJsonMime(accept)) { + return accept; + } + } return StringUtil.join(accepts, ","); } @@ -574,8 +591,14 @@ public class ApiClient { * JSON will be used. */ public String selectHeaderContentType(String[] contentTypes) { - if (contentTypes.length == 0) return "application/json"; - if (StringUtil.containsIgnoreCase(contentTypes, "application/json")) return "application/json"; + if (contentTypes.length == 0) { + return "application/json"; + } + for (String contentType : contentTypes) { + if (isJsonMime(contentType)) { + return contentType; + } + } return contentTypes[0]; } @@ -626,7 +649,7 @@ public class ApiClient { // ensuring a default content type contentType = "application/json"; } - if (contentType.startsWith("application/json")) { + if (isJsonMime(contentType)) { return json.deserialize(respBody, returnType); } else if (returnType.equals(String.class)) { // Expecting string, return the raw response body. @@ -650,7 +673,7 @@ public class ApiClient { * @throws ApiException If fail to serialize the given object */ public String serialize(Object obj, String contentType) throws ApiException { - if (contentType.startsWith("application/json")) { + if (isJsonMime(contentType)) { if (obj != null) return json.serialize(obj); else @@ -822,7 +845,9 @@ public class ApiClient { String contentType = (String) headerParams.get("Content-Type"); // ensuring a default content type - if (contentType == null) contentType = "application/json"; + if (contentType == null) { + contentType = "application/json"; + } RequestBody reqBody; if (!HttpMethod.permitsRequestBody(method)) { diff --git a/modules/swagger-codegen/src/main/resources/Java/pom.mustache b/modules/swagger-codegen/src/main/resources/Java/pom.mustache index c5bfbc65b746..f2c20a96740b 100644 --- a/modules/swagger-codegen/src/main/resources/Java/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/pom.mustache @@ -137,6 +137,11 @@ jackson-databind ${jackson-version} + + com.fasterxml.jackson.jaxrs + jackson-jaxrs-json-provider + ${jackson-version} + com.fasterxml.jackson.datatype jackson-datatype-joda diff --git a/modules/swagger-codegen/src/main/resources/Javascript/api.mustache b/modules/swagger-codegen/src/main/resources/Javascript/api.mustache index a9af0d54c15a..9957fc4e2c51 100644 --- a/modules/swagger-codegen/src/main/resources/Javascript/api.mustache +++ b/modules/swagger-codegen/src/main/resources/Javascript/api.mustache @@ -1,17 +1,20 @@ -/* - * {{>generatedAnnotation}} - */ +// require files in Node.js environment +var ${{#imports}}, {{import}}{{/imports}}; +if (typeof module === 'object' && module.exports) { + $ = require('jquery');{{#imports}} + {{import}} = require('../model/{{import}}.js');{{/imports}} +} -//export module +// export module for AMD if ( typeof define === "function" && define.amd ) { - define(['jquery'], function($) { + define(['jquery'{{#imports}}, '{{import}}'{{/imports}}], function(${{#imports}}, {{import}}{{/imports}}) { return {{classname}}; }); } var {{classname}} = function {{classname}}() { var self = this; -{{#operations}} + {{#operations}} {{#operation}} /** * {{summary}} @@ -20,8 +23,7 @@ var {{classname}} = function {{classname}}() { {{/allParams}} * @param {function} callback the callback function * @return {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} */ - self.{{nickname}} = function({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}, callback) { - + self.{{nickname}} = function({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}{{#hasParams}}, {{/hasParams}}callback) { var {{localVariablePrefix}}postBody = {{#bodyParam}}{{^isBinary}}JSON.stringify({{paramName}}){{/isBinary}}{{#isBinary}}null{{/isBinary}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}}; var {{localVariablePrefix}}postBinaryBody = {{#bodyParam}}{{#isBinary}}{{paramName}}{{/isBinary}}{{^isBinary}}null{{/isBinary}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}}; {{#allParams}}{{#required}} @@ -39,8 +41,8 @@ var {{classname}} = function {{classname}}() { basePath = basePath.substring(0, basePath.length-1); } - var {{localVariablePrefix}}path = basePath + replaceAll(replaceAll("{{{path}}}", "\\{format\\}","json"){{#pathParams}} -, "\\{" + "{{baseName}}" + "\\}", {{localVariablePrefix}}apiClient.escapeString({{{paramName}}}.toString()){{/pathParams}}); + var {{localVariablePrefix}}path = basePath + replaceAll(replaceAll("{{{path}}}", "\\{format\\}","json"){{#pathParams}} +, "\\{" + "{{baseName}}" + "\\}", encodeURIComponent({{{paramName}}}.toString()){{/pathParams}}); var queryParams = {}; var headerParams = {}; @@ -50,58 +52,46 @@ var {{classname}} = function {{classname}}() { queryParams.{{baseName}} = {{paramName}}; {{/queryParams}} {{#headerParams}}if ({{paramName}} != null) - {{localVariablePrefix}}headerParams.put("{{baseName}}", {{localVariablePrefix}}apiClient.parameterToString({{paramName}})); + {{localVariablePrefix}}headerParams.put("{{baseName}}", {{paramName}}); {{/headerParams}} {{#formParams}}if ({{paramName}} != null) {{localVariablePrefix}}formParams.put("{{baseName}}", {{paramName}}); {{/formParams}} - path += createQueryString(queryParams); + path += createQueryString(queryParams); - //if (console) { - //console.log('path: ' + path); - //console.log('queryParams: ' + queryParams); - //} - - {{#isResponseBinary}} - byte[] {{localVariablePrefix}}response = null; - {{localVariablePrefix}}response = {{localVariablePrefix}}apiClient.invokeBinaryAPI({{localVariablePrefix}}path, "{{httpMethod}}", {{localVariablePrefix}}queryParams,{{localVariablePrefix}} postBody, {{localVariablePrefix}}postBinaryBody, {{localVariablePrefix}}headerParams, {{localVariablePrefix}}formParams, {{localVariablePrefix}}accept, {{localVariablePrefix}}contentType, {{localVariablePrefix}}authNames); - return {{localVariablePrefix}}response; - {{/isResponseBinary}} - - {{^isResponseBinary}} - {{#returnType}} - //TypeRef {{localVariablePrefix}}returnType = new TypeRef<{{{returnType}}}>() {}; - //return {{localVariablePrefix}}apiClient.invokeAPI({{localVariablePrefix}}path, "{{httpMethod}}", {{localVariablePrefix}}queryParams, {{localVariablePrefix}}postBody, {{localVariablePrefix}}postBinaryBody, {{localVariablePrefix}}headerParams, {{localVariablePrefix}}formParams, {{localVariablePrefix}}accept, {{localVariablePrefix}}contentType, {{localVariablePrefix}}authNames, {{localVariablePrefix}}returnType); - - var options = {type: "{{httpMethod}}", async: true, contentType: "application/json", dataType: "json", data: postBody}; + var options = {type: "{{httpMethod}}", async: true, contentType: "application/json", dataType: "json", data: postBody}; var request = $.ajax(path, options); - //request.fail(function(jqXHR, textStatus, errorThrown){ - // errorHandler(jqXHR, textStatus, errorThrown); - //}); - - - request.done(function(response, textStatus, jqXHR){ - /** - * @returns {{{returnType}}} - */ - {{#returnTypeIsPrimitive}} var myResponse = response;{{/returnTypeIsPrimitive}} - {{^returnTypeIsPrimitive}} var myResponse = new {{{returnType}}}(); - myResponse.constructFromObject(response);{{/returnTypeIsPrimitive}} - - callback(myResponse, textStatus, jqXHR); - }); - - {{/returnType}}{{^returnType}} - {{localVariablePrefix}}apiClient.invokeAPI({{localVariablePrefix}}path, "{{httpMethod}}", {{localVariablePrefix}}queryParams, {{localVariablePrefix}}postBody, {{localVariablePrefix}}postBinaryBody, {{localVariablePrefix}}headerParams, {{localVariablePrefix}}formParams, {{localVariablePrefix}}accept, {{localVariablePrefix}}contentType, {{localVariablePrefix}}authNames, null); - {{/returnType}} - {{/isResponseBinary}} - + request.fail(function(jqXHR, textStatus, errorThrown){ + if (callback) { + var error = errorThrown || textStatus || jqXHR.statusText || 'error'; + callback(null, textStatus, jqXHR, error); + } + }); + + request.done(function(response, textStatus, jqXHR){ + {{#returnType}} + /** + * @returns {{{returnType}}} + */ + {{#returnTypeIsPrimitive}}var myResponse = response;{{/returnTypeIsPrimitive}} + {{^returnTypeIsPrimitive}}var myResponse = new {{{returnType}}}(); + myResponse.constructFromObject(response);{{/returnTypeIsPrimitive}} + if (callback) { + callback(myResponse, textStatus, jqXHR); + } + {{/returnType}}{{^returnType}} + if (callback) { + callback(response, textStatus, jqXHR); + } + {{/returnType}} + }); + + return request; } {{/operation}} - -{{/operations}} + {{/operations}} function replaceAll (haystack, needle, replace) { var result= haystack; @@ -128,3 +118,8 @@ var {{classname}} = function {{classname}}() { return queryString; } } + +// export module for Node.js +if (typeof module === 'object' && module.exports) { + module.exports = {{classname}}; +} diff --git a/modules/swagger-codegen/src/main/resources/Javascript/generatedAnnotation.mustache b/modules/swagger-codegen/src/main/resources/Javascript/generatedAnnotation.mustache deleted file mode 100644 index 49110fc1ad93..000000000000 --- a/modules/swagger-codegen/src/main/resources/Javascript/generatedAnnotation.mustache +++ /dev/null @@ -1 +0,0 @@ -@javax.annotation.Generated(value = "{{generatorClass}}", date = "{{generatedDate}}") \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/Javascript/index.mustache b/modules/swagger-codegen/src/main/resources/Javascript/index.mustache new file mode 100644 index 000000000000..a0207a6cc916 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Javascript/index.mustache @@ -0,0 +1,10 @@ +if (typeof module === 'object' && module.exports) { + var {{moduleName}} = {}; + {{#models}} + {{moduleName}}.{{importPath}} = require('./model/{{importPath}}.js'); + {{/models}} + {{#apiInfo}}{{#apis}} + {{moduleName}}.{{importPath}} = require('./api/{{importPath}}.js'); + {{/apis}}{{/apiInfo}} + module.exports = {{moduleName}}; +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/Javascript/model.mustache b/modules/swagger-codegen/src/main/resources/Javascript/model.mustache index acf0bcffc195..0588d03a8c13 100644 --- a/modules/swagger-codegen/src/main/resources/Javascript/model.mustache +++ b/modules/swagger-codegen/src/main/resources/Javascript/model.mustache @@ -1,37 +1,48 @@ +// require files in Node.js environment +{{#imports}} +var {{import}};{{/imports}} +if (typeof module === 'object' && module.exports) { + {{#imports}} + {{import}} = require('./{{import}}.js');{{/imports}} +} + {{#models}}{{#model}} {{#vars}}{{#isEnum}}{{>enumClass}}{{/isEnum}}{{#items.isEnum}}{{#items}} {{>enumClass}}{{/items}}*/{{/items.isEnum}}{{/vars}} //export module -if ( typeof define === "function" && define.amd ) { - define('{{classname}}', ['jquery'{{#vars}}{{^isPrimitiveType}}{{^-last}}, {{/-last}}'{{datatypeWithEnum}}'{{/isPrimitiveType}}{{/vars}}], - function(${{#vars}}{{^isPrimitiveType}}{{^-last}}, {{/-last}}{{datatypeWithEnum}}{{/isPrimitiveType}}{{/vars}}) { - return {{classname}}; - }); +if ( typeof define === "function" && define.amd ) { + define('{{classname}}', ['jquery'{{#vars}}{{^isPrimitiveType}}{{^-last}}, {{/-last}}'{{datatypeWithEnum}}'{{/isPrimitiveType}}{{/vars}}], + function(${{#vars}}{{^isPrimitiveType}}{{^-last}}, {{/-last}}{{datatypeWithEnum}}{{/isPrimitiveType}}{{/vars}}) { + return {{classname}}; + }); } {{#description}}/** * {{description}} **/{{/description}} var {{classname}} = function {{classname}}({{#mandatory}}{{this}}{{^-last}}, {{/-last}}{{/mandatory}}) { {{#parent}}/* extends {{{parent}}}*/{{/parent}} - var self = this; - {{#vars}} - /**{{#description}} - * {{{description}}}{{/description}} - * datatype: {{{datatypeWithEnum}}}{{#required}} - * required{{/required}}{{#minimum}} - * minimum: {{minimum}}{{/minimum}}{{#maximum}} - * maximum: {{maximum}}{{/maximum}} - **/ - self.{{name}} = {{#required}}{{name}}{{/required}}{{^required}}{{{defaultValue}}}{{/required}}; - {{/vars}} - - self.constructFromObject = function(data) { - {{#vars}} - self.{{name}}{{{defaultValueWithParam}}} - {{/vars}} - } + var self = this; + {{#vars}} + /**{{#description}} + * {{{description}}}{{/description}} + * datatype: {{{datatypeWithEnum}}}{{#required}} + * required{{/required}}{{#minimum}} + * minimum: {{minimum}}{{/minimum}}{{#maximum}} + * maximum: {{maximum}}{{/maximum}} + **/ + self.{{name}} = {{#required}}{{name}}{{/required}}{{^required}}{{{defaultValue}}}{{/required}}; + {{/vars}} + self.constructFromObject = function(data) { + if (!data) { + return; + } + {{#vars}} + self.{{name}}{{{defaultValueWithParam}}} + {{/vars}} + } + {{#vars}} /**{{#description}} * get {{{description}}}{{/description}}{{#minimum}} @@ -42,7 +53,7 @@ var {{classname}} = function {{classname}}({{#mandatory}}{{this}}{{^-last}}, {{/ self.{{getter}} = function() { return self.{{name}}; } - + /**{{#description}} * set {{{description}}}{{/description}} * @param {{=<% %>=}}{<% datatypeWithEnum %>}<%={{ }}=%> {{name}} @@ -53,8 +64,12 @@ var {{classname}} = function {{classname}}({{#mandatory}}{{this}}{{^-last}}, {{/ {{/vars}} self.toJson = function () { - return JSON.stringify(self); + return JSON.stringify(self); } } + +if (typeof module === 'object' && module.exports) { + module.exports = {{classname}}; +} {{/model}} {{/models}} diff --git a/modules/swagger-codegen/src/main/resources/Javascript/package.mustache b/modules/swagger-codegen/src/main/resources/Javascript/package.mustache new file mode 100644 index 000000000000..c77ee835709e --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Javascript/package.mustache @@ -0,0 +1,20 @@ +{ + "name": "{{{projectName}}}", + "version": "{{{projectVersion}}}", + "description": "{{{projectDescription}}}",{{#projectLicenseName}} + "license": "{{{projectLicenseName}}}",{{/projectLicenseName}} + "main": "{{sourceFolder}}/index.js", + "scripts": { + "test": "./node_modules/mocha/bin/mocha --recursive" + }, + "dependencies": { + "jquery": "~2.1.4" + }, + "devDependencies": { + "mocha": "~2.3.4", + "expect.js": "~0.3.1", + "mockrequire": "~0.0.5", + "domino": "~1.0.20", + "xmlhttprequest": "~1.8.0" + } +} diff --git a/modules/swagger-codegen/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig b/modules/swagger-codegen/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig index 349fe78b4a0b..5d8a4f0fc6bf 100644 --- a/modules/swagger-codegen/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig +++ b/modules/swagger-codegen/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig @@ -8,6 +8,7 @@ io.swagger.codegen.languages.JavaClientCodegen io.swagger.codegen.languages.JavascriptClientCodegen io.swagger.codegen.languages.JaxRSServerCodegen io.swagger.codegen.languages.JavaInflectorServerCodegen +io.swagger.codegen.languages.JMeterCodegen io.swagger.codegen.languages.NodeJSServerCodegen io.swagger.codegen.languages.ObjcClientCodegen io.swagger.codegen.languages.PerlClientCodegen diff --git a/modules/swagger-codegen/src/main/resources/clojure/core.mustache b/modules/swagger-codegen/src/main/resources/clojure/core.mustache index 79d0ee9b5eec..0da2a4514954 100644 --- a/modules/swagger-codegen/src/main/resources/clojure/core.mustache +++ b/modules/swagger-codegen/src/main/resources/clojure/core.mustache @@ -174,7 +174,7 @@ [mime] (if mime (or (= :json mime) - (re-matches #"application/json(;.*)?" (name mime))))) + (re-matches #"(?i)application/json(;.*)?" (name mime))))) (defn json-preferred-mime "Choose a MIME from the given MIMEs with JSON preferred, diff --git a/modules/swagger-codegen/src/main/resources/csharp/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/csharp/ApiClient.mustache index 5dda78a41a46..db865e2b27d4 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/ApiClient.mustache @@ -19,23 +19,56 @@ namespace {{packageName}}.Client public class ApiClient { /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class + /// with default configuration and base path ({{basePath}}). + /// + public ApiClient() + { + Configuration = Configuration.Default; + RestClient = new RestClient("{{basePath}}"); + } + + /// + /// Initializes a new instance of the class + /// with default base path ({{basePath}}). + /// + /// An instance of Configuration. + public ApiClient(Configuration config = null) + { + if (config == null) + Configuration = Configuration.Default; + else + Configuration = config; + + RestClient = new RestClient("{{basePath}}"); + } + + /// + /// Initializes a new instance of the class + /// with default configuration. /// /// The base path. - public ApiClient(String basePath="{{basePath}}") + public ApiClient(String basePath = "{{basePath}}") { if (String.IsNullOrEmpty(basePath)) throw new ArgumentException("basePath cannot be empty"); RestClient = new RestClient(basePath); + Configuration = Configuration.Default; } /// /// Gets or sets the default API client for making HTTP calls. /// /// The default API client. - public static ApiClient Default = new ApiClient(); + public static ApiClient Default = new ApiClient(Configuration.Default); + /// + /// Gets or sets the Configuration. + /// + /// An instance of the Configuration. + public Configuration Configuration { get; set; } + /// /// Gets or sets the RestClient. /// @@ -147,7 +180,7 @@ namespace {{packageName}}.Client } /// - /// If parameter is DateTime, output in ISO8601 format. + /// If parameter is DateTime, output in a formatted string (default ISO 8601), customizable with Configuration.DateTime. /// If parameter is a list, join the list with ",". /// Otherwise just return the string. /// @@ -156,16 +189,21 @@ namespace {{packageName}}.Client public string ParameterToString(object obj) { if (obj is DateTime) - return ((DateTime)obj).ToString ("u"); + // Return a formatted date string - Can be customized with Configuration.DateTimeFormat + // Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o") + // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 + // For example: 2009-06-15T13:45:30.0000000 + return ((DateTime)obj).ToString (Configuration.DateTimeFormat); else if (obj is IList) { - string flattenString = ""; - string separator = ","; + var flattenedString = new StringBuilder(); foreach (var param in (IList)obj) { - flattenString += param.ToString() + separator; + if (flattenedString.Length > 0) + flattenedString.Append(","); + flattenedString.Append(param); } - return flattenString.Remove(flattenString.Length - 1);; + return flattenedString.ToString(); } else return Convert.ToString (obj); diff --git a/modules/swagger-codegen/src/main/resources/csharp/Configuration.mustache b/modules/swagger-codegen/src/main/resources/csharp/Configuration.mustache index 46dde35d8d3a..b5ebd08ba877 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/Configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/Configuration.mustache @@ -12,6 +12,45 @@ namespace {{packageName}}.Client /// public class Configuration { + /// + /// Initializes a new instance of the Configuration class with different settings + /// + /// Api client + /// Dictionary of default HTTP header + /// Username + /// Password + /// accessToken + /// Dictionary of API key + /// Dictionary of API key prefix + /// Temp folder path + /// DateTime format string + public Configuration(ApiClient apiClient, + Dictionary defaultHeader, + string username, + string password, + string accessToken, + Dictionary apiKey, + Dictionary apiKeyPrefix, + string tempFolderPath, + string dateTimeFormat + ) + { + if (apiClient == null) + ApiClient = ApiClient.Default; + else + ApiClient = apiClient; + + Username = username; + Password = password; + AccessToken = accessToken; + ApiKey = apiKey; + ApiKeyPrefix = apiKeyPrefix; + + TempFolderPath = tempFolderPath; + DateTimeFormat = dateTimeFormat; + + } + /// /// Initializes a new instance of the Configuration class. /// @@ -109,13 +148,13 @@ namespace {{packageName}}.Client return apiKeyValue; } - private static string _tempFolderPath = Path.GetTempPath(); + private string _tempFolderPath = Path.GetTempPath(); /// /// Gets or sets the temporary folder path to store the files downloaded from the server. /// /// Folder path. - public static String TempFolderPath + public String TempFolderPath { get { return _tempFolderPath; } @@ -138,7 +177,40 @@ namespace {{packageName}}.Client _tempFolderPath = value + Path.DirectorySeparatorChar; } } - + + private const string ISO8601_DATETIME_FORMAT = "o"; + + private string _dateTimeFormat = ISO8601_DATETIME_FORMAT; + + /// + /// Gets or sets the the date time format used when serializing in the ApiClient + /// By default, it's set to ISO 8601 - "o", for others see: + /// https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx + /// and https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx + /// No validation is done to ensure that the string you're providing is valid + /// + /// The DateTimeFormat string + public String DateTimeFormat + { + get + { + return _dateTimeFormat; + } + set + { + if (string.IsNullOrEmpty(value)) + { + // Never allow a blank or null string, go back to the default + _dateTimeFormat = ISO8601_DATETIME_FORMAT; + return; + } + + // Caution, no validation when you choose date time format other than ISO 8601 + // Take a look at the above links + _dateTimeFormat = value; + } + } + /// /// Returns a string with essential information for debugging. /// diff --git a/modules/swagger-codegen/src/main/resources/objc/ApiClient-body.mustache b/modules/swagger-codegen/src/main/resources/objc/ApiClient-body.mustache index d1908e5d2f11..25b5d9adfbff 100644 --- a/modules/swagger-codegen/src/main/resources/objc/ApiClient-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/ApiClient-body.mustache @@ -128,24 +128,25 @@ static void (^reachabilityChangeBlock)(int); /* * Detect `Accept` from accepts */ -+ (NSString *) selectHeaderAccept:(NSArray *)accepts -{ ++ (NSString *) selectHeaderAccept:(NSArray *)accepts { if (accepts == nil || [accepts count] == 0) { return @""; } NSMutableArray *lowerAccepts = [[NSMutableArray alloc] initWithCapacity:[accepts count]]; - [accepts enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { - [lowerAccepts addObject:[obj lowercaseString]]; - }]; - - - if ([lowerAccepts containsObject:@"application/json"]) { - return @"application/json"; + for (NSString *string in accepts) { + NSString * lowerAccept = [string lowercaseString]; + if ([lowerAccept containsString:@"application/json"]) { + return @"application/json"; + } + [lowerAccepts addObject:lowerAccept]; } - else { - return [lowerAccepts componentsJoinedByString:@", "]; + + if (lowerAccepts.count == 1) { + return [lowerAccepts firstObject]; } + + return [lowerAccepts componentsJoinedByString:@", "]; } /* @@ -171,7 +172,7 @@ static void (^reachabilityChangeBlock)(int); } + (NSString*)escape:(id)unescaped { - if([unescaped isKindOfClass:[NSString class]]){ + if ([unescaped isKindOfClass:[NSString class]]){ return (NSString *)CFBridgingRelease (CFURLCreateStringByAddingPercentEscapes( NULL, @@ -212,7 +213,7 @@ static void (^reachabilityChangeBlock)(int); -(Boolean) executeRequestWithId:(NSNumber*) requestId { NSSet* matchingItems = [queuedRequests objectsPassingTest:^BOOL(id obj, BOOL *stop) { - if([obj intValue] == [requestId intValue]) { + if ([obj intValue] == [requestId intValue]) { return YES; } else { @@ -220,7 +221,7 @@ static void (^reachabilityChangeBlock)(int); } }]; - if(matchingItems.count == 1) { + if (matchingItems.count == 1) { {{classPrefix}}DebugLog(@"removed request id %@", requestId); [queuedRequests removeObject:requestId]; return YES; @@ -268,7 +269,7 @@ static void (^reachabilityChangeBlock)(int); } // call the reachability block, if configured - if(reachabilityChangeBlock != nil) { + if (reachabilityChangeBlock != nil) { reachabilityChangeBlock(status); } }]; @@ -410,16 +411,16 @@ static void (^reachabilityChangeBlock)(int); completionBlock: (void (^)(id, NSError *))completionBlock { AFHTTPRequestOperation *op = [self HTTPRequestOperationWithRequest:request success:^(AFHTTPRequestOperation *operation, id response) { - if([self executeRequestWithId:requestId]) { + if ([self executeRequestWithId:requestId]) { [self logResponse:operation forRequest:request error:nil]; NSDictionary *responseHeaders = [[operation response] allHeaderFields]; self.HTTPResponseHeaders = responseHeaders; completionBlock(response, nil); } } failure:^(AFHTTPRequestOperation *operation, NSError *error) { - if([self executeRequestWithId:requestId]) { + if ([self executeRequestWithId:requestId]) { NSMutableDictionary *userInfo = [error.userInfo mutableCopy]; - if(operation.responseObject) { + if (operation.responseObject) { // Add in the (parsed) response body. userInfo[{{classPrefix}}ResponseObjectErrorKey] = operation.responseObject; } @@ -590,10 +591,10 @@ static void (^reachabilityChangeBlock)(int); // request cache BOOL hasHeaderParams = false; - if(headerParams != nil && [headerParams count] > 0) { + if (headerParams != nil && [headerParams count] > 0) { hasHeaderParams = true; } - if(offlineState) { + if (offlineState) { {{classPrefix}}DebugLog(@"%@ cache forced", resourcePath); [request setCachePolicy:NSURLRequestReturnCacheDataDontLoad]; } @@ -606,7 +607,7 @@ static void (^reachabilityChangeBlock)(int); [request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData]; } - if(hasHeaderParams){ + if (hasHeaderParams){ for(NSString * key in [headerParams keyEnumerator]){ [request setValue:[headerParams valueForKey:key] forHTTPHeaderField:key]; } @@ -639,36 +640,36 @@ static void (^reachabilityChangeBlock)(int); int counter = 0; NSMutableString * requestUrl = [NSMutableString stringWithFormat:@"%@", path]; - if(queryParams != nil){ + if (queryParams != nil){ for(NSString * key in [queryParams keyEnumerator]){ - if(counter == 0) separator = @"?"; + if (counter == 0) separator = @"?"; else separator = @"&"; id queryParam = [queryParams valueForKey:key]; - if([queryParam isKindOfClass:[NSString class]]){ + if ([queryParam isKindOfClass:[NSString class]]){ [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, [{{classPrefix}}ApiClient escape:key], [{{classPrefix}}ApiClient escape:[queryParams valueForKey:key]]]]; } - else if([queryParam isKindOfClass:[{{classPrefix}}QueryParamCollection class]]){ + else if ([queryParam isKindOfClass:[{{classPrefix}}QueryParamCollection class]]){ {{classPrefix}}QueryParamCollection * coll = ({{classPrefix}}QueryParamCollection*) queryParam; NSArray* values = [coll values]; NSString* format = [coll format]; - if([format isEqualToString:@"csv"]) { + if ([format isEqualToString:@"csv"]) { [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, [{{classPrefix}}ApiClient escape:key], [NSString stringWithFormat:@"%@", [values componentsJoinedByString:@","]]]]; } - else if([format isEqualToString:@"tsv"]) { + else if ([format isEqualToString:@"tsv"]) { [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, [{{classPrefix}}ApiClient escape:key], [NSString stringWithFormat:@"%@", [values componentsJoinedByString:@"\t"]]]]; } - else if([format isEqualToString:@"pipes"]) { + else if ([format isEqualToString:@"pipes"]) { [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, [{{classPrefix}}ApiClient escape:key], [NSString stringWithFormat:@"%@", [values componentsJoinedByString:@"|"]]]]; } - else if([format isEqualToString:@"multi"]) { + else if ([format isEqualToString:@"multi"]) { for(id obj in values) { [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, [{{classPrefix}}ApiClient escape:key], [NSString stringWithFormat:@"%@", obj]]]; diff --git a/modules/swagger-codegen/src/main/resources/objc/api-body.mustache b/modules/swagger-codegen/src/main/resources/objc/api-body.mustache index 60358e4e9da8..d84e350360f5 100644 --- a/modules/swagger-codegen/src/main/resources/objc/api-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/api-body.mustache @@ -105,7 +105,7 @@ static {{classname}}* singletonAPI = nil; {{/pathParams}} NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; - {{#queryParams}}if({{paramName}} != nil) { + {{#queryParams}}if ({{paramName}} != nil) { {{#collectionFormat}} queryParams[@"{{baseName}}"] = [[{{classPrefix}}QueryParamCollection alloc] initWithValuesAndFormat: {{baseName}} format: @"{{collectionFormat}}"]; {{/collectionFormat}} @@ -114,7 +114,7 @@ static {{classname}}* singletonAPI = nil; {{/queryParams}} NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; - {{#headerParams}}if({{paramName}} != nil) { + {{#headerParams}}if ({{paramName}} != nil) { headerParams[@"{{baseName}}"] = {{paramName}}; } {{/headerParams}} @@ -159,7 +159,7 @@ static {{classname}}* singletonAPI = nil; {{#requiredParamCount}} {{#requiredParams}} - if({{paramName}} == nil) { + if ({{paramName}} == nil) { // error } {{/requiredParams}} diff --git a/modules/swagger-codegen/src/main/resources/objc/model-body.mustache b/modules/swagger-codegen/src/main/resources/objc/model-body.mustache index 33c0f8cf42b5..3d70cebfae20 100644 --- a/modules/swagger-codegen/src/main/resources/objc/model-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/model-body.mustache @@ -4,6 +4,18 @@ @implementation {{classname}} +- (instancetype)init { + self = [super init]; + + if (self) { + // initalise property's default value, if any + {{#vars}}{{#defaultValue}}self.{{name}} = {{{defaultValue}}}; + {{/defaultValue}}{{/vars}} + } + + return self; +} + /** * Maps json key to property name. * This method is used by `JSONModel`. diff --git a/modules/swagger-codegen/src/main/resources/php/api.mustache b/modules/swagger-codegen/src/main/resources/php/api.mustache index 22ae27fc77d0..cce59f4d94b5 100644 --- a/modules/swagger-codegen/src/main/resources/php/api.mustache +++ b/modules/swagger-codegen/src/main/resources/php/api.mustache @@ -184,14 +184,14 @@ use \{{invokerPackage}}\ObjectSerializer; {{#authMethods}}{{#isApiKey}} // this endpoint requires API key authentication $apiKey = $this->apiClient->getApiKeyWithPrefix('{{keyParamName}}'); - if ($apiKey !== null) { + if (strlen($apiKey) !== 0) { {{#isKeyInHeader}}$headerParams['{{keyParamName}}'] = $apiKey;{{/isKeyInHeader}}{{#isKeyInQuery}}$queryParams['{{keyParamName}}'] = $apiKey;{{/isKeyInQuery}} }{{/isApiKey}} {{#isBasic}}// this endpoint requires HTTP basic authentication - if ($this->apiClient->getConfig()->getUsername() !== null or $this->apiClient->getConfig()->getPassword() !== null) { + if (strlen($this->apiClient->getConfig()->getUsername()) !== 0 or strlen($this->apiClient->getConfig()->getPassword()) !== 0) { $headerParams['Authorization'] = 'Basic ' . base64_encode($this->apiClient->getConfig()->getUsername() . ":" . $this->apiClient->getConfig()->getPassword()); }{{/isBasic}}{{#isOAuth}}// this endpoint requires OAuth (access token) - if ($this->apiClient->getConfig()->getAccessToken() !== null) { + if (strlen($this->apiClient->getConfig()->getAccessToken()) !== 0) { $headerParams['Authorization'] = 'Bearer ' . $this->apiClient->getConfig()->getAccessToken(); }{{/isOAuth}} {{/authMethods}} diff --git a/modules/swagger-codegen/src/main/resources/php/model.mustache b/modules/swagger-codegen/src/main/resources/php/model.mustache index 861673982f22..66cabf0122b9 100644 --- a/modules/swagger-codegen/src/main/resources/php/model.mustache +++ b/modules/swagger-codegen/src/main/resources/php/model.mustache @@ -89,7 +89,7 @@ class {{classname}} implements ArrayAccess * ${{name}} {{#description}}{{{description}}}{{/description}} * @var {{datatype}} */ - protected ${{name}}; + protected ${{name}}{{#defaultValue}} = {{{defaultValue}}}{{/defaultValue}}; {{/vars}} /** diff --git a/modules/swagger-codegen/src/main/resources/python/model.mustache b/modules/swagger-codegen/src/main/resources/python/model.mustache index 0dbe29add4fc..aae43175a2ed 100644 --- a/modules/swagger-codegen/src/main/resources/python/model.mustache +++ b/modules/swagger-codegen/src/main/resources/python/model.mustache @@ -49,7 +49,7 @@ class {{classname}}(object): } {{#vars}} - self._{{name}} = None + self._{{name}} = {{#defaultValue}}{{{defaultValue}}}{{/defaultValue}}{{^defaultValue}}None{{/defaultValue}} {{/vars}} {{#vars}} diff --git a/modules/swagger-codegen/src/main/resources/ruby/api.mustache b/modules/swagger-codegen/src/main/resources/ruby/api.mustache index 65e00081686e..d7967135336d 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/api.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/api.mustache @@ -5,8 +5,8 @@ module {{moduleName}} class {{classname}} attr_accessor :api_client - def initialize(api_client = nil) - @api_client = api_client || Configuration.api_client + def initialize(api_client = ApiClient.default) + @api_client = api_client end {{#operation}} {{newline}} @@ -28,8 +28,8 @@ module {{moduleName}} {{#allParams}}{{^required}} # @option opts [{{{dataType}}}] :{{paramName}} {{description}} {{/required}}{{/allParams}} # @return [Array<({{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}nil{{/returnType}}, Fixnum, Hash)>] {{#returnType}}{{{returnType}}} data{{/returnType}}{{^returnType}}nil{{/returnType}}, response status code and response headers def {{operationId}}_with_http_info({{#allParams}}{{#required}}{{paramName}}, {{/required}}{{/allParams}}opts = {}) - if Configuration.debugging - Configuration.logger.debug "Calling API: {{classname}}#{{operationId}} ..." + if @api_client.config.debugging + @api_client.config.logger.debug "Calling API: {{classname}}#{{operationId}} ..." end {{#allParams}}{{#required}} # verify the required parameter '{{paramName}}' is set @@ -81,8 +81,8 @@ module {{moduleName}} :body => post_body, :auth_names => auth_names{{#returnType}}, :return_type => '{{{returnType}}}'{{/returnType}}) - if Configuration.debugging - Configuration.logger.debug "API called: {{classname}}#{{operationId}}\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + if @api_client.config.debugging + @api_client.config.logger.debug "API called: {{classname}}#{{operationId}}\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" end return data, status_code, headers end diff --git a/modules/swagger-codegen/src/main/resources/ruby/api_client.mustache b/modules/swagger-codegen/src/main/resources/ruby/api_client.mustache index 3873d4765777..837b1234fd0b 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/api_client.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/api_client.mustache @@ -7,24 +7,27 @@ require 'uri' module {{moduleName}} class ApiClient - - attr_accessor :host + # The Configuration object holding settings to be used in the API client. + attr_accessor :config # Defines the headers to be used in HTTP requests of all API calls by default. # # @return [Hash] attr_accessor :default_headers - def initialize(host = nil) - @host = host || Configuration.base_url - @format = 'json' + def initialize(config = Configuration.default) + @config = config @user_agent = "ruby-swagger-#{VERSION}" @default_headers = { - 'Content-Type' => "application/#{@format.downcase}", + 'Content-Type' => "application/json", 'User-Agent' => @user_agent } end + def self.default + @@default ||= ApiClient.new + end + # Call an API with given options. # # @return [Array<(Object, Fixnum, Hash)>] an array of 3 elements: @@ -33,8 +36,8 @@ module {{moduleName}} request = build_request(http_method, path, opts) response = request.run - if Configuration.debugging - Configuration.logger.debug "HTTP response body ~BEGIN~\n#{response.body}\n~END~\n" + if @config.debugging + @config.logger.debug "HTTP response body ~BEGIN~\n#{response.body}\n~END~\n" end unless response.success? @@ -68,24 +71,33 @@ module {{moduleName}} :method => http_method, :headers => header_params, :params => query_params, - :ssl_verifypeer => Configuration.verify_ssl, - :sslcert => Configuration.cert_file, - :sslkey => Configuration.key_file, - :cainfo => Configuration.ssl_ca_cert, - :verbose => Configuration.debugging + :ssl_verifypeer => @config.verify_ssl, + :sslcert => @config.cert_file, + :sslkey => @config.key_file, + :cainfo => @config.ssl_ca_cert, + :verbose => @config.debugging } if [:post, :patch, :put, :delete].include?(http_method) req_body = build_request_body(header_params, form_params, opts[:body]) req_opts.update :body => req_body - if Configuration.debugging - Configuration.logger.debug "HTTP request body param ~BEGIN~\n#{req_body}\n~END~\n" + if @config.debugging + @config.logger.debug "HTTP request body param ~BEGIN~\n#{req_body}\n~END~\n" end end Typhoeus::Request.new(url, req_opts) end + # Check if the given MIME is a JSON MIME. + # JSON MIME examples: + # application/json + # application/json; charset=UTF8 + # APPLICATION/JSON + def json_mime?(mime) + !!(mime =~ /\Aapplication\/json(;.*)?\z/i) + end + # Deserialize the response to the given return type. # # @param [String] return_type some examples: "User", "Array[User]", "Hash[String,Integer]" @@ -99,9 +111,7 @@ module {{moduleName}} # ensuring a default content type content_type = response.headers['Content-Type'] || 'application/json' - unless content_type.start_with?('application/json') - fail "Content-Type is not supported: #{content_type}" - end + fail "Content-Type is not supported: #{content_type}" unless json_mime?(content_type) begin data = JSON.parse("[#{body}]", :symbolize_names => true)[0] @@ -161,7 +171,7 @@ module {{moduleName}} # @see Configuration#temp_folder_path # @return [File] the file downloaded def download_file(response) - tmp_file = Tempfile.new '', Configuration.temp_folder_path + tmp_file = Tempfile.new '', @config.temp_folder_path content_disposition = response.headers['Content-Disposition'] if content_disposition filename = content_disposition[/filename=['"]?([^'"\s]+)['"]?/, 1] @@ -173,15 +183,15 @@ module {{moduleName}} tmp_file.close! File.open(path, 'w') { |file| file.write(response.body) } - Configuration.logger.info "File written to #{path}. Please move the file to a proper "\ - "folder for further processing and delete the temp afterwards" + @config.logger.info "File written to #{path}. Please move the file to a proper folder "\ + "for further processing and delete the temp afterwards" File.new(path) end def build_request_url(path) # Add leading and trailing slashes to path path = "/#{path}".gsub(/\/+/, '/') - URI.encode(host + path) + URI.encode(@config.base_url + path) end def build_request_body(header_params, form_params, body) @@ -209,7 +219,7 @@ module {{moduleName}} # Update hearder and query params based on authentication settings. def update_params_for_auth!(header_params, query_params, auth_names) Array(auth_names).each do |auth_name| - auth_setting = Configuration.auth_settings[auth_name] + auth_setting = @config.auth_settings[auth_name] next unless auth_setting case auth_setting[:in] when 'header' then header_params[auth_setting[:key]] = auth_setting[:value] @@ -228,26 +238,21 @@ module {{moduleName}} # @param [Array] accepts array for Accept # @return [String] the Accept header (e.g. application/json) def select_header_accept(accepts) - if accepts.empty? - return - elsif accepts.any?{ |s| s.casecmp('application/json') == 0 } - 'application/json' # look for json data by default - else - accepts.join(',') - end + return nil if accepts.nil? || accepts.empty? + # use JSON when present, otherwise use all of the provided + json_accept = accepts.find { |s| json_mime?(s) } + return json_accept || accepts.join(',') end # Return Content-Type header based on an array of content types provided. # @param [Array] content_types array for Content-Type # @return [String] the Content-Type header (e.g. application/json) def select_header_content_type(content_types) - if content_types.empty? - 'application/json' # use application/json by default - elsif content_types.any?{ |s| s.casecmp('application/json')==0 } - 'application/json' # use application/json if it's included - else - content_types[0] # otherwise, use the first one - end + # use application/json by default + return 'application/json' if content_types.nil? || content_types.empty? + # use JSON when present, otherwise use the first one + json_content_type = content_types.find { |s| json_mime?(s) } + return json_content_type || content_types.first end # Convert object (array, hash, object, etc) to JSON string. diff --git a/modules/swagger-codegen/src/main/resources/ruby/configuration.mustache b/modules/swagger-codegen/src/main/resources/ruby/configuration.mustache index 89bf133b22c1..4c05f2560fa1 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/configuration.mustache @@ -1,14 +1,7 @@ require 'uri' -require 'singleton' module {{moduleName}} class Configuration - - include Singleton - - # Default api client - attr_accessor :api_client - # Defines url scheme attr_accessor :scheme @@ -94,17 +87,6 @@ module {{moduleName}} attr_accessor :force_ending_format - class << self - def method_missing(method_name, *args, &block) - config = Configuration.instance - if config.respond_to?(method_name) - config.send(method_name, *args, &block) - else - super - end - end - end - def initialize @scheme = '{{scheme}}' @host = '{{host}}' @@ -118,10 +100,17 @@ module {{moduleName}} @inject_format = false @force_ending_format = false @logger = defined?(Rails) ? Rails.logger : Logger.new(STDOUT) + + yield(self) if block_given? end - def api_client - @api_client ||= ApiClient.new + # The default Configuration object. + def self.default + @@default ||= Configuration.new + end + + def configure + yield(self) if block_given? end def scheme=(scheme) diff --git a/modules/swagger-codegen/src/main/resources/ruby/gem.mustache b/modules/swagger-codegen/src/main/resources/ruby/gem.mustache index eb0b8cfbf0f9..2000b2be86f1 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/gem.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/gem.mustache @@ -19,17 +19,17 @@ require '{{importPath}}' module {{moduleName}} class << self - # Configure sdk using block. - # {{moduleName}}.configure do |config| - # config.username = "xxx" - # config.password = "xxx" - # end - # If no block given, return the configuration singleton instance. + # Customize default settings for the SDK using block. + # {{moduleName}}.configure do |config| + # config.username = "xxx" + # config.password = "xxx" + # end + # If no block given, return the default Configuration object. def configure if block_given? - yield Configuration.instance + yield(Configuration.default) else - Configuration.instance + Configuration.default end end end diff --git a/modules/swagger-codegen/src/main/resources/ruby/model.mustache b/modules/swagger-codegen/src/main/resources/ruby/model.mustache index 35742384c260..f253a2c0e60f 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/model.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/model.mustache @@ -1,18 +1,20 @@ -module {{moduleName}} -{{#models}} # {{description}} -{{#model}} class {{classname}} < BaseObject - attr_accessor {{#vars}}:{{{name}}}{{#hasMore}}, {{/hasMore}}{{/vars}}{{newline}} - # attribute mapping from ruby-style variable name to JSON key +module {{moduleName}}{{#models}}{{#model}}{{#description}} + # {{{description}}}{{/description}} + class {{classname}} < BaseObject{{#vars}}{{#description}} + # {{{description}}}{{/description}} + attr_accessor :{{{name}}} +{{/vars}} + + # Attribute mapping from ruby-style variable name to JSON key. def self.attribute_map { {{#vars}} - # {{description}} :'{{{name}}}' => :'{{{baseName}}}'{{#hasMore}},{{/hasMore}} {{/vars}} } end - # attribute type + # Attribute type mapping. def self.swagger_types { {{#vars}}:'{{{name}}}' => :'{{{datatype}}}'{{#hasMore}},{{/hasMore}} @@ -21,7 +23,7 @@ module {{moduleName}} end def initialize(attributes = {}) - return if !attributes.is_a?(Hash) || attributes.empty? + return unless attributes.is_a?(Hash) # convert string to symbol for hash key attributes = attributes.inject({}){|memo,(k,v)| memo[k.to_sym] = v; memo} @@ -30,11 +32,14 @@ module {{moduleName}} if attributes[:'{{{baseName}}}'] {{#isContainer}}if (value = attributes[:'{{{baseName}}}']).is_a?(Array) self.{{{name}}} = value - end{{/isContainer}}{{^isContainer}}self.{{{name}}} = attributes[:'{{{baseName}}}']{{/isContainer}} + end{{/isContainer}}{{^isContainer}}self.{{{name}}} = attributes[:'{{{baseName}}}']{{/isContainer}}{{#defaultValue}} + else + self.{{{name}}} = {{{defaultValue}}}{{/defaultValue}} end {{/vars}} end {{#vars}}{{#isEnum}} + # Custom attribute writer method checking allowed values (enum). def {{{name}}}=({{{name}}}) allowed_values = [{{#allowableValues}}{{#values}}"{{{this}}}"{{^-last}}, {{/-last}}{{/values}}{{/allowableValues}}] if {{{name}}} && !allowed_values.include?({{{name}}}) @@ -43,16 +48,19 @@ module {{moduleName}} @{{{name}}} = {{{name}}} end {{/isEnum}}{{/vars}} + # Check equality by comparing each attribute. def ==(o) return true if self.equal?(o) self.class == o.class{{#vars}} && {{name}} == o.{{name}}{{/vars}} end + # @see the `==` method def eql?(o) self == o end + # Calculate hash code according to all attributes. def hash [{{#vars}}{{name}}{{#hasMore}}, {{/hasMore}}{{/vars}}].hash end diff --git a/modules/swagger-codegen/src/main/resources/sinatra/Swaggering.rb b/modules/swagger-codegen/src/main/resources/sinatra/Swaggering.rb index 79aca1da2c92..69cc74556ac6 100644 --- a/modules/swagger-codegen/src/main/resources/sinatra/Swaggering.rb +++ b/modules/swagger-codegen/src/main/resources/sinatra/Swaggering.rb @@ -26,14 +26,22 @@ class Swaggering < Sinatra::Base cross_origin Swaggering.to_resource_listing } + + # for swagger.yaml + get("/swagger.yaml") { + cross_origin + File.read("./swagger.yaml"); + } + @@configuration ||= Configuration.new yield(@@configuration) if block_given? end def self.add_route(method, path, swag={}, opts={}, &block) - fullPath = swag["resourcePath"].to_s + @@configuration.format_specifier + path + #fullPath = swag["resourcePath"].to_s + @@configuration.format_specifier + path + fullPath = path.gsub(/{(.*?)}/, ':\1') - accepted = case method + accepted = case method.to_s.downcase when 'get' get(fullPath, opts, &block) true @@ -47,6 +55,7 @@ class Swaggering < Sinatra::Base put(fullPath, opts, &block) true else + puts "Error adding route: #{method} #{fullPath}" false end diff --git a/modules/swagger-codegen/src/main/resources/sinatra/api.mustache b/modules/swagger-codegen/src/main/resources/sinatra/api.mustache index 7dffb94cdf0b..27830feed31e 100644 --- a/modules/swagger-codegen/src/main/resources/sinatra/api.mustache +++ b/modules/swagger-codegen/src/main/resources/sinatra/api.mustache @@ -3,7 +3,7 @@ require 'json' {{#operations}} {{#operation}} -MyApp.add_route('{{httpMethod}}', '{{path}}', { +MyApp.add_route('{{httpMethod}}', '{{basePathWithoutHost}}{{path}}', { "resourcePath" => "/{{baseName}}", "summary" => "{{{summary}}}", "nickname" => "{{nickname}}", diff --git a/modules/swagger-codegen/src/main/resources/sinatra/my_app.mustache b/modules/swagger-codegen/src/main/resources/sinatra/my_app.mustache index 8c4a16d7ff50..7d4e87adffc1 100644 --- a/modules/swagger-codegen/src/main/resources/sinatra/my_app.mustache +++ b/modules/swagger-codegen/src/main/resources/sinatra/my_app.mustache @@ -7,6 +7,7 @@ class MyApp < Swaggering end end -{{#apis}} -require './lib/{{className}}.rb' -{{/apis}} +# include the api files +Dir["./api/*.rb"].each { |file| + require file +} diff --git a/modules/swagger-codegen/src/main/resources/sinatra/swagger.mustache b/modules/swagger-codegen/src/main/resources/sinatra/swagger.mustache new file mode 100644 index 000000000000..51560926bba1 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/sinatra/swagger.mustache @@ -0,0 +1 @@ +{{{swagger-yaml}}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/swift/Cartfile.mustache b/modules/swagger-codegen/src/main/resources/swift/Cartfile.mustache index c27fd0c14d12..a0906ba59692 100644 --- a/modules/swagger-codegen/src/main/resources/swift/Cartfile.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/Cartfile.mustache @@ -1,2 +1,2 @@ -github "Alamofire/Alamofire" >= 3.0.0{{#usePromiseKit}} +github "Alamofire/Alamofire" >= 3.1.0{{#usePromiseKit}} github "mxcl/PromiseKit" >=1.5.3{{/usePromiseKit}} diff --git a/modules/swagger-codegen/src/main/resources/swift/Podspec.mustache b/modules/swagger-codegen/src/main/resources/swift/Podspec.mustache index 5cf337ad6f2a..d156ef144176 100644 --- a/modules/swagger-codegen/src/main/resources/swift/Podspec.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/Podspec.mustache @@ -16,5 +16,5 @@ Pod::Spec.new do |s| s.documentation_url = '{{podDocumentationURL}}'{{/podDocumentationURL}} s.source_files = '{{projectName}}/Classes/Swaggers/**/*.swift'{{#usePromiseKit}} s.dependency 'PromiseKit', '~> 2.1'{{/usePromiseKit}} - s.dependency 'Alamofire', '~> 3.0.0' + s.dependency 'Alamofire', '~> 3.1.0' end diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/php/PhpModelTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/php/PhpModelTest.java index 52ca64f2f596..79da2d2ccda4 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/php/PhpModelTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/php/PhpModelTest.java @@ -42,7 +42,7 @@ public class PhpModelTest { Assert.assertEquals(property1.baseName, "id"); Assert.assertEquals(property1.datatype, "int"); Assert.assertEquals(property1.name, "id"); - Assert.assertEquals(property1.defaultValue, "null"); + Assert.assertEquals(property1.defaultValue, null); Assert.assertEquals(property1.baseType, "int"); Assert.assertTrue(property1.hasMore); Assert.assertTrue(property1.required); @@ -53,7 +53,7 @@ public class PhpModelTest { Assert.assertEquals(property2.baseName, "name"); Assert.assertEquals(property2.datatype, "string"); Assert.assertEquals(property2.name, "name"); - Assert.assertEquals(property2.defaultValue, "null"); + Assert.assertEquals(property2.defaultValue, null); Assert.assertEquals(property2.baseType, "string"); Assert.assertTrue(property2.hasMore); Assert.assertTrue(property2.required); @@ -65,7 +65,7 @@ public class PhpModelTest { Assert.assertEquals(property3.complexType, "\\DateTime"); Assert.assertEquals(property3.datatype, "\\DateTime"); Assert.assertEquals(property3.name, "created_at"); - Assert.assertEquals(property3.defaultValue, "null"); + Assert.assertEquals(property3.defaultValue, null); Assert.assertEquals(property3.baseType, "\\DateTime"); Assert.assertNull(property3.hasMore); Assert.assertNull(property3.required); @@ -92,7 +92,7 @@ public class PhpModelTest { Assert.assertEquals(property1.baseName, "id"); Assert.assertEquals(property1.datatype, "int"); Assert.assertEquals(property1.name, "id"); - Assert.assertEquals(property1.defaultValue, "null"); + Assert.assertEquals(property1.defaultValue, null); Assert.assertEquals(property1.baseType, "int"); Assert.assertTrue(property1.hasMore); Assert.assertTrue(property1.required); diff --git a/pom.xml b/pom.xml index 112b277b18c0..cd1dd28b9d9b 100644 --- a/pom.xml +++ b/pom.xml @@ -377,6 +377,30 @@ samples/client/petstore/java/retrofit2 + + java-client-feign + + + env + java + + + + samples/client/petstore/java/feign + + + + javascript-client + + + env + javascript + + + + samples/client/petstore/javascript + + scala-client @@ -453,6 +477,7 @@ samples/client/petstore/java/okhttp-gson samples/client/petstore/java/retrofit samples/client/petstore/java/retrofit2 + samples/client/petstore/javascript samples/client/petstore/scala samples/server/petstore/spring-mvc diff --git a/samples/client/petstore/clojure/src/swagger_petstore/core.clj b/samples/client/petstore/clojure/src/swagger_petstore/core.clj index 4c8a84269681..665adfbc775c 100644 --- a/samples/client/petstore/clojure/src/swagger_petstore/core.clj +++ b/samples/client/petstore/clojure/src/swagger_petstore/core.clj @@ -174,7 +174,7 @@ [mime] (if mime (or (= :json mime) - (re-matches #"application/json(;.*)?" (name mime))))) + (re-matches #"(?i)application/json(;.*)?" (name mime))))) (defn json-preferred-mime "Choose a MIME from the given MIMEs with JSON preferred, diff --git a/samples/client/petstore/clojure/test/swagger_petstore/core_test.clj b/samples/client/petstore/clojure/test/swagger_petstore/core_test.clj index 27a9e1db2910..87ac0a8b73dd 100644 --- a/samples/client/petstore/clojure/test/swagger_petstore/core_test.clj +++ b/samples/client/petstore/clojure/test/swagger_petstore/core_test.clj @@ -151,10 +151,12 @@ (is (= expected (boolean (json-mime? mime)))) :json true "application/json" true + "APPLICATION/JSON" true "application/json; charset=utf8" true nil false :xml false - "application/pdf" false)) + "application/pdf" false + "application/jsonp" false)) (deftest test-json-preferred-mime (are [mimes expected] @@ -177,4 +179,4 @@ "{\"aa\": 1, \"bb\": \"2\"}" "application/json" {:aa 1 :bb "2"} "[1, \"2\"]" "application/json; charset=UTF8" [1 "2"] "{invalid json}" "application/json" "{invalid json}" - "plain text" "text/plain" "plain text")) \ No newline at end of file + "plain text" "text/plain" "plain text")) diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Client/ApiClient.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Client/ApiClient.cs index 07b31cbf8174..58ade0637180 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 @@ -19,23 +19,56 @@ namespace IO.Swagger.Client public class ApiClient { /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class + /// with default configuration and base path (http://petstore.swagger.io/v2). + /// + public ApiClient() + { + Configuration = Configuration.Default; + RestClient = new RestClient("http://petstore.swagger.io/v2"); + } + + /// + /// Initializes a new instance of the class + /// with default base path (http://petstore.swagger.io/v2). + /// + /// An instance of Configuration. + public ApiClient(Configuration config = null) + { + if (config == null) + Configuration = Configuration.Default; + else + Configuration = config; + + RestClient = new RestClient("http://petstore.swagger.io/v2"); + } + + /// + /// Initializes a new instance of the class + /// with default configuration. /// /// The base path. - public ApiClient(String basePath="http://petstore.swagger.io/v2") + public ApiClient(String basePath = "http://petstore.swagger.io/v2") { if (String.IsNullOrEmpty(basePath)) throw new ArgumentException("basePath cannot be empty"); RestClient = new RestClient(basePath); + Configuration = Configuration.Default; } /// /// Gets or sets the default API client for making HTTP calls. /// /// The default API client. - public static ApiClient Default = new ApiClient(); + public static ApiClient Default = new ApiClient(Configuration.Default); + /// + /// Gets or sets the Configuration. + /// + /// An instance of the Configuration. + public Configuration Configuration { get; set; } + /// /// Gets or sets the RestClient. /// @@ -147,7 +180,7 @@ namespace IO.Swagger.Client } /// - /// If parameter is DateTime, output in ISO8601 format. + /// If parameter is DateTime, output in a formatted string (default ISO 8601), customizable with Configuration.DateTime. /// If parameter is a list, join the list with ",". /// Otherwise just return the string. /// @@ -156,7 +189,11 @@ namespace IO.Swagger.Client public string ParameterToString(object obj) { if (obj is DateTime) - return ((DateTime)obj).ToString ("u"); + // Return a formatted date string - Can be customized with Configuration.DateTimeFormat + // Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o") + // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 + // For example: 2009-06-15T13:45:30.0000000 + return ((DateTime)obj).ToString (Configuration.DateTimeFormat); else if (obj is IList) { string flattenString = ""; 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 151e4e422488..bfbb9d7479d3 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Client/Configuration.cs +++ b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Client/Configuration.cs @@ -12,11 +12,53 @@ namespace IO.Swagger.Client /// public class Configuration { + /// + /// Initializes a new instance of the Configuration class with different settings + /// + /// Api client + /// Dictionary of default HTTP header + /// Username + /// Password + /// accessToken + /// Dictionary of API key + /// Dictionary of API key prefix + /// Temp folder path + /// DateTime format string + public Configuration(ApiClient apiClient = null, + Dictionary defaultHeader = null, + string username = null, + string password = null, + string accessToken = null, + Dictionary apiKey = null, + Dictionary apiKeyPrefix = null, + string tempFolderPath = null, + string dateTimeFormat = null + ) + { + if (apiClient == null) + ApiClient = ApiClient.Default; + else + ApiClient = apiClient; + + Username = username; + Password = password; + AccessToken = accessToken; + + if (apiKey != null) + ApiKey = apiKey; + if (apiKeyPrefix != null) + ApiKeyPrefix = apiKeyPrefix; + + TempFolderPath = tempFolderPath; + DateTimeFormat = dateTimeFormat; + + } + /// /// Initializes a new instance of the Configuration class. /// /// Api client. - public Configuration(ApiClient apiClient=null) + public Configuration(ApiClient apiClient) { if (apiClient == null) ApiClient = ApiClient.Default; @@ -109,13 +151,13 @@ namespace IO.Swagger.Client return apiKeyValue; } - private static string _tempFolderPath = Path.GetTempPath(); + private string _tempFolderPath = Path.GetTempPath(); /// /// Gets or sets the temporary folder path to store the files downloaded from the server. /// /// Folder path. - public static String TempFolderPath + public String TempFolderPath { get { return _tempFolderPath; } @@ -138,7 +180,40 @@ namespace IO.Swagger.Client _tempFolderPath = value + Path.DirectorySeparatorChar; } } - + + private const string ISO8601_DATETIME_FORMAT = "o"; + + private string _dateTimeFormat = ISO8601_DATETIME_FORMAT; + + /// + /// Gets or sets the the date time format used when serializing in the ApiClient + /// By default, it's set to ISO 8601 - "o", for others see: + /// https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx + /// and https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx + /// No validation is done to ensure that the string you're providing is valid + /// + /// The DateTimeFormat string + public String DateTimeFormat + { + get + { + return _dateTimeFormat; + } + set + { + if (string.IsNullOrEmpty(value)) + { + // Never allow a blank or null string, go back to the default + _dateTimeFormat = ISO8601_DATETIME_FORMAT; + return; + } + + // Caution, no validation when you choose date time format other than ISO 8601 + // Take a look at the above links + _dateTimeFormat = value; + } + } + /// /// Returns a string with essential information for debugging. /// diff --git a/samples/client/petstore/csharp/SwaggerClientTest/SwaggerClientTest.csproj b/samples/client/petstore/csharp/SwaggerClientTest/SwaggerClientTest.csproj index c1dc6a31e194..5556641ea1f7 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/SwaggerClientTest.csproj +++ b/samples/client/petstore/csharp/SwaggerClientTest/SwaggerClientTest.csproj @@ -1,4 +1,4 @@ - + Debug @@ -69,5 +69,9 @@ + + + + \ 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 ff81f6b7c76f..f0232c330f04 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/TestApiClient.cs +++ b/samples/client/petstore/csharp/SwaggerClientTest/TestApiClient.cs @@ -3,11 +3,18 @@ using System; using System.Collections.Generic; using IO.Swagger.Client; -namespace SwaggerClient.TestApiClient +namespace SwaggerClientTest.TestApiClient { public class TestApiClient { - [Test ()] + [TearDown()] + public void TearDown() + { + // Reset to default, just in case + Configuration.Default.DateTimeFormat = "o"; + } + + [Test ()] public void TestParameterToString () { ApiClient api = new ApiClient (); @@ -20,6 +27,54 @@ namespace SwaggerClient.TestApiClient List numList = new List(new int[] {1, 37}); Assert.AreEqual("1,37", api.ParameterToString (numList)); } - } + + [Test ()] + public void TestParameterToStringForDateTime () + { + ApiClient api = new ApiClient (); + + // test datetime + DateTime dateUtc = DateTime.Parse ("2008-04-10T13:30:00.0000000z", null, System.Globalization.DateTimeStyles.RoundtripKind); + Assert.AreEqual ("2008-04-10T13:30:00.0000000Z", api.ParameterToString (dateUtc)); + + // test datetime with no timezone + DateTime dateWithNoTz = DateTime.Parse ("2008-04-10T13:30:00.000", null, System.Globalization.DateTimeStyles.RoundtripKind); + Assert.AreEqual ("2008-04-10T13:30:00.0000000", api.ParameterToString (dateWithNoTz)); + } + + // The test below only passes when running at -04:00 timezone + [Ignore ()] + public void TestParameterToStringWithTimeZoneForDateTime () + { + ApiClient api = new ApiClient (); + // test datetime with a time zone + DateTime dateWithTz = DateTime.Parse("2008-04-10T13:30:00.0000000-04:00", null, System.Globalization.DateTimeStyles.RoundtripKind); + Assert.AreEqual("2008-04-10T13:30:00.0000000-04:00", api.ParameterToString(dateWithTz)); + } + + [Test ()] + public void TestParameterToStringForDateTimeWithUFormat () + { + // Setup the DateTimeFormat across all of the calls + Configuration.Default.DateTimeFormat = "u"; + ApiClient api = new ApiClient(); + + // test datetime + DateTime dateUtc = DateTime.Parse("2009-06-15 20:45:30Z", null, System.Globalization.DateTimeStyles.RoundtripKind); + Assert.AreEqual("2009-06-15 20:45:30Z", api.ParameterToString(dateUtc)); + } + + [Test ()] + public void TestParameterToStringForDateTimeWithCustomFormat () + { + // Setup the DateTimeFormat across all of the calls + Configuration.Default.DateTimeFormat = "dd/MM/yy HH:mm:ss"; + ApiClient api = new ApiClient(); + + // test datetime + DateTime dateUtc = DateTime.Parse("2009-06-15 20:45:30Z", null, System.Globalization.DateTimeStyles.RoundtripKind); + Assert.AreEqual("15/06/09 20:45:30", api.ParameterToString(dateUtc)); + } + } } diff --git a/samples/client/petstore/csharp/SwaggerClientTest/TestConfiguration.cs b/samples/client/petstore/csharp/SwaggerClientTest/TestConfiguration.cs index c508917e7d53..a72e1a5ed1d2 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/TestConfiguration.cs +++ b/samples/client/petstore/csharp/SwaggerClientTest/TestConfiguration.cs @@ -5,10 +5,17 @@ using IO.Swagger.Client; using IO.Swagger.Api; using IO.Swagger.Model; -namespace SwaggerClient.TestConfiguration +namespace SwaggerClientTest.TestConfiguration { public class TestConfiguration { + [TearDown ()] + public void TearDown () + { + // Reset to default, just in case + Configuration.Default.DateTimeFormat = "o"; + } + [Test ()] public void TestAuthentication () { @@ -32,7 +39,32 @@ namespace SwaggerClient.TestConfiguration Assert.AreNotSame (p.Configuration, Configuration.Default); } + [Test ()] + public void TestDateTimeFormat_Default () + { + // Should default to the Round-trip Format Specifier - "o" + // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 + Assert.AreEqual("o", Configuration.Default.DateTimeFormat); + } + + [Test ()] + public void TestDateTimeFormat_UType() + { + Configuration.Default.DateTimeFormat = "u"; + + Assert.AreEqual("u", Configuration.Default.DateTimeFormat); + } + [Test ()] + public void TestConstructor() + { + Configuration c = new Configuration (username: "test username", password: "test password"); + Assert.AreEqual (c.Username, "test username"); + Assert.AreEqual (c.Password, "test password"); + + } + + [Test ()] public void TestDefautlConfiguration () { PetApi p1 = new PetApi (); diff --git a/samples/client/petstore/csharp/SwaggerClientTest/TestPet.cs b/samples/client/petstore/csharp/SwaggerClientTest/TestPet.cs index 55d081f9bb18..7c21f8efeaf1 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/TestPet.cs +++ b/samples/client/petstore/csharp/SwaggerClientTest/TestPet.cs @@ -6,9 +6,9 @@ using System.Collections.Generic; using IO.Swagger.Api; using IO.Swagger.Model; using IO.Swagger.Client; +using System.Reflection; - -namespace SwaggerClient.TestPet +namespace SwaggerClientTest.TestPet { [TestFixture ()] public class TestPet @@ -166,15 +166,15 @@ namespace SwaggerClient.TestPet [Test ()] public void TestUploadFile () { - PetApi petApi = new PetApi (); - //NOTE: please provide a valid file (full path) - FileStream fileStream = new FileStream("/var/tmp/small.gif", FileMode.Open); + Assembly _assembly = Assembly.GetExecutingAssembly(); + Stream _imageStream = _assembly.GetManifestResourceStream("SwaggerClientTest.swagger-logo.png"); + PetApi petApi = new PetApi (); // test file upload with form parameters - petApi.UploadFile(petId, "new form name", fileStream); + petApi.UploadFile(petId, "new form name", _imageStream); // test file upload without any form parameters // using optional parameter syntax introduced at .net 4.0 - petApi.UploadFile(petId: petId, file: fileStream); + petApi.UploadFile(petId: petId, file: _imageStream); } diff --git a/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/SwaggerClientTest.dll b/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/SwaggerClientTest.dll index a438e1039547..1cc6bc94f0c9 100755 Binary files a/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/SwaggerClientTest.dll and b/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/SwaggerClientTest.dll differ diff --git a/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/SwaggerClientTest.dll.mdb b/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/SwaggerClientTest.dll.mdb index 79928c469eef..ce46e4ce0aa9 100644 Binary files a/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/SwaggerClientTest.dll.mdb and b/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/SwaggerClientTest.dll.mdb differ diff --git a/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.csproj.FilesWrittenAbsolute.txt b/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.csproj.FilesWrittenAbsolute.txt index 3e55ab909656..7d68ff048e5d 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.csproj.FilesWrittenAbsolute.txt +++ b/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.csproj.FilesWrittenAbsolute.txt @@ -1,4 +1,5 @@ /Users/williamcheng/Code/wing328/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/.NETFramework,Version=v4.5.AssemblyAttribute.cs +/Users/williamcheng/Code/wing328/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.swagger-logo.png /Users/williamcheng/Code/wing328/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/Newtonsoft.Json.dll /Users/williamcheng/Code/wing328/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/nunit.framework.dll /Users/williamcheng/Code/wing328/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/RestSharp.dll diff --git a/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.dll b/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.dll index a438e1039547..1cc6bc94f0c9 100755 Binary files a/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.dll and b/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.dll differ diff --git a/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.dll.mdb b/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.dll.mdb index 79928c469eef..ce46e4ce0aa9 100644 Binary files a/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.dll.mdb and b/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.dll.mdb differ diff --git a/samples/client/petstore/csharp/SwaggerClientTest/swagger-logo.png b/samples/client/petstore/csharp/SwaggerClientTest/swagger-logo.png new file mode 100644 index 000000000000..7671d64c7da5 Binary files /dev/null and b/samples/client/petstore/csharp/SwaggerClientTest/swagger-logo.png differ diff --git a/samples/client/petstore/java/default/pom.xml b/samples/client/petstore/java/default/pom.xml index 8a939b9dc34a..e35e30af5833 100644 --- a/samples/client/petstore/java/default/pom.xml +++ b/samples/client/petstore/java/default/pom.xml @@ -137,6 +137,11 @@ jackson-databind ${jackson-version} + + com.fasterxml.jackson.jaxrs + jackson-jaxrs-json-provider + ${jackson-version} + com.fasterxml.jackson.datatype jackson-datatype-joda diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/ApiClient.java index 1966b0a34c65..f34125eaa44a 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/ApiClient.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/ApiClient.java @@ -1,8 +1,13 @@ package io.swagger.client; +import com.fasterxml.jackson.annotation.*; +import com.fasterxml.jackson.databind.*; +import com.fasterxml.jackson.datatype.joda.*; +import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider; + import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.ClientResponse; -import com.sun.jersey.api.client.config.ClientConfig; +import com.sun.jersey.api.client.GenericType; import com.sun.jersey.api.client.config.DefaultClientConfig; import com.sun.jersey.api.client.filter.LoggingFilter; import com.sun.jersey.api.client.WebResource.Builder; @@ -25,27 +30,24 @@ import java.util.TimeZone; import java.net.URLEncoder; -import java.io.IOException; import java.io.File; import java.io.UnsupportedEncodingException; -import java.io.DataInputStream; import java.text.DateFormat; import java.text.SimpleDateFormat; -import java.text.ParseException; import io.swagger.client.auth.Authentication; import io.swagger.client.auth.HttpBasicAuth; import io.swagger.client.auth.ApiKeyAuth; import io.swagger.client.auth.OAuth; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-12-02T18:29:05.463+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-12-09T22:51:50.471-05:00") public class ApiClient { private Map hostMap = new HashMap(); private Map defaultHeaderMap = new HashMap(); private boolean debugging = false; private String basePath = "http://petstore.swagger.io/v2"; - private JSON json = new JSON(); + private ObjectMapper mapper; private Map authentications; @@ -55,6 +57,14 @@ public class ApiClient { private DateFormat dateFormat; public ApiClient() { + mapper = new ObjectMapper(); + mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); + mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING); + mapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING); + mapper.registerModule(new JodaModule()); + // Use RFC3339 format for date and datetime. // See http://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14 this.dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); @@ -62,7 +72,7 @@ public class ApiClient { // Use UTC as the default time zone. this.dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); - this.json.setDateFormat((DateFormat) dateFormat.clone()); + this.mapper.setDateFormat((DateFormat) dateFormat.clone()); // Set default User-Agent. setUserAgent("Java-Swagger"); @@ -75,13 +85,6 @@ public class ApiClient { authentications = Collections.unmodifiableMap(authentications); } - /** - * Gets the JSON instance to do JSON serialization and deserialization. - */ - public JSON getJSON() { - return json; - } - public String getBasePath() { return basePath; } @@ -236,7 +239,7 @@ public class ApiClient { public ApiClient setDateFormat(DateFormat dateFormat) { this.dateFormat = dateFormat; // also set the date format for model (de)serialization with Date properties - this.json.setDateFormat((DateFormat) dateFormat.clone()); + this.mapper.setDateFormat((DateFormat) dateFormat.clone()); return this; } @@ -268,7 +271,7 @@ public class ApiClient { return formatDate((Date) param); } else if (param instanceof Collection) { StringBuilder b = new StringBuilder(); - for(Object o : (Collection)param) { + for(Object o : (Collection)param) { if(b.length() > 0) { b.append(","); } @@ -289,9 +292,9 @@ public class ApiClient { // preconditions if (name == null || name.isEmpty() || value == null) return params; - Collection valueCollection = null; - if (value instanceof Collection) { - valueCollection = (Collection) value; + Collection valueCollection = null; + if (value instanceof Collection) { + valueCollection = (Collection) value; } else { params.add(new Pair(name, parameterToString(value))); return params; @@ -336,6 +339,17 @@ public class ApiClient { return params; } + /** + * Check if the given MIME is a JSON MIME. + * JSON MIME examples: + * application/json + * application/json; charset=UTF8 + * APPLICATION/JSON + */ + public boolean isJsonMime(String mime) { + return mime != null && mime.matches("(?i)application\\/json(;.*)?"); + } + /** * Select the Accept header's value from the given accepts array: * if JSON exists in the given array, use it; @@ -346,8 +360,14 @@ public class ApiClient { * null will be returned (not to set the Accept header explicitly). */ public String selectHeaderAccept(String[] accepts) { - if (accepts.length == 0) return null; - if (StringUtil.containsIgnoreCase(accepts, "application/json")) return "application/json"; + if (accepts.length == 0) { + return null; + } + for (String accept : accepts) { + if (isJsonMime(accept)) { + return accept; + } + } return StringUtil.join(accepts, ","); } @@ -361,8 +381,14 @@ public class ApiClient { * JSON will be used. */ public String selectHeaderContentType(String[] contentTypes) { - if (contentTypes.length == 0) return "application/json"; - if (StringUtil.containsIgnoreCase(contentTypes, "application/json")) return "application/json"; + if (contentTypes.length == 0) { + return "application/json"; + } + for (String contentType : contentTypes) { + if (isJsonMime(contentType)) { + return contentType; + } + } return contentTypes[0]; } @@ -381,49 +407,30 @@ public class ApiClient { * Serialize the given Java object into string according the given * Content-Type (only JSON is supported for now). */ - public String serialize(Object obj, String contentType) throws ApiException { - if (contentType.startsWith("application/json")) { - return json.serialize(obj); + public Object serialize(Object obj, String contentType, Map formParams) throws ApiException { + if (contentType.startsWith("multipart/form-data")) { + FormDataMultiPart mp = new FormDataMultiPart(); + for (Entry param: formParams.entrySet()) { + if (param.getValue() instanceof File) { + File file = (File) param.getValue(); + mp.bodyPart(new FileDataBodyPart(param.getKey(), file, MediaType.MULTIPART_FORM_DATA_TYPE)); + } else { + mp.field(param.getKey(), parameterToString(param.getValue()), MediaType.MULTIPART_FORM_DATA_TYPE); + } + } + return mp; + } else if (contentType.startsWith("application/x-www-form-urlencoded")) { + return this.getXWWWFormUrlencodedParams(formParams); } else { - throw new ApiException(400, "can not serialize object into Content-Type: " + contentType); + // We let Jersey attempt to serialize the body + return obj; } } - /** - * Deserialize response body to Java object according to the Content-Type. - */ - public T deserialize(ClientResponse response, TypeRef returnType) throws ApiException { - String contentType = null; - List contentTypes = response.getHeaders().get("Content-Type"); - if (contentTypes != null && !contentTypes.isEmpty()) - contentType = contentTypes.get(0); - if (contentType == null) - throw new ApiException(500, "missing Content-Type in response"); + private ClientResponse getAPIResponse(String path, String method, List queryParams, Object body, Map headerParams, Map formParams, String accept, String contentType, String[] authNames) throws ApiException { - String body; - if (response.hasEntity()) - body = (String) response.getEntity(String.class); - else - body = ""; - - if (contentType.startsWith("application/json")) { - return json.deserialize(body, returnType); - } else if (returnType.getType().equals(String.class)) { - // Expecting string, return the raw response body. - return (T) body; - } else { - throw new ApiException( - 500, - "Content type \"" + contentType + "\" is not supported for type: " - + returnType.getType() - ); - } - } - - private ClientResponse getAPIResponse(String path, String method, List queryParams, Object body, byte[] binaryBody, Map headerParams, Map formParams, String accept, String contentType, String[] authNames) throws ApiException { - - if (body != null && binaryBody != null){ - throw new ApiException(500, "either body or binaryBody must be null"); + if (body != null && !formParams.isEmpty()){ + throw new ApiException(500, "Cannot have body and form params"); } updateParamsForAuth(authNames, queryParams, headerParams); @@ -460,61 +467,16 @@ public class ApiClient { } } - String encodedFormParams = null; - if (contentType.startsWith("multipart/form-data")) { - FormDataMultiPart mp = new FormDataMultiPart(); - for (Entry param: formParams.entrySet()) { - if (param.getValue() instanceof File) { - File file = (File) param.getValue(); - mp.bodyPart(new FileDataBodyPart(param.getKey(), file, MediaType.MULTIPART_FORM_DATA_TYPE)); - } else { - mp.field(param.getKey(), parameterToString(param.getValue()), MediaType.MULTIPART_FORM_DATA_TYPE); - } - } - body = mp; - } else if (contentType.startsWith("application/x-www-form-urlencoded")) { - encodedFormParams = this.getXWWWFormUrlencodedParams(formParams); - } - ClientResponse response = null; if ("GET".equals(method)) { response = (ClientResponse) builder.get(ClientResponse.class); } else if ("POST".equals(method)) { - if (encodedFormParams != null) { - response = builder.type(contentType).post(ClientResponse.class, encodedFormParams); - } else if (body == null) { - if(binaryBody == null) - response = builder.post(ClientResponse.class, null); - else - response = builder.type(contentType).post(ClientResponse.class, binaryBody); - } else if (body instanceof FormDataMultiPart) { - response = builder.type(contentType).post(ClientResponse.class, body); - } else { - response = builder.type(contentType).post(ClientResponse.class, serialize(body, contentType)); - } + response = builder.type(contentType).post(ClientResponse.class, serialize(body, contentType, formParams)); } else if ("PUT".equals(method)) { - if (encodedFormParams != null) { - response = builder.type(contentType).put(ClientResponse.class, encodedFormParams); - } else if(body == null) { - if(binaryBody == null) - response = builder.put(ClientResponse.class, null); - else - response = builder.type(contentType).put(ClientResponse.class, binaryBody); - } else { - response = builder.type(contentType).put(ClientResponse.class, serialize(body, contentType)); - } + response = builder.type(contentType).put(ClientResponse.class, serialize(body, contentType, formParams)); } else if ("DELETE".equals(method)) { - if (encodedFormParams != null) { - response = builder.type(contentType).delete(ClientResponse.class, encodedFormParams); - } else if(body == null) { - if(binaryBody == null) - response = builder.delete(ClientResponse.class); - else - response = builder.type(contentType).delete(ClientResponse.class, binaryBody); - } else { - response = builder.type(contentType).delete(ClientResponse.class, serialize(body, contentType)); - } + response = builder.type(contentType).delete(ClientResponse.class, serialize(body, contentType, formParams)); } else { throw new ApiException(500, "unknown method type " + method); } @@ -528,7 +490,6 @@ public class ApiClient { * @param method The request method, one of "GET", "POST", "PUT", and "DELETE" * @param queryParams The query parameters * @param body The request body object - if it is not binary, otherwise null - * @param binaryBody The request body object - if it is binary, otherwise null * @param headerParams The header parameters * @param formParams The form parameters * @param accept The request's Accept header @@ -536,9 +497,9 @@ public class ApiClient { * @param authNames The authentications to apply * @return The response body in type of string */ - public T invokeAPI(String path, String method, List queryParams, Object body, byte[] binaryBody, Map headerParams, Map formParams, String accept, String contentType, String[] authNames, TypeRef returnType) throws ApiException { + public T invokeAPI(String path, String method, List queryParams, Object body, Map headerParams, Map formParams, String accept, String contentType, String[] authNames, GenericType returnType) throws ApiException { - ClientResponse response = getAPIResponse(path, method, queryParams, body, binaryBody, headerParams, formParams, accept, contentType, authNames); + ClientResponse response = getAPIResponse(path, method, queryParams, body, headerParams, formParams, accept, contentType, authNames); statusCode = response.getStatusInfo().getStatusCode(); responseHeaders = response.getHeaders(); @@ -549,13 +510,13 @@ public class ApiClient { if (returnType == null) return null; else - return deserialize(response, returnType); + return response.getEntity(returnType); } else { String message = "error"; String respBody = null; if (response.hasEntity()) { try { - respBody = String.valueOf(response.getEntity(String.class)); + respBody = response.getEntity(String.class); message = respBody; } catch (RuntimeException e) { // e.printStackTrace(); @@ -568,58 +529,6 @@ public class ApiClient { respBody); } } - /** - * Invoke API by sending HTTP request with the given options - return binary result - * - * @param path The sub-path of the HTTP URL - * @param method The request method, one of "GET", "POST", "PUT", and "DELETE" - * @param queryParams The query parameters - * @param body The request body object - if it is not binary, otherwise null - * @param binaryBody The request body object - if it is binary, otherwise null - * @param headerParams The header parameters - * @param formParams The form parameters - * @param accept The request's Accept header - * @param contentType The request's Content-Type header - * @param authNames The authentications to apply - * @return The response body in type of string - */ - public byte[] invokeBinaryAPI(String path, String method, List queryParams, Object body, byte[] binaryBody, Map headerParams, Map formParams, String accept, String contentType, String[]authNames) throws ApiException { - - ClientResponse response = getAPIResponse(path, method, queryParams, body, binaryBody, headerParams, formParams, accept, contentType, authNames); - - if(response.getStatusInfo() == ClientResponse.Status.NO_CONTENT) { - return null; - } - else if(response.getStatusInfo().getFamily() == Family.SUCCESSFUL) { - if(response.hasEntity()) { - DataInputStream stream = new DataInputStream(response.getEntityInputStream()); - byte[] data = new byte[response.getLength()]; - try { - stream.readFully(data); - } catch (IOException ex) { - throw new ApiException(500, "Error obtaining binary response data"); - } - return data; - } - else { - return new byte[0]; - } - } - else { - String message = "error"; - if(response.hasEntity()) { - try{ - message = String.valueOf(response.getEntity(String.class)); - } - catch (RuntimeException e) { - // e.printStackTrace(); - } - } - throw new ApiException( - response.getStatusInfo().getStatusCode(), - message); - } - } /** * Update query and header parameters based on authentication settings. @@ -641,7 +550,6 @@ public class ApiClient { StringBuilder formParamBuilder = new StringBuilder(); for (Entry param : formParams.entrySet()) { - String keyStr = param.getKey(); String valueStr = parameterToString(param.getValue()); try { formParamBuilder.append(URLEncoder.encode(param.getKey(), "utf8")) @@ -666,7 +574,11 @@ public class ApiClient { */ private Client getClient() { if(!hostMap.containsKey(basePath)) { - Client client = Client.create(); + // Add the JSON serialization support to Jersey + JacksonJsonProvider jsonProvider = new JacksonJsonProvider(mapper); + DefaultClientConfig conf = new DefaultClientConfig(); + conf.getSingletons().add(jsonProvider); + Client client = Client.create(conf); if (debugging) client.addFilter(new LoggingFilter()); hostMap.put(basePath, client); diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/JSON.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/JSON.java deleted file mode 100644 index e26cf13bee50..000000000000 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/JSON.java +++ /dev/null @@ -1,64 +0,0 @@ -package io.swagger.client; - -import com.fasterxml.jackson.annotation.*; -import com.fasterxml.jackson.databind.*; -import com.fasterxml.jackson.datatype.joda.*; - -import java.text.DateFormat; - -import java.io.IOException; - -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-11-29T00:18:25.953+08:00") -public class JSON { - private ObjectMapper mapper; - - public JSON() { - mapper = new ObjectMapper(); - mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); - mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING); - mapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING); - mapper.registerModule(new JodaModule()); - } - - /** - * Set the date format for JSON (de)serialization with Date properties. - */ - public void setDateFormat(DateFormat dateFormat) { - mapper.setDateFormat(dateFormat); - } - - /** - * Serialize the given Java object into JSON string. - */ - public String serialize(Object obj) throws ApiException { - try { - if (obj != null) - return mapper.writeValueAsString(obj); - else - return null; - } catch (Exception e) { - throw new ApiException(400, e.getMessage()); - } - } - - /** - * Deserialize the given JSON string to Java object. - * - * @param body The JSON string - * @param returnType The type to deserialize inot - * @return The deserialized Java object - */ - public T deserialize(String body, TypeRef returnType) throws ApiException { - JavaType javaType = mapper.constructType(returnType.getType()); - try { - return mapper.readValue(body, javaType); - } catch (IOException e) { - if (returnType.getType().equals(String.class)) - return (T) body; - else - throw new ApiException(500, e.getMessage(), null, body); - } - } -} diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/TypeRef.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/TypeRef.java deleted file mode 100644 index 41677e9d5570..000000000000 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/TypeRef.java +++ /dev/null @@ -1,26 +0,0 @@ -package io.swagger.client; - -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.Type; - -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-11-29T00:18:25.953+08:00") -public class TypeRef { - private final Type type; - - public TypeRef() { - this.type = getGenericType(getClass()); - } - - private static Type getGenericType(Class klass) { - Type superclass = klass.getGenericSuperclass(); - if (superclass instanceof Class) { - throw new RuntimeException("No type parameter provided"); - } - ParameterizedType parameterized = (ParameterizedType) superclass; - return parameterized.getActualTypeArguments()[0]; - } - - public Type getType() { - return type; - } -} diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/PetApi.java index 080d4aa1dab9..9f07449e6f89 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/PetApi.java @@ -1,17 +1,18 @@ package io.swagger.client.api; +import com.sun.jersey.api.client.GenericType; + import io.swagger.client.ApiException; import io.swagger.client.ApiClient; import io.swagger.client.Configuration; import io.swagger.client.Pair; -import io.swagger.client.TypeRef; import io.swagger.client.model.Pet; import java.io.File; import java.util.*; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-11-29T00:18:25.953+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-12-09T22:51:50.471-05:00") public class PetApi { private ApiClient apiClient; @@ -38,9 +39,8 @@ public class PetApi { * @param body Pet object that needs to be added to the store * @return void */ - public void updatePet (Pet body) throws ApiException { + public void updatePet(Pet body) throws ApiException { Object postBody = body; - byte[] postBinaryBody = null; // create path and map variables String path = "/pet".replaceAll("\\{format\\}","json"); @@ -69,14 +69,8 @@ public class PetApi { String[] authNames = new String[] { "petstore_auth" }; - + apiClient.invokeAPI(path, "PUT", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); - - apiClient.invokeAPI(path, "PUT", queryParams, postBody, postBinaryBody, headerParams, formParams, accept, contentType, authNames, null); - - - - } /** @@ -85,9 +79,8 @@ public class PetApi { * @param body Pet object that needs to be added to the store * @return void */ - public void addPet (Pet body) throws ApiException { + public void addPet(Pet body) throws ApiException { Object postBody = body; - byte[] postBinaryBody = null; // create path and map variables String path = "/pet".replaceAll("\\{format\\}","json"); @@ -116,14 +109,8 @@ public class PetApi { String[] authNames = new String[] { "petstore_auth" }; - + apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); - - apiClient.invokeAPI(path, "POST", queryParams, postBody, postBinaryBody, headerParams, formParams, accept, contentType, authNames, null); - - - - } /** @@ -132,9 +119,8 @@ public class PetApi { * @param status Status values that need to be considered for filter * @return List */ - public List findPetsByStatus (List status) throws ApiException { + public List findPetsByStatus(List status) throws ApiException { Object postBody = null; - byte[] postBinaryBody = null; // create path and map variables String path = "/pet/findByStatus".replaceAll("\\{format\\}","json"); @@ -165,15 +151,9 @@ public class PetApi { String[] authNames = new String[] { "petstore_auth" }; - + GenericType> returnType = new GenericType>() {}; + return apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); - - TypeRef returnType = new TypeRef>() {}; - return apiClient.invokeAPI(path, "GET", queryParams, postBody, postBinaryBody, headerParams, formParams, accept, contentType, authNames, returnType); - - - - } /** @@ -182,9 +162,8 @@ public class PetApi { * @param tags Tags to filter by * @return List */ - public List findPetsByTags (List tags) throws ApiException { + public List findPetsByTags(List tags) throws ApiException { Object postBody = null; - byte[] postBinaryBody = null; // create path and map variables String path = "/pet/findByTags".replaceAll("\\{format\\}","json"); @@ -215,15 +194,9 @@ public class PetApi { String[] authNames = new String[] { "petstore_auth" }; - + GenericType> returnType = new GenericType>() {}; + return apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); - - TypeRef returnType = new TypeRef>() {}; - return apiClient.invokeAPI(path, "GET", queryParams, postBody, postBinaryBody, headerParams, formParams, accept, contentType, authNames, returnType); - - - - } /** @@ -232,9 +205,8 @@ public class PetApi { * @param petId ID of pet that needs to be fetched * @return Pet */ - public Pet getPetById (Long petId) throws ApiException { + public Pet getPetById(Long petId) throws ApiException { Object postBody = null; - byte[] postBinaryBody = null; // verify the required parameter 'petId' is set if (petId == null) { @@ -269,15 +241,9 @@ public class PetApi { String[] authNames = new String[] { "api_key" }; - + GenericType returnType = new GenericType() {}; + return apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); - - TypeRef returnType = new TypeRef() {}; - return apiClient.invokeAPI(path, "GET", queryParams, postBody, postBinaryBody, headerParams, formParams, accept, contentType, authNames, returnType); - - - - } /** @@ -288,9 +254,8 @@ public class PetApi { * @param status Updated status of the pet * @return void */ - public void updatePetWithForm (String petId, String name, String status) throws ApiException { + public void updatePetWithForm(String petId, String name, String status) throws ApiException { Object postBody = null; - byte[] postBinaryBody = null; // verify the required parameter 'petId' is set if (petId == null) { @@ -329,14 +294,8 @@ public class PetApi { String[] authNames = new String[] { "petstore_auth" }; - + apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); - - apiClient.invokeAPI(path, "POST", queryParams, postBody, postBinaryBody, headerParams, formParams, accept, contentType, authNames, null); - - - - } /** @@ -346,9 +305,8 @@ public class PetApi { * @param apiKey * @return void */ - public void deletePet (Long petId, String apiKey) throws ApiException { + public void deletePet(Long petId, String apiKey) throws ApiException { Object postBody = null; - byte[] postBinaryBody = null; // verify the required parameter 'petId' is set if (petId == null) { @@ -385,14 +343,8 @@ public class PetApi { String[] authNames = new String[] { "petstore_auth" }; - + apiClient.invokeAPI(path, "DELETE", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); - - apiClient.invokeAPI(path, "DELETE", queryParams, postBody, postBinaryBody, headerParams, formParams, accept, contentType, authNames, null); - - - - } /** @@ -403,9 +355,8 @@ public class PetApi { * @param file file to upload * @return void */ - public void uploadFile (Long petId, String additionalMetadata, File file) throws ApiException { + public void uploadFile(Long petId, String additionalMetadata, File file) throws ApiException { Object postBody = null; - byte[] postBinaryBody = null; // verify the required parameter 'petId' is set if (petId == null) { @@ -444,14 +395,8 @@ public class PetApi { String[] authNames = new String[] { "petstore_auth" }; - + apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); - - apiClient.invokeAPI(path, "POST", queryParams, postBody, postBinaryBody, headerParams, formParams, accept, contentType, authNames, null); - - - - } } diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/StoreApi.java index b7ce75e5532e..f6f3b84708e7 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/StoreApi.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/StoreApi.java @@ -1,17 +1,18 @@ package io.swagger.client.api; +import com.sun.jersey.api.client.GenericType; + import io.swagger.client.ApiException; import io.swagger.client.ApiClient; import io.swagger.client.Configuration; import io.swagger.client.Pair; -import io.swagger.client.TypeRef; import java.util.Map; import io.swagger.client.model.Order; import java.util.*; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-11-29T00:18:25.953+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-12-09T22:51:50.471-05:00") public class StoreApi { private ApiClient apiClient; @@ -37,9 +38,8 @@ public class StoreApi { * Returns a map of status codes to quantities * @return Map */ - public Map getInventory () throws ApiException { + public Map getInventory() throws ApiException { Object postBody = null; - byte[] postBinaryBody = null; // create path and map variables String path = "/store/inventory".replaceAll("\\{format\\}","json"); @@ -68,15 +68,9 @@ public class StoreApi { String[] authNames = new String[] { "api_key" }; - + GenericType> returnType = new GenericType>() {}; + return apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); - - TypeRef returnType = new TypeRef>() {}; - return apiClient.invokeAPI(path, "GET", queryParams, postBody, postBinaryBody, headerParams, formParams, accept, contentType, authNames, returnType); - - - - } /** @@ -85,9 +79,8 @@ public class StoreApi { * @param body order placed for purchasing the pet * @return Order */ - public Order placeOrder (Order body) throws ApiException { + public Order placeOrder(Order body) throws ApiException { Object postBody = body; - byte[] postBinaryBody = null; // create path and map variables String path = "/store/order".replaceAll("\\{format\\}","json"); @@ -116,15 +109,9 @@ public class StoreApi { String[] authNames = new String[] { }; - + GenericType returnType = new GenericType() {}; + return apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); - - TypeRef returnType = new TypeRef() {}; - return apiClient.invokeAPI(path, "POST", queryParams, postBody, postBinaryBody, headerParams, formParams, accept, contentType, authNames, returnType); - - - - } /** @@ -133,9 +120,8 @@ public class StoreApi { * @param orderId ID of pet that needs to be fetched * @return Order */ - public Order getOrderById (String orderId) throws ApiException { + public Order getOrderById(String orderId) throws ApiException { Object postBody = null; - byte[] postBinaryBody = null; // verify the required parameter 'orderId' is set if (orderId == null) { @@ -170,15 +156,9 @@ public class StoreApi { String[] authNames = new String[] { }; - + GenericType returnType = new GenericType() {}; + return apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); - - TypeRef returnType = new TypeRef() {}; - return apiClient.invokeAPI(path, "GET", queryParams, postBody, postBinaryBody, headerParams, formParams, accept, contentType, authNames, returnType); - - - - } /** @@ -187,9 +167,8 @@ public class StoreApi { * @param orderId ID of the order that needs to be deleted * @return void */ - public void deleteOrder (String orderId) throws ApiException { + public void deleteOrder(String orderId) throws ApiException { Object postBody = null; - byte[] postBinaryBody = null; // verify the required parameter 'orderId' is set if (orderId == null) { @@ -224,14 +203,8 @@ public class StoreApi { String[] authNames = new String[] { }; - + apiClient.invokeAPI(path, "DELETE", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); - - apiClient.invokeAPI(path, "DELETE", queryParams, postBody, postBinaryBody, headerParams, formParams, accept, contentType, authNames, null); - - - - } } diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/UserApi.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/UserApi.java index 9a4f4086d34b..41b273b20b86 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/UserApi.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/UserApi.java @@ -1,17 +1,18 @@ package io.swagger.client.api; +import com.sun.jersey.api.client.GenericType; + import io.swagger.client.ApiException; import io.swagger.client.ApiClient; import io.swagger.client.Configuration; import io.swagger.client.Pair; -import io.swagger.client.TypeRef; import io.swagger.client.model.User; import java.util.*; import java.util.*; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-11-29T00:18:25.953+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-12-09T22:51:50.471-05:00") public class UserApi { private ApiClient apiClient; @@ -38,9 +39,8 @@ public class UserApi { * @param body Created user object * @return void */ - public void createUser (User body) throws ApiException { + public void createUser(User body) throws ApiException { Object postBody = body; - byte[] postBinaryBody = null; // create path and map variables String path = "/user".replaceAll("\\{format\\}","json"); @@ -69,14 +69,8 @@ public class UserApi { String[] authNames = new String[] { }; - + apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); - - apiClient.invokeAPI(path, "POST", queryParams, postBody, postBinaryBody, headerParams, formParams, accept, contentType, authNames, null); - - - - } /** @@ -85,9 +79,8 @@ public class UserApi { * @param body List of user object * @return void */ - public void createUsersWithArrayInput (List body) throws ApiException { + public void createUsersWithArrayInput(List body) throws ApiException { Object postBody = body; - byte[] postBinaryBody = null; // create path and map variables String path = "/user/createWithArray".replaceAll("\\{format\\}","json"); @@ -116,14 +109,8 @@ public class UserApi { String[] authNames = new String[] { }; - + apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); - - apiClient.invokeAPI(path, "POST", queryParams, postBody, postBinaryBody, headerParams, formParams, accept, contentType, authNames, null); - - - - } /** @@ -132,9 +119,8 @@ public class UserApi { * @param body List of user object * @return void */ - public void createUsersWithListInput (List body) throws ApiException { + public void createUsersWithListInput(List body) throws ApiException { Object postBody = body; - byte[] postBinaryBody = null; // create path and map variables String path = "/user/createWithList".replaceAll("\\{format\\}","json"); @@ -163,14 +149,8 @@ public class UserApi { String[] authNames = new String[] { }; - + apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); - - apiClient.invokeAPI(path, "POST", queryParams, postBody, postBinaryBody, headerParams, formParams, accept, contentType, authNames, null); - - - - } /** @@ -180,9 +160,8 @@ public class UserApi { * @param password The password for login in clear text * @return String */ - public String loginUser (String username, String password) throws ApiException { + public String loginUser(String username, String password) throws ApiException { Object postBody = null; - byte[] postBinaryBody = null; // create path and map variables String path = "/user/login".replaceAll("\\{format\\}","json"); @@ -215,15 +194,9 @@ public class UserApi { String[] authNames = new String[] { }; - + GenericType returnType = new GenericType() {}; + return apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); - - TypeRef returnType = new TypeRef() {}; - return apiClient.invokeAPI(path, "GET", queryParams, postBody, postBinaryBody, headerParams, formParams, accept, contentType, authNames, returnType); - - - - } /** @@ -231,9 +204,8 @@ public class UserApi { * * @return void */ - public void logoutUser () throws ApiException { + public void logoutUser() throws ApiException { Object postBody = null; - byte[] postBinaryBody = null; // create path and map variables String path = "/user/logout".replaceAll("\\{format\\}","json"); @@ -262,14 +234,8 @@ public class UserApi { String[] authNames = new String[] { }; - + apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); - - apiClient.invokeAPI(path, "GET", queryParams, postBody, postBinaryBody, headerParams, formParams, accept, contentType, authNames, null); - - - - } /** @@ -278,9 +244,8 @@ public class UserApi { * @param username The name that needs to be fetched. Use user1 for testing. * @return User */ - public User getUserByName (String username) throws ApiException { + public User getUserByName(String username) throws ApiException { Object postBody = null; - byte[] postBinaryBody = null; // verify the required parameter 'username' is set if (username == null) { @@ -315,15 +280,9 @@ public class UserApi { String[] authNames = new String[] { }; - + GenericType returnType = new GenericType() {}; + return apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); - - TypeRef returnType = new TypeRef() {}; - return apiClient.invokeAPI(path, "GET", queryParams, postBody, postBinaryBody, headerParams, formParams, accept, contentType, authNames, returnType); - - - - } /** @@ -333,9 +292,8 @@ public class UserApi { * @param body Updated user object * @return void */ - public void updateUser (String username, User body) throws ApiException { + public void updateUser(String username, User body) throws ApiException { Object postBody = body; - byte[] postBinaryBody = null; // verify the required parameter 'username' is set if (username == null) { @@ -370,14 +328,8 @@ public class UserApi { String[] authNames = new String[] { }; - + apiClient.invokeAPI(path, "PUT", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); - - apiClient.invokeAPI(path, "PUT", queryParams, postBody, postBinaryBody, headerParams, formParams, accept, contentType, authNames, null); - - - - } /** @@ -386,9 +338,8 @@ public class UserApi { * @param username The name that needs to be deleted * @return void */ - public void deleteUser (String username) throws ApiException { + public void deleteUser(String username) throws ApiException { Object postBody = null; - byte[] postBinaryBody = null; // verify the required parameter 'username' is set if (username == null) { @@ -423,14 +374,8 @@ public class UserApi { String[] authNames = new String[] { }; - + apiClient.invokeAPI(path, "DELETE", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); - - apiClient.invokeAPI(path, "DELETE", queryParams, postBody, postBinaryBody, headerParams, formParams, accept, contentType, authNames, null); - - - - } } diff --git a/samples/client/petstore/java/default/src/test/java/io/swagger/client/ApiClientTest.java b/samples/client/petstore/java/default/src/test/java/io/swagger/client/ApiClientTest.java index 3d57f3fa84cf..29eae3d017ea 100644 --- a/samples/client/petstore/java/default/src/test/java/io/swagger/client/ApiClientTest.java +++ b/samples/client/petstore/java/default/src/test/java/io/swagger/client/ApiClientTest.java @@ -38,16 +38,29 @@ public class ApiClientTest { assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T13:49:09+10:00"))); } + @Test + public void testIsJsonMime() { + assertFalse(apiClient.isJsonMime(null)); + assertFalse(apiClient.isJsonMime("")); + assertFalse(apiClient.isJsonMime("text/plain")); + assertFalse(apiClient.isJsonMime("application/xml")); + assertFalse(apiClient.isJsonMime("application/jsonp")); + + assertTrue(apiClient.isJsonMime("application/json")); + assertTrue(apiClient.isJsonMime("application/json; charset=UTF8")); + assertTrue(apiClient.isJsonMime("APPLICATION/JSON")); + } + @Test public void testSelectHeaderAccept() { - String[] accepts = {"APPLICATION/JSON", "APPLICATION/XML"}; + String[] accepts = {"application/json", "application/xml"}; assertEquals("application/json", apiClient.selectHeaderAccept(accepts)); - accepts = new String[]{"application/json", "application/xml"}; - assertEquals("application/json", apiClient.selectHeaderAccept(accepts)); + accepts = new String[]{"APPLICATION/XML", "APPLICATION/JSON"}; + assertEquals("APPLICATION/JSON", apiClient.selectHeaderAccept(accepts)); - accepts = new String[]{"application/xml", "application/json"}; - assertEquals("application/json", apiClient.selectHeaderAccept(accepts)); + accepts = new String[]{"application/xml", "application/json; charset=UTF8"}; + assertEquals("application/json; charset=UTF8", apiClient.selectHeaderAccept(accepts)); accepts = new String[]{"text/plain", "application/xml"}; assertEquals("text/plain,application/xml", apiClient.selectHeaderAccept(accepts)); @@ -58,14 +71,14 @@ public class ApiClientTest { @Test public void testSelectHeaderContentType() { - String[] contentTypes = {"APPLICATION/JSON", "APPLICATION/XML"}; + String[] contentTypes = {"application/json", "application/xml"}; assertEquals("application/json", apiClient.selectHeaderContentType(contentTypes)); - contentTypes = new String[]{"application/json", "application/xml"}; - assertEquals("application/json", apiClient.selectHeaderContentType(contentTypes)); + contentTypes = new String[]{"APPLICATION/JSON", "APPLICATION/XML"}; + assertEquals("APPLICATION/JSON", apiClient.selectHeaderContentType(contentTypes)); - contentTypes = new String[]{"application/xml", "application/json"}; - assertEquals("application/json", apiClient.selectHeaderContentType(contentTypes)); + contentTypes = new String[]{"application/xml", "application/json; charset=UTF8"}; + assertEquals("application/json; charset=UTF8", apiClient.selectHeaderContentType(contentTypes)); contentTypes = new String[]{"text/plain", "application/xml"}; assertEquals("text/plain", apiClient.selectHeaderContentType(contentTypes)); diff --git a/samples/client/petstore/java/default/src/test/java/io/swagger/client/JSONTest.java b/samples/client/petstore/java/default/src/test/java/io/swagger/client/JSONTest.java deleted file mode 100644 index 1250a135078f..000000000000 --- a/samples/client/petstore/java/default/src/test/java/io/swagger/client/JSONTest.java +++ /dev/null @@ -1,52 +0,0 @@ -package io.swagger.client; - -import io.swagger.client.model.Order; - -import java.lang.Exception; -import java.text.DateFormat; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.*; -import java.util.TimeZone; - -import org.junit.*; -import static org.junit.Assert.*; - - -public class JSONTest { - JSON json = null; - Order order = null; - - @Before - public void setup() { - json = new JSON(); - order = new Order(); - } - - @Test - public void testDefaultDate() throws Exception { - final DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); - dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); - final String dateStr = "2015-11-07T14:11:05.267Z"; - order.setShipDate(dateFormat.parse(dateStr)); - - String str = json.serialize(order); - TypeRef typeRef = new TypeRef() { }; - Order o = json.deserialize(str, typeRef); - assertEquals(dateStr, dateFormat.format(o.getShipDate())); - } - - @Test - public void testCustomDate() throws Exception { - final DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX"); - dateFormat.setTimeZone(TimeZone.getTimeZone("GMT-2")); - final String dateStr = "2015-11-07T14:11:05-02:00"; - order.setShipDate(dateFormat.parse(dateStr)); - - json.setDateFormat(dateFormat); - String str = json.serialize(order); - TypeRef typeRef = new TypeRef() { }; - Order o = json.deserialize(str, typeRef); - assertEquals(dateStr, dateFormat.format(o.getShipDate())); - } -} \ No newline at end of file diff --git a/samples/client/petstore/java/feign/README.md b/samples/client/petstore/java/feign/README.md new file mode 100644 index 000000000000..3ca7abfb5573 --- /dev/null +++ b/samples/client/petstore/java/feign/README.md @@ -0,0 +1,43 @@ +# swagger-petstore-feign + +## Requirements + +Building the API client library requires [Maven](https://maven.apache.org/) to be installed. + +## Installation & Usage + +To install the API client library to your local Maven repository, simply execute: + +```shell +mvn install +``` + +To deploy it to a remote Maven repository instead, configure the settings of the repository and execute: + +```shell +mvn deploy +``` + +Refer to the [official documentation](https://maven.apache.org/plugins/maven-deploy-plugin/usage.html) for more information. + +After the client libarary is installed/deployed, you can use it in your Maven project by adding the following to your *pom.xml*: + +```xml + + io.swagger + swagger-petstore-feign + 1.0.0 + compile + + +``` + +## Recommendation + +It's recommended to create an instance of `ApiClient` per thread in a multithreaded environment to avoid any potential issue. + +## Author + +apiteam@swagger.io + + diff --git a/samples/client/petstore/java/feign/build.gradle b/samples/client/petstore/java/feign/build.gradle new file mode 100644 index 000000000000..0bfcfbec71f2 --- /dev/null +++ b/samples/client/petstore/java/feign/build.gradle @@ -0,0 +1,113 @@ +group = 'io.swagger' +version = '1.0.0' + +buildscript { + repositories { + jcenter() + } + dependencies { + classpath 'com.android.tools.build:gradle:1.2.2' + classpath 'com.github.dcendents:android-maven-plugin:1.2' + } +} + +repositories { + jcenter() +} + + +if(hasProperty('target') && target == 'android') { + + apply plugin: 'com.android.library' + apply plugin: 'com.github.dcendents.android-maven' + + android { + compileSdkVersion 22 + buildToolsVersion '22.0.0' + defaultConfig { + minSdkVersion 14 + targetSdkVersion 22 + } + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_7 + targetCompatibility JavaVersion.VERSION_1_7 + } + + // Rename the aar correctly + libraryVariants.all { variant -> + variant.outputs.each { output -> + def outputFile = output.outputFile + if (outputFile != null && outputFile.name.endsWith('.aar')) { + def fileName = "${project.name}-${variant.baseName}-${version}.aar" + output.outputFile = new File(outputFile.parent, fileName) + } + } + } + + dependencies { + provided 'javax.annotation:jsr250-api:1.0' + } + } + + afterEvaluate { + android.libraryVariants.all { variant -> + def task = project.tasks.create "jar${variant.name.capitalize()}", Jar + task.description = "Create jar artifact for ${variant.name}" + task.dependsOn variant.javaCompile + task.from variant.javaCompile.destinationDir + task.destinationDir = project.file("${project.buildDir}/outputs/jar") + task.archiveName = "${project.name}-${variant.baseName}-${version}.jar" + artifacts.add('archives', task); + } + } + + task sourcesJar(type: Jar) { + from android.sourceSets.main.java.srcDirs + classifier = 'sources' + } + + artifacts { + archives sourcesJar + } + +} else { + + apply plugin: 'java' + apply plugin: 'maven' + + sourceCompatibility = JavaVersion.VERSION_1_7 + targetCompatibility = JavaVersion.VERSION_1_7 + + install { + repositories.mavenInstaller { + pom.artifactId = 'swagger-petstore-feign' + } + } + + task execute(type:JavaExec) { + main = System.getProperty('mainClass') + classpath = sourceSets.main.runtimeClasspath + } +} + +ext { + swagger_annotations_version = "1.5.0" + jackson_version = "2.6.3" + feign_version = "8.1.1" + jodatime_version = "2.5" + junit_version = "4.12" +} + +dependencies { + compile "io.swagger:swagger-annotations:$swagger_annotations_version" + compile "com.netflix.feign:feign-core:$feign_version" + compile "com.netflix.feign:feign-jackson:$feign_version" + compile "com.netflix.feign:feign-slf4j:$feign_version" + compile "com.fasterxml.jackson.core:jackson-core:$jackson_version" + compile "com.fasterxml.jackson.core:jackson-annotations:$jackson_version" + compile "com.fasterxml.jackson.core:jackson-databind:$jackson_version" + compile "com.fasterxml.jackson.datatype:jackson-datatype-joda:2.1.5" + compile "joda-time:joda-time:$jodatime_version" + compile "com.brsanthu:migbase64:2.2" + testCompile "junit:junit:$junit_version" +} diff --git a/samples/client/petstore/java/feign/gradle.properties b/samples/client/petstore/java/feign/gradle.properties new file mode 100644 index 000000000000..05644f0754af --- /dev/null +++ b/samples/client/petstore/java/feign/gradle.properties @@ -0,0 +1,2 @@ +# Uncomment to build for Android +#target = android \ No newline at end of file diff --git a/samples/client/petstore/java/feign/pom.xml b/samples/client/petstore/java/feign/pom.xml new file mode 100644 index 000000000000..5f7e95518625 --- /dev/null +++ b/samples/client/petstore/java/feign/pom.xml @@ -0,0 +1,183 @@ + + 4.0.0 + io.swagger + swagger-petstore-feign + jar + swagger-petstore-feign + 1.0.0 + + scm:git:git@github.com:swagger-api/swagger-mustache.git + scm:git:git@github.com:swagger-api/swagger-codegen.git + https://github.com/swagger-api/swagger-codegen + + + 2.2.0 + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.12 + + + + loggerPath + conf/log4j.properties + + + -Xms512m -Xmx1500m + methods + pertest + + + + maven-dependency-plugin + + + package + + copy-dependencies + + + ${project.build.directory}/lib + + + + + + + + org.apache.maven.plugins + maven-jar-plugin + 2.2 + + + + jar + test-jar + + + + + + + + + org.codehaus.mojo + build-helper-maven-plugin + + + add_sources + generate-sources + + add-source + + + + src/main/java + + + + + add_test_sources + generate-test-sources + + add-test-source + + + + src/test/java + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 2.3.2 + + 1.6 + 1.6 + + + + + + + io.swagger + swagger-annotations + ${swagger-annotations-version} + + + + + com.netflix.feign + feign-core + ${feign-version} + + + com.netflix.feign + feign-jackson + ${feign-version} + + + com.netflix.feign + feign-slf4j + ${feign-version} + + + + + com.fasterxml.jackson.core + jackson-core + ${jackson-version} + + + com.fasterxml.jackson.core + jackson-annotations + ${jackson-version} + + + com.fasterxml.jackson.core + jackson-databind + ${jackson-version} + + + com.fasterxml.jackson.datatype + jackson-datatype-joda + 2.1.5 + + + joda-time + joda-time + ${jodatime-version} + + + + + com.brsanthu + migbase64 + 2.2 + + + + + junit + junit + ${junit-version} + test + + + + 1.5.0 + 8.1.1 + 2.6.3 + 2.5 + 4.12 + 1.0.0 + + diff --git a/samples/client/petstore/java/feign/settings.gradle b/samples/client/petstore/java/feign/settings.gradle new file mode 100644 index 000000000000..a25109c126eb --- /dev/null +++ b/samples/client/petstore/java/feign/settings.gradle @@ -0,0 +1 @@ +rootProject.name = "swagger-petstore-feign" \ No newline at end of file diff --git a/samples/client/petstore/java/feign/src/main/AndroidManifest.xml b/samples/client/petstore/java/feign/src/main/AndroidManifest.xml new file mode 100644 index 000000000000..465dcb520c40 --- /dev/null +++ b/samples/client/petstore/java/feign/src/main/AndroidManifest.xml @@ -0,0 +1,3 @@ + + + diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/ApiClient.java new file mode 100644 index 000000000000..fae831971e9f --- /dev/null +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/ApiClient.java @@ -0,0 +1,86 @@ +package io.swagger.client; + +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; +import feign.Feign; +import feign.jackson.JacksonDecoder; +import feign.jackson.JacksonEncoder; +import feign.slf4j.Slf4jLogger; + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-12-10T16:26:30.730+08:00") +public class ApiClient { + public interface Api {} + + private ObjectMapper objectMapper; + private String basePath = "http://petstore.swagger.io/v2"; + + public ApiClient() { + objectMapper = createObjectMapper(); + } + + public String getBasePath() { + return basePath; + } + + public ApiClient setBasePath(String basePath) { + this.basePath = basePath; + return this; + } + + private ObjectMapper createObjectMapper() { + ObjectMapper objectMapper = new ObjectMapper(); + objectMapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING); + objectMapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING); + return objectMapper; + } + + /** + * Creates a feign client for given API interface. + * + * Usage: + * ApiClient apiClient = new ApiClient(); + * apiClient.setBasePath("http://localhost:8080"); + * XYZApi api = apiClient.buildClient(XYZApi.class); + * XYZResponse response = api.someMethod(...); + */ + public T buildClient(Class clientClass) { + return Feign.builder() + .encoder(new FormAwareEncoder(new JacksonEncoder(objectMapper))) + .decoder(new JacksonDecoder(objectMapper)) +// enable for basic auth: +// .requestInterceptor(new feign.auth.BasicAuthRequestInterceptor(username, password)) + .logger(new Slf4jLogger()) + .target(clientClass, basePath); + } + + /** + * Select the Accept header's value from the given accepts array: + * if JSON exists in the given array, use it; + * otherwise use all of them (joining into a string) + * + * @param accepts The accepts array to select from + * @return The Accept header to use. If the given array is empty, + * null will be returned (not to set the Accept header explicitly). + */ + public String selectHeaderAccept(String[] accepts) { + if (accepts.length == 0) return null; + if (StringUtil.containsIgnoreCase(accepts, "application/json")) return "application/json"; + return StringUtil.join(accepts, ","); + } + + /** + * Select the Content-Type header's value from the given array: + * if JSON exists in the given array, use it; + * otherwise use the first one of the array. + * + * @param contentTypes The Content-Type array to select from + * @return The Content-Type header to use. If the given array is empty, + * JSON will be used. + */ + public String selectHeaderContentType(String[] contentTypes) { + if (contentTypes.length == 0) return "application/json"; + if (StringUtil.containsIgnoreCase(contentTypes, "application/json")) return "application/json"; + return contentTypes[0]; + } +} diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/FormAwareEncoder.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/FormAwareEncoder.java new file mode 100644 index 000000000000..e9ee05b16a4b --- /dev/null +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/FormAwareEncoder.java @@ -0,0 +1,197 @@ +package io.swagger.client; + +import java.io.*; +import java.lang.reflect.Type; +import java.net.URLEncoder; +import java.net.URLConnection; +import java.nio.charset.Charset; +import java.util.*; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; + +import feign.codec.EncodeException; +import feign.codec.Encoder; +import feign.RequestTemplate; + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-12-10T16:26:30.730+08:00") +public class FormAwareEncoder implements Encoder { + public static final String UTF_8 = "utf-8"; + private static final String LINE_FEED = "\r\n"; + private static final String TWO_DASH = "--"; + private static final String BOUNDARY = "----------------314159265358979323846"; + + private byte[] lineFeedBytes; + private byte[] boundaryBytes; + private byte[] twoDashBytes; + private byte[] atBytes; + private byte[] eqBytes; + + private final Encoder delegate; + private final DateFormat dateFormat; + + public FormAwareEncoder(Encoder delegate) { + this.delegate = delegate; + // Use RFC3339 format for date and datetime. + // See http://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14 + this.dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); + + // Use UTC as the default time zone. + this.dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); + try { + this.lineFeedBytes = LINE_FEED.getBytes(UTF_8); + this.boundaryBytes = BOUNDARY.getBytes(UTF_8); + this.twoDashBytes = TWO_DASH.getBytes(UTF_8); + this.atBytes = "&".getBytes(UTF_8); + this.eqBytes = "=".getBytes(UTF_8); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + } + } + + public void encode(Object object, Type bodyType, RequestTemplate template) throws EncodeException { + if (object instanceof Map) { + try { + encodeFormParams(template, (Map) object); + } catch (IOException e) { + throw new EncodeException("Failed to create request", e); + } + } else { + delegate.encode(object, bodyType, template); + } + } + + private void encodeFormParams(RequestTemplate template, Map formParams) throws IOException { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + + boolean isMultiPart = isMultiPart(formParams); + boolean isFirstField = true; + for (Map.Entry param : formParams.entrySet()) { + String keyStr = param.getKey(); + if (param.getValue() instanceof File) { + addFilePart(baos, keyStr, (File) param.getValue()); + } else { + String valueStr = parameterToString(param.getValue()); + if (isMultiPart) { + addMultiPartFormField(baos, keyStr, valueStr); + } else { + addEncodedFormField(baos, keyStr, valueStr, isFirstField); + isFirstField = false; + } + } + } + + if (isMultiPart) { + baos.write(lineFeedBytes); + baos.write(twoDashBytes); + baos.write(boundaryBytes); + baos.write(twoDashBytes); + baos.write(lineFeedBytes); + } + + String contentType = isMultiPart ? "multipart/form-data; boundary=" + BOUNDARY : "application/x-www-form-urlencoded"; + template.header("Content-type"); + template.header("Content-type", contentType); + template.header("MIME-Version", "1.0"); + template.body(baos.toByteArray(), Charset.forName(UTF_8)); + } + + /* + * Currently only supports text files + */ + private void addFilePart(ByteArrayOutputStream baos, String fieldName, File uploadFile) throws IOException { + String fileName = uploadFile.getName(); + baos.write(twoDashBytes); + baos.write(boundaryBytes); + baos.write(lineFeedBytes); + + String contentDisposition = "Content-Disposition: form-data; name=\"" + fieldName + + "\"; filename=\"" + fileName + "\""; + baos.write(contentDisposition.getBytes(UTF_8)); + baos.write(lineFeedBytes); + String contentType = "Content-Type: " + URLConnection.guessContentTypeFromName(fileName); + baos.write(contentType.getBytes(UTF_8)); + baos.write(lineFeedBytes); + baos.write(lineFeedBytes); + + BufferedReader reader = new BufferedReader(new FileReader(uploadFile)); + InputStream input = new FileInputStream(uploadFile); + byte[] bytes = new byte[4096]; + int len = bytes.length; + while ((len = input.read(bytes)) != -1) { + baos.write(bytes, 0, len); + baos.write(lineFeedBytes); + } + + baos.write(lineFeedBytes); + } + + private void addEncodedFormField(ByteArrayOutputStream baos, String name, String value, boolean isFirstField) throws IOException { + if (!isFirstField) { + baos.write(atBytes); + } + + String encodedName = URLEncoder.encode(name, UTF_8); + String encodedValue = URLEncoder.encode(value, UTF_8); + baos.write(encodedName.getBytes(UTF_8)); + baos.write("=".getBytes(UTF_8)); + baos.write(encodedValue.getBytes(UTF_8)); + } + + private void addMultiPartFormField(ByteArrayOutputStream baos, String name, String value) throws IOException { + baos.write(twoDashBytes); + baos.write(boundaryBytes); + baos.write(lineFeedBytes); + + String contentDisposition = "Content-Disposition: form-data; name=\"" + name + "\""; + String contentType = "Content-Type: text/plain; charset=utf-8"; + + baos.write(contentDisposition.getBytes(UTF_8)); + baos.write(lineFeedBytes); + baos.write(contentType.getBytes(UTF_8)); + baos.write(lineFeedBytes); + baos.write(lineFeedBytes); + baos.write(value.getBytes(UTF_8)); + baos.write(lineFeedBytes); + } + + private boolean isMultiPart(Map formParams) { + boolean isMultiPart = false; + for (Map.Entry entry : formParams.entrySet()) { + if (entry.getValue() instanceof File) { + isMultiPart = true; + break; + } + } + return isMultiPart; + } + + /** + * Format the given parameter object into string. + */ + public String parameterToString(Object param) { + if (param == null) { + return ""; + } else if (param instanceof Date) { + return formatDate((Date) param); + } else if (param instanceof Collection) { + StringBuilder b = new StringBuilder(); + for(Object o : (Collection)param) { + if(b.length() > 0) { + b.append(","); + } + b.append(String.valueOf(o)); + } + return b.toString(); + } else { + return String.valueOf(param); + } + } + + /** + * Format the given Date object into string. + */ + public String formatDate(Date date) { + return dateFormat.format(date); + } +} diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/StringUtil.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/StringUtil.java new file mode 100644 index 000000000000..c843634389db --- /dev/null +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/StringUtil.java @@ -0,0 +1,51 @@ +package io.swagger.client; + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-12-10T16:26:30.730+08:00") +public class StringUtil { + /** + * Check if the given array contains the given value (with case-insensitive comparison). + * + * @param array The array + * @param value The value to search + * @return true if the array contains the value + */ + public static boolean containsIgnoreCase(String[] array, String value) { + for (String str : array) { + if (value == null && str == null) return true; + if (value != null && value.equalsIgnoreCase(str)) return true; + } + return false; + } + + /** + * Join an array of strings with the given separator. + *

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

+ * + * @param array The array of strings + * @param separator The separator + * @return the resulting string + */ + public static String join(String[] array, String separator) { + int len = array.length; + if (len == 0) return ""; + + StringBuilder out = new StringBuilder(); + out.append(array[0]); + for (int i = 1; i < len; i++) { + out.append(separator).append(array[i]); + } + return out.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + public static String toIndentedString(Object o) { + if (o == null) return "null"; + return o.toString().replace("\n", "\n "); + } +} diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/PetApi.java new file mode 100644 index 000000000000..cdf1c4d75d36 --- /dev/null +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/PetApi.java @@ -0,0 +1,125 @@ +package io.swagger.client.api; + +import io.swagger.client.ApiClient; + +import io.swagger.client.model.Pet; +import java.io.File; + +import java.util.*; +import feign.*; + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-12-10T16:26:30.730+08:00") +public interface PetApi extends ApiClient.Api { + + + /** + * Update an existing pet + * + * @param body Pet object that needs to be added to the store + * @return void + */ + @RequestLine("PUT /pet") + @Headers({ + "Content-type: application/json", + "Accepts: application/json", + }) + void updatePet(Pet body); + + /** + * Add a new pet to the store + * + * @param body Pet object that needs to be added to the store + * @return void + */ + @RequestLine("POST /pet") + @Headers({ + "Content-type: application/json", + "Accepts: application/json", + }) + void addPet(Pet body); + + /** + * Finds Pets by status + * Multiple status values can be provided with comma seperated strings + * @param status Status values that need to be considered for filter + * @return List + */ + @RequestLine("GET /pet/findByStatus?status={status}") + @Headers({ + "Content-type: application/json", + "Accepts: application/json", + }) + List findPetsByStatus(@Param("status") List status); + + /** + * Finds Pets by tags + * Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + * @param tags Tags to filter by + * @return List + */ + @RequestLine("GET /pet/findByTags?tags={tags}") + @Headers({ + "Content-type: application/json", + "Accepts: application/json", + }) + List findPetsByTags(@Param("tags") List tags); + + /** + * Find pet by ID + * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + * @param petId ID of pet that needs to be fetched + * @return Pet + */ + @RequestLine("GET /pet/{petId}") + @Headers({ + "Content-type: application/json", + "Accepts: application/json", + }) + Pet getPetById(@Param("petId") Long petId); + + /** + * Updates a pet in the store with form data + * + * @param petId ID of pet that needs to be updated + * @param name Updated name of the pet + * @param status Updated status of the pet + * @return void + */ + @RequestLine("POST /pet/{petId}") + @Headers({ + "Content-type: application/x-www-form-urlencoded", + "Accepts: application/json", + }) + void updatePetWithForm(@Param("petId") String petId, @Param("name") String name, @Param("status") String status); + + /** + * Deletes a pet + * + * @param petId Pet id to delete + * @param apiKey + * @return void + */ + @RequestLine("DELETE /pet/{petId}") + @Headers({ + "Content-type: application/json", + "Accepts: application/json", + "apiKey: {apiKey}" + }) + void deletePet(@Param("petId") Long petId, @Param("apiKey") String apiKey); + + /** + * uploads an image + * + * @param petId ID of pet to update + * @param additionalMetadata Additional data to pass to server + * @param file file to upload + * @return void + */ + @RequestLine("POST /pet/{petId}/uploadImage") + @Headers({ + "Content-type: multipart/form-data", + "Accepts: application/json", + }) + void uploadFile(@Param("petId") Long petId, @Param("additionalMetadata") String additionalMetadata, @Param("file") File file); + +} diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/StoreApi.java new file mode 100644 index 000000000000..3983ee7d0461 --- /dev/null +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/StoreApi.java @@ -0,0 +1,66 @@ +package io.swagger.client.api; + +import io.swagger.client.ApiClient; + +import java.util.Map; +import io.swagger.client.model.Order; + +import java.util.*; +import feign.*; + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-12-10T16:26:30.730+08:00") +public interface StoreApi extends ApiClient.Api { + + + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + * @return Map + */ + @RequestLine("GET /store/inventory") + @Headers({ + "Content-type: application/json", + "Accepts: application/json", + }) + Map getInventory(); + + /** + * Place an order for a pet + * + * @param body order placed for purchasing the pet + * @return Order + */ + @RequestLine("POST /store/order") + @Headers({ + "Content-type: application/json", + "Accepts: application/json", + }) + Order placeOrder(Order body); + + /** + * Find purchase order by ID + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * @param orderId ID of pet that needs to be fetched + * @return Order + */ + @RequestLine("GET /store/order/{orderId}") + @Headers({ + "Content-type: application/json", + "Accepts: application/json", + }) + Order getOrderById(@Param("orderId") String orderId); + + /** + * Delete purchase order by ID + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * @param orderId ID of the order that needs to be deleted + * @return void + */ + @RequestLine("DELETE /store/order/{orderId}") + @Headers({ + "Content-type: application/json", + "Accepts: application/json", + }) + void deleteOrder(@Param("orderId") String orderId); + +} diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/UserApi.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/UserApi.java new file mode 100644 index 000000000000..95d4ade78d6c --- /dev/null +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/UserApi.java @@ -0,0 +1,120 @@ +package io.swagger.client.api; + +import io.swagger.client.ApiClient; + +import io.swagger.client.model.User; +import java.util.*; + +import java.util.*; +import feign.*; + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-12-10T16:26:30.730+08:00") +public interface UserApi extends ApiClient.Api { + + + /** + * Create user + * This can only be done by the logged in user. + * @param body Created user object + * @return void + */ + @RequestLine("POST /user") + @Headers({ + "Content-type: application/json", + "Accepts: application/json", + }) + void createUser(User body); + + /** + * Creates list of users with given input array + * + * @param body List of user object + * @return void + */ + @RequestLine("POST /user/createWithArray") + @Headers({ + "Content-type: application/json", + "Accepts: application/json", + }) + void createUsersWithArrayInput(List body); + + /** + * Creates list of users with given input array + * + * @param body List of user object + * @return void + */ + @RequestLine("POST /user/createWithList") + @Headers({ + "Content-type: application/json", + "Accepts: application/json", + }) + void createUsersWithListInput(List body); + + /** + * Logs user into the system + * + * @param username The user name for login + * @param password The password for login in clear text + * @return String + */ + @RequestLine("GET /user/login?username={username}&password={password}") + @Headers({ + "Content-type: application/json", + "Accepts: application/json", + }) + String loginUser(@Param("username") String username, @Param("password") String password); + + /** + * Logs out current logged in user session + * + * @return void + */ + @RequestLine("GET /user/logout") + @Headers({ + "Content-type: application/json", + "Accepts: application/json", + }) + void logoutUser(); + + /** + * Get user by user name + * + * @param username The name that needs to be fetched. Use user1 for testing. + * @return User + */ + @RequestLine("GET /user/{username}") + @Headers({ + "Content-type: application/json", + "Accepts: application/json", + }) + User getUserByName(@Param("username") String username); + + /** + * Updated user + * This can only be done by the logged in user. + * @param username name that need to be deleted + * @param body Updated user object + * @return void + */ + @RequestLine("PUT /user/{username}") + @Headers({ + "Content-type: application/json", + "Accepts: application/json", + }) + void updateUser(@Param("username") String username, User body); + + /** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted + * @return void + */ + @RequestLine("DELETE /user/{username}") + @Headers({ + "Content-type: application/json", + "Accepts: application/json", + }) + void deleteUser(@Param("username") String username); + +} diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ApiResponse.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ApiResponse.java new file mode 100644 index 000000000000..ab98bf61e891 --- /dev/null +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ApiResponse.java @@ -0,0 +1,92 @@ +package io.swagger.client.model; + +import io.swagger.client.StringUtil; + + + +import java.util.Objects; + +import io.swagger.annotations.*; +import com.fasterxml.jackson.annotation.JsonProperty; + + + +@ApiModel(description = "") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-12-09T22:59:22.180-05:00") +public class ApiResponse { + + private Integer code = null; + private String type = null; + private String message = null; + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("code") + public Integer getCode() { + return code; + } + public void setCode(Integer code) { + this.code = code; + } + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("type") + public String getType() { + return type; + } + public void setType(String type) { + this.type = type; + } + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("message") + public String getMessage() { + return message; + } + public void setMessage(String message) { + this.message = message; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ApiResponse apiResponse = (ApiResponse) o; + return Objects.equals(code, apiResponse.code) && + Objects.equals(type, apiResponse.type) && + Objects.equals(message, apiResponse.message); + } + + @Override + public int hashCode() { + return Objects.hash(code, type, message); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ApiResponse {\n"); + + sb.append(" code: ").append(StringUtil.toIndentedString(code)).append("\n"); + sb.append(" type: ").append(StringUtil.toIndentedString(type)).append("\n"); + sb.append(" message: ").append(StringUtil.toIndentedString(message)).append("\n"); + sb.append("}"); + return sb.toString(); + } +} + + diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Category.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Category.java new file mode 100644 index 000000000000..463da28c6384 --- /dev/null +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Category.java @@ -0,0 +1,73 @@ +package io.swagger.client.model; + +import io.swagger.client.StringUtil; + + +import java.util.Objects; + +import io.swagger.annotations.*; +import com.fasterxml.jackson.annotation.*; + + +@ApiModel(description = "") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-12-10T16:26:30.730+08:00") +public class Category { + + private Long id = null; + private String name = null; + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("id") + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("name") + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Category category = (Category) o; + return Objects.equals(id, category.id) && + Objects.equals(name, category.name); + } + + @Override + public int hashCode() { + return Objects.hash(id, name); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Category {\n"); + + sb.append(" id: ").append(StringUtil.toIndentedString(id)).append("\n"); + sb.append(" name: ").append(StringUtil.toIndentedString(name)).append("\n"); + sb.append("}"); + return sb.toString(); + } +} diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Order.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Order.java new file mode 100644 index 000000000000..9b4907677594 --- /dev/null +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Order.java @@ -0,0 +1,155 @@ +package io.swagger.client.model; + +import io.swagger.client.StringUtil; +import java.util.Date; + + +import java.util.Objects; + +import io.swagger.annotations.*; +import com.fasterxml.jackson.annotation.*; + + +@ApiModel(description = "") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-12-10T16:26:30.730+08:00") +public class Order { + + private Long id = null; + private Long petId = null; + private Integer quantity = null; + private Date shipDate = null; + + +public enum StatusEnum { + PLACED("placed"), + APPROVED("approved"), + DELIVERED("delivered"); + + private String value; + + StatusEnum(String value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return value; + } +} + + private StatusEnum status = null; + private Boolean complete = null; + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("id") + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("petId") + public Long getPetId() { + return petId; + } + public void setPetId(Long petId) { + this.petId = petId; + } + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("quantity") + public Integer getQuantity() { + return quantity; + } + public void setQuantity(Integer quantity) { + this.quantity = quantity; + } + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("shipDate") + public Date getShipDate() { + return shipDate; + } + public void setShipDate(Date shipDate) { + this.shipDate = shipDate; + } + + + /** + * Order Status + **/ + @ApiModelProperty(value = "Order Status") + @JsonProperty("status") + public StatusEnum getStatus() { + return status; + } + public void setStatus(StatusEnum status) { + this.status = status; + } + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("complete") + public Boolean getComplete() { + return complete; + } + public void setComplete(Boolean complete) { + this.complete = complete; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Order order = (Order) o; + return Objects.equals(id, order.id) && + Objects.equals(petId, order.petId) && + Objects.equals(quantity, order.quantity) && + Objects.equals(shipDate, order.shipDate) && + Objects.equals(status, order.status) && + Objects.equals(complete, order.complete); + } + + @Override + public int hashCode() { + return Objects.hash(id, petId, quantity, shipDate, status, complete); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Order {\n"); + + sb.append(" id: ").append(StringUtil.toIndentedString(id)).append("\n"); + sb.append(" petId: ").append(StringUtil.toIndentedString(petId)).append("\n"); + sb.append(" quantity: ").append(StringUtil.toIndentedString(quantity)).append("\n"); + sb.append(" shipDate: ").append(StringUtil.toIndentedString(shipDate)).append("\n"); + sb.append(" status: ").append(StringUtil.toIndentedString(status)).append("\n"); + sb.append(" complete: ").append(StringUtil.toIndentedString(complete)).append("\n"); + sb.append("}"); + return sb.toString(); + } +} diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Pet.java new file mode 100644 index 000000000000..471bbe34b006 --- /dev/null +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Pet.java @@ -0,0 +1,157 @@ +package io.swagger.client.model; + +import io.swagger.client.StringUtil; +import io.swagger.client.model.Category; +import io.swagger.client.model.Tag; +import java.util.*; + + +import java.util.Objects; + +import io.swagger.annotations.*; +import com.fasterxml.jackson.annotation.*; + + +@ApiModel(description = "") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-12-10T16:26:30.730+08:00") +public class Pet { + + private Long id = null; + private Category category = null; + private String name = null; + private List photoUrls = new ArrayList(); + private List tags = new ArrayList(); + + +public enum StatusEnum { + AVAILABLE("available"), + PENDING("pending"), + SOLD("sold"); + + private String value; + + StatusEnum(String value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return value; + } +} + + private StatusEnum status = null; + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("id") + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("category") + public Category getCategory() { + return category; + } + public void setCategory(Category category) { + this.category = category; + } + + + /** + **/ + @ApiModelProperty(required = true, value = "") + @JsonProperty("name") + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + + + /** + **/ + @ApiModelProperty(required = true, value = "") + @JsonProperty("photoUrls") + public List getPhotoUrls() { + return photoUrls; + } + public void setPhotoUrls(List photoUrls) { + this.photoUrls = photoUrls; + } + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("tags") + public List getTags() { + return tags; + } + public void setTags(List tags) { + this.tags = tags; + } + + + /** + * pet status in the store + **/ + @ApiModelProperty(value = "pet status in the store") + @JsonProperty("status") + public StatusEnum getStatus() { + return status; + } + public void setStatus(StatusEnum status) { + this.status = status; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Pet pet = (Pet) o; + return Objects.equals(id, pet.id) && + Objects.equals(category, pet.category) && + Objects.equals(name, pet.name) && + Objects.equals(photoUrls, pet.photoUrls) && + Objects.equals(tags, pet.tags) && + Objects.equals(status, pet.status); + } + + @Override + public int hashCode() { + return Objects.hash(id, category, name, photoUrls, tags, status); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Pet {\n"); + + sb.append(" id: ").append(StringUtil.toIndentedString(id)).append("\n"); + sb.append(" category: ").append(StringUtil.toIndentedString(category)).append("\n"); + sb.append(" name: ").append(StringUtil.toIndentedString(name)).append("\n"); + sb.append(" photoUrls: ").append(StringUtil.toIndentedString(photoUrls)).append("\n"); + sb.append(" tags: ").append(StringUtil.toIndentedString(tags)).append("\n"); + sb.append(" status: ").append(StringUtil.toIndentedString(status)).append("\n"); + sb.append("}"); + return sb.toString(); + } +} diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Tag.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Tag.java new file mode 100644 index 000000000000..02b5b85be403 --- /dev/null +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Tag.java @@ -0,0 +1,73 @@ +package io.swagger.client.model; + +import io.swagger.client.StringUtil; + + +import java.util.Objects; + +import io.swagger.annotations.*; +import com.fasterxml.jackson.annotation.*; + + +@ApiModel(description = "") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-12-10T16:26:30.730+08:00") +public class Tag { + + private Long id = null; + private String name = null; + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("id") + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("name") + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Tag tag = (Tag) o; + return Objects.equals(id, tag.id) && + Objects.equals(name, tag.name); + } + + @Override + public int hashCode() { + return Objects.hash(id, name); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Tag {\n"); + + sb.append(" id: ").append(StringUtil.toIndentedString(id)).append("\n"); + sb.append(" name: ").append(StringUtil.toIndentedString(name)).append("\n"); + sb.append("}"); + return sb.toString(); + } +} diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/User.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/User.java new file mode 100644 index 000000000000..4d072f67d477 --- /dev/null +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/User.java @@ -0,0 +1,164 @@ +package io.swagger.client.model; + +import io.swagger.client.StringUtil; + + +import java.util.Objects; + +import io.swagger.annotations.*; +import com.fasterxml.jackson.annotation.*; + + +@ApiModel(description = "") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-12-10T16:26:30.730+08:00") +public class User { + + private Long id = null; + private String username = null; + private String firstName = null; + private String lastName = null; + private String email = null; + private String password = null; + private String phone = null; + private Integer userStatus = null; + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("id") + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("username") + public String getUsername() { + return username; + } + public void setUsername(String username) { + this.username = username; + } + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("firstName") + public String getFirstName() { + return firstName; + } + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("lastName") + public String getLastName() { + return lastName; + } + public void setLastName(String lastName) { + this.lastName = lastName; + } + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("email") + public String getEmail() { + return email; + } + public void setEmail(String email) { + this.email = email; + } + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("password") + public String getPassword() { + return password; + } + public void setPassword(String password) { + this.password = password; + } + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("phone") + public String getPhone() { + return phone; + } + public void setPhone(String phone) { + this.phone = phone; + } + + + /** + * User Status + **/ + @ApiModelProperty(value = "User Status") + @JsonProperty("userStatus") + public Integer getUserStatus() { + return userStatus; + } + public void setUserStatus(Integer userStatus) { + this.userStatus = userStatus; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + User user = (User) o; + return Objects.equals(id, user.id) && + Objects.equals(username, user.username) && + Objects.equals(firstName, user.firstName) && + Objects.equals(lastName, user.lastName) && + Objects.equals(email, user.email) && + Objects.equals(password, user.password) && + Objects.equals(phone, user.phone) && + Objects.equals(userStatus, user.userStatus); + } + + @Override + public int hashCode() { + return Objects.hash(id, username, firstName, lastName, email, password, phone, userStatus); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class User {\n"); + + sb.append(" id: ").append(StringUtil.toIndentedString(id)).append("\n"); + sb.append(" username: ").append(StringUtil.toIndentedString(username)).append("\n"); + sb.append(" firstName: ").append(StringUtil.toIndentedString(firstName)).append("\n"); + sb.append(" lastName: ").append(StringUtil.toIndentedString(lastName)).append("\n"); + sb.append(" email: ").append(StringUtil.toIndentedString(email)).append("\n"); + sb.append(" password: ").append(StringUtil.toIndentedString(password)).append("\n"); + sb.append(" phone: ").append(StringUtil.toIndentedString(phone)).append("\n"); + sb.append(" userStatus: ").append(StringUtil.toIndentedString(userStatus)).append("\n"); + sb.append("}"); + return sb.toString(); + } +} diff --git a/samples/client/petstore/java/feign/src/test/java/io/swagger/client/StringUtilTest.java b/samples/client/petstore/java/feign/src/test/java/io/swagger/client/StringUtilTest.java new file mode 100644 index 000000000000..c93908b84821 --- /dev/null +++ b/samples/client/petstore/java/feign/src/test/java/io/swagger/client/StringUtilTest.java @@ -0,0 +1,32 @@ +package io.swagger.client; + +import org.junit.*; +import static org.junit.Assert.*; + +public class StringUtilTest { + @Test + public void testContainsIgnoreCase() { + assertTrue(StringUtil.containsIgnoreCase(new String[]{"abc"}, "abc")); + assertTrue(StringUtil.containsIgnoreCase(new String[]{"abc"}, "ABC")); + assertTrue(StringUtil.containsIgnoreCase(new String[]{"ABC"}, "abc")); + assertTrue(StringUtil.containsIgnoreCase(new String[]{null, "abc"}, "ABC")); + assertTrue(StringUtil.containsIgnoreCase(new String[]{null, "abc"}, null)); + + assertFalse(StringUtil.containsIgnoreCase(new String[]{"abc"}, "def")); + assertFalse(StringUtil.containsIgnoreCase(new String[]{}, "ABC")); + assertFalse(StringUtil.containsIgnoreCase(new String[]{}, null)); + } + + @Test + public void testJoin() { + String[] array = {"aa", "bb", "cc"}; + assertEquals("aa,bb,cc", StringUtil.join(array, ",")); + assertEquals("aa, bb, cc", StringUtil.join(array, ", ")); + assertEquals("aabbcc", StringUtil.join(array, "")); + assertEquals("aa bb cc", StringUtil.join(array, " ")); + assertEquals("aa\nbb\ncc", StringUtil.join(array, "\n")); + + assertEquals("", StringUtil.join(new String[]{}, ",")); + assertEquals("abc", StringUtil.join(new String[]{"abc"}, ",")); + } +} \ No newline at end of file diff --git a/samples/client/petstore/java/feign/src/test/java/io/swagger/petstore/test/PetApiTest.java b/samples/client/petstore/java/feign/src/test/java/io/swagger/petstore/test/PetApiTest.java new file mode 100644 index 000000000000..aef8ab25610f --- /dev/null +++ b/samples/client/petstore/java/feign/src/test/java/io/swagger/petstore/test/PetApiTest.java @@ -0,0 +1,199 @@ +package io.swagger.petstore.test; + +import io.swagger.client.ApiClient; + +import io.swagger.client.api.*; +import io.swagger.client.model.*; + +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileWriter; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import org.junit.*; +import static org.junit.Assert.*; + +public class PetApiTest { + ApiClient apiClient; + PetApi api; + + @Before + public void setup() { + apiClient = new ApiClient(); + api = apiClient.buildClient(PetApi.class); + } + + @Test + public void testApiClient() { + // the default api client is used + assertEquals("http://petstore.swagger.io/v2", apiClient.getBasePath()); + + ApiClient newClient = new ApiClient(); + newClient.setBasePath("http://example.com"); + + assertEquals("http://example.com", newClient.getBasePath()); + } + + @Test + public void testCreateAndGetPet() throws Exception { + Pet pet = createRandomPet(); + api.addPet(pet); + + Pet fetched = api.getPetById(pet.getId()); + assertNotNull(fetched); + assertEquals(pet.getId(), fetched.getId()); + assertNotNull(fetched.getCategory()); + assertEquals(fetched.getCategory().getName(), pet.getCategory().getName()); + } + + @Test + public void testUpdatePet() throws Exception { + Pet pet = createRandomPet(); + pet.setName("programmer"); + + api.updatePet(pet); + + Pet fetched = api.getPetById(pet.getId()); + assertNotNull(fetched); + assertEquals(pet.getId(), fetched.getId()); + assertNotNull(fetched.getCategory()); + assertEquals(fetched.getCategory().getName(), pet.getCategory().getName()); + } + + @Test + public void testFindPetsByStatus() throws Exception { + Pet pet = createRandomPet(); + pet.setName("programmer"); + pet.setStatus(Pet.StatusEnum.AVAILABLE); + + api.updatePet(pet); + + List pets = api.findPetsByStatus(Arrays.asList(new String[]{"available"})); + assertNotNull(pets); + + boolean found = false; + for (Pet fetched : pets) { + if (fetched.getId().equals(pet.getId())) { + found = true; + break; + } + } + + assertTrue(found); + } + + @Test + public void testFindPetsByTags() throws Exception { + Pet pet = createRandomPet(); + pet.setName("monster"); + pet.setStatus(Pet.StatusEnum.AVAILABLE); + + List tags = new ArrayList(); + Tag tag1 = new Tag(); + tag1.setName("friendly"); + tags.add(tag1); + pet.setTags(tags); + + api.updatePet(pet); + + List pets = api.findPetsByTags(Arrays.asList(new String[]{"friendly"})); + assertNotNull(pets); + + boolean found = false; + for (Pet fetched : pets) { + if (fetched.getId().equals(pet.getId())) { + found = true; + break; + } + } + assertTrue(found); + } + + @Test + public void testUpdatePetWithForm() throws Exception { + Pet pet = createRandomPet(); + pet.setName("frank"); + api.addPet(pet); + + Pet fetched = api.getPetById(pet.getId()); + + api.updatePetWithForm(fetched.getId().toString(), "furt", null); + Pet updated = api.getPetById(fetched.getId()); + + assertEquals(updated.getName(), "furt"); + } + + @Test + public void testDeletePet() throws Exception { + Pet pet = createRandomPet(); + api.addPet(pet); + + Pet fetched = api.getPetById(pet.getId()); + api.deletePet(fetched.getId(), null); + + try { + fetched = api.getPetById(fetched.getId()); + fail("expected an error"); + } catch (Exception e) { +// assertEquals(404, e.getCode()); + } + } + + @Test + public void testUploadFile() throws Exception { + Pet pet = createRandomPet(); + api.addPet(pet); + + File file = new File("hello.txt"); + BufferedWriter writer = new BufferedWriter(new FileWriter(file)); + writer.write("Hello world!"); + writer.close(); + + api.uploadFile(pet.getId(), "a test file", new File(file.getAbsolutePath())); + } + + @Test + public void testEqualsAndHashCode() { + Pet pet1 = new Pet(); + Pet pet2 = new Pet(); + assertTrue(pet1.equals(pet2)); + assertTrue(pet2.equals(pet1)); + assertTrue(pet1.hashCode() == pet2.hashCode()); + assertTrue(pet1.equals(pet1)); + assertTrue(pet1.hashCode() == pet1.hashCode()); + + pet2.setName("really-happy"); + pet2.setPhotoUrls(Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"})); + assertFalse(pet1.equals(pet2)); + assertFalse(pet2.equals(pet1)); + assertFalse(pet1.hashCode() == (pet2.hashCode())); + assertTrue(pet2.equals(pet2)); + assertTrue(pet2.hashCode() == pet2.hashCode()); + + pet1.setName("really-happy"); + pet1.setPhotoUrls(Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"})); + assertTrue(pet1.equals(pet2)); + assertTrue(pet2.equals(pet1)); + assertTrue(pet1.hashCode() == pet2.hashCode()); + assertTrue(pet1.equals(pet1)); + assertTrue(pet1.hashCode() == pet1.hashCode()); + } + + private Pet createRandomPet() { + Pet pet = new Pet(); + pet.setId(System.currentTimeMillis()); + pet.setName("gorilla"); + + Category category = new Category(); + category.setName("really-happy"); + + pet.setCategory(category); + pet.setStatus(Pet.StatusEnum.AVAILABLE); + List photos = Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"}); + pet.setPhotoUrls(photos); + + return pet; + } +} diff --git a/samples/client/petstore/java/feign/src/test/java/io/swagger/petstore/test/StoreApiTest.java b/samples/client/petstore/java/feign/src/test/java/io/swagger/petstore/test/StoreApiTest.java new file mode 100644 index 000000000000..dd5bf4e71f4c --- /dev/null +++ b/samples/client/petstore/java/feign/src/test/java/io/swagger/petstore/test/StoreApiTest.java @@ -0,0 +1,64 @@ +package io.swagger.petstore.test; + +import io.swagger.client.*; +import io.swagger.client.api.*; +import io.swagger.client.model.*; + +import java.util.Map; + +import org.junit.*; +import static org.junit.Assert.*; + +public class StoreApiTest { + ApiClient apiClient; + StoreApi api; + + @Before + public void setup() { + apiClient = new ApiClient(); + api = apiClient.buildClient(StoreApi.class); + } + + @Test + public void testGetInventory() throws Exception { + Map inventory = api.getInventory(); + assertTrue(inventory.keySet().size() > 0); + } + + @Test + public void testPlaceOrder() throws Exception { + Order order = createOrder(); + api.placeOrder(order); + + Order fetched = api.getOrderById(order.getId().toString()); + assertEquals(order.getId(), fetched.getId()); + assertEquals(order.getPetId(), fetched.getPetId()); + assertEquals(order.getQuantity(), fetched.getQuantity()); + } + + @Test + public void testDeleteOrder() throws Exception { + Order order = createOrder(); + api.placeOrder(order); + + Order fetched = api.getOrderById(order.getId().toString()); + assertEquals(fetched.getId(), order.getId()); + + api.deleteOrder(String.valueOf(order.getId())); + + api.getOrderById(order.getId().toString()); +// fail("expected an error"); + } + + private Order createOrder() { + Order order = new Order(); + order.setId(new Long(System.currentTimeMillis())); + order.setPetId(new Long(200)); + order.setQuantity(new Integer(13)); + order.setShipDate(new java.util.Date()); + order.setStatus(Order.StatusEnum.PLACED); + order.setComplete(true); + + return order; + } +} diff --git a/samples/client/petstore/java/feign/src/test/java/io/swagger/petstore/test/UserApiTest.java b/samples/client/petstore/java/feign/src/test/java/io/swagger/petstore/test/UserApiTest.java new file mode 100644 index 000000000000..1615dbf1dce7 --- /dev/null +++ b/samples/client/petstore/java/feign/src/test/java/io/swagger/petstore/test/UserApiTest.java @@ -0,0 +1,87 @@ +package io.swagger.petstore.test; + +import io.swagger.client.ApiClient; +import io.swagger.client.api.*; +import io.swagger.client.model.*; + +import java.util.Arrays; + +import org.junit.*; +import static org.junit.Assert.*; + +public class UserApiTest { + ApiClient apiClient; + UserApi api; + + @Before + public void setup() { + apiClient = new ApiClient(); + api = apiClient.buildClient(UserApi.class); + } + + @Test + public void testCreateUser() throws Exception { + User user = createUser(); + + api.createUser(user); + + User fetched = api.getUserByName(user.getUsername()); + assertEquals(user.getId(), fetched.getId()); + } + + @Test + public void testCreateUsersWithArray() throws Exception { + User user1 = createUser(); + user1.setUsername("abc123"); + User user2 = createUser(); + user2.setUsername("123abc"); + + api.createUsersWithArrayInput(Arrays.asList(new User[]{user1, user2})); + + User fetched = api.getUserByName(user1.getUsername()); + assertEquals(user1.getId(), fetched.getId()); + } + + @Test + public void testCreateUsersWithList() throws Exception { + User user1 = createUser(); + user1.setUsername("abc123"); + User user2 = createUser(); + user2.setUsername("123abc"); + + api.createUsersWithListInput(Arrays.asList(new User[]{user1, user2})); + + User fetched = api.getUserByName(user1.getUsername()); + assertEquals(user1.getId(), fetched.getId()); + } + + // ignore for the time being, please refer to the following for more info: + // https://github.com/swagger-api/swagger-codegen/issues/1660 + @Ignore @Test + public void testLoginUser() throws Exception { + User user = createUser(); + api.createUser(user); + + String token = api.loginUser(user.getUsername(), user.getPassword()); + assertTrue(token.startsWith("logged in user session:")); + } + + @Test + public void logoutUser() throws Exception { + api.logoutUser(); + } + + private User createUser() { + User user = new User(); + user.setId(System.currentTimeMillis()); + user.setUsername("fred" + user.getId()); + user.setFirstName("Fred"); + user.setLastName("Meyer"); + user.setEmail("fred@fredmeyer.com"); + user.setPassword("xxXXxx"); + user.setPhone("408-867-5309"); + user.setUserStatus(123); + + return user; + } +} diff --git a/samples/client/petstore/java/jersey2/pom.xml b/samples/client/petstore/java/jersey2/pom.xml index 0881cc293746..6b0ba2cba08f 100644 --- a/samples/client/petstore/java/jersey2/pom.xml +++ b/samples/client/petstore/java/jersey2/pom.xml @@ -124,7 +124,12 @@ jersey-media-multipart ${jersey-version}
- + + org.glassfish.jersey.media + jersey-media-json-jackson + 2.22.1 + + com.fasterxml.jackson.core diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiClient.java index e9c55bfb710f..4ca24fbabb0c 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiClient.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiClient.java @@ -6,6 +6,7 @@ import javax.ws.rs.client.Entity; import javax.ws.rs.client.Invocation; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.Form; +import javax.ws.rs.core.GenericType; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; @@ -29,20 +30,18 @@ import java.util.TimeZone; import java.net.URLEncoder; -import java.io.IOException; import java.io.File; import java.io.UnsupportedEncodingException; import java.text.DateFormat; import java.text.SimpleDateFormat; -import java.text.ParseException; import io.swagger.client.auth.Authentication; import io.swagger.client.auth.HttpBasicAuth; import io.swagger.client.auth.ApiKeyAuth; import io.swagger.client.auth.OAuth; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-12-02T18:29:08.393+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-12-09T12:31:44.572-05:00") public class ApiClient { private Client client; private Map hostMap = new HashMap(); @@ -343,6 +342,17 @@ public class ApiClient { return params; } + /** + * Check if the given MIME is a JSON MIME. + * JSON MIME examples: + * application/json + * application/json; charset=UTF8 + * APPLICATION/JSON + */ + public boolean isJsonMime(String mime) { + return mime != null && mime.matches("(?i)application\\/json(;.*)?"); + } + /** * Select the Accept header's value from the given accepts array: * if JSON exists in the given array, use it; @@ -353,8 +363,14 @@ public class ApiClient { * null will be returned (not to set the Accept header explicitly). */ public String selectHeaderAccept(String[] accepts) { - if (accepts.length == 0) return null; - if (StringUtil.containsIgnoreCase(accepts, "application/json")) return "application/json"; + if (accepts.length == 0) { + return null; + } + for (String accept : accepts) { + if (isJsonMime(accept)) { + return accept; + } + } return StringUtil.join(accepts, ","); } @@ -368,8 +384,14 @@ public class ApiClient { * JSON will be used. */ public String selectHeaderContentType(String[] contentTypes) { - if (contentTypes.length == 0) return "application/json"; - if (StringUtil.containsIgnoreCase(contentTypes, "application/json")) return "application/json"; + if (contentTypes.length == 0) { + return "application/json"; + } + for (String contentType : contentTypes) { + if (isJsonMime(contentType)) { + return contentType; + } + } return contentTypes[0]; } @@ -388,18 +410,39 @@ public class ApiClient { * Serialize the given Java object into string entity according the given * Content-Type (only JSON is supported for now). */ - public Entity serialize(Object obj, String contentType) throws ApiException { - if (contentType.startsWith("application/json")) { - return Entity.json(json.serialize(obj)); + public Entity serialize(Object obj, Map formParams, String contentType) throws ApiException { + Entity entity = null; + if (contentType.startsWith("multipart/form-data")) { + MultiPart multiPart = new MultiPart(); + for (Entry param: formParams.entrySet()) { + if (param.getValue() instanceof File) { + File file = (File) param.getValue(); + FormDataContentDisposition contentDisp = FormDataContentDisposition.name(param.getKey()) + .fileName(file.getName()).size(file.length()).build(); + multiPart.bodyPart(new FormDataBodyPart(contentDisp, file, MediaType.APPLICATION_OCTET_STREAM_TYPE)); + } else { + FormDataContentDisposition contentDisp = FormDataContentDisposition.name(param.getKey()).build(); + multiPart.bodyPart(new FormDataBodyPart(contentDisp, parameterToString(param.getValue()))); + } + } + entity = Entity.entity(multiPart, MediaType.MULTIPART_FORM_DATA_TYPE); + } else if (contentType.startsWith("application/x-www-form-urlencoded")) { + Form form = new Form(); + for (Entry param: formParams.entrySet()) { + form.param(param.getKey(), parameterToString(param.getValue())); + } + entity = Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE); } else { - throw new ApiException(400, "can not serialize object into Content-Type: " + contentType); + // We let jersey handle the serialization + entity = Entity.entity(obj, contentType); } + return entity; } /** * Deserialize response body to Java object according to the Content-Type. */ - public T deserialize(Response response, TypeRef returnType) throws ApiException { + public T deserialize(Response response, GenericType returnType) throws ApiException { String contentType = null; List contentTypes = response.getHeaders().get("Content-Type"); if (contentTypes != null && !contentTypes.isEmpty()) @@ -407,24 +450,7 @@ public class ApiClient { if (contentType == null) throw new ApiException(500, "missing Content-Type in response"); - String body; - if (response.hasEntity()) - body = (String) response.readEntity(String.class); - else - body = ""; - - if (contentType.startsWith("application/json")) { - return json.deserialize(body, returnType); - } else if (returnType.getType().equals(String.class)) { - // Expecting string, return the raw response body. - return (T) body; - } else { - throw new ApiException( - 500, - "Content type \"" + contentType + "\" is not supported for type: " - + returnType.getType() - ); - } + return response.readEntity(returnType); } /** @@ -442,7 +468,7 @@ public class ApiClient { * @param returnType The return type into which to deserialize the response * @return The response body in type of string */ - public T invokeAPI(String path, String method, List queryParams, Object body, Map headerParams, Map formParams, String accept, String contentType, String[] authNames, TypeRef returnType) throws ApiException { + public T invokeAPI(String path, String method, List queryParams, Object body, Map headerParams, Map formParams, String accept, String contentType, String[] authNames, GenericType returnType) throws ApiException { updateParamsForAuth(authNames, queryParams, headerParams); WebTarget target = client.target(this.basePath).path(path); @@ -473,50 +499,16 @@ public class ApiClient { } } - Entity formEntity = null; - - if (contentType.startsWith("multipart/form-data")) { - MultiPart multiPart = new MultiPart(); - for (Entry param: formParams.entrySet()) { - if (param.getValue() instanceof File) { - File file = (File) param.getValue(); - FormDataContentDisposition contentDisp = FormDataContentDisposition.name(param.getKey()) - .fileName(file.getName()).size(file.length()).build(); - multiPart.bodyPart(new FormDataBodyPart(contentDisp, file, MediaType.APPLICATION_OCTET_STREAM_TYPE)); - } else { - FormDataContentDisposition contentDisp = FormDataContentDisposition.name(param.getKey()).build(); - multiPart.bodyPart(new FormDataBodyPart(contentDisp, parameterToString(param.getValue()))); - } - } - formEntity = Entity.entity(multiPart, MediaType.MULTIPART_FORM_DATA_TYPE); - } else if (contentType.startsWith("application/x-www-form-urlencoded")) { - Form form = new Form(); - for (Entry param: formParams.entrySet()) { - form.param(param.getKey(), parameterToString(param.getValue())); - } - formEntity = Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE); - } + Entity entity = serialize(body, formParams, contentType); Response response = null; if ("GET".equals(method)) { response = invocationBuilder.get(); } else if ("POST".equals(method)) { - if (formEntity != null) { - response = invocationBuilder.post(formEntity); - } else if (body == null) { - response = invocationBuilder.post(null); - } else { - response = invocationBuilder.post(serialize(body, contentType)); - } + response = invocationBuilder.post(entity); } else if ("PUT".equals(method)) { - if (formEntity != null) { - response = invocationBuilder.put(formEntity); - } else if (body == null) { - response = invocationBuilder.put(null); - } else { - response = invocationBuilder.put(serialize(body, contentType)); - } + response = invocationBuilder.put(entity); } else if ("DELETE".equals(method)) { response = invocationBuilder.delete(); } else { @@ -555,6 +547,8 @@ public class ApiClient { private void buildClient() { final ClientConfig clientConfig = new ClientConfig(); clientConfig.register(MultiPartFeature.class); + clientConfig.register(json); + clientConfig.register(org.glassfish.jersey.jackson.JacksonFeature.class); if (debugging) { clientConfig.register(LoggingFilter.class); } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/JSON.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/JSON.java index 9116d3663083..aab2d27e4638 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/JSON.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/JSON.java @@ -6,10 +6,10 @@ import com.fasterxml.jackson.datatype.joda.*; import java.text.DateFormat; -import java.io.IOException; +import javax.ws.rs.ext.ContextResolver; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-11-29T00:18:01.946+08:00") -public class JSON { +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-12-09T12:31:44.572-05:00") +public class JSON implements ContextResolver { private ObjectMapper mapper; public JSON() { @@ -29,36 +29,8 @@ public class JSON { mapper.setDateFormat(dateFormat); } - /** - * Serialize the given Java object into JSON string. - */ - public String serialize(Object obj) throws ApiException { - try { - if (obj != null) - return mapper.writeValueAsString(obj); - else - return null; - } catch (Exception e) { - throw new ApiException(400, e.getMessage()); - } - } - - /** - * Deserialize the given JSON string to Java object. - * - * @param body The JSON string - * @param returnType The type to deserialize inot - * @return The deserialized Java object - */ - public T deserialize(String body, TypeRef returnType) throws ApiException { - JavaType javaType = mapper.constructType(returnType.getType()); - try { - return mapper.readValue(body, javaType); - } catch (IOException e) { - if (returnType.getType().equals(String.class)) - return (T) body; - else - throw new ApiException(500, e.getMessage(), null, body); - } + @Override + public ObjectMapper getContext(Class type) { + return mapper; } } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/TypeRef.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/TypeRef.java deleted file mode 100644 index 9c97f34cd792..000000000000 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/TypeRef.java +++ /dev/null @@ -1,26 +0,0 @@ -package io.swagger.client; - -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.Type; - -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-11-29T00:18:01.946+08:00") -public class TypeRef { - private final Type type; - - public TypeRef() { - this.type = getGenericType(getClass()); - } - - private static Type getGenericType(Class klass) { - Type superclass = klass.getGenericSuperclass(); - if (superclass instanceof Class) { - throw new RuntimeException("No type parameter provided"); - } - ParameterizedType parameterized = (ParameterizedType) superclass; - return parameterized.getActualTypeArguments()[0]; - } - - public Type getType() { - return type; - } -} diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/PetApi.java index a645de12c719..ab33fca7c798 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/PetApi.java @@ -4,14 +4,15 @@ import io.swagger.client.ApiException; import io.swagger.client.ApiClient; import io.swagger.client.Configuration; import io.swagger.client.Pair; -import io.swagger.client.TypeRef; + +import javax.ws.rs.core.GenericType; import io.swagger.client.model.Pet; import java.io.File; import java.util.*; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-11-29T00:18:01.946+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-12-09T12:31:44.572-05:00") public class PetApi { private ApiClient apiClient; @@ -38,7 +39,7 @@ public class PetApi { * @param body Pet object that needs to be added to the store * @return void */ - public void updatePet (Pet body) throws ApiException { + public void updatePet(Pet body) throws ApiException { Object postBody = body; // create path and map variables @@ -78,7 +79,7 @@ public class PetApi { * @param body Pet object that needs to be added to the store * @return void */ - public void addPet (Pet body) throws ApiException { + public void addPet(Pet body) throws ApiException { Object postBody = body; // create path and map variables @@ -118,7 +119,7 @@ public class PetApi { * @param status Status values that need to be considered for filter * @return List */ - public List findPetsByStatus (List status) throws ApiException { + public List findPetsByStatus(List status) throws ApiException { Object postBody = null; // create path and map variables @@ -150,7 +151,7 @@ public class PetApi { String[] authNames = new String[] { "petstore_auth" }; - TypeRef returnType = new TypeRef>() {}; + GenericType> returnType = new GenericType>() {}; return apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); } @@ -161,7 +162,7 @@ public class PetApi { * @param tags Tags to filter by * @return List */ - public List findPetsByTags (List tags) throws ApiException { + public List findPetsByTags(List tags) throws ApiException { Object postBody = null; // create path and map variables @@ -193,7 +194,7 @@ public class PetApi { String[] authNames = new String[] { "petstore_auth" }; - TypeRef returnType = new TypeRef>() {}; + GenericType> returnType = new GenericType>() {}; return apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); } @@ -204,7 +205,7 @@ public class PetApi { * @param petId ID of pet that needs to be fetched * @return Pet */ - public Pet getPetById (Long petId) throws ApiException { + public Pet getPetById(Long petId) throws ApiException { Object postBody = null; // verify the required parameter 'petId' is set @@ -240,7 +241,7 @@ public class PetApi { String[] authNames = new String[] { "api_key" }; - TypeRef returnType = new TypeRef() {}; + GenericType returnType = new GenericType() {}; return apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); } @@ -253,7 +254,7 @@ public class PetApi { * @param status Updated status of the pet * @return void */ - public void updatePetWithForm (String petId, String name, String status) throws ApiException { + public void updatePetWithForm(String petId, String name, String status) throws ApiException { Object postBody = null; // verify the required parameter 'petId' is set @@ -304,7 +305,7 @@ public class PetApi { * @param apiKey * @return void */ - public void deletePet (Long petId, String apiKey) throws ApiException { + public void deletePet(Long petId, String apiKey) throws ApiException { Object postBody = null; // verify the required parameter 'petId' is set @@ -354,7 +355,7 @@ public class PetApi { * @param file file to upload * @return void */ - public void uploadFile (Long petId, String additionalMetadata, File file) throws ApiException { + public void uploadFile(Long petId, String additionalMetadata, File file) throws ApiException { Object postBody = null; // verify the required parameter 'petId' is set diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/StoreApi.java index 7253d1909b60..5dfdbcc3e62c 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/StoreApi.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/StoreApi.java @@ -4,14 +4,15 @@ import io.swagger.client.ApiException; import io.swagger.client.ApiClient; import io.swagger.client.Configuration; import io.swagger.client.Pair; -import io.swagger.client.TypeRef; + +import javax.ws.rs.core.GenericType; import java.util.Map; import io.swagger.client.model.Order; import java.util.*; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-11-29T00:18:01.946+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-12-09T12:31:44.572-05:00") public class StoreApi { private ApiClient apiClient; @@ -37,7 +38,7 @@ public class StoreApi { * Returns a map of status codes to quantities * @return Map */ - public Map getInventory () throws ApiException { + public Map getInventory() throws ApiException { Object postBody = null; // create path and map variables @@ -67,7 +68,7 @@ public class StoreApi { String[] authNames = new String[] { "api_key" }; - TypeRef returnType = new TypeRef>() {}; + GenericType> returnType = new GenericType>() {}; return apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); } @@ -78,7 +79,7 @@ public class StoreApi { * @param body order placed for purchasing the pet * @return Order */ - public Order placeOrder (Order body) throws ApiException { + public Order placeOrder(Order body) throws ApiException { Object postBody = body; // create path and map variables @@ -108,7 +109,7 @@ public class StoreApi { String[] authNames = new String[] { }; - TypeRef returnType = new TypeRef() {}; + GenericType returnType = new GenericType() {}; return apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); } @@ -119,7 +120,7 @@ public class StoreApi { * @param orderId ID of pet that needs to be fetched * @return Order */ - public Order getOrderById (String orderId) throws ApiException { + public Order getOrderById(String orderId) throws ApiException { Object postBody = null; // verify the required parameter 'orderId' is set @@ -155,7 +156,7 @@ public class StoreApi { String[] authNames = new String[] { }; - TypeRef returnType = new TypeRef() {}; + GenericType returnType = new GenericType() {}; return apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); } @@ -166,7 +167,7 @@ public class StoreApi { * @param orderId ID of the order that needs to be deleted * @return void */ - public void deleteOrder (String orderId) throws ApiException { + public void deleteOrder(String orderId) throws ApiException { Object postBody = null; // verify the required parameter 'orderId' is set diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/UserApi.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/UserApi.java index d6115d939fc3..0424382e7c33 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/UserApi.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/UserApi.java @@ -4,14 +4,15 @@ import io.swagger.client.ApiException; import io.swagger.client.ApiClient; import io.swagger.client.Configuration; import io.swagger.client.Pair; -import io.swagger.client.TypeRef; + +import javax.ws.rs.core.GenericType; import io.swagger.client.model.User; import java.util.*; import java.util.*; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-11-29T00:18:01.946+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-12-09T12:31:44.572-05:00") public class UserApi { private ApiClient apiClient; @@ -38,7 +39,7 @@ public class UserApi { * @param body Created user object * @return void */ - public void createUser (User body) throws ApiException { + public void createUser(User body) throws ApiException { Object postBody = body; // create path and map variables @@ -78,7 +79,7 @@ public class UserApi { * @param body List of user object * @return void */ - public void createUsersWithArrayInput (List body) throws ApiException { + public void createUsersWithArrayInput(List body) throws ApiException { Object postBody = body; // create path and map variables @@ -118,7 +119,7 @@ public class UserApi { * @param body List of user object * @return void */ - public void createUsersWithListInput (List body) throws ApiException { + public void createUsersWithListInput(List body) throws ApiException { Object postBody = body; // create path and map variables @@ -159,7 +160,7 @@ public class UserApi { * @param password The password for login in clear text * @return String */ - public String loginUser (String username, String password) throws ApiException { + public String loginUser(String username, String password) throws ApiException { Object postBody = null; // create path and map variables @@ -193,7 +194,7 @@ public class UserApi { String[] authNames = new String[] { }; - TypeRef returnType = new TypeRef() {}; + GenericType returnType = new GenericType() {}; return apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); } @@ -203,7 +204,7 @@ public class UserApi { * * @return void */ - public void logoutUser () throws ApiException { + public void logoutUser() throws ApiException { Object postBody = null; // create path and map variables @@ -243,7 +244,7 @@ public class UserApi { * @param username The name that needs to be fetched. Use user1 for testing. * @return User */ - public User getUserByName (String username) throws ApiException { + public User getUserByName(String username) throws ApiException { Object postBody = null; // verify the required parameter 'username' is set @@ -279,7 +280,7 @@ public class UserApi { String[] authNames = new String[] { }; - TypeRef returnType = new TypeRef() {}; + GenericType returnType = new GenericType() {}; return apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); } @@ -291,7 +292,7 @@ public class UserApi { * @param body Updated user object * @return void */ - public void updateUser (String username, User body) throws ApiException { + public void updateUser(String username, User body) throws ApiException { Object postBody = body; // verify the required parameter 'username' is set @@ -337,7 +338,7 @@ public class UserApi { * @param username The name that needs to be deleted * @return void */ - public void deleteUser (String username) throws ApiException { + public void deleteUser(String username) throws ApiException { Object postBody = null; // verify the required parameter 'username' is set diff --git a/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/ApiClientTest.java b/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/ApiClientTest.java index 3d57f3fa84cf..29eae3d017ea 100644 --- a/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/ApiClientTest.java +++ b/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/ApiClientTest.java @@ -38,16 +38,29 @@ public class ApiClientTest { assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T13:49:09+10:00"))); } + @Test + public void testIsJsonMime() { + assertFalse(apiClient.isJsonMime(null)); + assertFalse(apiClient.isJsonMime("")); + assertFalse(apiClient.isJsonMime("text/plain")); + assertFalse(apiClient.isJsonMime("application/xml")); + assertFalse(apiClient.isJsonMime("application/jsonp")); + + assertTrue(apiClient.isJsonMime("application/json")); + assertTrue(apiClient.isJsonMime("application/json; charset=UTF8")); + assertTrue(apiClient.isJsonMime("APPLICATION/JSON")); + } + @Test public void testSelectHeaderAccept() { - String[] accepts = {"APPLICATION/JSON", "APPLICATION/XML"}; + String[] accepts = {"application/json", "application/xml"}; assertEquals("application/json", apiClient.selectHeaderAccept(accepts)); - accepts = new String[]{"application/json", "application/xml"}; - assertEquals("application/json", apiClient.selectHeaderAccept(accepts)); + accepts = new String[]{"APPLICATION/XML", "APPLICATION/JSON"}; + assertEquals("APPLICATION/JSON", apiClient.selectHeaderAccept(accepts)); - accepts = new String[]{"application/xml", "application/json"}; - assertEquals("application/json", apiClient.selectHeaderAccept(accepts)); + accepts = new String[]{"application/xml", "application/json; charset=UTF8"}; + assertEquals("application/json; charset=UTF8", apiClient.selectHeaderAccept(accepts)); accepts = new String[]{"text/plain", "application/xml"}; assertEquals("text/plain,application/xml", apiClient.selectHeaderAccept(accepts)); @@ -58,14 +71,14 @@ public class ApiClientTest { @Test public void testSelectHeaderContentType() { - String[] contentTypes = {"APPLICATION/JSON", "APPLICATION/XML"}; + String[] contentTypes = {"application/json", "application/xml"}; assertEquals("application/json", apiClient.selectHeaderContentType(contentTypes)); - contentTypes = new String[]{"application/json", "application/xml"}; - assertEquals("application/json", apiClient.selectHeaderContentType(contentTypes)); + contentTypes = new String[]{"APPLICATION/JSON", "APPLICATION/XML"}; + assertEquals("APPLICATION/JSON", apiClient.selectHeaderContentType(contentTypes)); - contentTypes = new String[]{"application/xml", "application/json"}; - assertEquals("application/json", apiClient.selectHeaderContentType(contentTypes)); + contentTypes = new String[]{"application/xml", "application/json; charset=UTF8"}; + assertEquals("application/json; charset=UTF8", apiClient.selectHeaderContentType(contentTypes)); contentTypes = new String[]{"text/plain", "application/xml"}; assertEquals("text/plain", apiClient.selectHeaderContentType(contentTypes)); diff --git a/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/JSONTest.java b/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/JSONTest.java index 1250a135078f..f10909ab9e73 100644 --- a/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/JSONTest.java +++ b/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/JSONTest.java @@ -4,9 +4,7 @@ import io.swagger.client.model.Order; import java.lang.Exception; import java.text.DateFormat; -import java.text.ParseException; import java.text.SimpleDateFormat; -import java.util.*; import java.util.TimeZone; import org.junit.*; @@ -30,9 +28,8 @@ public class JSONTest { final String dateStr = "2015-11-07T14:11:05.267Z"; order.setShipDate(dateFormat.parse(dateStr)); - String str = json.serialize(order); - TypeRef typeRef = new TypeRef() { }; - Order o = json.deserialize(str, typeRef); + String str = json.getContext(null).writeValueAsString(order); + Order o = json.getContext(null).readValue(str, Order.class); assertEquals(dateStr, dateFormat.format(o.getShipDate())); } @@ -44,9 +41,8 @@ public class JSONTest { order.setShipDate(dateFormat.parse(dateStr)); json.setDateFormat(dateFormat); - String str = json.serialize(order); - TypeRef typeRef = new TypeRef() { }; - Order o = json.deserialize(str, typeRef); + String str = json.getContext(null).writeValueAsString(order); + Order o = json.getContext(null).readValue(str, Order.class); assertEquals(dateStr, dateFormat.format(o.getShipDate())); } } \ No newline at end of file diff --git a/samples/client/petstore/java/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 d4ee79cb3ad7..19cb83d620cb 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 @@ -548,6 +548,17 @@ public class ApiClient { return params; } + /** + * Check if the given MIME is a JSON MIME. + * JSON MIME examples: + * application/json + * application/json; charset=UTF8 + * APPLICATION/JSON + */ + public boolean isJsonMime(String mime) { + return mime != null && mime.matches("(?i)application\\/json(;.*)?"); + } + /** * Select the Accept header's value from the given accepts array: * if JSON exists in the given array, use it; @@ -558,8 +569,14 @@ public class ApiClient { * null will be returned (not to set the Accept header explicitly). */ public String selectHeaderAccept(String[] accepts) { - if (accepts.length == 0) return null; - if (StringUtil.containsIgnoreCase(accepts, "application/json")) return "application/json"; + if (accepts.length == 0) { + return null; + } + for (String accept : accepts) { + if (isJsonMime(accept)) { + return accept; + } + } return StringUtil.join(accepts, ","); } @@ -573,8 +590,14 @@ public class ApiClient { * JSON will be used. */ public String selectHeaderContentType(String[] contentTypes) { - if (contentTypes.length == 0) return "application/json"; - if (StringUtil.containsIgnoreCase(contentTypes, "application/json")) return "application/json"; + if (contentTypes.length == 0) { + return "application/json"; + } + for (String contentType : contentTypes) { + if (isJsonMime(contentType)) { + return contentType; + } + } return contentTypes[0]; } @@ -625,7 +648,7 @@ public class ApiClient { // ensuring a default content type contentType = "application/json"; } - if (contentType.startsWith("application/json")) { + if (isJsonMime(contentType)) { return json.deserialize(respBody, returnType); } else if (returnType.equals(String.class)) { // Expecting string, return the raw response body. @@ -649,7 +672,7 @@ public class ApiClient { * @throws ApiException If fail to serialize the given object */ public String serialize(Object obj, String contentType) throws ApiException { - if (contentType.startsWith("application/json")) { + if (isJsonMime(contentType)) { if (obj != null) return json.serialize(obj); else @@ -821,7 +844,9 @@ public class ApiClient { String contentType = (String) headerParams.get("Content-Type"); // ensuring a default content type - if (contentType == null) contentType = "application/json"; + if (contentType == null) { + contentType = "application/json"; + } RequestBody reqBody; if (!HttpMethod.permitsRequestBody(method)) { 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 aaf4f33c49ef..9b5c68057448 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/ApiClientTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/ApiClientTest.java @@ -77,16 +77,29 @@ public class ApiClientTest { assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11"))); } + @Test + public void testIsJsonMime() { + assertFalse(apiClient.isJsonMime(null)); + assertFalse(apiClient.isJsonMime("")); + assertFalse(apiClient.isJsonMime("text/plain")); + assertFalse(apiClient.isJsonMime("application/xml")); + assertFalse(apiClient.isJsonMime("application/jsonp")); + + assertTrue(apiClient.isJsonMime("application/json")); + assertTrue(apiClient.isJsonMime("application/json; charset=UTF8")); + assertTrue(apiClient.isJsonMime("APPLICATION/JSON")); + } + @Test public void testSelectHeaderAccept() { - String[] accepts = {"APPLICATION/JSON", "APPLICATION/XML"}; + String[] accepts = {"application/json", "application/xml"}; assertEquals("application/json", apiClient.selectHeaderAccept(accepts)); - accepts = new String[]{"application/json", "application/xml"}; - assertEquals("application/json", apiClient.selectHeaderAccept(accepts)); + accepts = new String[]{"APPLICATION/XML", "APPLICATION/JSON"}; + assertEquals("APPLICATION/JSON", apiClient.selectHeaderAccept(accepts)); - accepts = new String[]{"application/xml", "application/json"}; - assertEquals("application/json", apiClient.selectHeaderAccept(accepts)); + accepts = new String[]{"application/xml", "application/json; charset=UTF8"}; + assertEquals("application/json; charset=UTF8", apiClient.selectHeaderAccept(accepts)); accepts = new String[]{"text/plain", "application/xml"}; assertEquals("text/plain,application/xml", apiClient.selectHeaderAccept(accepts)); @@ -97,14 +110,14 @@ public class ApiClientTest { @Test public void testSelectHeaderContentType() { - String[] contentTypes = {"APPLICATION/JSON", "APPLICATION/XML"}; + String[] contentTypes = {"application/json", "application/xml"}; assertEquals("application/json", apiClient.selectHeaderContentType(contentTypes)); - contentTypes = new String[]{"application/json", "application/xml"}; - assertEquals("application/json", apiClient.selectHeaderContentType(contentTypes)); + contentTypes = new String[]{"APPLICATION/JSON", "APPLICATION/XML"}; + assertEquals("APPLICATION/JSON", apiClient.selectHeaderContentType(contentTypes)); - contentTypes = new String[]{"application/xml", "application/json"}; - assertEquals("application/json", apiClient.selectHeaderContentType(contentTypes)); + contentTypes = new String[]{"application/xml", "application/json; charset=UTF8"}; + assertEquals("application/json; charset=UTF8", apiClient.selectHeaderContentType(contentTypes)); contentTypes = new String[]{"text/plain", "application/xml"}; assertEquals("text/plain", apiClient.selectHeaderContentType(contentTypes)); diff --git a/samples/client/petstore/javascript/.gitignore b/samples/client/petstore/javascript/.gitignore new file mode 100644 index 000000000000..2ccbe4656c60 --- /dev/null +++ b/samples/client/petstore/javascript/.gitignore @@ -0,0 +1 @@ +/node_modules/ diff --git a/samples/client/petstore/javascript/package.json b/samples/client/petstore/javascript/package.json new file mode 100644 index 000000000000..6810fd633de5 --- /dev/null +++ b/samples/client/petstore/javascript/package.json @@ -0,0 +1,20 @@ +{ + "name": "swagger-petstore", + "version": "1.0.0", + "description": "This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters", + "license": "Apache 2.0", + "main": "src/index.js", + "scripts": { + "test": "./node_modules/mocha/bin/mocha --recursive" + }, + "dependencies": { + "jquery": "~2.1.4" + }, + "devDependencies": { + "mocha": "~2.3.4", + "expect.js": "~0.3.1", + "mockrequire": "~0.0.5", + "domino": "~1.0.20", + "xmlhttprequest": "~1.8.0" + } +} diff --git a/samples/client/petstore/javascript/pom.xml b/samples/client/petstore/javascript/pom.xml new file mode 100644 index 000000000000..b7a17c92b79c --- /dev/null +++ b/samples/client/petstore/javascript/pom.xml @@ -0,0 +1,45 @@ + + 4.0.0 + io.swagger + swagger-petstore-javascript + pom + 1.0-SNAPSHOT + Swagger Petstore - Javascript Client + + + + org.codehaus.mojo + exec-maven-plugin + 1.2.1 + + + npm-install + pre-integration-test + + exec + + + npm + + install + + + + + mocha + integration-test + + exec + + + npm + + test + + + + + + + + diff --git a/samples/client/petstore/javascript/src/scripts/rest/api/PetApi.js b/samples/client/petstore/javascript/src/api/PetApi.js similarity index 56% rename from samples/client/petstore/javascript/src/scripts/rest/api/PetApi.js rename to samples/client/petstore/javascript/src/api/PetApi.js index a693d83dbc2d..3b6d9c5b4c62 100644 --- a/samples/client/petstore/javascript/src/scripts/rest/api/PetApi.js +++ b/samples/client/petstore/javascript/src/api/PetApi.js @@ -1,10 +1,13 @@ -/* - * @javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavascriptClientCodegen", date = "2015-12-07T10:51:19.835+08:00") - */ +// require files in Node.js environment +var $, Pet; +if (typeof module === 'object' && module.exports) { + $ = require('jquery'); + Pet = require('../model/Pet.js'); +} -//export module +// export module for AMD if ( typeof define === "function" && define.amd ) { - define(['jquery'], function($) { + define(['jquery', 'Pet'], function($, Pet) { return PetApi; }); } @@ -12,6 +15,7 @@ if ( typeof define === "function" && define.amd ) { var PetApi = function PetApi() { var self = this; + /** * Update an existing pet * @@ -20,7 +24,6 @@ var PetApi = function PetApi() { * @return void */ self.updatePet = function(body, callback) { - var postBody = JSON.stringify(body); var postBinaryBody = null; @@ -31,7 +34,7 @@ var PetApi = function PetApi() { basePath = basePath.substring(0, basePath.length-1); } - var path = basePath + replaceAll(replaceAll("/pet", "\\{format\\}","json")); + var path = basePath + replaceAll(replaceAll("/pet", "\\{format\\}","json")); var queryParams = {}; var headerParams = {}; @@ -41,22 +44,27 @@ var PetApi = function PetApi() { - path += createQueryString(queryParams); - - //if (console) { - //console.log('path: ' + path); - //console.log('queryParams: ' + queryParams); - //} - - - - - - apiClient.invokeAPI(path, "PUT", queryParams, postBody, postBinaryBody, headerParams, formParams, accept, contentType, authNames, null); - - + path += createQueryString(queryParams); + var options = {type: "PUT", async: true, contentType: "application/json", dataType: "json", data: postBody}; + var request = $.ajax(path, options); + request.fail(function(jqXHR, textStatus, errorThrown){ + if (callback) { + var error = errorThrown || textStatus || jqXHR.statusText || 'error'; + callback(null, textStatus, jqXHR, error); + } + }); + + request.done(function(response, textStatus, jqXHR){ + + if (callback) { + callback(response, textStatus, jqXHR); + } + + }); + + return request; } /** @@ -67,7 +75,6 @@ var PetApi = function PetApi() { * @return void */ self.addPet = function(body, callback) { - var postBody = JSON.stringify(body); var postBinaryBody = null; @@ -78,7 +85,7 @@ var PetApi = function PetApi() { basePath = basePath.substring(0, basePath.length-1); } - var path = basePath + replaceAll(replaceAll("/pet", "\\{format\\}","json")); + var path = basePath + replaceAll(replaceAll("/pet", "\\{format\\}","json")); var queryParams = {}; var headerParams = {}; @@ -88,22 +95,27 @@ var PetApi = function PetApi() { - path += createQueryString(queryParams); - - //if (console) { - //console.log('path: ' + path); - //console.log('queryParams: ' + queryParams); - //} - - - - - - apiClient.invokeAPI(path, "POST", queryParams, postBody, postBinaryBody, headerParams, formParams, accept, contentType, authNames, null); - - + path += createQueryString(queryParams); + var options = {type: "POST", async: true, contentType: "application/json", dataType: "json", data: postBody}; + var request = $.ajax(path, options); + request.fail(function(jqXHR, textStatus, errorThrown){ + if (callback) { + var error = errorThrown || textStatus || jqXHR.statusText || 'error'; + callback(null, textStatus, jqXHR, error); + } + }); + + request.done(function(response, textStatus, jqXHR){ + + if (callback) { + callback(response, textStatus, jqXHR); + } + + }); + + return request; } /** @@ -114,7 +126,6 @@ var PetApi = function PetApi() { * @return Array */ self.findPetsByStatus = function(status, callback) { - var postBody = null; var postBinaryBody = null; @@ -125,7 +136,7 @@ var PetApi = function PetApi() { basePath = basePath.substring(0, basePath.length-1); } - var path = basePath + replaceAll(replaceAll("/pet/findByStatus", "\\{format\\}","json")); + var path = basePath + replaceAll(replaceAll("/pet/findByStatus", "\\{format\\}","json")); var queryParams = {}; var headerParams = {}; @@ -137,42 +148,33 @@ var PetApi = function PetApi() { - path += createQueryString(queryParams); + path += createQueryString(queryParams); - //if (console) { - //console.log('path: ' + path); - //console.log('queryParams: ' + queryParams); - //} - - - - - - //TypeRef returnType = new TypeRef() {}; - //return apiClient.invokeAPI(path, "GET", queryParams, postBody, postBinaryBody, headerParams, formParams, accept, contentType, authNames, returnType); - - var options = {type: "GET", async: true, contentType: "application/json", dataType: "json", data: postBody}; + var options = {type: "GET", async: true, contentType: "application/json", dataType: "json", data: postBody}; var request = $.ajax(path, options); - //request.fail(function(jqXHR, textStatus, errorThrown){ - // errorHandler(jqXHR, textStatus, errorThrown); - //}); - - - request.done(function(response, textStatus, jqXHR){ - /** - * @returns Array - */ - - var myResponse = new Array(); - myResponse.constructFromObject(response); - - callback(myResponse, textStatus, jqXHR); - }); - - - - + request.fail(function(jqXHR, textStatus, errorThrown){ + if (callback) { + var error = errorThrown || textStatus || jqXHR.statusText || 'error'; + callback(null, textStatus, jqXHR, error); + } + }); + + request.done(function(response, textStatus, jqXHR){ + + /** + * @returns Array + */ + + var myResponse = new Array(); + myResponse.constructFromObject(response); + if (callback) { + callback(myResponse, textStatus, jqXHR); + } + + }); + + return request; } /** @@ -183,7 +185,6 @@ var PetApi = function PetApi() { * @return Array */ self.findPetsByTags = function(tags, callback) { - var postBody = null; var postBinaryBody = null; @@ -194,7 +195,7 @@ var PetApi = function PetApi() { basePath = basePath.substring(0, basePath.length-1); } - var path = basePath + replaceAll(replaceAll("/pet/findByTags", "\\{format\\}","json")); + var path = basePath + replaceAll(replaceAll("/pet/findByTags", "\\{format\\}","json")); var queryParams = {}; var headerParams = {}; @@ -206,53 +207,43 @@ var PetApi = function PetApi() { - path += createQueryString(queryParams); + path += createQueryString(queryParams); - //if (console) { - //console.log('path: ' + path); - //console.log('queryParams: ' + queryParams); - //} - - - - - - //TypeRef returnType = new TypeRef() {}; - //return apiClient.invokeAPI(path, "GET", queryParams, postBody, postBinaryBody, headerParams, formParams, accept, contentType, authNames, returnType); - - var options = {type: "GET", async: true, contentType: "application/json", dataType: "json", data: postBody}; + var options = {type: "GET", async: true, contentType: "application/json", dataType: "json", data: postBody}; var request = $.ajax(path, options); - //request.fail(function(jqXHR, textStatus, errorThrown){ - // errorHandler(jqXHR, textStatus, errorThrown); - //}); - - - request.done(function(response, textStatus, jqXHR){ - /** - * @returns Array - */ - - var myResponse = new Array(); - myResponse.constructFromObject(response); - - callback(myResponse, textStatus, jqXHR); - }); - - - - + request.fail(function(jqXHR, textStatus, errorThrown){ + if (callback) { + var error = errorThrown || textStatus || jqXHR.statusText || 'error'; + callback(null, textStatus, jqXHR, error); + } + }); + + request.done(function(response, textStatus, jqXHR){ + + /** + * @returns Array + */ + + var myResponse = new Array(); + myResponse.constructFromObject(response); + if (callback) { + callback(myResponse, textStatus, jqXHR); + } + + }); + + return request; } /** * Find pet by ID * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions - * @param {Long} petId ID of pet that needs to be fetched + * @param {Integer} petId ID of pet that needs to be fetched * @param {function} callback the callback function * @return Pet */ self.getPetById = function(petId, callback) { - var postBody = null; var postBinaryBody = null; @@ -270,8 +261,8 @@ var PetApi = function PetApi() { basePath = basePath.substring(0, basePath.length-1); } - var path = basePath + replaceAll(replaceAll("/pet/{petId}", "\\{format\\}","json") -, "\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); + var path = basePath + replaceAll(replaceAll("/pet/{petId}", "\\{format\\}","json") +, "\\{" + "petId" + "\\}", encodeURIComponent(petId.toString())); var queryParams = {}; var headerParams = {}; @@ -281,42 +272,33 @@ var PetApi = function PetApi() { - path += createQueryString(queryParams); + path += createQueryString(queryParams); - //if (console) { - //console.log('path: ' + path); - //console.log('queryParams: ' + queryParams); - //} - - - - - - //TypeRef returnType = new TypeRef() {}; - //return apiClient.invokeAPI(path, "GET", queryParams, postBody, postBinaryBody, headerParams, formParams, accept, contentType, authNames, returnType); - - var options = {type: "GET", async: true, contentType: "application/json", dataType: "json", data: postBody}; + var options = {type: "GET", async: true, contentType: "application/json", dataType: "json", data: postBody}; var request = $.ajax(path, options); - //request.fail(function(jqXHR, textStatus, errorThrown){ - // errorHandler(jqXHR, textStatus, errorThrown); - //}); - - - request.done(function(response, textStatus, jqXHR){ - /** - * @returns Pet - */ - - var myResponse = new Pet(); - myResponse.constructFromObject(response); - - callback(myResponse, textStatus, jqXHR); - }); - - - - + request.fail(function(jqXHR, textStatus, errorThrown){ + if (callback) { + var error = errorThrown || textStatus || jqXHR.statusText || 'error'; + callback(null, textStatus, jqXHR, error); + } + }); + + request.done(function(response, textStatus, jqXHR){ + + /** + * @returns Pet + */ + + var myResponse = new Pet(); + myResponse.constructFromObject(response); + if (callback) { + callback(myResponse, textStatus, jqXHR); + } + + }); + + return request; } /** @@ -329,7 +311,6 @@ var PetApi = function PetApi() { * @return void */ self.updatePetWithForm = function(petId, name, status, callback) { - var postBody = null; var postBinaryBody = null; @@ -347,8 +328,8 @@ var PetApi = function PetApi() { basePath = basePath.substring(0, basePath.length-1); } - var path = basePath + replaceAll(replaceAll("/pet/{petId}", "\\{format\\}","json") -, "\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); + var path = basePath + replaceAll(replaceAll("/pet/{petId}", "\\{format\\}","json") +, "\\{" + "petId" + "\\}", encodeURIComponent(petId.toString())); var queryParams = {}; var headerParams = {}; @@ -362,34 +343,38 @@ var PetApi = function PetApi() { formParams.put("status", status); - path += createQueryString(queryParams); - - //if (console) { - //console.log('path: ' + path); - //console.log('queryParams: ' + queryParams); - //} - - - - - - apiClient.invokeAPI(path, "POST", queryParams, postBody, postBinaryBody, headerParams, formParams, accept, contentType, authNames, null); - - + path += createQueryString(queryParams); + var options = {type: "POST", async: true, contentType: "application/json", dataType: "json", data: postBody}; + var request = $.ajax(path, options); + request.fail(function(jqXHR, textStatus, errorThrown){ + if (callback) { + var error = errorThrown || textStatus || jqXHR.statusText || 'error'; + callback(null, textStatus, jqXHR, error); + } + }); + + request.done(function(response, textStatus, jqXHR){ + + if (callback) { + callback(response, textStatus, jqXHR); + } + + }); + + return request; } /** * Deletes a pet * - * @param {Long} petId Pet id to delete + * @param {Integer} petId Pet id to delete * @param {String} apiKey * @param {function} callback the callback function * @return void */ self.deletePet = function(petId, apiKey, callback) { - var postBody = null; var postBinaryBody = null; @@ -407,8 +392,8 @@ var PetApi = function PetApi() { basePath = basePath.substring(0, basePath.length-1); } - var path = basePath + replaceAll(replaceAll("/pet/{petId}", "\\{format\\}","json") -, "\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); + var path = basePath + replaceAll(replaceAll("/pet/{petId}", "\\{format\\}","json") +, "\\{" + "petId" + "\\}", encodeURIComponent(petId.toString())); var queryParams = {}; var headerParams = {}; @@ -416,39 +401,43 @@ var PetApi = function PetApi() { if (apiKey != null) - headerParams.put("api_key", apiClient.parameterToString(apiKey)); + headerParams.put("api_key", apiKey); - path += createQueryString(queryParams); - - //if (console) { - //console.log('path: ' + path); - //console.log('queryParams: ' + queryParams); - //} - - - - - - apiClient.invokeAPI(path, "DELETE", queryParams, postBody, postBinaryBody, headerParams, formParams, accept, contentType, authNames, null); - - + path += createQueryString(queryParams); + var options = {type: "DELETE", async: true, contentType: "application/json", dataType: "json", data: postBody}; + var request = $.ajax(path, options); + request.fail(function(jqXHR, textStatus, errorThrown){ + if (callback) { + var error = errorThrown || textStatus || jqXHR.statusText || 'error'; + callback(null, textStatus, jqXHR, error); + } + }); + + request.done(function(response, textStatus, jqXHR){ + + if (callback) { + callback(response, textStatus, jqXHR); + } + + }); + + return request; } /** * uploads an image * - * @param {Long} petId ID of pet to update + * @param {Integer} petId ID of pet to update * @param {String} additionalMetadata Additional data to pass to server * @param {File} file file to upload * @param {function} callback the callback function * @return void */ self.uploadFile = function(petId, additionalMetadata, file, callback) { - var postBody = null; var postBinaryBody = null; @@ -466,8 +455,8 @@ var PetApi = function PetApi() { basePath = basePath.substring(0, basePath.length-1); } - var path = basePath + replaceAll(replaceAll("/pet/{petId}/uploadImage", "\\{format\\}","json") -, "\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); + var path = basePath + replaceAll(replaceAll("/pet/{petId}/uploadImage", "\\{format\\}","json") +, "\\{" + "petId" + "\\}", encodeURIComponent(petId.toString())); var queryParams = {}; var headerParams = {}; @@ -481,25 +470,30 @@ var PetApi = function PetApi() { formParams.put("file", file); - path += createQueryString(queryParams); - - //if (console) { - //console.log('path: ' + path); - //console.log('queryParams: ' + queryParams); - //} - - - - - - apiClient.invokeAPI(path, "POST", queryParams, postBody, postBinaryBody, headerParams, formParams, accept, contentType, authNames, null); - - + path += createQueryString(queryParams); + var options = {type: "POST", async: true, contentType: "application/json", dataType: "json", data: postBody}; + var request = $.ajax(path, options); + request.fail(function(jqXHR, textStatus, errorThrown){ + if (callback) { + var error = errorThrown || textStatus || jqXHR.statusText || 'error'; + callback(null, textStatus, jqXHR, error); + } + }); + + request.done(function(response, textStatus, jqXHR){ + + if (callback) { + callback(response, textStatus, jqXHR); + } + + }); + + return request; } - + function replaceAll (haystack, needle, replace) { var result= haystack; @@ -526,3 +520,8 @@ var PetApi = function PetApi() { return queryString; } } + +// export module for Node.js +if (typeof module === 'object' && module.exports) { + module.exports = PetApi; +} diff --git a/samples/client/petstore/javascript/src/scripts/rest/api/StoreApi.js b/samples/client/petstore/javascript/src/api/StoreApi.js similarity index 54% rename from samples/client/petstore/javascript/src/scripts/rest/api/StoreApi.js rename to samples/client/petstore/javascript/src/api/StoreApi.js index 086ce8b4ae9a..e52a31059645 100644 --- a/samples/client/petstore/javascript/src/scripts/rest/api/StoreApi.js +++ b/samples/client/petstore/javascript/src/api/StoreApi.js @@ -1,10 +1,13 @@ -/* - * @javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavascriptClientCodegen", date = "2015-12-07T10:51:19.835+08:00") - */ +// require files in Node.js environment +var $, Order; +if (typeof module === 'object' && module.exports) { + $ = require('jquery'); + Order = require('../model/Order.js'); +} -//export module +// export module for AMD if ( typeof define === "function" && define.amd ) { - define(['jquery'], function($) { + define(['jquery', 'Order'], function($, Order) { return StoreApi; }); } @@ -12,14 +15,14 @@ if ( typeof define === "function" && define.amd ) { var StoreApi = function StoreApi() { var self = this; + /** * Returns pet inventories by status * Returns a map of status codes to quantities * @param {function} callback the callback function - * @return Map + * @return Object */ - self.getInventory = function(, callback) { - + self.getInventory = function(callback) { var postBody = null; var postBinaryBody = null; @@ -30,7 +33,7 @@ var StoreApi = function StoreApi() { basePath = basePath.substring(0, basePath.length-1); } - var path = basePath + replaceAll(replaceAll("/store/inventory", "\\{format\\}","json")); + var path = basePath + replaceAll(replaceAll("/store/inventory", "\\{format\\}","json")); var queryParams = {}; var headerParams = {}; @@ -40,42 +43,32 @@ var StoreApi = function StoreApi() { - path += createQueryString(queryParams); + path += createQueryString(queryParams); - //if (console) { - //console.log('path: ' + path); - //console.log('queryParams: ' + queryParams); - //} - - - - - - //TypeRef returnType = new TypeRef>() {}; - //return apiClient.invokeAPI(path, "GET", queryParams, postBody, postBinaryBody, headerParams, formParams, accept, contentType, authNames, returnType); - - var options = {type: "GET", async: true, contentType: "application/json", dataType: "json", data: postBody}; + var options = {type: "GET", async: true, contentType: "application/json", dataType: "json", data: postBody}; var request = $.ajax(path, options); - //request.fail(function(jqXHR, textStatus, errorThrown){ - // errorHandler(jqXHR, textStatus, errorThrown); - //}); - - - request.done(function(response, textStatus, jqXHR){ - /** - * @returns Map - */ - - var myResponse = new Map(); - myResponse.constructFromObject(response); - - callback(myResponse, textStatus, jqXHR); - }); - - - - + request.fail(function(jqXHR, textStatus, errorThrown){ + if (callback) { + var error = errorThrown || textStatus || jqXHR.statusText || 'error'; + callback(null, textStatus, jqXHR, error); + } + }); + + request.done(function(response, textStatus, jqXHR){ + + /** + * @returns Object + */ + var myResponse = response; + + if (callback) { + callback(myResponse, textStatus, jqXHR); + } + + }); + + return request; } /** @@ -86,7 +79,6 @@ var StoreApi = function StoreApi() { * @return Order */ self.placeOrder = function(body, callback) { - var postBody = JSON.stringify(body); var postBinaryBody = null; @@ -97,7 +89,7 @@ var StoreApi = function StoreApi() { basePath = basePath.substring(0, basePath.length-1); } - var path = basePath + replaceAll(replaceAll("/store/order", "\\{format\\}","json")); + var path = basePath + replaceAll(replaceAll("/store/order", "\\{format\\}","json")); var queryParams = {}; var headerParams = {}; @@ -107,42 +99,33 @@ var StoreApi = function StoreApi() { - path += createQueryString(queryParams); + path += createQueryString(queryParams); - //if (console) { - //console.log('path: ' + path); - //console.log('queryParams: ' + queryParams); - //} - - - - - - //TypeRef returnType = new TypeRef() {}; - //return apiClient.invokeAPI(path, "POST", queryParams, postBody, postBinaryBody, headerParams, formParams, accept, contentType, authNames, returnType); - - var options = {type: "POST", async: true, contentType: "application/json", dataType: "json", data: postBody}; + var options = {type: "POST", async: true, contentType: "application/json", dataType: "json", data: postBody}; var request = $.ajax(path, options); - //request.fail(function(jqXHR, textStatus, errorThrown){ - // errorHandler(jqXHR, textStatus, errorThrown); - //}); - - - request.done(function(response, textStatus, jqXHR){ - /** - * @returns Order - */ - - var myResponse = new Order(); - myResponse.constructFromObject(response); - - callback(myResponse, textStatus, jqXHR); - }); - - - - + request.fail(function(jqXHR, textStatus, errorThrown){ + if (callback) { + var error = errorThrown || textStatus || jqXHR.statusText || 'error'; + callback(null, textStatus, jqXHR, error); + } + }); + + request.done(function(response, textStatus, jqXHR){ + + /** + * @returns Order + */ + + var myResponse = new Order(); + myResponse.constructFromObject(response); + if (callback) { + callback(myResponse, textStatus, jqXHR); + } + + }); + + return request; } /** @@ -153,7 +136,6 @@ var StoreApi = function StoreApi() { * @return Order */ self.getOrderById = function(orderId, callback) { - var postBody = null; var postBinaryBody = null; @@ -171,8 +153,8 @@ var StoreApi = function StoreApi() { basePath = basePath.substring(0, basePath.length-1); } - var path = basePath + replaceAll(replaceAll("/store/order/{orderId}", "\\{format\\}","json") -, "\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.toString())); + var path = basePath + replaceAll(replaceAll("/store/order/{orderId}", "\\{format\\}","json") +, "\\{" + "orderId" + "\\}", encodeURIComponent(orderId.toString())); var queryParams = {}; var headerParams = {}; @@ -182,42 +164,33 @@ var StoreApi = function StoreApi() { - path += createQueryString(queryParams); + path += createQueryString(queryParams); - //if (console) { - //console.log('path: ' + path); - //console.log('queryParams: ' + queryParams); - //} - - - - - - //TypeRef returnType = new TypeRef() {}; - //return apiClient.invokeAPI(path, "GET", queryParams, postBody, postBinaryBody, headerParams, formParams, accept, contentType, authNames, returnType); - - var options = {type: "GET", async: true, contentType: "application/json", dataType: "json", data: postBody}; + var options = {type: "GET", async: true, contentType: "application/json", dataType: "json", data: postBody}; var request = $.ajax(path, options); - //request.fail(function(jqXHR, textStatus, errorThrown){ - // errorHandler(jqXHR, textStatus, errorThrown); - //}); - - - request.done(function(response, textStatus, jqXHR){ - /** - * @returns Order - */ - - var myResponse = new Order(); - myResponse.constructFromObject(response); - - callback(myResponse, textStatus, jqXHR); - }); - - - - + request.fail(function(jqXHR, textStatus, errorThrown){ + if (callback) { + var error = errorThrown || textStatus || jqXHR.statusText || 'error'; + callback(null, textStatus, jqXHR, error); + } + }); + + request.done(function(response, textStatus, jqXHR){ + + /** + * @returns Order + */ + + var myResponse = new Order(); + myResponse.constructFromObject(response); + if (callback) { + callback(myResponse, textStatus, jqXHR); + } + + }); + + return request; } /** @@ -228,7 +201,6 @@ var StoreApi = function StoreApi() { * @return void */ self.deleteOrder = function(orderId, callback) { - var postBody = null; var postBinaryBody = null; @@ -246,8 +218,8 @@ var StoreApi = function StoreApi() { basePath = basePath.substring(0, basePath.length-1); } - var path = basePath + replaceAll(replaceAll("/store/order/{orderId}", "\\{format\\}","json") -, "\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.toString())); + var path = basePath + replaceAll(replaceAll("/store/order/{orderId}", "\\{format\\}","json") +, "\\{" + "orderId" + "\\}", encodeURIComponent(orderId.toString())); var queryParams = {}; var headerParams = {}; @@ -257,25 +229,30 @@ var StoreApi = function StoreApi() { - path += createQueryString(queryParams); - - //if (console) { - //console.log('path: ' + path); - //console.log('queryParams: ' + queryParams); - //} - - - - - - apiClient.invokeAPI(path, "DELETE", queryParams, postBody, postBinaryBody, headerParams, formParams, accept, contentType, authNames, null); - - + path += createQueryString(queryParams); + var options = {type: "DELETE", async: true, contentType: "application/json", dataType: "json", data: postBody}; + var request = $.ajax(path, options); + request.fail(function(jqXHR, textStatus, errorThrown){ + if (callback) { + var error = errorThrown || textStatus || jqXHR.statusText || 'error'; + callback(null, textStatus, jqXHR, error); + } + }); + + request.done(function(response, textStatus, jqXHR){ + + if (callback) { + callback(response, textStatus, jqXHR); + } + + }); + + return request; } - + function replaceAll (haystack, needle, replace) { var result= haystack; @@ -302,3 +279,8 @@ var StoreApi = function StoreApi() { return queryString; } } + +// export module for Node.js +if (typeof module === 'object' && module.exports) { + module.exports = StoreApi; +} diff --git a/samples/client/petstore/javascript/src/scripts/rest/api/UserApi.js b/samples/client/petstore/javascript/src/api/UserApi.js similarity index 55% rename from samples/client/petstore/javascript/src/scripts/rest/api/UserApi.js rename to samples/client/petstore/javascript/src/api/UserApi.js index 53cecbdf8f74..148e6171ed40 100644 --- a/samples/client/petstore/javascript/src/scripts/rest/api/UserApi.js +++ b/samples/client/petstore/javascript/src/api/UserApi.js @@ -1,10 +1,13 @@ -/* - * @javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavascriptClientCodegen", date = "2015-12-07T10:51:19.835+08:00") - */ +// require files in Node.js environment +var $, User; +if (typeof module === 'object' && module.exports) { + $ = require('jquery'); + User = require('../model/User.js'); +} -//export module +// export module for AMD if ( typeof define === "function" && define.amd ) { - define(['jquery'], function($) { + define(['jquery', 'User'], function($, User) { return UserApi; }); } @@ -12,6 +15,7 @@ if ( typeof define === "function" && define.amd ) { var UserApi = function UserApi() { var self = this; + /** * Create user * This can only be done by the logged in user. @@ -20,7 +24,6 @@ var UserApi = function UserApi() { * @return void */ self.createUser = function(body, callback) { - var postBody = JSON.stringify(body); var postBinaryBody = null; @@ -31,7 +34,7 @@ var UserApi = function UserApi() { basePath = basePath.substring(0, basePath.length-1); } - var path = basePath + replaceAll(replaceAll("/user", "\\{format\\}","json")); + var path = basePath + replaceAll(replaceAll("/user", "\\{format\\}","json")); var queryParams = {}; var headerParams = {}; @@ -41,22 +44,27 @@ var UserApi = function UserApi() { - path += createQueryString(queryParams); - - //if (console) { - //console.log('path: ' + path); - //console.log('queryParams: ' + queryParams); - //} - - - - - - apiClient.invokeAPI(path, "POST", queryParams, postBody, postBinaryBody, headerParams, formParams, accept, contentType, authNames, null); - - + path += createQueryString(queryParams); + var options = {type: "POST", async: true, contentType: "application/json", dataType: "json", data: postBody}; + var request = $.ajax(path, options); + request.fail(function(jqXHR, textStatus, errorThrown){ + if (callback) { + var error = errorThrown || textStatus || jqXHR.statusText || 'error'; + callback(null, textStatus, jqXHR, error); + } + }); + + request.done(function(response, textStatus, jqXHR){ + + if (callback) { + callback(response, textStatus, jqXHR); + } + + }); + + return request; } /** @@ -67,7 +75,6 @@ var UserApi = function UserApi() { * @return void */ self.createUsersWithArrayInput = function(body, callback) { - var postBody = JSON.stringify(body); var postBinaryBody = null; @@ -78,7 +85,7 @@ var UserApi = function UserApi() { basePath = basePath.substring(0, basePath.length-1); } - var path = basePath + replaceAll(replaceAll("/user/createWithArray", "\\{format\\}","json")); + var path = basePath + replaceAll(replaceAll("/user/createWithArray", "\\{format\\}","json")); var queryParams = {}; var headerParams = {}; @@ -88,22 +95,27 @@ var UserApi = function UserApi() { - path += createQueryString(queryParams); - - //if (console) { - //console.log('path: ' + path); - //console.log('queryParams: ' + queryParams); - //} - - - - - - apiClient.invokeAPI(path, "POST", queryParams, postBody, postBinaryBody, headerParams, formParams, accept, contentType, authNames, null); - - + path += createQueryString(queryParams); + var options = {type: "POST", async: true, contentType: "application/json", dataType: "json", data: postBody}; + var request = $.ajax(path, options); + request.fail(function(jqXHR, textStatus, errorThrown){ + if (callback) { + var error = errorThrown || textStatus || jqXHR.statusText || 'error'; + callback(null, textStatus, jqXHR, error); + } + }); + + request.done(function(response, textStatus, jqXHR){ + + if (callback) { + callback(response, textStatus, jqXHR); + } + + }); + + return request; } /** @@ -114,7 +126,6 @@ var UserApi = function UserApi() { * @return void */ self.createUsersWithListInput = function(body, callback) { - var postBody = JSON.stringify(body); var postBinaryBody = null; @@ -125,7 +136,7 @@ var UserApi = function UserApi() { basePath = basePath.substring(0, basePath.length-1); } - var path = basePath + replaceAll(replaceAll("/user/createWithList", "\\{format\\}","json")); + var path = basePath + replaceAll(replaceAll("/user/createWithList", "\\{format\\}","json")); var queryParams = {}; var headerParams = {}; @@ -135,22 +146,27 @@ var UserApi = function UserApi() { - path += createQueryString(queryParams); - - //if (console) { - //console.log('path: ' + path); - //console.log('queryParams: ' + queryParams); - //} - - - - - - apiClient.invokeAPI(path, "POST", queryParams, postBody, postBinaryBody, headerParams, formParams, accept, contentType, authNames, null); - - + path += createQueryString(queryParams); + var options = {type: "POST", async: true, contentType: "application/json", dataType: "json", data: postBody}; + var request = $.ajax(path, options); + request.fail(function(jqXHR, textStatus, errorThrown){ + if (callback) { + var error = errorThrown || textStatus || jqXHR.statusText || 'error'; + callback(null, textStatus, jqXHR, error); + } + }); + + request.done(function(response, textStatus, jqXHR){ + + if (callback) { + callback(response, textStatus, jqXHR); + } + + }); + + return request; } /** @@ -162,7 +178,6 @@ var UserApi = function UserApi() { * @return String */ self.loginUser = function(username, password, callback) { - var postBody = null; var postBinaryBody = null; @@ -173,7 +188,7 @@ var UserApi = function UserApi() { basePath = basePath.substring(0, basePath.length-1); } - var path = basePath + replaceAll(replaceAll("/user/login", "\\{format\\}","json")); + var path = basePath + replaceAll(replaceAll("/user/login", "\\{format\\}","json")); var queryParams = {}; var headerParams = {}; @@ -187,41 +202,32 @@ var UserApi = function UserApi() { - path += createQueryString(queryParams); + path += createQueryString(queryParams); - //if (console) { - //console.log('path: ' + path); - //console.log('queryParams: ' + queryParams); - //} - - - - - - //TypeRef returnType = new TypeRef() {}; - //return apiClient.invokeAPI(path, "GET", queryParams, postBody, postBinaryBody, headerParams, formParams, accept, contentType, authNames, returnType); - - var options = {type: "GET", async: true, contentType: "application/json", dataType: "json", data: postBody}; + var options = {type: "GET", async: true, contentType: "application/json", dataType: "json", data: postBody}; var request = $.ajax(path, options); - //request.fail(function(jqXHR, textStatus, errorThrown){ - // errorHandler(jqXHR, textStatus, errorThrown); - //}); - - - request.done(function(response, textStatus, jqXHR){ - /** - * @returns String - */ - var myResponse = response; - - - callback(myResponse, textStatus, jqXHR); - }); - - - - + request.fail(function(jqXHR, textStatus, errorThrown){ + if (callback) { + var error = errorThrown || textStatus || jqXHR.statusText || 'error'; + callback(null, textStatus, jqXHR, error); + } + }); + + request.done(function(response, textStatus, jqXHR){ + + /** + * @returns String + */ + var myResponse = response; + + if (callback) { + callback(myResponse, textStatus, jqXHR); + } + + }); + + return request; } /** @@ -230,8 +236,7 @@ var UserApi = function UserApi() { * @param {function} callback the callback function * @return void */ - self.logoutUser = function(, callback) { - + self.logoutUser = function(callback) { var postBody = null; var postBinaryBody = null; @@ -242,7 +247,7 @@ var UserApi = function UserApi() { basePath = basePath.substring(0, basePath.length-1); } - var path = basePath + replaceAll(replaceAll("/user/logout", "\\{format\\}","json")); + var path = basePath + replaceAll(replaceAll("/user/logout", "\\{format\\}","json")); var queryParams = {}; var headerParams = {}; @@ -252,22 +257,27 @@ var UserApi = function UserApi() { - path += createQueryString(queryParams); - - //if (console) { - //console.log('path: ' + path); - //console.log('queryParams: ' + queryParams); - //} - - - - - - apiClient.invokeAPI(path, "GET", queryParams, postBody, postBinaryBody, headerParams, formParams, accept, contentType, authNames, null); - - + path += createQueryString(queryParams); + var options = {type: "GET", async: true, contentType: "application/json", dataType: "json", data: postBody}; + var request = $.ajax(path, options); + request.fail(function(jqXHR, textStatus, errorThrown){ + if (callback) { + var error = errorThrown || textStatus || jqXHR.statusText || 'error'; + callback(null, textStatus, jqXHR, error); + } + }); + + request.done(function(response, textStatus, jqXHR){ + + if (callback) { + callback(response, textStatus, jqXHR); + } + + }); + + return request; } /** @@ -278,7 +288,6 @@ var UserApi = function UserApi() { * @return User */ self.getUserByName = function(username, callback) { - var postBody = null; var postBinaryBody = null; @@ -296,8 +305,8 @@ var UserApi = function UserApi() { basePath = basePath.substring(0, basePath.length-1); } - var path = basePath + replaceAll(replaceAll("/user/{username}", "\\{format\\}","json") -, "\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); + var path = basePath + replaceAll(replaceAll("/user/{username}", "\\{format\\}","json") +, "\\{" + "username" + "\\}", encodeURIComponent(username.toString())); var queryParams = {}; var headerParams = {}; @@ -307,42 +316,33 @@ var UserApi = function UserApi() { - path += createQueryString(queryParams); + path += createQueryString(queryParams); - //if (console) { - //console.log('path: ' + path); - //console.log('queryParams: ' + queryParams); - //} - - - - - - //TypeRef returnType = new TypeRef() {}; - //return apiClient.invokeAPI(path, "GET", queryParams, postBody, postBinaryBody, headerParams, formParams, accept, contentType, authNames, returnType); - - var options = {type: "GET", async: true, contentType: "application/json", dataType: "json", data: postBody}; + var options = {type: "GET", async: true, contentType: "application/json", dataType: "json", data: postBody}; var request = $.ajax(path, options); - //request.fail(function(jqXHR, textStatus, errorThrown){ - // errorHandler(jqXHR, textStatus, errorThrown); - //}); - - - request.done(function(response, textStatus, jqXHR){ - /** - * @returns User - */ - - var myResponse = new User(); - myResponse.constructFromObject(response); - - callback(myResponse, textStatus, jqXHR); - }); - - - - + request.fail(function(jqXHR, textStatus, errorThrown){ + if (callback) { + var error = errorThrown || textStatus || jqXHR.statusText || 'error'; + callback(null, textStatus, jqXHR, error); + } + }); + + request.done(function(response, textStatus, jqXHR){ + + /** + * @returns User + */ + + var myResponse = new User(); + myResponse.constructFromObject(response); + if (callback) { + callback(myResponse, textStatus, jqXHR); + } + + }); + + return request; } /** @@ -354,7 +354,6 @@ var UserApi = function UserApi() { * @return void */ self.updateUser = function(username, body, callback) { - var postBody = JSON.stringify(body); var postBinaryBody = null; @@ -372,8 +371,8 @@ var UserApi = function UserApi() { basePath = basePath.substring(0, basePath.length-1); } - var path = basePath + replaceAll(replaceAll("/user/{username}", "\\{format\\}","json") -, "\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); + var path = basePath + replaceAll(replaceAll("/user/{username}", "\\{format\\}","json") +, "\\{" + "username" + "\\}", encodeURIComponent(username.toString())); var queryParams = {}; var headerParams = {}; @@ -383,22 +382,27 @@ var UserApi = function UserApi() { - path += createQueryString(queryParams); - - //if (console) { - //console.log('path: ' + path); - //console.log('queryParams: ' + queryParams); - //} - - - - - - apiClient.invokeAPI(path, "PUT", queryParams, postBody, postBinaryBody, headerParams, formParams, accept, contentType, authNames, null); - - + path += createQueryString(queryParams); + var options = {type: "PUT", async: true, contentType: "application/json", dataType: "json", data: postBody}; + var request = $.ajax(path, options); + request.fail(function(jqXHR, textStatus, errorThrown){ + if (callback) { + var error = errorThrown || textStatus || jqXHR.statusText || 'error'; + callback(null, textStatus, jqXHR, error); + } + }); + + request.done(function(response, textStatus, jqXHR){ + + if (callback) { + callback(response, textStatus, jqXHR); + } + + }); + + return request; } /** @@ -409,7 +413,6 @@ var UserApi = function UserApi() { * @return void */ self.deleteUser = function(username, callback) { - var postBody = null; var postBinaryBody = null; @@ -427,8 +430,8 @@ var UserApi = function UserApi() { basePath = basePath.substring(0, basePath.length-1); } - var path = basePath + replaceAll(replaceAll("/user/{username}", "\\{format\\}","json") -, "\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); + var path = basePath + replaceAll(replaceAll("/user/{username}", "\\{format\\}","json") +, "\\{" + "username" + "\\}", encodeURIComponent(username.toString())); var queryParams = {}; var headerParams = {}; @@ -438,25 +441,30 @@ var UserApi = function UserApi() { - path += createQueryString(queryParams); - - //if (console) { - //console.log('path: ' + path); - //console.log('queryParams: ' + queryParams); - //} - - - - - - apiClient.invokeAPI(path, "DELETE", queryParams, postBody, postBinaryBody, headerParams, formParams, accept, contentType, authNames, null); - - + path += createQueryString(queryParams); + var options = {type: "DELETE", async: true, contentType: "application/json", dataType: "json", data: postBody}; + var request = $.ajax(path, options); + request.fail(function(jqXHR, textStatus, errorThrown){ + if (callback) { + var error = errorThrown || textStatus || jqXHR.statusText || 'error'; + callback(null, textStatus, jqXHR, error); + } + }); + + request.done(function(response, textStatus, jqXHR){ + + if (callback) { + callback(response, textStatus, jqXHR); + } + + }); + + return request; } - + function replaceAll (haystack, needle, replace) { var result= haystack; @@ -483,3 +491,8 @@ var UserApi = function UserApi() { return queryString; } } + +// export module for Node.js +if (typeof module === 'object' && module.exports) { + module.exports = UserApi; +} diff --git a/samples/client/petstore/javascript/src/index.js b/samples/client/petstore/javascript/src/index.js new file mode 100644 index 000000000000..b772f6024dca --- /dev/null +++ b/samples/client/petstore/javascript/src/index.js @@ -0,0 +1,22 @@ +if (typeof module === 'object' && module.exports) { + var SwaggerPetstore = {}; + + SwaggerPetstore.User = require('./model/User.js'); + + SwaggerPetstore.Category = require('./model/Category.js'); + + SwaggerPetstore.Pet = require('./model/Pet.js'); + + SwaggerPetstore.Tag = require('./model/Tag.js'); + + SwaggerPetstore.Order = require('./model/Order.js'); + + + SwaggerPetstore.UserApi = require('./api/UserApi.js'); + + SwaggerPetstore.StoreApi = require('./api/StoreApi.js'); + + SwaggerPetstore.PetApi = require('./api/PetApi.js'); + + module.exports = SwaggerPetstore; +} \ No newline at end of file diff --git a/samples/client/petstore/javascript/src/model/Category.js b/samples/client/petstore/javascript/src/model/Category.js new file mode 100644 index 000000000000..ff40497a61a0 --- /dev/null +++ b/samples/client/petstore/javascript/src/model/Category.js @@ -0,0 +1,81 @@ +// require files in Node.js environment + +if (typeof module === 'object' && module.exports) { + +} + + + + +//export module +if ( typeof define === "function" && define.amd ) { + define('Category', ['jquery'], + function($) { + return Category; + }); +} + + +var Category = function Category() { + var self = this; + + /** + * datatype: Integer + **/ + self.id = null; + + /** + * datatype: String + **/ + self.name = null; + + + self.constructFromObject = function(data) { + if (!data) { + return; + } + + self.id = data.id; + + self.name = data.name; + + } + + + /** + * @return {Integer} + **/ + self.getId = function() { + return self.id; + } + + /** + * @param {Integer} id + **/ + self.setId = function (id) { + self.id = id; + } + + /** + * @return {String} + **/ + self.getName = function() { + return self.name; + } + + /** + * @param {String} name + **/ + self.setName = function (name) { + self.name = name; + } + + + self.toJson = function () { + return JSON.stringify(self); + } +} + +if (typeof module === 'object' && module.exports) { + module.exports = Category; +} diff --git a/samples/client/petstore/javascript/src/scripts/rest/model/Order.js b/samples/client/petstore/javascript/src/model/Order.js similarity index 59% rename from samples/client/petstore/javascript/src/scripts/rest/model/Order.js rename to samples/client/petstore/javascript/src/model/Order.js index 73618cef8889..3cf2335b5356 100644 --- a/samples/client/petstore/javascript/src/scripts/rest/model/Order.js +++ b/samples/client/petstore/javascript/src/model/Order.js @@ -1,3 +1,9 @@ +// require files in Node.js environment + +if (typeof module === 'object' && module.exports) { + +} + //export module @@ -30,89 +36,92 @@ var StatusEnum = function StatusEnum() { //export module -if ( typeof define === "function" && define.amd ) { - define('Order', ['jquery', 'Date'], - function($, Date) { - return Order; - }); +if ( typeof define === "function" && define.amd ) { + define('Order', ['jquery'], + function($) { + return Order; + }); } var Order = function Order() { - var self = this; - - /** - * datatype: Long - **/ - self.id = null; - - /** - * datatype: Long - **/ - self.petId = null; - - /** - * datatype: Integer - **/ - self.quantity = null; - - /** - * datatype: Date - **/ - self.shipDate = null; - - /** - * Order Status - * datatype: StatusEnum - **/ - self.status = null; - - /** - * datatype: Boolean - **/ - self.complete = null; - - - self.constructFromObject = function(data) { - - self.id = data.id; - - self.petId = data.petId; - - self.quantity = data.quantity; - - self.shipDate = data.shipDate; - - self.status = data.status; - - self.complete = data.complete; - - } - + var self = this; /** - * @return {Long} + * datatype: Integer + **/ + self.id = null; + + /** + * datatype: Integer + **/ + self.petId = null; + + /** + * datatype: Integer + **/ + self.quantity = null; + + /** + * datatype: Date + **/ + self.shipDate = null; + + /** + * Order Status + * datatype: StatusEnum + **/ + self.status = null; + + /** + * datatype: Boolean + **/ + self.complete = null; + + + self.constructFromObject = function(data) { + if (!data) { + return; + } + + self.id = data.id; + + self.petId = data.petId; + + self.quantity = data.quantity; + + self.shipDate = data.shipDate; + + self.status = data.status; + + self.complete = data.complete; + + } + + + /** + * @return {Integer} **/ self.getId = function() { return self.id; } - + /** - * @param {Long} id + * @param {Integer} id **/ self.setId = function (id) { self.id = id; } /** - * @return {Long} + * @return {Integer} **/ self.getPetId = function() { return self.petId; } - + /** - * @param {Long} petId + * @param {Integer} petId **/ self.setPetId = function (petId) { self.petId = petId; @@ -124,7 +133,7 @@ var Order = function Order() { self.getQuantity = function() { return self.quantity; } - + /** * @param {Integer} quantity **/ @@ -138,7 +147,7 @@ var Order = function Order() { self.getShipDate = function() { return self.shipDate; } - + /** * @param {Date} shipDate **/ @@ -153,7 +162,7 @@ var Order = function Order() { self.getStatus = function() { return self.status; } - + /** * set Order Status * @param {StatusEnum} status @@ -168,7 +177,7 @@ var Order = function Order() { self.getComplete = function() { return self.complete; } - + /** * @param {Boolean} complete **/ @@ -178,6 +187,10 @@ var Order = function Order() { self.toJson = function () { - return JSON.stringify(self); + return JSON.stringify(self); } } + +if (typeof module === 'object' && module.exports) { + module.exports = Order; +} diff --git a/samples/client/petstore/javascript/src/scripts/rest/model/Pet.js b/samples/client/petstore/javascript/src/model/Pet.js similarity index 56% rename from samples/client/petstore/javascript/src/scripts/rest/model/Pet.js rename to samples/client/petstore/javascript/src/model/Pet.js index e3f3a747c84c..25ae2e951c80 100644 --- a/samples/client/petstore/javascript/src/scripts/rest/model/Pet.js +++ b/samples/client/petstore/javascript/src/model/Pet.js @@ -1,3 +1,11 @@ +// require files in Node.js environment +var Category;var Tag; +if (typeof module === 'object' && module.exports) { + + Category = require('./Category.js'); + Tag = require('./Tag.js'); +} + //export module @@ -30,77 +38,80 @@ var StatusEnum = function StatusEnum() { //export module -if ( typeof define === "function" && define.amd ) { - define('Pet', ['jquery', 'Category', 'Array'], - function($, Category, Array) { - return Pet; - }); +if ( typeof define === "function" && define.amd ) { + define('Pet', ['jquery', 'Category', 'Array'], + function($, Category, Array) { + return Pet; + }); } -var Pet = function Pet(name, photoUrls) { - var self = this; - - /** - * datatype: Long - **/ - self.id = null; - - /** - * datatype: Category - **/ - self.category = new Category(); - - /** - * datatype: String - * required - **/ - self.name = name; - - /** - * datatype: Array - * required - **/ - self.photoUrls = photoUrls; - - /** - * datatype: Array - **/ - self.tags = new Array(); - - /** - * pet status in the store - * datatype: StatusEnum - **/ - self.status = null; - - - self.constructFromObject = function(data) { - - self.id = data.id; - - self.category.constructFromObject(data.category); - - self.name = data.name; - - self.photoUrls = new Array(); - - self.tags = new Array(); - - self.status = data.status; - - } - +var Pet = function Pet(photoUrls, name) { + var self = this; /** - * @return {Long} + * datatype: Integer + **/ + self.id = null; + + /** + * datatype: Category + **/ + self.category = new Category(); + + /** + * datatype: String + * required + **/ + self.name = name; + + /** + * datatype: Array + * required + **/ + self.photoUrls = photoUrls; + + /** + * datatype: Array + **/ + self.tags = []; + + /** + * pet status in the store + * datatype: StatusEnum + **/ + self.status = null; + + + self.constructFromObject = function(data) { + if (!data) { + return; + } + + self.id = data.id; + + self.category.constructFromObject(data.category); + + self.name = data.name; + + self.photoUrls = new Array(); + + self.tags = new Array(); + + self.status = data.status; + + } + + + /** + * @return {Integer} **/ self.getId = function() { return self.id; } - + /** - * @param {Long} id + * @param {Integer} id **/ self.setId = function (id) { self.id = id; @@ -112,7 +123,7 @@ var Pet = function Pet(name, photoUrls) { self.getCategory = function() { return self.category; } - + /** * @param {Category} category **/ @@ -126,7 +137,7 @@ var Pet = function Pet(name, photoUrls) { self.getName = function() { return self.name; } - + /** * @param {String} name **/ @@ -140,7 +151,7 @@ var Pet = function Pet(name, photoUrls) { self.getPhotoUrls = function() { return self.photoUrls; } - + /** * @param {Array} photoUrls **/ @@ -154,7 +165,7 @@ var Pet = function Pet(name, photoUrls) { self.getTags = function() { return self.tags; } - + /** * @param {Array} tags **/ @@ -169,7 +180,7 @@ var Pet = function Pet(name, photoUrls) { self.getStatus = function() { return self.status; } - + /** * set pet status in the store * @param {StatusEnum} status @@ -180,6 +191,10 @@ var Pet = function Pet(name, photoUrls) { self.toJson = function () { - return JSON.stringify(self); + return JSON.stringify(self); } } + +if (typeof module === 'object' && module.exports) { + module.exports = Pet; +} diff --git a/samples/client/petstore/javascript/src/model/Tag.js b/samples/client/petstore/javascript/src/model/Tag.js new file mode 100644 index 000000000000..0fa97bd8c78a --- /dev/null +++ b/samples/client/petstore/javascript/src/model/Tag.js @@ -0,0 +1,81 @@ +// require files in Node.js environment + +if (typeof module === 'object' && module.exports) { + +} + + + + +//export module +if ( typeof define === "function" && define.amd ) { + define('Tag', ['jquery'], + function($) { + return Tag; + }); +} + + +var Tag = function Tag() { + var self = this; + + /** + * datatype: Integer + **/ + self.id = null; + + /** + * datatype: String + **/ + self.name = null; + + + self.constructFromObject = function(data) { + if (!data) { + return; + } + + self.id = data.id; + + self.name = data.name; + + } + + + /** + * @return {Integer} + **/ + self.getId = function() { + return self.id; + } + + /** + * @param {Integer} id + **/ + self.setId = function (id) { + self.id = id; + } + + /** + * @return {String} + **/ + self.getName = function() { + return self.name; + } + + /** + * @param {String} name + **/ + self.setName = function (name) { + self.name = name; + } + + + self.toJson = function () { + return JSON.stringify(self); + } +} + +if (typeof module === 'object' && module.exports) { + module.exports = Tag; +} diff --git a/samples/client/petstore/javascript/src/scripts/rest/model/User.js b/samples/client/petstore/javascript/src/model/User.js similarity index 58% rename from samples/client/petstore/javascript/src/scripts/rest/model/User.js rename to samples/client/petstore/javascript/src/model/User.js index 19afab44ee68..632208a523c8 100644 --- a/samples/client/petstore/javascript/src/scripts/rest/model/User.js +++ b/samples/client/petstore/javascript/src/model/User.js @@ -1,90 +1,99 @@ +// require files in Node.js environment + +if (typeof module === 'object' && module.exports) { + +} + //export module -if ( typeof define === "function" && define.amd ) { - define('User', ['jquery'], - function($) { - return User; - }); +if ( typeof define === "function" && define.amd ) { + define('User', ['jquery'], + function($) { + return User; + }); } var User = function User() { - var self = this; - - /** - * datatype: Long - **/ - self.id = null; - - /** - * datatype: String - **/ - self.username = null; - - /** - * datatype: String - **/ - self.firstName = null; - - /** - * datatype: String - **/ - self.lastName = null; - - /** - * datatype: String - **/ - self.email = null; - - /** - * datatype: String - **/ - self.password = null; - - /** - * datatype: String - **/ - self.phone = null; - - /** - * User Status - * datatype: Integer - **/ - self.userStatus = null; - - - self.constructFromObject = function(data) { - - self.id = data.id; - - self.username = data.username; - - self.firstName = data.firstName; - - self.lastName = data.lastName; - - self.email = data.email; - - self.password = data.password; - - self.phone = data.phone; - - self.userStatus = data.userStatus; - - } - + var self = this; /** - * @return {Long} + * datatype: Integer + **/ + self.id = null; + + /** + * datatype: String + **/ + self.username = null; + + /** + * datatype: String + **/ + self.firstName = null; + + /** + * datatype: String + **/ + self.lastName = null; + + /** + * datatype: String + **/ + self.email = null; + + /** + * datatype: String + **/ + self.password = null; + + /** + * datatype: String + **/ + self.phone = null; + + /** + * User Status + * datatype: Integer + **/ + self.userStatus = null; + + + self.constructFromObject = function(data) { + if (!data) { + return; + } + + self.id = data.id; + + self.username = data.username; + + self.firstName = data.firstName; + + self.lastName = data.lastName; + + self.email = data.email; + + self.password = data.password; + + self.phone = data.phone; + + self.userStatus = data.userStatus; + + } + + + /** + * @return {Integer} **/ self.getId = function() { return self.id; } - + /** - * @param {Long} id + * @param {Integer} id **/ self.setId = function (id) { self.id = id; @@ -96,7 +105,7 @@ var User = function User() { self.getUsername = function() { return self.username; } - + /** * @param {String} username **/ @@ -110,7 +119,7 @@ var User = function User() { self.getFirstName = function() { return self.firstName; } - + /** * @param {String} firstName **/ @@ -124,7 +133,7 @@ var User = function User() { self.getLastName = function() { return self.lastName; } - + /** * @param {String} lastName **/ @@ -138,7 +147,7 @@ var User = function User() { self.getEmail = function() { return self.email; } - + /** * @param {String} email **/ @@ -152,7 +161,7 @@ var User = function User() { self.getPassword = function() { return self.password; } - + /** * @param {String} password **/ @@ -166,7 +175,7 @@ var User = function User() { self.getPhone = function() { return self.phone; } - + /** * @param {String} phone **/ @@ -181,7 +190,7 @@ var User = function User() { self.getUserStatus = function() { return self.userStatus; } - + /** * set User Status * @param {Integer} userStatus @@ -192,6 +201,10 @@ var User = function User() { self.toJson = function () { - return JSON.stringify(self); + return JSON.stringify(self); } } + +if (typeof module === 'object' && module.exports) { + module.exports = User; +} diff --git a/samples/client/petstore/javascript/src/scripts/rest/model/Category.js b/samples/client/petstore/javascript/src/scripts/rest/model/Category.js deleted file mode 100644 index aec80bf36355..000000000000 --- a/samples/client/petstore/javascript/src/scripts/rest/model/Category.js +++ /dev/null @@ -1,68 +0,0 @@ - - - -//export module -if ( typeof define === "function" && define.amd ) { - define('Category', ['jquery'], - function($) { - return Category; - }); -} - - -var Category = function Category() { - var self = this; - - /** - * datatype: Long - **/ - self.id = null; - - /** - * datatype: String - **/ - self.name = null; - - - self.constructFromObject = function(data) { - - self.id = data.id; - - self.name = data.name; - - } - - - /** - * @return {Long} - **/ - self.getId = function() { - return self.id; - } - - /** - * @param {Long} id - **/ - self.setId = function (id) { - self.id = id; - } - - /** - * @return {String} - **/ - self.getName = function() { - return self.name; - } - - /** - * @param {String} name - **/ - self.setName = function (name) { - self.name = name; - } - - - self.toJson = function () { - return JSON.stringify(self); - } -} diff --git a/samples/client/petstore/javascript/src/scripts/rest/model/Tag.js b/samples/client/petstore/javascript/src/scripts/rest/model/Tag.js deleted file mode 100644 index 07994ec3dc93..000000000000 --- a/samples/client/petstore/javascript/src/scripts/rest/model/Tag.js +++ /dev/null @@ -1,68 +0,0 @@ - - - -//export module -if ( typeof define === "function" && define.amd ) { - define('Tag', ['jquery'], - function($) { - return Tag; - }); -} - - -var Tag = function Tag() { - var self = this; - - /** - * datatype: Long - **/ - self.id = null; - - /** - * datatype: String - **/ - self.name = null; - - - self.constructFromObject = function(data) { - - self.id = data.id; - - self.name = data.name; - - } - - - /** - * @return {Long} - **/ - self.getId = function() { - return self.id; - } - - /** - * @param {Long} id - **/ - self.setId = function (id) { - self.id = id; - } - - /** - * @return {String} - **/ - self.getName = function() { - return self.name; - } - - /** - * @param {String} name - **/ - self.setName = function (name) { - self.name = name; - } - - - self.toJson = function () { - return JSON.stringify(self); - } -} diff --git a/samples/client/petstore/javascript/test/api/PetApiTest.js b/samples/client/petstore/javascript/test/api/PetApiTest.js new file mode 100644 index 000000000000..325cc16b616a --- /dev/null +++ b/samples/client/petstore/javascript/test/api/PetApiTest.js @@ -0,0 +1,189 @@ +if (typeof module === 'object' && module.exports) { + var expect = require('expect.js'); + var requireApiWithMocks = require('../helper.js').requireApiWithMocks; + var PetApi = requireApiWithMocks('PetApi'); + var Pet = require('../../src/model/Pet'); + var Category = require('../../src/model/Category'); + var Tag = require('../../src/model/Tag'); +} + +var api; + +beforeEach(function() { + api = new PetApi(); +}); + +var createRandomPet = function() { + var id = new Date().getTime(); + var pet = new Pet(); + pet.setId(id); + pet.setName("gorilla" + id); + + var category = new Category(); + category.setName("really-happy"); + pet.setCategory(category); + + pet.setStatus('available'); + var photos = ["http://foo.bar.com/1", "http://foo.bar.com/2"]; + pet.setPhotoUrls(photos); + + return pet; +}; + +describe('PetApi', function() { + it('should create and get pet', function (done) { + var pet = createRandomPet(); + api.addPet(pet).then(function() { + api.getPetById(pet.id, function(fetched, textStatus, jqXHR, error) { + if (error) throw error; + + expect(textStatus).to.be('success'); + expect(fetched).to.be.ok(); + expect(fetched.id).to.be(pet.id); + expect(fetched.getCategory()).to.be.ok(); + expect(fetched.getCategory().getName()).to.be(pet.getCategory().getName()); + + api.deletePet(pet.id); + done(); + }); + }, function(jqXHR, textStatus, errorThrown) { + throw errorThrown || textStatus; + }); + }); +}); + +/* + @Test + public void testUpdatePet() throws Exception { + Pet pet = createRandomPet(); + pet.setName("programmer"); + + api.updatePet(pet); + + Pet fetched = api.getPetById(pet.getId()); + assertNotNull(fetched); + assertEquals(pet.getId(), fetched.getId()); + assertNotNull(fetched.getCategory()); + assertEquals(fetched.getCategory().getName(), pet.getCategory().getName()); + } + + @Test + public void testFindPetsByStatus() throws Exception { + Pet pet = createRandomPet(); + pet.setName("programmer"); + pet.setStatus(Pet.StatusEnum.AVAILABLE); + + api.updatePet(pet); + + List pets = api.findPetsByStatus(Arrays.asList(new String[]{"available"})); + assertNotNull(pets); + + boolean found = false; + for (Pet fetched : pets) { + if (fetched.getId().equals(pet.getId())) { + found = true; + break; + } + } + + assertTrue(found); + } + + @Test + public void testFindPetsByTags() throws Exception { + Pet pet = createRandomPet(); + pet.setName("monster"); + pet.setStatus(Pet.StatusEnum.AVAILABLE); + + List tags = new ArrayList(); + Tag tag1 = new Tag(); + tag1.setName("friendly"); + tags.add(tag1); + pet.setTags(tags); + + api.updatePet(pet); + + List pets = api.findPetsByTags(Arrays.asList(new String[]{"friendly"})); + assertNotNull(pets); + + boolean found = false; + for (Pet fetched : pets) { + if (fetched.getId().equals(pet.getId())) { + found = true; + break; + } + } + assertTrue(found); + } + + @Test + public void testUpdatePetWithForm() throws Exception { + Pet pet = createRandomPet(); + pet.setName("frank"); + api.addPet(pet); + + Pet fetched = api.getPetById(pet.getId()); + + api.updatePetWithForm(String.valueOf(fetched.getId()), "furt", null); + Pet updated = api.getPetById(fetched.getId()); + + assertEquals(updated.getName(), "furt"); + } + + @Test + public void testDeletePet() throws Exception { + Pet pet = createRandomPet(); + api.addPet(pet); + + Pet fetched = api.getPetById(pet.getId()); + api.deletePet(fetched.getId(), null); + + try { + fetched = api.getPetById(fetched.getId()); + fail("expected an error"); + } catch (ApiException e) { + assertEquals(404, e.getCode()); + } + } + + @Test + public void testUploadFile() throws Exception { + Pet pet = createRandomPet(); + api.addPet(pet); + + File file = new File("hello.txt"); + BufferedWriter writer = new BufferedWriter(new FileWriter(file)); + writer.write("Hello world!"); + writer.close(); + + api.uploadFile(pet.getId(), "a test file", new File(file.getAbsolutePath())); + } + + @Test + public void testEqualsAndHashCode() { + Pet pet1 = new Pet(); + Pet pet2 = new Pet(); + assertTrue(pet1.equals(pet2)); + assertTrue(pet2.equals(pet1)); + assertTrue(pet1.hashCode() == pet2.hashCode()); + assertTrue(pet1.equals(pet1)); + assertTrue(pet1.hashCode() == pet1.hashCode()); + + pet2.setName("really-happy"); + pet2.setPhotoUrls(Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"})); + assertFalse(pet1.equals(pet2)); + assertFalse(pet2.equals(pet1)); + assertFalse(pet1.hashCode() == (pet2.hashCode())); + assertTrue(pet2.equals(pet2)); + assertTrue(pet2.hashCode() == pet2.hashCode()); + + pet1.setName("really-happy"); + pet1.setPhotoUrls(Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"})); + assertTrue(pet1.equals(pet2)); + assertTrue(pet2.equals(pet1)); + assertTrue(pet1.hashCode() == pet2.hashCode()); + assertTrue(pet1.equals(pet1)); + assertTrue(pet1.hashCode() == pet1.hashCode()); + } +} +*/ diff --git a/samples/client/petstore/javascript/test/api/StoreApiTest.java b/samples/client/petstore/javascript/test/api/StoreApiTest.java new file mode 100644 index 000000000000..6094f2242e11 --- /dev/null +++ b/samples/client/petstore/javascript/test/api/StoreApiTest.java @@ -0,0 +1,75 @@ +package io.swagger.petstore.test; + +import io.swagger.client.ApiException; + +import io.swagger.client.*; +import io.swagger.client.api.*; +import io.swagger.client.auth.*; +import io.swagger.client.model.*; + +import java.util.Map; +import java.text.SimpleDateFormat; + +import org.junit.*; +import static org.junit.Assert.*; + +public class StoreApiTest { + StoreApi api = null; + + @Before + public void setup() { + api = new StoreApi(); + // setup authentication + ApiKeyAuth apiKeyAuth = (ApiKeyAuth) api.getApiClient().getAuthentication("api_key"); + apiKeyAuth.setApiKey("special-key"); + // set custom date format that is used by the petstore server + api.getApiClient().setDateFormat(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ")); + } + + @Test + public void testGetInventory() throws Exception { + Map inventory = api.getInventory(); + assertTrue(inventory.keySet().size() > 0); + } + + @Test + public void testPlaceOrder() throws Exception { + Order order = createOrder(); + api.placeOrder(order); + + Order fetched = api.getOrderById(String.valueOf(order.getId())); + assertEquals(order.getId(), fetched.getId()); + assertEquals(order.getPetId(), fetched.getPetId()); + assertEquals(order.getQuantity(), fetched.getQuantity()); + } + + @Test + public void testDeleteOrder() throws Exception { + Order order = createOrder(); + api.placeOrder(order); + + Order fetched = api.getOrderById(String.valueOf(order.getId())); + assertEquals(fetched.getId(), order.getId()); + + api.deleteOrder(String.valueOf(order.getId())); + + try { + api.getOrderById(String.valueOf(order.getId())); + // fail("expected an error"); + } catch (ApiException e) { + // ok + } + } + + private Order createOrder() { + Order order = new Order(); + order.setId(new Long(System.currentTimeMillis())); + order.setPetId(new Long(200)); + order.setQuantity(new Integer(13)); + order.setShipDate(new java.util.Date()); + order.setStatus(Order.StatusEnum.PLACED); + order.setComplete(true); + + return order; + } +} diff --git a/samples/client/petstore/javascript/test/api/UserApiTest.java b/samples/client/petstore/javascript/test/api/UserApiTest.java new file mode 100644 index 000000000000..a3f257f568bf --- /dev/null +++ b/samples/client/petstore/javascript/test/api/UserApiTest.java @@ -0,0 +1,86 @@ +package io.swagger.petstore.test; + +import io.swagger.client.api.*; +import io.swagger.client.auth.*; +import io.swagger.client.model.*; + +import java.util.Arrays; + +import org.junit.*; +import static org.junit.Assert.*; + +public class UserApiTest { + UserApi api = null; + + @Before + public void setup() { + api = new UserApi(); + // setup authentication + ApiKeyAuth apiKeyAuth = (ApiKeyAuth) api.getApiClient().getAuthentication("api_key"); + apiKeyAuth.setApiKey("special-key"); + } + + @Test + public void testCreateUser() throws Exception { + User user = createUser(); + + api.createUser(user); + + User fetched = api.getUserByName(user.getUsername()); + assertEquals(user.getId(), fetched.getId()); + } + + @Test + public void testCreateUsersWithArray() throws Exception { + User user1 = createUser(); + user1.setUsername("abc123"); + User user2 = createUser(); + user2.setUsername("123abc"); + + api.createUsersWithArrayInput(Arrays.asList(new User[]{user1, user2})); + + User fetched = api.getUserByName(user1.getUsername()); + assertEquals(user1.getId(), fetched.getId()); + } + + @Test + public void testCreateUsersWithList() throws Exception { + User user1 = createUser(); + user1.setUsername("abc123"); + User user2 = createUser(); + user2.setUsername("123abc"); + + api.createUsersWithListInput(Arrays.asList(new User[]{user1, user2})); + + User fetched = api.getUserByName(user1.getUsername()); + assertEquals(user1.getId(), fetched.getId()); + } + + @Test + public void testLoginUser() throws Exception { + User user = createUser(); + api.createUser(user); + + String token = api.loginUser(user.getUsername(), user.getPassword()); + assertTrue(token.startsWith("logged in user session:")); + } + + @Test + public void logoutUser() throws Exception { + api.logoutUser(); + } + + private User createUser() { + User user = new User(); + user.setId(System.currentTimeMillis()); + user.setUsername("fred" + user.getId()); + user.setFirstName("Fred"); + user.setLastName("Meyer"); + user.setEmail("fred@fredmeyer.com"); + user.setPassword("xxXXxx"); + user.setPhone("408-867-5309"); + user.setUserStatus(123); + + return user; + } +} diff --git a/samples/client/petstore/javascript/test/helper.js b/samples/client/petstore/javascript/test/helper.js new file mode 100644 index 000000000000..018b6428af66 --- /dev/null +++ b/samples/client/petstore/javascript/test/helper.js @@ -0,0 +1,19 @@ +var mockrequire = require('mockrequire'); + +var jquery = require('jquery'); +var domino = require('domino'); +var XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest; +var window = domino.createWindow(); +var $ = jquery(window); +$.support.cors = true; +$.ajaxSettings.xhr = function() { + return new XMLHttpRequest(); +}; + +var requireApiWithMocks = function(path) { + return mockrequire('../src/api/' + path, { + 'jquery': $ + }); +}; + +exports.requireApiWithMocks = requireApiWithMocks; diff --git a/samples/client/petstore/javascript/test/mocha.opts b/samples/client/petstore/javascript/test/mocha.opts new file mode 100644 index 000000000000..907011807d68 --- /dev/null +++ b/samples/client/petstore/javascript/test/mocha.opts @@ -0,0 +1 @@ +--timeout 10000 diff --git a/samples/client/petstore/javascript/test/run_tests.html b/samples/client/petstore/javascript/test/run_tests.html new file mode 100644 index 000000000000..c5655275cc52 --- /dev/null +++ b/samples/client/petstore/javascript/test/run_tests.html @@ -0,0 +1,33 @@ + + + + Mocha Tests + + + +
+ + + + + + + + + + + + + + + + diff --git a/samples/client/petstore/objc/SwaggerClient/SWGApiClient.m b/samples/client/petstore/objc/SwaggerClient/SWGApiClient.m index dcd33575fc6f..4dce6d2fa8bc 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGApiClient.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGApiClient.m @@ -128,24 +128,25 @@ static void (^reachabilityChangeBlock)(int); /* * Detect `Accept` from accepts */ -+ (NSString *) selectHeaderAccept:(NSArray *)accepts -{ ++ (NSString *) selectHeaderAccept:(NSArray *)accepts { if (accepts == nil || [accepts count] == 0) { return @""; } NSMutableArray *lowerAccepts = [[NSMutableArray alloc] initWithCapacity:[accepts count]]; - [accepts enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { - [lowerAccepts addObject:[obj lowercaseString]]; - }]; - - - if ([lowerAccepts containsObject:@"application/json"]) { - return @"application/json"; + for (NSString *string in accepts) { + NSString * lowerAccept = [string lowercaseString]; + if ([lowerAccept containsString:@"application/json"]) { + return @"application/json"; + } + [lowerAccepts addObject:lowerAccept]; } - else { - return [lowerAccepts componentsJoinedByString:@", "]; + + if (lowerAccepts.count == 1) { + return [lowerAccepts firstObject]; } + + return [lowerAccepts componentsJoinedByString:@", "]; } /* @@ -171,7 +172,7 @@ static void (^reachabilityChangeBlock)(int); } + (NSString*)escape:(id)unescaped { - if([unescaped isKindOfClass:[NSString class]]){ + if ([unescaped isKindOfClass:[NSString class]]){ return (NSString *)CFBridgingRelease (CFURLCreateStringByAddingPercentEscapes( NULL, @@ -212,7 +213,7 @@ static void (^reachabilityChangeBlock)(int); -(Boolean) executeRequestWithId:(NSNumber*) requestId { NSSet* matchingItems = [queuedRequests objectsPassingTest:^BOOL(id obj, BOOL *stop) { - if([obj intValue] == [requestId intValue]) { + if ([obj intValue] == [requestId intValue]) { return YES; } else { @@ -220,7 +221,7 @@ static void (^reachabilityChangeBlock)(int); } }]; - if(matchingItems.count == 1) { + if (matchingItems.count == 1) { SWGDebugLog(@"removed request id %@", requestId); [queuedRequests removeObject:requestId]; return YES; @@ -268,7 +269,7 @@ static void (^reachabilityChangeBlock)(int); } // call the reachability block, if configured - if(reachabilityChangeBlock != nil) { + if (reachabilityChangeBlock != nil) { reachabilityChangeBlock(status); } }]; @@ -410,16 +411,16 @@ static void (^reachabilityChangeBlock)(int); completionBlock: (void (^)(id, NSError *))completionBlock { AFHTTPRequestOperation *op = [self HTTPRequestOperationWithRequest:request success:^(AFHTTPRequestOperation *operation, id response) { - if([self executeRequestWithId:requestId]) { + if ([self executeRequestWithId:requestId]) { [self logResponse:operation forRequest:request error:nil]; NSDictionary *responseHeaders = [[operation response] allHeaderFields]; self.HTTPResponseHeaders = responseHeaders; completionBlock(response, nil); } } failure:^(AFHTTPRequestOperation *operation, NSError *error) { - if([self executeRequestWithId:requestId]) { + if ([self executeRequestWithId:requestId]) { NSMutableDictionary *userInfo = [error.userInfo mutableCopy]; - if(operation.responseObject) { + if (operation.responseObject) { // Add in the (parsed) response body. userInfo[SWGResponseObjectErrorKey] = operation.responseObject; } @@ -590,10 +591,10 @@ static void (^reachabilityChangeBlock)(int); // request cache BOOL hasHeaderParams = false; - if(headerParams != nil && [headerParams count] > 0) { + if (headerParams != nil && [headerParams count] > 0) { hasHeaderParams = true; } - if(offlineState) { + if (offlineState) { SWGDebugLog(@"%@ cache forced", resourcePath); [request setCachePolicy:NSURLRequestReturnCacheDataDontLoad]; } @@ -606,7 +607,7 @@ static void (^reachabilityChangeBlock)(int); [request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData]; } - if(hasHeaderParams){ + if (hasHeaderParams){ for(NSString * key in [headerParams keyEnumerator]){ [request setValue:[headerParams valueForKey:key] forHTTPHeaderField:key]; } @@ -639,36 +640,36 @@ static void (^reachabilityChangeBlock)(int); int counter = 0; NSMutableString * requestUrl = [NSMutableString stringWithFormat:@"%@", path]; - if(queryParams != nil){ + if (queryParams != nil){ for(NSString * key in [queryParams keyEnumerator]){ - if(counter == 0) separator = @"?"; + if (counter == 0) separator = @"?"; else separator = @"&"; id queryParam = [queryParams valueForKey:key]; - if([queryParam isKindOfClass:[NSString class]]){ + if ([queryParam isKindOfClass:[NSString class]]){ [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, [SWGApiClient escape:key], [SWGApiClient escape:[queryParams valueForKey:key]]]]; } - else if([queryParam isKindOfClass:[SWGQueryParamCollection class]]){ + else if ([queryParam isKindOfClass:[SWGQueryParamCollection class]]){ SWGQueryParamCollection * coll = (SWGQueryParamCollection*) queryParam; NSArray* values = [coll values]; NSString* format = [coll format]; - if([format isEqualToString:@"csv"]) { + if ([format isEqualToString:@"csv"]) { [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, [SWGApiClient escape:key], [NSString stringWithFormat:@"%@", [values componentsJoinedByString:@","]]]]; } - else if([format isEqualToString:@"tsv"]) { + else if ([format isEqualToString:@"tsv"]) { [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, [SWGApiClient escape:key], [NSString stringWithFormat:@"%@", [values componentsJoinedByString:@"\t"]]]]; } - else if([format isEqualToString:@"pipes"]) { + else if ([format isEqualToString:@"pipes"]) { [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, [SWGApiClient escape:key], [NSString stringWithFormat:@"%@", [values componentsJoinedByString:@"|"]]]]; } - else if([format isEqualToString:@"multi"]) { + else if ([format isEqualToString:@"multi"]) { for(id obj in values) { [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, [SWGApiClient escape:key], [NSString stringWithFormat:@"%@", obj]]]; diff --git a/samples/client/petstore/objc/SwaggerClient/SWGCategory.m b/samples/client/petstore/objc/SwaggerClient/SWGCategory.m index fb3ccecf1760..0d10e25426ea 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGCategory.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGCategory.m @@ -2,6 +2,17 @@ @implementation SWGCategory +- (instancetype)init { + self = [super init]; + + if (self) { + // initalise property's default value, if any + + } + + return self; +} + /** * Maps json key to property name. * This method is used by `JSONModel`. diff --git a/samples/client/petstore/objc/SwaggerClient/SWGOrder.m b/samples/client/petstore/objc/SwaggerClient/SWGOrder.m index 83fe5741cd7f..abf77a7b399d 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGOrder.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGOrder.m @@ -2,6 +2,17 @@ @implementation SWGOrder +- (instancetype)init { + self = [super init]; + + if (self) { + // initalise property's default value, if any + + } + + return self; +} + /** * Maps json key to property name. * This method is used by `JSONModel`. diff --git a/samples/client/petstore/objc/SwaggerClient/SWGPet.m b/samples/client/petstore/objc/SwaggerClient/SWGPet.m index 3fd315ab0118..f4fd77ea33f0 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGPet.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGPet.m @@ -2,6 +2,17 @@ @implementation SWGPet +- (instancetype)init { + self = [super init]; + + if (self) { + // initalise property's default value, if any + + } + + return self; +} + /** * Maps json key to property name. * This method is used by `JSONModel`. diff --git a/samples/client/petstore/objc/SwaggerClient/SWGPetApi.m b/samples/client/petstore/objc/SwaggerClient/SWGPetApi.m index bff6c3765b1e..c7c2ed175c6f 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGPetApi.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGPetApi.m @@ -250,7 +250,7 @@ static SWGPetApi* singletonAPI = nil; NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; - if(status != nil) { + if (status != nil) { queryParams[@"status"] = [[SWGQueryParamCollection alloc] initWithValuesAndFormat: status format: @"multi"]; @@ -334,7 +334,7 @@ static SWGPetApi* singletonAPI = nil; NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; - if(tags != nil) { + if (tags != nil) { queryParams[@"tags"] = [[SWGQueryParamCollection alloc] initWithValuesAndFormat: tags format: @"multi"]; @@ -622,7 +622,7 @@ static SWGPetApi* singletonAPI = nil; NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; - if(apiKey != nil) { + if (apiKey != nil) { headerParams[@"api_key"] = apiKey; } diff --git a/samples/client/petstore/objc/SwaggerClient/SWGTag.m b/samples/client/petstore/objc/SwaggerClient/SWGTag.m index 3bcb9973dfd2..b19085e2e6b5 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGTag.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGTag.m @@ -2,6 +2,17 @@ @implementation SWGTag +- (instancetype)init { + self = [super init]; + + if (self) { + // initalise property's default value, if any + + } + + return self; +} + /** * Maps json key to property name. * This method is used by `JSONModel`. diff --git a/samples/client/petstore/objc/SwaggerClient/SWGUser.m b/samples/client/petstore/objc/SwaggerClient/SWGUser.m index d040a6bce6da..ac059240e7fe 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGUser.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGUser.m @@ -2,6 +2,17 @@ @implementation SWGUser +- (instancetype)init { + self = [super init]; + + if (self) { + // initalise property's default value, if any + + } + + return self; +} + /** * Maps json key to property name. * This method is used by `JSONModel`. diff --git a/samples/client/petstore/objc/SwaggerClient/SWGUserApi.m b/samples/client/petstore/objc/SwaggerClient/SWGUserApi.m index 75cf8d51b0ea..faf0f928baf5 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGUserApi.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGUserApi.m @@ -331,11 +331,11 @@ static SWGUserApi* singletonAPI = nil; NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; - if(username != nil) { + if (username != nil) { queryParams[@"username"] = username; } - if(password != nil) { + if (password != nil) { queryParams[@"password"] = password; } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php index 18aeba64072d..bd82444f4fe0 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php @@ -152,7 +152,7 @@ class PetApi } // this endpoint requires OAuth (access token) - if ($this->apiClient->getConfig()->getAccessToken() !== null) { + if (strlen($this->apiClient->getConfig()->getAccessToken()) !== 0) { $headerParams['Authorization'] = 'Bearer ' . $this->apiClient->getConfig()->getAccessToken(); } @@ -235,7 +235,7 @@ class PetApi } // this endpoint requires OAuth (access token) - if ($this->apiClient->getConfig()->getAccessToken() !== null) { + if (strlen($this->apiClient->getConfig()->getAccessToken()) !== 0) { $headerParams['Authorization'] = 'Bearer ' . $this->apiClient->getConfig()->getAccessToken(); } @@ -317,7 +317,7 @@ class PetApi } // this endpoint requires OAuth (access token) - if ($this->apiClient->getConfig()->getAccessToken() !== null) { + if (strlen($this->apiClient->getConfig()->getAccessToken()) !== 0) { $headerParams['Authorization'] = 'Bearer ' . $this->apiClient->getConfig()->getAccessToken(); } @@ -407,7 +407,7 @@ class PetApi } // this endpoint requires OAuth (access token) - if ($this->apiClient->getConfig()->getAccessToken() !== null) { + if (strlen($this->apiClient->getConfig()->getAccessToken()) !== 0) { $headerParams['Authorization'] = 'Bearer ' . $this->apiClient->getConfig()->getAccessToken(); } @@ -506,7 +506,7 @@ class PetApi // this endpoint requires API key authentication $apiKey = $this->apiClient->getApiKeyWithPrefix('api_key'); - if ($apiKey !== null) { + if (strlen($apiKey) !== 0) { $headerParams['api_key'] = $apiKey; } @@ -621,7 +621,7 @@ class PetApi } // this endpoint requires OAuth (access token) - if ($this->apiClient->getConfig()->getAccessToken() !== null) { + if (strlen($this->apiClient->getConfig()->getAccessToken()) !== 0) { $headerParams['Authorization'] = 'Bearer ' . $this->apiClient->getConfig()->getAccessToken(); } @@ -716,7 +716,7 @@ class PetApi } // this endpoint requires OAuth (access token) - if ($this->apiClient->getConfig()->getAccessToken() !== null) { + if (strlen($this->apiClient->getConfig()->getAccessToken()) !== 0) { $headerParams['Authorization'] = 'Bearer ' . $this->apiClient->getConfig()->getAccessToken(); } @@ -828,7 +828,7 @@ class PetApi } // this endpoint requires OAuth (access token) - if ($this->apiClient->getConfig()->getAccessToken() !== null) { + if (strlen($this->apiClient->getConfig()->getAccessToken()) !== 0) { $headerParams['Authorization'] = 'Bearer ' . $this->apiClient->getConfig()->getAccessToken(); } 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 4539aeeeab45..4faed9a36baa 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php @@ -147,7 +147,7 @@ class StoreApi // this endpoint requires API key authentication $apiKey = $this->apiClient->getApiKeyWithPrefix('api_key'); - if ($apiKey !== null) { + if (strlen($apiKey) !== 0) { $headerParams['api_key'] = $apiKey; } diff --git a/samples/client/petstore/php/swagger_client_profiling.output b/samples/client/petstore/php/swagger_client_profiling.output new file mode 100644 index 000000000000..487dd36f4dac --- /dev/null +++ b/samples/client/petstore/php/swagger_client_profiling.output @@ -0,0 +1,31 @@ +0: NEW PETAPI => 0.050940 +0: ADD PET => 0.901768 +0: GET PET => 0.368627 +0: UPDATE PET => 0.366801 +0: DELETE PET => 0.368657 +1: NEW PETAPI => 0.000020 +1: ADD PET => 0.365229 +1: GET PET => 0.366909 +1: UPDATE PET => 0.366458 +1: DELETE PET => 0.365904 +2: NEW PETAPI => 0.000018 +2: ADD PET => 0.367664 +2: GET PET => 0.364671 +2: UPDATE PET => 0.365267 +2: DELETE PET => 0.366162 +3: NEW PETAPI => 0.000018 +3: ADD PET => 0.364907 +3: GET PET => 0.364156 +3: UPDATE PET => 0.366996 +3: DELETE PET => 0.366705 +4: NEW PETAPI => 0.000018 +4: ADD PET => 0.370373 +4: GET PET => 0.365455 +4: UPDATE PET => 0.365915 +4: DELETE PET => 0.368835 +5: NEW PETAPI => 0.000017 +5: ADD PET => 0.367148 +5: GET PET => 0.368994 +5: UPDATE PET => 0.368870 +5: DELETE PET => 0.367270 +6: FINISH diff --git a/samples/client/petstore/php/swagger_client_profiling.php b/samples/client/petstore/php/swagger_client_profiling.php new file mode 100644 index 000000000000..20a3d6b6bf58 --- /dev/null +++ b/samples/client/petstore/php/swagger_client_profiling.php @@ -0,0 +1,80 @@ + %f\n", $prof_names[$i], $prof_timing[$i+1]-$prof_timing[$i]); + } + echo "{$prof_names[$size-1]}\n"; +} + +$counter = 5; // run 5 times by default +$new_pet_id = 50001; // ID of pet that needs to be fetched + +for ($x = 0; $x <= $counter; $x++) { + try { + prof_flag("$x: NEW PETAPI"); + $pet_api = new Swagger\Client\Api\PetApi(); + + // ~~~ ADD PET ~~~ + prof_flag("$x: ADD PET"); + // add pet (post json) + $new_pet = new Swagger\Client\Model\Pet; + $new_pet->setId($new_pet_id); + $new_pet->setName("profiler"); + $new_pet->setStatus("available"); + $new_pet->setPhotoUrls(array("http://profiler.com")); + // new tag + $tag= new Swagger\Client\Model\Tag; + $tag->setId($new_pet_id); // use the same id as pet + $tag->setName("profile tag 1"); + // new category + $category = new Swagger\Client\Model\Category; + $category->setId($new_pet_id); // use the same id as pet + $category->setName("profile category 1"); + + $new_pet->setTags(array($tag)); + $new_pet->setCategory($category); + + // add a new pet (model) + $add_response = $pet_api->addPet($new_pet); + + // ~~~ GET PET ~~~ + prof_flag("$x: GET PET"); + $response = $pet_api->getPetById($new_pet_id); + + // ~~~ UPDATE PET WITH FORM ~~~ + prof_flag("$x: UPDATE PET"); + $response = $pet_api->updatePetWithForm($new_pet_id, "new profiler", "sold"); + + // ~~~ DELETE PET ~~~ + prof_flag("$x: DELETE PET"); + $response = $pet_api->deletePet($new_pet_id); + + } catch (Swagger\Client\ApiException $e) { + echo 'Caught exception: ', $e->getMessage(), "\n"; + echo 'HTTP response headers: ', print_r($e->getResponseHeaders(), true), "\n"; + echo 'HTTP response body: ', print_r($e->getResponseBody(), true), "\n"; + echo 'HTTP status code: ', $e->getCode(), "\n"; + } + +} + +prof_flag("$x: FINISH"); +prof_print(); + + diff --git a/samples/client/petstore/python/.coverage b/samples/client/petstore/python/.coverage index 98dd5627b871..26331c636b39 100644 --- a/samples/client/petstore/python/.coverage +++ b/samples/client/petstore/python/.coverage @@ -1 +1 @@ -!coverage.py: This is a private format, don't read it directly!{"lines": {"/Users/williamcheng/Code/wing328/swagger-codegen/samples/client/petstore/python/swagger_client/models/order.py": [130, 172, 141, 173, 19, 21, 22, 152, 25, 29, 30, 161, 163, 39, 40, 41, 42, 43, 44, 45, 174, 175, 48, 49, 50, 51, 180, 53, 54, 52, 58, 59, 60, 61, 62, 191, 64, 202, 75, 86, 57, 176, 222, 97, 228, 178, 234, 108, 240, 119], "/Users/williamcheng/Code/wing328/swagger-codegen/samples/client/petstore/python/swagger_client/models/tag.py": [128, 132, 134, 19, 21, 22, 25, 29, 30, 39, 40, 41, 44, 45, 46, 49, 50, 52, 61, 63, 72, 74, 83, 85, 94, 96, 100, 102, 103, 104, 109, 112, 114, 116, 122], "/Users/williamcheng/Code/wing328/swagger-codegen/samples/client/petstore/python/swagger_client/models/__init__.py": [1, 4, 5, 6, 7, 8], "/Users/williamcheng/Code/wing328/swagger-codegen/samples/client/petstore/python/swagger_client/apis/__init__.py": [1, 4, 5, 6], "/Users/williamcheng/Code/wing328/swagger-codegen/samples/client/petstore/python/swagger_client/models/pet.py": [128, 130, 150, 172, 139, 141, 19, 215, 21, 22, 152, 25, 29, 30, 161, 163, 39, 40, 41, 42, 43, 44, 45, 174, 48, 49, 50, 51, 52, 53, 54, 183, 185, 58, 59, 60, 61, 62, 64, 194, 195, 200, 73, 202, 75, 206, 208, 209, 210, 211, 84, 213, 86, 57, 216, 218, 220, 222, 95, 97, 226, 228, 234, 108, 238, 240, 117, 119, 212, 106], "/Users/williamcheng/Code/wing328/swagger-codegen/samples/client/petstore/python/swagger_client/configuration.py": [135, 136, 137, 138, 139, 142, 19, 149, 22, 23, 25, 26, 157, 158, 31, 32, 34, 36, 37, 39, 40, 41, 170, 43, 172, 46, 47, 189, 179, 52, 54, 59, 61, 190, 63, 192, 224, 67, 69, 71, 200, 73, 204, 80, 81, 82, 84, 213, 86, 199, 88, 90, 219, 92, 221, 222, 223, 96, 225, 98, 100, 102, 230, 104, 167, 111, 76, 168, 122, 123, 42, 21], "/Users/williamcheng/Code/wing328/swagger-codegen/samples/client/petstore/python/swagger_client/apis/store_api.py": [87, 18, 276, 22, 23, 26, 28, 29, 197, 32, 37, 39, 40, 41, 44, 46, 48, 68, 69, 71, 72, 79, 82, 83, 85, 121, 89, 91, 92, 94, 97, 98, 99, 103, 104, 107, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 20], "/Users/williamcheng/Code/wing328/swagger-codegen/samples/client/petstore/python/swagger_client/models/category.py": [128, 134, 19, 21, 22, 25, 29, 30, 39, 40, 41, 44, 45, 46, 49, 50, 52, 61, 63, 72, 74, 83, 85, 94, 96, 100, 102, 103, 104, 109, 112, 114, 116, 122], "/Users/williamcheng/Code/wing328/swagger-codegen/samples/client/petstore/python/swagger_client/api_client.py": [518, 525, 526, 527, 19, 21, 22, 23, 24, 537, 26, 27, 28, 29, 30, 31, 32, 33, 34, 547, 36, 37, 40, 42, 44, 45, 558, 47, 49, 52, 566, 568, 569, 570, 571, 572, 573, 575, 68, 69, 70, 75, 76, 77, 79, 80, 82, 84, 91, 96, 98, 102, 103, 104, 107, 108, 109, 111, 112, 115, 116, 117, 118, 119, 120, 123, 124, 125, 126, 129, 130, 131, 134, 137, 138, 141, 144, 145, 146, 147, 149, 152, 153, 155, 157, 158, 160, 162, 171, 172, 174, 176, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 204, 205, 212, 213, 214, 216, 217, 219, 231, 235, 236, 240, 242, 251, 252, 254, 255, 256, 257, 258, 260, 261, 262, 263, 267, 268, 269, 272, 274, 275, 276, 278, 279, 280, 281, 283, 286, 287, 288, 316, 317, 318, 319, 320, 322, 323, 324, 325, 326, 327, 328, 329, 330, 332, 333, 337, 338, 339, 340, 341, 345, 351, 352, 353, 354, 355, 356, 357, 358, 359, 360, 361, 362, 363, 369, 370, 371, 372, 379, 387, 389, 390, 392, 393, 394, 395, 548, 397, 398, 399, 400, 401, 402, 404, 406, 413, 414, 416, 418, 419, 421, 423, 430, 431, 433, 435, 436, 438, 440, 448, 450, 453, 454, 455, 456, 458, 459, 467, 546, 493, 502, 503, 508, 510], "/Users/williamcheng/Code/wing328/swagger-codegen/samples/client/petstore/python/swagger_client/apis/pet_api.py": [512, 513, 514, 516, 86, 18, 20, 22, 23, 26, 539, 28, 29, 542, 543, 32, 548, 37, 39, 40, 41, 42, 555, 556, 45, 558, 559, 48, 562, 564, 565, 566, 568, 569, 345, 571, 574, 575, 576, 580, 581, 70, 584, 73, 586, 587, 588, 589, 590, 591, 592, 593, 594, 595, 596, 598, 88, 90, 92, 93, 95, 96, 97, 100, 101, 102, 106, 107, 621, 622, 624, 625, 626, 79, 116, 117, 118, 631, 632, 121, 122, 635, 124, 638, 639, 641, 642, 643, 645, 647, 649, 650, 651, 652, 653, 654, 656, 145, 146, 659, 660, 149, 150, 665, 666, 155, 156, 669, 671, 160, 673, 162, 675, 164, 677, 166, 679, 168, 169, 171, 172, 173, 541, 176, 177, 178, 115, 182, 183, 186, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 200, 119, 120, 377, 221, 222, 549, 224, 225, 226, 231, 232, 235, 236, 110, 238, 240, 552, 242, 244, 246, 247, 249, 383, 252, 253, 254, 258, 259, 262, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 276, 46, 560, 538, 297, 298, 300, 301, 302, 44, 307, 308, 311, 312, 314, 316, 317, 318, 320, 322, 323, 325, 113, 328, 329, 330, 334, 335, 338, 340, 341, 342, 343, 344, 241, 346, 347, 348, 349, 350, 485, 352, 84, 114, 373, 374, 376, 148, 378, 661, 384, 387, 390, 391, 393, 394, 395, 397, 399, 401, 402, 404, 407, 408, 409, 413, 414, 69, 417, 419, 420, 421, 422, 423, 424, 425, 426, 427, 428, 429, 431, 72, 159, 74, 672, 83, 454, 455, 457, 458, 459, 674, 112, 464, 465, 468, 471, 472, 676, 474, 475, 476, 478, 480, 80, 482, 483, 484, 678, 486, 487, 489, 492, 493, 494, 680, 498, 499, 502, 681, 504, 505, 506, 507, 508, 509, 510, 511], "/Users/williamcheng/Code/wing328/swagger-codegen/samples/client/petstore/python/swagger_client/apis/user_api.py": [32, 355, 37, 39, 200, 124, 428, 589, 48, 18, 20, 22, 23, 276, 26, 507, 28, 29], "/Users/williamcheng/Code/wing328/swagger-codegen/samples/client/petstore/python/swagger_client/models/user.py": [278, 136, 266, 272, 147, 21, 22, 25, 284, 29, 158, 169, 180, 30, 191, 70, 202, 81, 213, 92, 224, 103, 235, 114, 19, 246, 125], "/Users/williamcheng/Code/wing328/swagger-codegen/samples/client/petstore/python/swagger_client/__init__.py": [1, 4, 5, 6, 7, 8, 11, 12, 13, 16, 18, 20], "/Users/williamcheng/Code/wing328/swagger-codegen/samples/client/petstore/python/swagger_client/rest.py": [20, 21, 23, 24, 25, 26, 27, 28, 31, 33, 35, 36, 40, 42, 43, 45, 48, 51, 53, 54, 55, 56, 57, 59, 63, 65, 72, 74, 82, 83, 88, 92, 95, 98, 101, 102, 103, 104, 105, 106, 109, 110, 121, 122, 124, 129, 130, 132, 135, 137, 138, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 152, 153, 154, 155, 156, 159, 160, 161, 166, 170, 174, 176, 177, 179, 181, 182, 183, 184, 186, 191, 198, 199, 200, 201, 203, 204, 205, 206, 207, 208, 210, 211, 212, 213, 214, 215, 217, 225, 227, 228, 229, 230, 231, 232, 239, 243, 244, 245, 246, 248, 249, 251]}} \ No newline at end of file +!coverage.py: This is a private format, don't read it directly!{"lines": {"/Users/williamcheng/Code/wing328/swagger-codegen/samples/client/petstore/python/swagger_client/__init__.py": [1, 4, 5, 6, 7, 8, 11, 12, 13, 16, 18, 20], "/Users/williamcheng/Code/wing328/swagger-codegen/samples/client/petstore/python/swagger_client/apis/pet_api.py": [512, 513, 514, 516, 86, 18, 20, 22, 23, 26, 539, 28, 29, 542, 543, 32, 548, 37, 39, 40, 41, 42, 555, 556, 45, 558, 559, 560, 562, 564, 565, 566, 568, 569, 571, 574, 575, 576, 580, 581, 70, 584, 73, 586, 587, 588, 589, 590, 591, 592, 593, 594, 595, 596, 598, 88, 90, 92, 93, 95, 96, 97, 100, 101, 102, 106, 107, 621, 622, 624, 625, 626, 79, 116, 117, 118, 631, 632, 121, 122, 635, 124, 638, 639, 641, 642, 643, 645, 647, 649, 650, 651, 652, 653, 654, 656, 145, 146, 659, 148, 661, 150, 665, 666, 155, 156, 538, 159, 160, 673, 162, 675, 164, 677, 166, 679, 168, 169, 171, 172, 173, 541, 176, 177, 178, 115, 182, 183, 186, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 200, 119, 120, 377, 221, 222, 549, 224, 225, 226, 231, 232, 431, 235, 236, 110, 238, 240, 552, 242, 244, 246, 247, 249, 383, 252, 253, 254, 258, 259, 262, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 276, 46, 48, 297, 298, 300, 301, 302, 44, 307, 308, 311, 312, 314, 316, 317, 318, 320, 322, 323, 325, 113, 328, 329, 330, 334, 335, 338, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 485, 352, 84, 114, 373, 374, 376, 660, 378, 149, 384, 387, 390, 391, 393, 394, 395, 397, 399, 401, 402, 404, 407, 408, 409, 413, 414, 69, 417, 419, 420, 421, 422, 423, 424, 425, 426, 427, 428, 429, 669, 72, 241, 671, 74, 672, 83, 454, 455, 457, 458, 459, 674, 112, 464, 465, 468, 471, 472, 676, 474, 475, 476, 478, 480, 80, 482, 483, 484, 678, 486, 487, 489, 492, 493, 494, 680, 498, 499, 502, 681, 504, 505, 506, 507, 508, 509, 510, 511], "/Users/williamcheng/Code/wing328/swagger-codegen/samples/client/petstore/python/swagger_client/models/order.py": [130, 172, 141, 173, 19, 21, 22, 152, 25, 29, 30, 52, 161, 163, 39, 40, 41, 42, 43, 44, 45, 174, 175, 48, 49, 50, 51, 180, 53, 54, 57, 58, 59, 60, 61, 62, 191, 64, 202, 75, 86, 176, 222, 97, 228, 178, 234, 108, 240, 119], "/Users/williamcheng/Code/wing328/swagger-codegen/samples/client/petstore/python/swagger_client/models/__init__.py": [1, 4, 5, 6, 7, 8], "/Users/williamcheng/Code/wing328/swagger-codegen/samples/client/petstore/python/swagger_client/models/tag.py": [128, 132, 134, 72, 74, 109, 19, 21, 22, 104, 25, 29, 30, 96, 100, 114, 102, 39, 40, 41, 103, 44, 45, 46, 112, 49, 50, 83, 116, 94, 52, 122, 61, 85, 63], "/Users/williamcheng/Code/wing328/swagger-codegen/samples/client/petstore/python/swagger_client/apis/user_api.py": [32, 355, 37, 39, 200, 124, 428, 589, 48, 18, 20, 22, 23, 276, 26, 507, 28, 29], "/Users/williamcheng/Code/wing328/swagger-codegen/samples/client/petstore/python/swagger_client/configuration.py": [135, 136, 137, 138, 139, 142, 19, 149, 22, 23, 25, 26, 27, 29, 158, 31, 32, 34, 36, 37, 39, 40, 41, 170, 43, 172, 46, 47, 189, 179, 52, 54, 59, 61, 190, 63, 192, 224, 67, 69, 71, 200, 73, 204, 80, 81, 82, 84, 213, 86, 199, 88, 90, 219, 92, 221, 222, 223, 96, 225, 98, 100, 102, 230, 104, 167, 111, 76, 168, 157, 122, 123, 42, 21], "/Users/williamcheng/Code/wing328/swagger-codegen/samples/client/petstore/python/swagger_client/apis/store_api.py": [18, 276, 22, 23, 26, 28, 29, 197, 32, 37, 39, 40, 41, 44, 46, 48, 20, 68, 69, 71, 72, 79, 82, 83, 85, 87, 89, 91, 92, 94, 97, 98, 99, 103, 104, 107, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 121], "/Users/williamcheng/Code/wing328/swagger-codegen/samples/client/petstore/python/swagger_client/models/category.py": [128, 134, 72, 74, 109, 19, 21, 22, 104, 25, 29, 30, 96, 100, 114, 102, 39, 40, 41, 103, 44, 45, 46, 112, 49, 50, 83, 116, 94, 52, 122, 61, 85, 63], "/Users/williamcheng/Code/wing328/swagger-codegen/samples/client/petstore/python/swagger_client/rest.py": [20, 21, 23, 24, 25, 26, 27, 28, 31, 33, 35, 36, 40, 42, 48, 51, 53, 54, 55, 56, 57, 59, 63, 65, 72, 74, 82, 83, 88, 92, 95, 98, 101, 102, 103, 104, 105, 106, 109, 110, 121, 122, 124, 129, 130, 132, 135, 137, 138, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 152, 153, 154, 155, 156, 159, 160, 161, 166, 170, 171, 174, 176, 177, 179, 181, 182, 183, 184, 186, 191, 198, 199, 200, 201, 203, 204, 205, 206, 207, 208, 210, 211, 212, 213, 214, 215, 217, 225, 227, 228, 229, 230, 231, 232, 239, 243, 244, 245, 246, 248, 249, 251], "/Users/williamcheng/Code/wing328/swagger-codegen/samples/client/petstore/python/swagger_client/models/pet.py": [128, 130, 150, 172, 139, 141, 19, 215, 21, 22, 152, 25, 29, 30, 161, 163, 39, 40, 41, 42, 43, 44, 45, 174, 48, 49, 50, 51, 52, 53, 54, 183, 57, 58, 59, 60, 61, 62, 64, 194, 195, 200, 73, 202, 75, 206, 208, 209, 210, 211, 84, 213, 86, 185, 216, 218, 220, 222, 95, 97, 226, 228, 234, 108, 238, 240, 117, 119, 212, 106], "/Users/williamcheng/Code/wing328/swagger-codegen/samples/client/petstore/python/swagger_client/api_client.py": [518, 525, 526, 527, 19, 21, 22, 23, 24, 537, 26, 27, 28, 29, 30, 31, 32, 33, 34, 547, 36, 37, 40, 42, 44, 558, 49, 52, 566, 568, 569, 570, 571, 572, 573, 575, 68, 69, 70, 75, 76, 77, 79, 80, 82, 84, 91, 96, 98, 102, 103, 104, 107, 108, 109, 111, 112, 115, 116, 117, 118, 119, 120, 123, 124, 125, 126, 129, 130, 131, 134, 137, 138, 141, 144, 145, 146, 147, 149, 152, 153, 155, 157, 158, 160, 162, 171, 172, 174, 176, 191, 192, 194, 195, 196, 197, 198, 199, 200, 201, 202, 204, 205, 212, 213, 214, 216, 217, 219, 231, 235, 236, 240, 242, 251, 252, 254, 255, 256, 257, 258, 260, 261, 262, 263, 267, 268, 269, 272, 274, 275, 276, 278, 279, 280, 281, 283, 286, 287, 288, 316, 317, 318, 319, 320, 322, 323, 324, 325, 326, 327, 328, 329, 330, 332, 333, 337, 338, 339, 340, 341, 345, 351, 352, 353, 354, 355, 356, 357, 358, 359, 360, 361, 362, 363, 369, 370, 371, 372, 379, 387, 389, 390, 392, 393, 394, 395, 548, 397, 398, 399, 400, 401, 402, 404, 406, 413, 414, 416, 418, 419, 421, 423, 430, 431, 433, 435, 436, 438, 440, 448, 450, 453, 454, 455, 456, 458, 459, 467, 546, 493, 502, 503, 508, 510], "/Users/williamcheng/Code/wing328/swagger-codegen/samples/client/petstore/python/swagger_client/models/user.py": [278, 70, 136, 202, 272, 81, 147, 213, 22, 25, 92, 29, 158, 224, 103, 169, 235, 284, 114, 19, 180, 30, 246, 266, 191, 125, 21], "/Users/williamcheng/Code/wing328/swagger-codegen/samples/client/petstore/python/swagger_client/apis/__init__.py": [1, 4, 5, 6]}} \ No newline at end of file diff --git a/samples/client/petstore/python/dev-requirements.txt.log b/samples/client/petstore/python/dev-requirements.txt.log index 382d1cf081d6..bd935e805bfb 100644 --- a/samples/client/petstore/python/dev-requirements.txt.log +++ b/samples/client/petstore/python/dev-requirements.txt.log @@ -69,3 +69,59 @@ Requirement already satisfied (use --upgrade to upgrade): randomize in ./venv/li Requirement already satisfied (use --upgrade to upgrade): virtualenv>=1.11.2 in ./venv/lib/python2.7/site-packages (from tox->-r dev-requirements.txt (line 2)) Requirement already satisfied (use --upgrade to upgrade): py>=1.4.17 in ./venv/lib/python2.7/site-packages (from tox->-r dev-requirements.txt (line 2)) Requirement already satisfied (use --upgrade to upgrade): pluggy<0.4.0,>=0.3.0 in ./venv/lib/python2.7/site-packages (from tox->-r dev-requirements.txt (line 2)) +Collecting nose (from -r dev-requirements.txt (line 1)) + Using cached nose-1.3.7-py2-none-any.whl +Collecting tox (from -r dev-requirements.txt (line 2)) + Using cached tox-2.2.1-py2.py3-none-any.whl +Collecting coverage (from -r dev-requirements.txt (line 3)) + Downloading coverage-4.0.3.tar.gz (354kB) +Collecting randomize (from -r dev-requirements.txt (line 4)) + Using cached randomize-0.13-py2.py3-none-any.whl +Requirement already satisfied (use --upgrade to upgrade): virtualenv>=1.11.2 in /Library/Python/2.7/site-packages (from tox->-r dev-requirements.txt (line 2)) +Collecting py>=1.4.17 (from tox->-r dev-requirements.txt (line 2)) + Downloading py-1.4.31-py2.py3-none-any.whl (81kB) +Collecting pluggy<0.4.0,>=0.3.0 (from tox->-r dev-requirements.txt (line 2)) + Using cached pluggy-0.3.1-py2.py3-none-any.whl +Installing collected packages: nose, py, pluggy, tox, coverage, randomize +Collecting nose (from -r dev-requirements.txt (line 1)) + Using cached nose-1.3.7-py2-none-any.whl +Collecting tox (from -r dev-requirements.txt (line 2)) + Using cached tox-2.2.1-py2.py3-none-any.whl +Collecting coverage (from -r dev-requirements.txt (line 3)) + Using cached coverage-4.0.3.tar.gz +Collecting randomize (from -r dev-requirements.txt (line 4)) + Using cached randomize-0.13-py2.py3-none-any.whl +Requirement already satisfied (use --upgrade to upgrade): virtualenv>=1.11.2 in /Library/Python/2.7/site-packages (from tox->-r dev-requirements.txt (line 2)) +Collecting py>=1.4.17 (from tox->-r dev-requirements.txt (line 2)) + Using cached py-1.4.31-py2.py3-none-any.whl +Collecting pluggy<0.4.0,>=0.3.0 (from tox->-r dev-requirements.txt (line 2)) + Using cached pluggy-0.3.1-py2.py3-none-any.whl +Installing collected packages: nose, py, pluggy, tox, coverage, randomize +Requirement already satisfied (use --upgrade to upgrade): nose in ./venv/lib/python2.7/site-packages (from -r dev-requirements.txt (line 1)) +Requirement already satisfied (use --upgrade to upgrade): tox in ./venv/lib/python2.7/site-packages (from -r dev-requirements.txt (line 2)) +Requirement already satisfied (use --upgrade to upgrade): coverage in ./venv/lib/python2.7/site-packages (from -r dev-requirements.txt (line 3)) +Requirement already satisfied (use --upgrade to upgrade): randomize in ./venv/lib/python2.7/site-packages (from -r dev-requirements.txt (line 4)) +Requirement already satisfied (use --upgrade to upgrade): virtualenv>=1.11.2 in ./venv/lib/python2.7/site-packages (from tox->-r dev-requirements.txt (line 2)) +Requirement already satisfied (use --upgrade to upgrade): py>=1.4.17 in ./venv/lib/python2.7/site-packages (from tox->-r dev-requirements.txt (line 2)) +Requirement already satisfied (use --upgrade to upgrade): pluggy<0.4.0,>=0.3.0 in ./venv/lib/python2.7/site-packages (from tox->-r dev-requirements.txt (line 2)) +Requirement already satisfied (use --upgrade to upgrade): nose in ./venv/lib/python2.7/site-packages (from -r dev-requirements.txt (line 1)) +Requirement already satisfied (use --upgrade to upgrade): tox in ./venv/lib/python2.7/site-packages (from -r dev-requirements.txt (line 2)) +Requirement already satisfied (use --upgrade to upgrade): coverage in ./venv/lib/python2.7/site-packages (from -r dev-requirements.txt (line 3)) +Requirement already satisfied (use --upgrade to upgrade): randomize in ./venv/lib/python2.7/site-packages (from -r dev-requirements.txt (line 4)) +Requirement already satisfied (use --upgrade to upgrade): virtualenv>=1.11.2 in ./venv/lib/python2.7/site-packages (from tox->-r dev-requirements.txt (line 2)) +Requirement already satisfied (use --upgrade to upgrade): py>=1.4.17 in ./venv/lib/python2.7/site-packages (from tox->-r dev-requirements.txt (line 2)) +Requirement already satisfied (use --upgrade to upgrade): pluggy<0.4.0,>=0.3.0 in ./venv/lib/python2.7/site-packages (from tox->-r dev-requirements.txt (line 2)) +Requirement already satisfied (use --upgrade to upgrade): nose in ./venv/lib/python2.7/site-packages (from -r dev-requirements.txt (line 1)) +Requirement already satisfied (use --upgrade to upgrade): tox in ./venv/lib/python2.7/site-packages (from -r dev-requirements.txt (line 2)) +Requirement already satisfied (use --upgrade to upgrade): coverage in ./venv/lib/python2.7/site-packages (from -r dev-requirements.txt (line 3)) +Requirement already satisfied (use --upgrade to upgrade): randomize in ./venv/lib/python2.7/site-packages (from -r dev-requirements.txt (line 4)) +Requirement already satisfied (use --upgrade to upgrade): virtualenv>=1.11.2 in ./venv/lib/python2.7/site-packages (from tox->-r dev-requirements.txt (line 2)) +Requirement already satisfied (use --upgrade to upgrade): py>=1.4.17 in ./venv/lib/python2.7/site-packages (from tox->-r dev-requirements.txt (line 2)) +Requirement already satisfied (use --upgrade to upgrade): pluggy<0.4.0,>=0.3.0 in ./venv/lib/python2.7/site-packages (from tox->-r dev-requirements.txt (line 2)) +Requirement already satisfied (use --upgrade to upgrade): nose in ./venv/lib/python2.7/site-packages (from -r dev-requirements.txt (line 1)) +Requirement already satisfied (use --upgrade to upgrade): tox in ./venv/lib/python2.7/site-packages (from -r dev-requirements.txt (line 2)) +Requirement already satisfied (use --upgrade to upgrade): coverage in ./venv/lib/python2.7/site-packages (from -r dev-requirements.txt (line 3)) +Requirement already satisfied (use --upgrade to upgrade): randomize in ./venv/lib/python2.7/site-packages (from -r dev-requirements.txt (line 4)) +Requirement already satisfied (use --upgrade to upgrade): virtualenv>=1.11.2 in ./venv/lib/python2.7/site-packages (from tox->-r dev-requirements.txt (line 2)) +Requirement already satisfied (use --upgrade to upgrade): py>=1.4.17 in ./venv/lib/python2.7/site-packages (from tox->-r dev-requirements.txt (line 2)) +Requirement already satisfied (use --upgrade to upgrade): pluggy<0.4.0,>=0.3.0 in ./venv/lib/python2.7/site-packages (from tox->-r dev-requirements.txt (line 2)) diff --git a/samples/client/petstore/ruby/lib/petstore.rb b/samples/client/petstore/ruby/lib/petstore.rb index c13e99f29fc4..4c21fb331d3f 100644 --- a/samples/client/petstore/ruby/lib/petstore.rb +++ b/samples/client/petstore/ruby/lib/petstore.rb @@ -19,17 +19,17 @@ require 'petstore/api/pet_api' module Petstore class << self - # Configure sdk using block. - # Petstore.configure do |config| - # config.username = "xxx" - # config.password = "xxx" - # end - # If no block given, return the configuration singleton instance. + # Customize default settings for the SDK using block. + # Petstore.configure do |config| + # config.username = "xxx" + # config.password = "xxx" + # end + # If no block given, return the default Configuration object. def configure if block_given? - yield Configuration.instance + yield(Configuration.default) else - Configuration.instance + Configuration.default end end end diff --git a/samples/client/petstore/ruby/lib/petstore/api/pet_api.rb b/samples/client/petstore/ruby/lib/petstore/api/pet_api.rb index acbd564db530..9641ad0b7079 100644 --- a/samples/client/petstore/ruby/lib/petstore/api/pet_api.rb +++ b/samples/client/petstore/ruby/lib/petstore/api/pet_api.rb @@ -4,8 +4,8 @@ module Petstore class PetApi attr_accessor :api_client - def initialize(api_client = nil) - @api_client = api_client || Configuration.api_client + def initialize(api_client = ApiClient.default) + @api_client = api_client end # Update an existing pet @@ -24,8 +24,8 @@ module Petstore # @option opts [Pet] :body Pet object that needs to be added to the store # @return [Array<(nil, Fixnum, Hash)>] nil, response status code and response headers def update_pet_with_http_info(opts = {}) - if Configuration.debugging - Configuration.logger.debug "Calling API: PetApi#update_pet ..." + if @api_client.config.debugging + @api_client.config.logger.debug "Calling API: PetApi#update_pet ..." end # resource path @@ -59,8 +59,8 @@ module Petstore :form_params => form_params, :body => post_body, :auth_names => auth_names) - if Configuration.debugging - Configuration.logger.debug "API called: PetApi#update_pet\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + if @api_client.config.debugging + @api_client.config.logger.debug "API called: PetApi#update_pet\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" end return data, status_code, headers end @@ -81,8 +81,8 @@ module Petstore # @option opts [Pet] :body Pet object that needs to be added to the store # @return [Array<(nil, Fixnum, Hash)>] nil, response status code and response headers def add_pet_with_http_info(opts = {}) - if Configuration.debugging - Configuration.logger.debug "Calling API: PetApi#add_pet ..." + if @api_client.config.debugging + @api_client.config.logger.debug "Calling API: PetApi#add_pet ..." end # resource path @@ -116,8 +116,8 @@ module Petstore :form_params => form_params, :body => post_body, :auth_names => auth_names) - if Configuration.debugging - Configuration.logger.debug "API called: PetApi#add_pet\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + if @api_client.config.debugging + @api_client.config.logger.debug "API called: PetApi#add_pet\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" end return data, status_code, headers end @@ -138,8 +138,8 @@ module Petstore # @option opts [Array] :status Status values that need to be considered for filter # @return [Array<(Array, Fixnum, Hash)>] Array data, response status code and response headers def find_pets_by_status_with_http_info(opts = {}) - if Configuration.debugging - Configuration.logger.debug "Calling API: PetApi#find_pets_by_status ..." + if @api_client.config.debugging + @api_client.config.logger.debug "Calling API: PetApi#find_pets_by_status ..." end # resource path @@ -175,8 +175,8 @@ module Petstore :body => post_body, :auth_names => auth_names, :return_type => 'Array') - if Configuration.debugging - Configuration.logger.debug "API called: PetApi#find_pets_by_status\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + if @api_client.config.debugging + @api_client.config.logger.debug "API called: PetApi#find_pets_by_status\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" end return data, status_code, headers end @@ -197,8 +197,8 @@ module Petstore # @option opts [Array] :tags Tags to filter by # @return [Array<(Array, Fixnum, Hash)>] Array data, response status code and response headers def find_pets_by_tags_with_http_info(opts = {}) - if Configuration.debugging - Configuration.logger.debug "Calling API: PetApi#find_pets_by_tags ..." + if @api_client.config.debugging + @api_client.config.logger.debug "Calling API: PetApi#find_pets_by_tags ..." end # resource path @@ -234,8 +234,8 @@ module Petstore :body => post_body, :auth_names => auth_names, :return_type => 'Array') - if Configuration.debugging - Configuration.logger.debug "API called: PetApi#find_pets_by_tags\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + if @api_client.config.debugging + @api_client.config.logger.debug "API called: PetApi#find_pets_by_tags\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" end return data, status_code, headers end @@ -256,8 +256,8 @@ module Petstore # @param [Hash] opts the optional parameters # @return [Array<(Pet, Fixnum, Hash)>] Pet data, response status code and response headers def get_pet_by_id_with_http_info(pet_id, opts = {}) - if Configuration.debugging - Configuration.logger.debug "Calling API: PetApi#get_pet_by_id ..." + if @api_client.config.debugging + @api_client.config.logger.debug "Calling API: PetApi#get_pet_by_id ..." end # verify the required parameter 'pet_id' is set @@ -295,8 +295,8 @@ module Petstore :body => post_body, :auth_names => auth_names, :return_type => 'Pet') - if Configuration.debugging - Configuration.logger.debug "API called: PetApi#get_pet_by_id\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + if @api_client.config.debugging + @api_client.config.logger.debug "API called: PetApi#get_pet_by_id\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" end return data, status_code, headers end @@ -321,8 +321,8 @@ module Petstore # @option opts [String] :status Updated status of the pet # @return [Array<(nil, Fixnum, Hash)>] nil, response status code and response headers def update_pet_with_form_with_http_info(pet_id, opts = {}) - if Configuration.debugging - Configuration.logger.debug "Calling API: PetApi#update_pet_with_form ..." + if @api_client.config.debugging + @api_client.config.logger.debug "Calling API: PetApi#update_pet_with_form ..." end # verify the required parameter 'pet_id' is set @@ -361,8 +361,8 @@ module Petstore :form_params => form_params, :body => post_body, :auth_names => auth_names) - if Configuration.debugging - Configuration.logger.debug "API called: PetApi#update_pet_with_form\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + if @api_client.config.debugging + @api_client.config.logger.debug "API called: PetApi#update_pet_with_form\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" end return data, status_code, headers end @@ -385,8 +385,8 @@ module Petstore # @option opts [String] :api_key # @return [Array<(nil, Fixnum, Hash)>] nil, response status code and response headers def delete_pet_with_http_info(pet_id, opts = {}) - if Configuration.debugging - Configuration.logger.debug "Calling API: PetApi#delete_pet ..." + if @api_client.config.debugging + @api_client.config.logger.debug "Calling API: PetApi#delete_pet ..." end # verify the required parameter 'pet_id' is set @@ -424,8 +424,8 @@ module Petstore :form_params => form_params, :body => post_body, :auth_names => auth_names) - if Configuration.debugging - Configuration.logger.debug "API called: PetApi#delete_pet\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + if @api_client.config.debugging + @api_client.config.logger.debug "API called: PetApi#delete_pet\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" end return data, status_code, headers end @@ -450,8 +450,8 @@ module Petstore # @option opts [File] :file file to upload # @return [Array<(nil, Fixnum, Hash)>] nil, response status code and response headers def upload_file_with_http_info(pet_id, opts = {}) - if Configuration.debugging - Configuration.logger.debug "Calling API: PetApi#upload_file ..." + if @api_client.config.debugging + @api_client.config.logger.debug "Calling API: PetApi#upload_file ..." end # verify the required parameter 'pet_id' is set @@ -490,8 +490,8 @@ module Petstore :form_params => form_params, :body => post_body, :auth_names => auth_names) - if Configuration.debugging - Configuration.logger.debug "API called: PetApi#upload_file\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + if @api_client.config.debugging + @api_client.config.logger.debug "API called: PetApi#upload_file\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" end return data, status_code, headers end diff --git a/samples/client/petstore/ruby/lib/petstore/api/store_api.rb b/samples/client/petstore/ruby/lib/petstore/api/store_api.rb index 548973eefd31..1d8a92e288f9 100644 --- a/samples/client/petstore/ruby/lib/petstore/api/store_api.rb +++ b/samples/client/petstore/ruby/lib/petstore/api/store_api.rb @@ -4,8 +4,8 @@ module Petstore class StoreApi attr_accessor :api_client - def initialize(api_client = nil) - @api_client = api_client || Configuration.api_client + def initialize(api_client = ApiClient.default) + @api_client = api_client end # Returns pet inventories by status @@ -22,8 +22,8 @@ module Petstore # @param [Hash] opts the optional parameters # @return [Array<(Hash, Fixnum, Hash)>] Hash data, response status code and response headers def get_inventory_with_http_info(opts = {}) - if Configuration.debugging - Configuration.logger.debug "Calling API: StoreApi#get_inventory ..." + if @api_client.config.debugging + @api_client.config.logger.debug "Calling API: StoreApi#get_inventory ..." end # resource path @@ -58,8 +58,8 @@ module Petstore :body => post_body, :auth_names => auth_names, :return_type => 'Hash') - if Configuration.debugging - Configuration.logger.debug "API called: StoreApi#get_inventory\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + if @api_client.config.debugging + @api_client.config.logger.debug "API called: StoreApi#get_inventory\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" end return data, status_code, headers end @@ -80,8 +80,8 @@ module Petstore # @option opts [Order] :body order placed for purchasing the pet # @return [Array<(Order, Fixnum, Hash)>] Order data, response status code and response headers def place_order_with_http_info(opts = {}) - if Configuration.debugging - Configuration.logger.debug "Calling API: StoreApi#place_order ..." + if @api_client.config.debugging + @api_client.config.logger.debug "Calling API: StoreApi#place_order ..." end # resource path @@ -116,8 +116,8 @@ module Petstore :body => post_body, :auth_names => auth_names, :return_type => 'Order') - if Configuration.debugging - Configuration.logger.debug "API called: StoreApi#place_order\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + if @api_client.config.debugging + @api_client.config.logger.debug "API called: StoreApi#place_order\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" end return data, status_code, headers end @@ -138,8 +138,8 @@ module Petstore # @param [Hash] opts the optional parameters # @return [Array<(Order, Fixnum, Hash)>] Order data, response status code and response headers def get_order_by_id_with_http_info(order_id, opts = {}) - if Configuration.debugging - Configuration.logger.debug "Calling API: StoreApi#get_order_by_id ..." + if @api_client.config.debugging + @api_client.config.logger.debug "Calling API: StoreApi#get_order_by_id ..." end # verify the required parameter 'order_id' is set @@ -177,8 +177,8 @@ module Petstore :body => post_body, :auth_names => auth_names, :return_type => 'Order') - if Configuration.debugging - Configuration.logger.debug "API called: StoreApi#get_order_by_id\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + if @api_client.config.debugging + @api_client.config.logger.debug "API called: StoreApi#get_order_by_id\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" end return data, status_code, headers end @@ -199,8 +199,8 @@ module Petstore # @param [Hash] opts the optional parameters # @return [Array<(nil, Fixnum, Hash)>] nil, response status code and response headers def delete_order_with_http_info(order_id, opts = {}) - if Configuration.debugging - Configuration.logger.debug "Calling API: StoreApi#delete_order ..." + if @api_client.config.debugging + @api_client.config.logger.debug "Calling API: StoreApi#delete_order ..." end # verify the required parameter 'order_id' is set @@ -237,8 +237,8 @@ module Petstore :form_params => form_params, :body => post_body, :auth_names => auth_names) - if Configuration.debugging - Configuration.logger.debug "API called: StoreApi#delete_order\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + if @api_client.config.debugging + @api_client.config.logger.debug "API called: StoreApi#delete_order\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" end return data, status_code, headers end diff --git a/samples/client/petstore/ruby/lib/petstore/api/user_api.rb b/samples/client/petstore/ruby/lib/petstore/api/user_api.rb index 35623175f350..e1c8332b8359 100644 --- a/samples/client/petstore/ruby/lib/petstore/api/user_api.rb +++ b/samples/client/petstore/ruby/lib/petstore/api/user_api.rb @@ -4,8 +4,8 @@ module Petstore class UserApi attr_accessor :api_client - def initialize(api_client = nil) - @api_client = api_client || Configuration.api_client + def initialize(api_client = ApiClient.default) + @api_client = api_client end # Create user @@ -24,8 +24,8 @@ module Petstore # @option opts [User] :body Created user object # @return [Array<(nil, Fixnum, Hash)>] nil, response status code and response headers def create_user_with_http_info(opts = {}) - if Configuration.debugging - Configuration.logger.debug "Calling API: UserApi#create_user ..." + if @api_client.config.debugging + @api_client.config.logger.debug "Calling API: UserApi#create_user ..." end # resource path @@ -59,8 +59,8 @@ module Petstore :form_params => form_params, :body => post_body, :auth_names => auth_names) - if Configuration.debugging - Configuration.logger.debug "API called: UserApi#create_user\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + if @api_client.config.debugging + @api_client.config.logger.debug "API called: UserApi#create_user\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" end return data, status_code, headers end @@ -81,8 +81,8 @@ module Petstore # @option opts [Array] :body List of user object # @return [Array<(nil, Fixnum, Hash)>] nil, response status code and response headers def create_users_with_array_input_with_http_info(opts = {}) - if Configuration.debugging - Configuration.logger.debug "Calling API: UserApi#create_users_with_array_input ..." + if @api_client.config.debugging + @api_client.config.logger.debug "Calling API: UserApi#create_users_with_array_input ..." end # resource path @@ -116,8 +116,8 @@ module Petstore :form_params => form_params, :body => post_body, :auth_names => auth_names) - if Configuration.debugging - Configuration.logger.debug "API called: UserApi#create_users_with_array_input\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + if @api_client.config.debugging + @api_client.config.logger.debug "API called: UserApi#create_users_with_array_input\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" end return data, status_code, headers end @@ -138,8 +138,8 @@ module Petstore # @option opts [Array] :body List of user object # @return [Array<(nil, Fixnum, Hash)>] nil, response status code and response headers def create_users_with_list_input_with_http_info(opts = {}) - if Configuration.debugging - Configuration.logger.debug "Calling API: UserApi#create_users_with_list_input ..." + if @api_client.config.debugging + @api_client.config.logger.debug "Calling API: UserApi#create_users_with_list_input ..." end # resource path @@ -173,8 +173,8 @@ module Petstore :form_params => form_params, :body => post_body, :auth_names => auth_names) - if Configuration.debugging - Configuration.logger.debug "API called: UserApi#create_users_with_list_input\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + if @api_client.config.debugging + @api_client.config.logger.debug "API called: UserApi#create_users_with_list_input\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" end return data, status_code, headers end @@ -197,8 +197,8 @@ module Petstore # @option opts [String] :password The password for login in clear text # @return [Array<(String, Fixnum, Hash)>] String data, response status code and response headers def login_user_with_http_info(opts = {}) - if Configuration.debugging - Configuration.logger.debug "Calling API: UserApi#login_user ..." + if @api_client.config.debugging + @api_client.config.logger.debug "Calling API: UserApi#login_user ..." end # resource path @@ -235,8 +235,8 @@ module Petstore :body => post_body, :auth_names => auth_names, :return_type => 'String') - if Configuration.debugging - Configuration.logger.debug "API called: UserApi#login_user\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + if @api_client.config.debugging + @api_client.config.logger.debug "API called: UserApi#login_user\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" end return data, status_code, headers end @@ -255,8 +255,8 @@ module Petstore # @param [Hash] opts the optional parameters # @return [Array<(nil, Fixnum, Hash)>] nil, response status code and response headers def logout_user_with_http_info(opts = {}) - if Configuration.debugging - Configuration.logger.debug "Calling API: UserApi#logout_user ..." + if @api_client.config.debugging + @api_client.config.logger.debug "Calling API: UserApi#logout_user ..." end # resource path @@ -290,8 +290,8 @@ module Petstore :form_params => form_params, :body => post_body, :auth_names => auth_names) - if Configuration.debugging - Configuration.logger.debug "API called: UserApi#logout_user\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + if @api_client.config.debugging + @api_client.config.logger.debug "API called: UserApi#logout_user\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" end return data, status_code, headers end @@ -312,8 +312,8 @@ module Petstore # @param [Hash] opts the optional parameters # @return [Array<(User, Fixnum, Hash)>] User data, response status code and response headers def get_user_by_name_with_http_info(username, opts = {}) - if Configuration.debugging - Configuration.logger.debug "Calling API: UserApi#get_user_by_name ..." + if @api_client.config.debugging + @api_client.config.logger.debug "Calling API: UserApi#get_user_by_name ..." end # verify the required parameter 'username' is set @@ -351,8 +351,8 @@ module Petstore :body => post_body, :auth_names => auth_names, :return_type => 'User') - if Configuration.debugging - Configuration.logger.debug "API called: UserApi#get_user_by_name\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + if @api_client.config.debugging + @api_client.config.logger.debug "API called: UserApi#get_user_by_name\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" end return data, status_code, headers end @@ -375,8 +375,8 @@ module Petstore # @option opts [User] :body Updated user object # @return [Array<(nil, Fixnum, Hash)>] nil, response status code and response headers def update_user_with_http_info(username, opts = {}) - if Configuration.debugging - Configuration.logger.debug "Calling API: UserApi#update_user ..." + if @api_client.config.debugging + @api_client.config.logger.debug "Calling API: UserApi#update_user ..." end # verify the required parameter 'username' is set @@ -413,8 +413,8 @@ module Petstore :form_params => form_params, :body => post_body, :auth_names => auth_names) - if Configuration.debugging - Configuration.logger.debug "API called: UserApi#update_user\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + if @api_client.config.debugging + @api_client.config.logger.debug "API called: UserApi#update_user\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" end return data, status_code, headers end @@ -435,8 +435,8 @@ module Petstore # @param [Hash] opts the optional parameters # @return [Array<(nil, Fixnum, Hash)>] nil, response status code and response headers def delete_user_with_http_info(username, opts = {}) - if Configuration.debugging - Configuration.logger.debug "Calling API: UserApi#delete_user ..." + if @api_client.config.debugging + @api_client.config.logger.debug "Calling API: UserApi#delete_user ..." end # verify the required parameter 'username' is set @@ -473,8 +473,8 @@ module Petstore :form_params => form_params, :body => post_body, :auth_names => auth_names) - if Configuration.debugging - Configuration.logger.debug "API called: UserApi#delete_user\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + if @api_client.config.debugging + @api_client.config.logger.debug "API called: UserApi#delete_user\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" end return data, status_code, headers end diff --git a/samples/client/petstore/ruby/lib/petstore/api_client.rb b/samples/client/petstore/ruby/lib/petstore/api_client.rb index 412fb7946ad4..52a3eb43855c 100644 --- a/samples/client/petstore/ruby/lib/petstore/api_client.rb +++ b/samples/client/petstore/ruby/lib/petstore/api_client.rb @@ -7,24 +7,27 @@ require 'uri' module Petstore class ApiClient - - attr_accessor :host + # The Configuration object holding settings to be used in the API client. + attr_accessor :config # Defines the headers to be used in HTTP requests of all API calls by default. # # @return [Hash] attr_accessor :default_headers - def initialize(host = nil) - @host = host || Configuration.base_url - @format = 'json' + def initialize(config = Configuration.default) + @config = config @user_agent = "ruby-swagger-#{VERSION}" @default_headers = { - 'Content-Type' => "application/#{@format.downcase}", + 'Content-Type' => "application/json", 'User-Agent' => @user_agent } end + def self.default + @@default ||= ApiClient.new + end + # Call an API with given options. # # @return [Array<(Object, Fixnum, Hash)>] an array of 3 elements: @@ -33,8 +36,8 @@ module Petstore request = build_request(http_method, path, opts) response = request.run - if Configuration.debugging - Configuration.logger.debug "HTTP response body ~BEGIN~\n#{response.body}\n~END~\n" + if @config.debugging + @config.logger.debug "HTTP response body ~BEGIN~\n#{response.body}\n~END~\n" end unless response.success? @@ -68,24 +71,33 @@ module Petstore :method => http_method, :headers => header_params, :params => query_params, - :ssl_verifypeer => Configuration.verify_ssl, - :sslcert => Configuration.cert_file, - :sslkey => Configuration.key_file, - :cainfo => Configuration.ssl_ca_cert, - :verbose => Configuration.debugging + :ssl_verifypeer => @config.verify_ssl, + :sslcert => @config.cert_file, + :sslkey => @config.key_file, + :cainfo => @config.ssl_ca_cert, + :verbose => @config.debugging } if [:post, :patch, :put, :delete].include?(http_method) req_body = build_request_body(header_params, form_params, opts[:body]) req_opts.update :body => req_body - if Configuration.debugging - Configuration.logger.debug "HTTP request body param ~BEGIN~\n#{req_body}\n~END~\n" + if @config.debugging + @config.logger.debug "HTTP request body param ~BEGIN~\n#{req_body}\n~END~\n" end end Typhoeus::Request.new(url, req_opts) end + # Check if the given MIME is a JSON MIME. + # JSON MIME examples: + # application/json + # application/json; charset=UTF8 + # APPLICATION/JSON + def json_mime?(mime) + !!(mime =~ /\Aapplication\/json(;.*)?\z/i) + end + # Deserialize the response to the given return type. # # @param [String] return_type some examples: "User", "Array[User]", "Hash[String,Integer]" @@ -99,9 +111,7 @@ module Petstore # ensuring a default content type content_type = response.headers['Content-Type'] || 'application/json' - unless content_type.start_with?('application/json') - fail "Content-Type is not supported: #{content_type}" - end + fail "Content-Type is not supported: #{content_type}" unless json_mime?(content_type) begin data = JSON.parse("[#{body}]", :symbolize_names => true)[0] @@ -161,7 +171,7 @@ module Petstore # @see Configuration#temp_folder_path # @return [File] the file downloaded def download_file(response) - tmp_file = Tempfile.new '', Configuration.temp_folder_path + tmp_file = Tempfile.new '', @config.temp_folder_path content_disposition = response.headers['Content-Disposition'] if content_disposition filename = content_disposition[/filename=['"]?([^'"\s]+)['"]?/, 1] @@ -173,15 +183,15 @@ module Petstore tmp_file.close! File.open(path, 'w') { |file| file.write(response.body) } - Configuration.logger.info "File written to #{path}. Please move the file to a proper "\ - "folder for further processing and delete the temp afterwards" + @config.logger.info "File written to #{path}. Please move the file to a proper folder "\ + "for further processing and delete the temp afterwards" File.new(path) end def build_request_url(path) # Add leading and trailing slashes to path path = "/#{path}".gsub(/\/+/, '/') - URI.encode(host + path) + URI.encode(@config.base_url + path) end def build_request_body(header_params, form_params, body) @@ -209,7 +219,7 @@ module Petstore # Update hearder and query params based on authentication settings. def update_params_for_auth!(header_params, query_params, auth_names) Array(auth_names).each do |auth_name| - auth_setting = Configuration.auth_settings[auth_name] + auth_setting = @config.auth_settings[auth_name] next unless auth_setting case auth_setting[:in] when 'header' then header_params[auth_setting[:key]] = auth_setting[:value] @@ -228,26 +238,21 @@ module Petstore # @param [Array] accepts array for Accept # @return [String] the Accept header (e.g. application/json) def select_header_accept(accepts) - if accepts.empty? - return - elsif accepts.any?{ |s| s.casecmp('application/json') == 0 } - 'application/json' # look for json data by default - else - accepts.join(',') - end + return nil if accepts.nil? || accepts.empty? + # use JSON when present, otherwise use all of the provided + json_accept = accepts.find { |s| json_mime?(s) } + return json_accept || accepts.join(',') end # Return Content-Type header based on an array of content types provided. # @param [Array] content_types array for Content-Type # @return [String] the Content-Type header (e.g. application/json) def select_header_content_type(content_types) - if content_types.empty? - 'application/json' # use application/json by default - elsif content_types.any?{ |s| s.casecmp('application/json')==0 } - 'application/json' # use application/json if it's included - else - content_types[0] # otherwise, use the first one - end + # use application/json by default + return 'application/json' if content_types.nil? || content_types.empty? + # use JSON when present, otherwise use the first one + json_content_type = content_types.find { |s| json_mime?(s) } + return json_content_type || content_types.first end # Convert object (array, hash, object, etc) to JSON string. diff --git a/samples/client/petstore/ruby/lib/petstore/configuration.rb b/samples/client/petstore/ruby/lib/petstore/configuration.rb index 4f7bd1c1b803..7173a4450c64 100644 --- a/samples/client/petstore/ruby/lib/petstore/configuration.rb +++ b/samples/client/petstore/ruby/lib/petstore/configuration.rb @@ -1,14 +1,7 @@ require 'uri' -require 'singleton' module Petstore class Configuration - - include Singleton - - # Default api client - attr_accessor :api_client - # Defines url scheme attr_accessor :scheme @@ -94,17 +87,6 @@ module Petstore attr_accessor :force_ending_format - class << self - def method_missing(method_name, *args, &block) - config = Configuration.instance - if config.respond_to?(method_name) - config.send(method_name, *args, &block) - else - super - end - end - end - def initialize @scheme = 'http' @host = 'petstore.swagger.io' @@ -118,10 +100,17 @@ module Petstore @inject_format = false @force_ending_format = false @logger = defined?(Rails) ? Rails.logger : Logger.new(STDOUT) + + yield(self) if block_given? end - def api_client - @api_client ||= ApiClient.new + # The default Configuration object. + def self.default + @@default ||= Configuration.new + end + + def configure + yield(self) if block_given? end def scheme=(scheme) diff --git a/samples/client/petstore/ruby/lib/petstore/models/category.rb b/samples/client/petstore/ruby/lib/petstore/models/category.rb index ab5b9cabbaaa..e223e747e747 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/category.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/category.rb @@ -1,21 +1,21 @@ module Petstore - # class Category < BaseObject - attr_accessor :id, :name - # attribute mapping from ruby-style variable name to JSON key + attr_accessor :id + + attr_accessor :name + + # Attribute mapping from ruby-style variable name to JSON key. def self.attribute_map { - # :'id' => :'id', - # :'name' => :'name' } end - # attribute type + # Attribute type mapping. def self.swagger_types { :'id' => :'Integer', @@ -25,7 +25,7 @@ module Petstore end def initialize(attributes = {}) - return if !attributes.is_a?(Hash) || attributes.empty? + return unless attributes.is_a?(Hash) # convert string to symbol for hash key attributes = attributes.inject({}){|memo,(k,v)| memo[k.to_sym] = v; memo} @@ -41,6 +41,7 @@ module Petstore end + # Check equality by comparing each attribute. def ==(o) return true if self.equal?(o) self.class == o.class && @@ -48,10 +49,12 @@ module Petstore name == o.name end + # @see the `==` method def eql?(o) self == o end + # Calculate hash code according to all attributes. def hash [id, name].hash end diff --git a/samples/client/petstore/ruby/lib/petstore/models/order.rb b/samples/client/petstore/ruby/lib/petstore/models/order.rb index 74eab3436e3e..19a33d1cfc30 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/order.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/order.rb @@ -1,33 +1,38 @@ module Petstore - # class Order < BaseObject - attr_accessor :id, :pet_id, :quantity, :ship_date, :status, :complete - # attribute mapping from ruby-style variable name to JSON key + attr_accessor :id + + attr_accessor :pet_id + + attr_accessor :quantity + + attr_accessor :ship_date + + # Order Status + attr_accessor :status + + attr_accessor :complete + + # Attribute mapping from ruby-style variable name to JSON key. def self.attribute_map { - # :'id' => :'id', - # :'pet_id' => :'petId', - # :'quantity' => :'quantity', - # :'ship_date' => :'shipDate', - # Order Status :'status' => :'status', - # :'complete' => :'complete' } end - # attribute type + # Attribute type mapping. def self.swagger_types { :'id' => :'Integer', @@ -41,7 +46,7 @@ module Petstore end def initialize(attributes = {}) - return if !attributes.is_a?(Hash) || attributes.empty? + return unless attributes.is_a?(Hash) # convert string to symbol for hash key attributes = attributes.inject({}){|memo,(k,v)| memo[k.to_sym] = v; memo} @@ -73,6 +78,7 @@ module Petstore end + # Custom attribute writer method checking allowed values (enum). def status=(status) allowed_values = ["placed", "approved", "delivered"] if status && !allowed_values.include?(status) @@ -81,6 +87,7 @@ module Petstore @status = status end + # Check equality by comparing each attribute. def ==(o) return true if self.equal?(o) self.class == o.class && @@ -92,10 +99,12 @@ module Petstore complete == o.complete end + # @see the `==` method def eql?(o) self == o end + # Calculate hash code according to all attributes. def hash [id, pet_id, quantity, ship_date, status, complete].hash end diff --git a/samples/client/petstore/ruby/lib/petstore/models/pet.rb b/samples/client/petstore/ruby/lib/petstore/models/pet.rb index 8c5fe6e17e7f..fb967cbbab4f 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/pet.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/pet.rb @@ -1,33 +1,38 @@ module Petstore - # class Pet < BaseObject - attr_accessor :id, :category, :name, :photo_urls, :tags, :status - # attribute mapping from ruby-style variable name to JSON key + attr_accessor :id + + attr_accessor :category + + attr_accessor :name + + attr_accessor :photo_urls + + attr_accessor :tags + + # pet status in the store + attr_accessor :status + + # Attribute mapping from ruby-style variable name to JSON key. def self.attribute_map { - # :'id' => :'id', - # :'category' => :'category', - # :'name' => :'name', - # :'photo_urls' => :'photoUrls', - # :'tags' => :'tags', - # pet status in the store :'status' => :'status' } end - # attribute type + # Attribute type mapping. def self.swagger_types { :'id' => :'Integer', @@ -41,7 +46,7 @@ module Petstore end def initialize(attributes = {}) - return if !attributes.is_a?(Hash) || attributes.empty? + return unless attributes.is_a?(Hash) # convert string to symbol for hash key attributes = attributes.inject({}){|memo,(k,v)| memo[k.to_sym] = v; memo} @@ -77,6 +82,7 @@ module Petstore end + # Custom attribute writer method checking allowed values (enum). def status=(status) allowed_values = ["available", "pending", "sold"] if status && !allowed_values.include?(status) @@ -85,6 +91,7 @@ module Petstore @status = status end + # Check equality by comparing each attribute. def ==(o) return true if self.equal?(o) self.class == o.class && @@ -96,10 +103,12 @@ module Petstore status == o.status end + # @see the `==` method def eql?(o) self == o end + # Calculate hash code according to all attributes. def hash [id, category, name, photo_urls, tags, status].hash end diff --git a/samples/client/petstore/ruby/lib/petstore/models/tag.rb b/samples/client/petstore/ruby/lib/petstore/models/tag.rb index 51439de58466..681c2a2a5c94 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/tag.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/tag.rb @@ -1,21 +1,21 @@ module Petstore - # class Tag < BaseObject - attr_accessor :id, :name - # attribute mapping from ruby-style variable name to JSON key + attr_accessor :id + + attr_accessor :name + + # Attribute mapping from ruby-style variable name to JSON key. def self.attribute_map { - # :'id' => :'id', - # :'name' => :'name' } end - # attribute type + # Attribute type mapping. def self.swagger_types { :'id' => :'Integer', @@ -25,7 +25,7 @@ module Petstore end def initialize(attributes = {}) - return if !attributes.is_a?(Hash) || attributes.empty? + return unless attributes.is_a?(Hash) # convert string to symbol for hash key attributes = attributes.inject({}){|memo,(k,v)| memo[k.to_sym] = v; memo} @@ -41,6 +41,7 @@ module Petstore end + # Check equality by comparing each attribute. def ==(o) return true if self.equal?(o) self.class == o.class && @@ -48,10 +49,12 @@ module Petstore name == o.name end + # @see the `==` method def eql?(o) self == o end + # Calculate hash code according to all attributes. def hash [id, name].hash end diff --git a/samples/client/petstore/ruby/lib/petstore/models/user.rb b/samples/client/petstore/ruby/lib/petstore/models/user.rb index 3d20ab95c4f4..ca00bf34be13 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/user.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/user.rb @@ -1,39 +1,46 @@ module Petstore - # class User < BaseObject - attr_accessor :id, :username, :first_name, :last_name, :email, :password, :phone, :user_status - # attribute mapping from ruby-style variable name to JSON key + attr_accessor :id + + attr_accessor :username + + attr_accessor :first_name + + attr_accessor :last_name + + attr_accessor :email + + attr_accessor :password + + attr_accessor :phone + + # User Status + attr_accessor :user_status + + # Attribute mapping from ruby-style variable name to JSON key. def self.attribute_map { - # :'id' => :'id', - # :'username' => :'username', - # :'first_name' => :'firstName', - # :'last_name' => :'lastName', - # :'email' => :'email', - # :'password' => :'password', - # :'phone' => :'phone', - # User Status :'user_status' => :'userStatus' } end - # attribute type + # Attribute type mapping. def self.swagger_types { :'id' => :'Integer', @@ -49,7 +56,7 @@ module Petstore end def initialize(attributes = {}) - return if !attributes.is_a?(Hash) || attributes.empty? + return unless attributes.is_a?(Hash) # convert string to symbol for hash key attributes = attributes.inject({}){|memo,(k,v)| memo[k.to_sym] = v; memo} @@ -89,6 +96,7 @@ module Petstore end + # Check equality by comparing each attribute. def ==(o) return true if self.equal?(o) self.class == o.class && @@ -102,10 +110,12 @@ module Petstore user_status == o.user_status end + # @see the `==` method def eql?(o) self == o end + # Calculate hash code according to all attributes. def hash [id, username, first_name, last_name, email, password, phone, user_status].hash end diff --git a/samples/client/petstore/ruby/petstore_profiling.output b/samples/client/petstore/ruby/petstore_profiling.output new file mode 100644 index 000000000000..36750b5e2b9e --- /dev/null +++ b/samples/client/petstore/ruby/petstore_profiling.output @@ -0,0 +1,315 @@ +Measure Mode: wall_time +Thread ID: 70329221636600 +Fiber ID: 70329234076680 +Total: 10.998497 +Sort by: self_time + + %self total self wait child calls name + 99.20 10.920 10.911 0.000 0.010 20 #easy_perform + 0.05 0.005 0.005 0.000 0.000 1392 Symbol#to_s + 0.04 0.019 0.005 0.000 0.015 268 Ethon::Curls::Options#set_option + 0.02 0.003 0.003 0.000 0.000 718 Ethon::Easy::Operations#handle + 0.02 0.003 0.003 0.000 0.000 657 String#downcase + 0.02 0.003 0.003 0.000 0.000 658 FFI::Enum#to_native + 0.02 0.003 0.003 0.000 0.000 678 FFI::Enum#from_native + 0.02 0.029 0.002 0.000 0.027 200 *Proc#call + 0.02 0.034 0.002 0.000 0.032 210 *Array#each + 0.02 0.014 0.002 0.000 0.012 309 *Class#new + 0.02 0.004 0.002 0.000 0.003 390 #easy_getinfo + 0.02 0.002 0.002 0.000 0.000 175 Typhoeus::EasyFactory#renamed_options + 0.01 0.001 0.001 0.000 0.000 744 Kernel#respond_to? + 0.01 0.003 0.001 0.000 0.002 201 *#method_missing + 0.01 0.006 0.001 0.000 0.005 75 Hash#each + 0.01 0.020 0.001 0.000 0.019 56 *Hash#each_pair + 0.01 0.001 0.001 0.000 0.000 430 Symbol#to_sym + 0.01 0.004 0.001 0.000 0.003 210 Ethon::Curls::Infos#get_info_double + 0.01 0.003 0.001 0.000 0.002 175 *Array#map + 0.01 0.001 0.001 0.000 0.000 268 Ethon::Curls::Options#easy_options + 0.01 0.001 0.001 0.000 0.000 201 #instance + 0.01 0.001 0.001 0.000 0.000 420 Ethon::Curls::Infos#double_ptr + 0.01 0.002 0.001 0.000 0.001 250 FFI::Pointer#read_string + 0.01 0.001 0.001 0.000 0.000 80 Hash#initialize_copy + 0.01 0.001 0.001 0.000 0.000 240 Typhoeus::Response::Header#set_value + 0.01 0.001 0.001 0.000 0.000 656 Kernel#is_a? + 0.01 0.001 0.001 0.000 0.000 42 String#gsub + 0.01 0.003 0.001 0.000 0.002 120 Ethon::Curls::Infos#get_info_long + 0.01 0.004 0.001 0.000 0.004 120 Typhoeus::Response::Header#process_line + 0.01 0.001 0.001 0.000 0.001 85 #easy_setopt_string + 0.01 0.001 0.001 0.000 0.000 140 String#split + 0.01 0.001 0.001 0.000 0.000 485 Kernel#nil? + 0.01 0.001 0.001 0.000 0.000 240 Ethon::Curls::Infos#long_ptr + 0.01 0.001 0.001 0.000 0.000 42 #easy_setopt_callback + 0.01 0.006 0.001 0.000 0.006 20 Petstore::ApiClient#build_request + 0.00 0.001 0.000 0.000 0.001 90 #easy_setopt_long + 0.00 0.000 0.000 0.000 0.000 170 FFI::AbstractMemory#get_bytes + 0.00 0.001 0.000 0.000 0.000 30 #informations_to_mirror + 0.00 0.002 0.000 0.000 0.002 120 Typhoeus::Response::Header#process_pair + 0.00 0.002 0.000 0.000 0.002 60 Ethon::Curls::Infos#get_info_string + 0.00 0.000 0.000 0.000 0.000 190 String#to_s + 0.00 0.000 0.000 0.000 0.000 130 Kernel#class + 0.00 0.000 0.000 0.000 0.000 240 String#strip + 0.00 0.001 0.000 0.000 0.001 42 Mutex#synchronize + 0.00 0.000 0.000 0.000 0.000 268 Hash#include? + 0.00 0.000 0.000 0.000 0.000 36 String#sub + 0.00 0.001 0.000 0.000 0.001 21 FFI::AutoPointer#initialize + 0.00 0.000 0.000 0.000 0.000 400 Array#include? + 0.00 10.941 0.000 0.000 10.941 20 Ethon::Easy::Operations#perform + 0.00 0.000 0.000 0.000 0.000 185 Integer#to_i + 0.00 0.006 0.000 0.000 0.006 21 Ethon::Easy::Callbacks#set_callbacks + 0.00 0.001 0.000 0.000 0.001 80 Ethon::Easy::Header#compose_header + 0.00 0.000 0.000 0.000 0.000 210 FFI::AbstractMemory#read_double + 0.00 0.001 0.000 0.000 0.000 90 #find_type + 0.00 0.001 0.000 0.000 0.001 90 #type_size + 0.00 0.002 0.000 0.000 0.001 30 Ethon::Easy::Informations#httpauth_avail + 0.00 0.000 0.000 0.000 0.000 80 #slist_append + 0.00 0.001 0.000 0.000 0.001 85 Kernel#initialize_dup + 0.00 0.000 0.000 0.000 0.000 330 Hash#has_key? + 0.00 10.993 0.000 0.000 10.992 20 Petstore::ApiClient#call_api + 0.00 0.000 0.000 0.000 0.000 80 String#encode + 0.00 0.001 0.000 0.000 0.000 20 Petstore::Configuration#auth_settings + 0.00 0.001 0.000 0.000 0.000 140 Typhoeus::Response::Informations#response_code + 0.00 0.000 0.000 0.000 0.000 65 #attribute_map + 0.00 0.000 0.000 0.000 0.000 35 Petstore::ApiClient#json_mime? + 0.00 0.001 0.000 0.000 0.000 85 Ethon::Easy::Http::Actionable#form + 0.00 0.000 0.000 0.000 0.000 45 Hash#keys + 0.00 0.023 0.000 0.000 0.022 20 Ethon::Easy::Http::Actionable#setup + 0.00 0.002 0.000 0.000 0.001 80 Typhoeus::EasyFactory#easy + 0.00 0.001 0.000 0.000 0.001 20 Typhoeus::Request::Callbacks#execute_callbacks + 0.00 0.001 0.000 0.000 0.000 40 Hash#merge + 0.00 0.001 0.000 0.000 0.000 80 Ethon::Easy::Util#escape_zero_byte + 0.00 0.000 0.000 0.000 0.000 120 Ethon::Curls::Infos#string_ptr + 0.00 0.001 0.000 0.000 0.000 50 Enumerable#find + 0.00 0.000 0.000 0.000 0.000 80 FFI::AbstractMemory#get_string + 0.00 0.000 0.000 0.000 0.000 80 Typhoeus::Request::Responseable#response + 0.00 0.000 0.000 0.000 0.000 120 FFI::AbstractMemory#read_long + 0.00 0.000 0.000 0.000 0.000 120 Hash#[]= + 0.00 0.001 0.000 0.000 0.001 40 Typhoeus::Response::Status#success? + 0.00 10.998 0.000 0.000 10.998 5 PetstoreProfiling#call_apis + 0.00 0.000 0.000 0.000 0.000 20 #easy_reset + 0.00 0.007 0.000 0.000 0.007 25 Typhoeus::Response::Informations#headers + 0.00 0.000 0.000 0.000 0.000 90 Fixnum#<< + 0.00 0.001 0.000 0.000 0.001 20 Petstore::ApiClient#build_request_url + 0.00 0.032 0.000 0.000 0.031 20 Typhoeus::EasyFactory#get + 0.00 0.001 0.000 0.000 0.001 45 Kernel#dup + 0.00 0.000 0.000 0.000 0.000 21 #easy_setopt_debug_callback + 0.00 0.016 0.000 0.000 0.016 30 #from_easy + 0.00 0.000 0.000 0.000 0.000 20 String#lines + 0.00 0.001 0.000 0.000 0.000 20 Typhoeus::Request#set_defaults + 0.00 0.006 0.000 0.000 0.006 20 Typhoeus::Response::Header#initialize + 0.00 0.000 0.000 0.000 0.000 40 Typhoeus::Request::Callbacks::Types#on_complete + 0.00 0.000 0.000 0.000 0.000 120 Symbol#to_proc + 0.00 0.001 0.000 0.000 0.000 20 Typhoeus::EasyFactory#set_callback + 0.00 10.974 0.000 0.000 10.973 20 Typhoeus::Request::Operations#run + 0.00 0.001 0.000 0.000 0.001 60 *Petstore::BaseObject#_to_hash + 0.00 0.000 0.000 0.000 0.000 90 FFI::Type#size + 0.00 0.000 0.000 0.000 0.000 60 FFI::AbstractMemory#read_pointer + 0.00 0.002 0.000 0.000 0.002 20 Typhoeus::Request::Operations#finish + 0.00 0.001 0.000 0.000 0.000 21 URI::Escape#escape + 0.00 0.000 0.000 0.000 0.000 40 Typhoeus::Request::Callbacks::Types#on_success + 0.00 0.000 0.000 0.000 0.000 22 Ethon::Loggable#logger + 0.00 0.000 0.000 0.000 0.000 65 Typhoeus::Response#mock + 0.00 0.006 0.000 0.000 0.006 20 Ethon::Easy#reset + 0.00 0.001 0.000 0.000 0.000 30 #easy_setopt_ffipointer + 0.00 0.001 0.000 0.000 0.001 5 JSON::Ext::Generator::GeneratorMethods::Hash#to_json + 0.00 3.494 0.000 0.000 3.494 5 Petstore::PetApi#get_pet_by_id_with_http_info + 0.00 0.000 0.000 0.000 0.000 160 Kernel#block_given? + 0.00 3.220 0.000 0.000 3.219 5 Petstore::PetApi#update_pet_with_form_with_http_info + 0.00 0.001 0.000 0.000 0.001 30 Ethon::Easy::Informations#effective_url + 0.00 0.006 0.000 0.000 0.006 20 Typhoeus::Response::Header#parse + 0.00 10.975 0.000 0.000 10.975 20 Typhoeus::Request::Before#run + 0.00 0.011 0.000 0.000 0.011 20 Ethon::Easy#mirror + 0.00 0.000 0.000 0.000 0.000 40 #easies + 0.00 0.000 0.000 0.000 0.000 40 Typhoeus::EasyFactory#sanitize_timeout! + 0.00 0.000 0.000 0.000 0.000 5 JSON::Ext::Parser#parse + 0.00 0.000 0.000 0.000 0.000 50 String#to_sym + 0.00 0.000 0.000 0.000 0.000 70 Hash#fetch + 0.00 0.001 0.000 0.000 0.001 20 Typhoeus::Request#initialize + 0.00 0.005 0.000 0.000 0.005 20 Typhoeus::EasyFactory#sanitize + 0.00 0.000 0.000 0.000 0.000 21 URI::RFC2396_Parser#escape + 0.00 0.001 0.000 0.000 0.001 30 Ethon::Easy::Informations#total_time + 0.00 0.001 0.000 0.000 0.001 30 Ethon::Easy::Informations#appconnect_time + 0.00 2.141 0.000 0.000 2.141 5 Petstore::PetApi#delete_pet_with_http_info + 0.00 0.001 0.000 0.000 0.000 20 Petstore::ApiClient#select_header_accept + 0.00 0.000 0.000 0.000 0.000 30 Enumerable#inject + 0.00 0.000 0.000 0.000 0.000 80 Integer#chr + 0.00 0.000 0.000 0.000 0.000 90 Fixnum#< + 0.00 10.974 0.000 0.000 10.974 20 Typhoeus::Request::BlockConnection#run + 0.00 2.143 0.000 0.000 2.143 5 Petstore::PetApi#add_pet_with_http_info + 0.00 0.000 0.000 0.000 0.000 21 Logger#add + 0.00 0.020 0.000 0.000 0.020 20 Ethon::Easy::ResponseCallbacks#complete + 0.00 0.000 0.000 0.000 0.000 21 Logger#debug + 0.00 10.975 0.000 0.000 10.974 20 Typhoeus::Request::Stubbable#run + 0.00 0.004 0.000 0.000 0.004 20 Ethon::Easy::Header#headers= + 0.00 0.000 0.000 0.000 0.000 20 Typhoeus::Request::Cacheable#response= + 0.00 0.001 0.000 0.000 0.001 50 *Petstore::BaseObject#_deserialize + 0.00 0.000 0.000 0.000 0.000 35 Module#const_get + 0.00 0.000 0.000 0.000 0.000 20 Ethon::Easy::Http::Actionable#params + 0.00 0.003 0.000 0.000 0.003 10 Ethon::Easy::Http::Postable#set_form + 0.00 0.000 0.000 0.000 0.000 50 Symbol#=~ + 0.00 0.001 0.000 0.000 0.001 30 Ethon::Easy::Informations#pretransfer_time + 0.00 0.000 0.000 0.000 0.000 30 Typhoeus::Response#initialize + 0.00 0.000 0.000 0.000 0.000 10 Petstore::Pet#initialize + 0.00 0.000 0.000 0.000 0.000 20 Petstore::ApiClient#select_header_content_type + 0.00 0.002 0.000 0.000 0.002 20 Ethon::Easy::Options#nosignal= + 0.00 0.001 0.000 0.000 0.001 20 Ethon::Easy::Http::Actionable#initialize + 0.00 0.000 0.000 0.000 0.000 21 #define_finalizer + 0.00 0.002 0.000 0.000 0.001 20 Ethon::Easy::Http#fabricate + 0.00 0.001 0.000 0.000 0.001 30 Ethon::Easy::Informations#primary_ip + 0.00 0.000 0.000 0.000 0.000 119 NilClass#nil? + 0.00 0.001 0.000 0.000 0.001 30 Ethon::Easy::Informations#redirect_time + 0.00 0.001 0.000 0.000 0.001 30 Ethon::Easy::Informations#starttransfer_time + 0.00 0.000 0.000 0.000 0.000 20 Symbol#downcase + 0.00 0.000 0.000 0.000 0.000 21 Kernel#method + 0.00 0.000 0.000 0.000 0.000 20 Petstore::Configuration#api_key_with_prefix + 0.00 0.000 0.000 0.000 0.000 25 #attribute_map + 0.00 10.974 0.000 0.000 10.974 20 Typhoeus::Request::Cacheable#run + 0.00 0.000 0.000 0.000 0.000 20 Typhoeus::Request::Callbacks::Types#on_headers + 0.00 0.001 0.000 0.000 0.001 30 Ethon::Easy::Informations#namelookup_time + 0.00 0.001 0.000 0.000 0.001 30 Ethon::Easy::Informations#connect_time + 0.00 0.001 0.000 0.000 0.001 30 Ethon::Easy::Informations#request_size + 0.00 0.000 0.000 0.000 0.000 21 String#force_encoding + 0.00 0.000 0.000 0.000 0.000 20 #before + 0.00 0.000 0.000 0.000 0.000 40 Typhoeus::Response::Informations#return_code + 0.00 0.000 0.000 0.000 0.000 30 Ethon::Easy::Mirror#initialize + 0.00 0.000 0.000 0.000 0.000 15 Petstore::ApiClient#build_request_body + 0.00 0.001 0.000 0.000 0.001 30 Ethon::Easy::Informations#redirect_count + 0.00 0.025 0.000 0.000 0.025 20 Ethon::Easy::Http#http_request + 0.00 0.001 0.000 0.000 0.001 30 Ethon::Easy::Informations#response_code + 0.00 0.000 0.000 0.000 0.000 50 Ethon::Easy::Http::Actionable#query_options + 0.00 0.000 0.000 0.000 0.000 25 #attribute_map + 0.00 0.000 0.000 0.000 0.000 25 NilClass#to_s + 0.00 0.007 0.000 0.000 0.007 20 #release + 0.00 0.000 0.000 0.000 0.000 20 Ethon::Easy::ResponseCallbacks#on_headers + 0.00 0.000 0.000 0.000 0.000 20 #response_for + 0.00 0.001 0.000 0.000 0.001 20 Ethon::Easy::Http::Actionable#parse_options + 0.00 0.000 0.000 0.000 0.000 35 Hash#delete + 0.00 0.000 0.000 0.000 0.000 45 Typhoeus::Response::Informations#response_headers + 0.00 0.000 0.000 0.000 0.000 20 #easy_escape + 0.00 0.000 0.000 0.000 0.000 21 FFI::AutoPointer::Releaser#initialize + 0.00 0.000 0.000 0.000 0.000 21 Ethon::Easy::Callbacks#header_write_callback + 0.00 0.000 0.000 0.000 0.000 21 Ethon::Easy::DebugInfo#initialize + 0.00 0.000 0.000 0.000 0.000 20 Typhoeus::EasyFactory#initialize + 0.00 0.000 0.000 0.000 0.000 20 Typhoeus::Request::Memoizable#response= + 0.00 0.000 0.000 0.000 0.000 105 Module#=== + 0.00 0.000 0.000 0.000 0.000 80 String#include? + 0.00 0.000 0.000 0.000 0.000 21 Ethon::Easy::Callbacks#body_write_callback + 0.00 0.000 0.000 0.000 0.000 16 Array#join + 0.00 0.000 0.000 0.000 0.000 20 #find_by + 0.00 0.005 0.000 0.000 0.005 5 Petstore::ApiClient#deserialize + 0.00 0.000 0.000 0.000 0.000 30 Regexp#=== + 0.00 0.006 0.000 0.000 0.006 10 Ethon::Easy::ResponseCallbacks#headers + 0.00 0.000 0.000 0.000 0.000 21 Ethon::Easy::Callbacks#debug_callback + 0.00 0.000 0.000 0.000 0.000 20 Ethon::Easy::ResponseCallbacks#on_complete + 0.00 0.002 0.000 0.000 0.002 20 Ethon::Easy::Options#url= + 0.00 0.000 0.000 0.000 0.000 84 Kernel#kind_of? + 0.00 0.000 0.000 0.000 0.000 40 Typhoeus::Request::Cacheable#cacheable? + 0.00 0.017 0.000 0.000 0.017 21 Ethon::Easy#set_attributes + 0.00 0.000 0.000 0.000 0.000 20 Module#const_defined? + 0.00 0.001 0.000 0.000 0.001 20 #get + 0.00 0.000 0.000 0.000 0.000 20 #pid + 0.00 0.000 0.000 0.000 0.000 40 String#bytesize + 0.00 0.000 0.000 0.000 0.000 20 Ethon::Easy::Params#initialize + 0.00 0.000 0.000 0.000 0.000 20 Kernel#lambda + 0.00 0.000 0.000 0.000 0.000 20 String#capitalize + 0.00 0.000 0.000 0.000 0.000 25 Ethon::Easy::Queryable#query_pairs + 0.00 0.000 0.000 0.000 0.000 195 Symbol#=== + 0.00 0.000 0.000 0.000 0.000 20 Ethon::Easy::Form#initialize + 0.00 0.000 0.000 0.000 0.000 13 FFI::MemoryPointer#initialize + 0.00 0.000 0.000 0.000 0.000 105 Hash#key? + 0.00 0.000 0.000 0.000 0.000 20 Ethon::Easy#escape + 0.00 0.000 0.000 0.000 0.000 20 #all + 0.00 0.000 0.000 0.000 0.000 10 Typhoeus::Request::Callbacks#execute_headers_callbacks + 0.00 0.000 0.000 0.000 0.000 20 Typhoeus::Response::Header#set_default_proc_on + 0.00 0.000 0.000 0.000 0.000 15 Hash#update + 0.00 0.000 0.000 0.000 0.000 60 FFI::Pointer#null? + 0.00 0.001 0.000 0.000 0.001 20 Ethon::Easy::Options#sslcert= + 0.00 0.001 0.000 0.000 0.001 20 Ethon::Easy::Queryable#to_s + 0.00 0.000 0.000 0.000 0.000 55 Ethon::Easy::Queryable#empty? + 0.00 0.000 0.000 0.000 0.000 20 Hash#default_proc= + 0.00 0.000 0.000 0.000 0.000 10 Petstore::Category#initialize + 0.00 0.000 0.000 0.000 0.000 10 Petstore::Tag#initialize + 0.00 0.000 0.000 0.000 0.000 21 FFI::Pointer#initialize + 0.00 0.002 0.000 0.000 0.001 20 Ethon::Easy::Options#verbose= + 0.00 0.002 0.000 0.000 0.002 20 Ethon::Easy::Options#maxredirs= + 0.00 0.001 0.000 0.000 0.001 20 Ethon::Easy::Options#sslkey= + 0.00 0.000 0.000 0.000 0.000 20 Array#pop + 0.00 0.000 0.000 0.000 0.000 21 FFI::Pointer#type_size + 0.00 0.000 0.000 0.000 0.000 20 Ethon::Easy::Http::Actionable#url + 0.00 0.000 0.000 0.000 0.000 20 Typhoeus::Request::BlockConnection#blocked? + 0.00 0.002 0.000 0.000 0.002 20 Ethon::Easy::Options#ssl_verifypeer= + 0.00 0.000 0.000 0.000 0.000 20 Ethon::Easy::Http::Actionable#options + 0.00 0.000 0.000 0.000 0.000 10 Ethon::Easy::ResponseCallbacks#body + 0.00 0.000 0.000 0.000 0.000 10 Petstore::Pet#status= + 0.00 0.001 0.000 0.000 0.001 20 Ethon::Easy::Options#cainfo= + 0.00 0.000 0.000 0.000 0.000 30 Array#last + 0.00 0.001 0.000 0.000 0.001 20 Petstore::ApiClient#update_params_for_auth! + 0.00 0.003 0.000 0.000 0.003 5 Petstore::ApiClient#convert_to_type + 0.00 10.998 0.000 0.000 10.998 1 PetstoreProfiling#run + 0.00 0.012 0.000 0.000 0.011 10 Ethon::Easy::Http::Post#setup + 0.00 0.000 0.000 0.000 0.000 5 JSON::Ext::Parser#initialize + 0.00 0.000 0.000 0.000 0.000 20 Typhoeus::Request::Memoizable#memoizable? + 0.00 0.000 0.000 0.000 0.000 20 Typhoeus::Response::Header#raw + 0.00 0.002 0.000 0.000 0.002 5 Petstore::ApiClient#object_to_http_body + 0.00 0.000 0.000 0.000 0.000 20 Typhoeus::Request::Responseable#response= + 0.00 0.000 0.000 0.000 0.000 15 Fixnum#to_s + 0.00 0.001 0.000 0.000 0.001 15 *Petstore::BaseObject#to_hash + 0.00 0.000 0.000 0.000 0.000 10 Array#any? + 0.00 0.000 0.000 0.000 0.000 10 Ethon::Easy::Queryable#build_query_pairs + 0.00 0.000 0.000 0.000 0.000 1 #easy_init + 0.00 0.000 0.000 0.000 0.000 10 Ethon::Easy::Queryable#pairs_for + 0.00 0.001 0.000 0.000 0.000 5 Petstore::PetApi#initialize + 0.00 0.000 0.000 0.000 0.000 10 Array#compact + 0.00 0.003 0.000 0.000 0.002 15 *Petstore::BaseObject#build_from_hash + 0.00 0.000 0.000 0.000 0.000 20 Typhoeus::Request::Streamable#streaming? + 0.00 0.000 0.000 0.000 0.000 10 Ethon::Easy::Http::Actionable#params_encoding + 0.00 0.000 0.000 0.000 0.000 10 FFI::AbstractMemory#put_bytes + 0.00 3.494 0.000 0.000 3.494 5 Petstore::PetApi#get_pet_by_id + 0.00 0.000 0.000 0.000 0.000 20 Proc#to_proc + 0.00 0.000 0.000 0.000 0.000 5 Petstore::Configuration#api_client + 0.00 0.006 0.000 0.000 0.006 5 Ethon::Easy::Http::Delete#setup + 0.00 0.001 0.000 0.000 0.001 10 Ethon::Easy::Options#postfieldsize= + 0.00 0.001 0.000 0.000 0.001 10 Ethon::Easy::Options#copypostfields= + 0.00 0.005 0.000 0.000 0.005 5 Ethon::Easy::Http::Get#setup + 0.00 2.143 0.000 0.000 2.143 5 Petstore::PetApi#add_pet + 0.00 0.000 0.000 0.000 0.000 20 #free + 0.00 0.000 0.000 0.000 0.000 1 Petstore::Configuration#initialize + 0.00 2.141 0.000 0.000 2.141 5 Petstore::PetApi#delete_pet + 0.00 0.000 0.000 0.000 0.000 20 Kernel#Array + 0.00 0.000 0.000 0.000 0.000 45 Kernel#respond_to_missing? + 0.00 0.000 0.000 0.000 0.000 1 #global_init + 0.00 0.000 0.000 0.000 0.000 5 #swagger_types + 0.00 0.001 0.000 0.000 0.001 5 Petstore::ApiClient#object_to_hash + 0.00 0.000 0.000 0.000 0.000 2 Logger#initialize + 0.00 0.000 0.000 0.000 0.000 10 Ethon::Easy::Form#multipart? + 0.00 0.000 0.000 0.000 0.000 5 JSON::Ext::Generator::State#initialize_copy + 0.00 0.000 0.000 0.000 0.000 2 MonitorMixin#initialize + 0.00 3.220 0.000 0.000 3.220 5 Petstore::PetApi#update_pet_with_form + 0.00 0.000 0.000 0.000 0.000 5 #swagger_types + 0.00 0.000 0.000 0.000 0.000 1 Petstore::ApiClient#initialize + 0.00 0.003 0.000 0.000 0.003 5 Kernel#tap + 0.00 0.000 0.000 0.000 0.000 5 JSON#parse + 0.00 0.000 0.000 0.000 0.000 5 Ethon::Easy::Options#customrequest= + 0.00 0.000 0.000 0.000 0.000 5 Ethon::Easy::Queryable#recursively_generate_pairs + 0.00 0.000 0.000 0.000 0.000 5 #swagger_types + 0.00 0.000 0.000 0.000 0.000 2 Logger::LogDevice#initialize + 0.00 10.998 0.000 0.000 10.998 1 Integer#times + 0.00 0.000 0.000 0.000 0.000 1 Petstore::Configuration#base_url + 0.00 0.000 0.000 0.000 0.000 2 MonitorMixin#mon_initialize + 0.00 0.000 0.000 0.000 0.000 35 String#=== + 0.00 0.000 0.000 0.000 0.000 3 Kernel#proc + 0.00 0.000 0.000 0.000 0.000 5 Typhoeus::Response::Informations#response_body + 0.00 0.000 0.000 0.000 0.000 10 Kernel#=== + 0.00 0.001 0.000 0.000 0.001 1 Ethon::Easy#initialize + 0.00 0.000 0.000 0.000 0.000 5 Ethon::Easy::Queryable#encode_hash_pairs + 0.00 0.000 0.000 0.000 0.000 5 String#encoding + 0.00 0.000 0.000 0.000 0.000 5 Array#first + 0.00 0.000 0.000 0.000 0.000 5 Hash#[] + 0.00 0.000 0.000 0.000 0.000 2 BasicObject#initialize + 0.00 0.000 0.000 0.000 0.000 1 Ethon::Loggable#default_logger + 0.00 0.000 0.000 0.000 0.000 2 Logger::Formatter#initialize + 0.00 0.000 0.000 0.000 0.000 1 #init + 0.00 0.000 0.000 0.000 0.000 2 Mutex#initialize + 0.00 0.000 0.000 0.000 0.000 1 Ethon::Loggable#rails_logger + 0.00 0.000 0.000 0.000 0.000 10 BasicObject#== + +* indicates recursively called methods diff --git a/samples/client/petstore/ruby/petstore_profiling.rb b/samples/client/petstore/ruby/petstore_profiling.rb new file mode 100644 index 000000000000..485bd40c0c76 --- /dev/null +++ b/samples/client/petstore/ruby/petstore_profiling.rb @@ -0,0 +1,75 @@ +# To run this profiling: +# gem install ruby-prof +# ruby -Ilib petstore_profiling.rb + +require 'petstore' +require 'ruby-prof' + +class PetstoreProfiling + attr_accessor :total, :new_pet_id, :output_file + + def initialize + @total = 5 + @new_pet_id = 50002 + @output_file = './petstore_profiling.output' + end + + def call_apis + pet_api = Petstore::PetApi.new + + ### ADD PET ### + pet = Petstore::Pet.new + pet.id = new_pet_id + pet.name = "profiler" + pet.status = "available" + pet.photo_urls = ["http://profiler.com"] + # new tag + tag= Petstore::Tag.new + tag.id = new_pet_id # use the same id as pet + tag.name = "profile tag 1" + # new category + category = Petstore::Category.new + category.id = new_pet_id # use the same id as pet + category.name = "profile category 1" + + pet.tags = [tag] + pet.category = category + + # add a new pet (model) + pet_api.add_pet(body: pet) + + ### GET PET ### + pet = pet_api.get_pet_by_id(new_pet_id) + + ### UPDATE PET WITH FORM ### + pet_api.update_pet_with_form(new_pet_id, name: 'new profiler', status: 'sold') + + ### DELETE PET ### + pet_api.delete_pet(new_pet_id) + rescue Petstore::ApiError => e + puts "Caught error: #{e.message}" + puts "HTTP response headers: #{e.response_headers}" + puts "HTTP response body: #{e.response_body}" + puts "HTTP status code: #{e.code}" + end + + def run + puts "Running profiling... (total: #{@total})" + + RubyProf.start + @total.times { call_apis } + result = RubyProf.stop + + printer = RubyProf::FlatPrinter.new(result) + File.open(@output_file, 'w') do |file| + printer.print(file) + end + + puts "Profiling results written to #{@output_file}" + end +end + +if __FILE__ == $0 + profiling = PetstoreProfiling.new + profiling.run +end diff --git a/samples/client/petstore/ruby/spec/api_client_spec.rb b/samples/client/petstore/ruby/spec/api_client_spec.rb index eeb27300bf37..c2bfef4e8e4e 100644 --- a/samples/client/petstore/ruby/spec/api_client_spec.rb +++ b/samples/client/petstore/ruby/spec/api_client_spec.rb @@ -10,34 +10,34 @@ describe Petstore::ApiClient do context 'host' do it 'removes http from host' do Petstore.configure { |c| c.host = 'http://example.com' } - Petstore.configure.host.should == 'example.com' + Petstore::Configuration.default.host.should == 'example.com' end it 'removes https from host' do Petstore.configure { |c| c.host = 'https://wookiee.com' } - Petstore.configure.host.should == 'wookiee.com' + Petstore::ApiClient.default.config.host.should == 'wookiee.com' end it 'removes trailing path from host' do Petstore.configure { |c| c.host = 'hobo.com/v4' } - Petstore.configure.host.should == 'hobo.com' + Petstore::Configuration.default.host.should == 'hobo.com' end end context 'base_path' do it "prepends a slash to base_path" do Petstore.configure { |c| c.base_path = 'v4/dog' } - Petstore.configure.base_path.should == '/v4/dog' + Petstore::Configuration.default.base_path.should == '/v4/dog' end it "doesn't prepend a slash if one is already there" do Petstore.configure { |c| c.base_path = '/v4/dog' } - Petstore.configure.base_path.should == '/v4/dog' + Petstore::Configuration.default.base_path.should == '/v4/dog' end it "ends up as a blank string if nil" do Petstore.configure { |c| c.base_path = nil } - Petstore.configure.base_path.should == '' + Petstore::Configuration.default.base_path.should == '' end end @@ -53,13 +53,26 @@ describe Petstore::ApiClient do end api_client = Petstore::ApiClient.new + + config2 = Petstore::Configuration.new do |c| + c.api_key_prefix['api_key'] = 'PREFIX2' + c.api_key['api_key'] = 'special-key2' + end + api_client2 = Petstore::ApiClient.new(config2) + auth_names = ['api_key', 'unknown'] + header_params = {} query_params = {} - auth_names = ['api_key', 'unknown'] api_client.update_params_for_auth! header_params, query_params, auth_names header_params.should == {'api_key' => 'PREFIX special-key'} query_params.should == {} + + header_params = {} + query_params = {} + api_client2.update_params_for_auth! header_params, query_params, auth_names + header_params.should == {'api_key' => 'PREFIX2 special-key2'} + query_params.should == {} end it "sets header api-key parameter without prefix" do @@ -145,4 +158,52 @@ describe Petstore::ApiClient do end end + describe "#json_mime?" do + let(:api_client) { Petstore::ApiClient.new } + + it "works" do + api_client.json_mime?(nil).should == false + api_client.json_mime?('').should == false + + api_client.json_mime?('application/json').should == true + api_client.json_mime?('application/json; charset=UTF8').should == true + api_client.json_mime?('APPLICATION/JSON').should == true + + api_client.json_mime?('application/xml').should == false + api_client.json_mime?('text/plain').should == false + api_client.json_mime?('application/jsonp').should == false + end + end + + describe "#select_header_accept" do + let(:api_client) { Petstore::ApiClient.new } + + it "works" do + api_client.select_header_accept(nil).should == nil + api_client.select_header_accept([]).should == nil + + api_client.select_header_accept(['application/json']).should == 'application/json' + api_client.select_header_accept(['application/xml', 'application/json; charset=UTF8']).should == 'application/json; charset=UTF8' + api_client.select_header_accept(['APPLICATION/JSON', 'text/html']).should == 'APPLICATION/JSON' + + api_client.select_header_accept(['application/xml']).should == 'application/xml' + api_client.select_header_accept(['text/html', 'application/xml']).should == 'text/html,application/xml' + end + end + + describe "#select_header_content_type" do + let(:api_client) { Petstore::ApiClient.new } + + it "works" do + api_client.select_header_content_type(nil).should == 'application/json' + api_client.select_header_content_type([]).should == 'application/json' + + api_client.select_header_content_type(['application/json']).should == 'application/json' + api_client.select_header_content_type(['application/xml', 'application/json; charset=UTF8']).should == 'application/json; charset=UTF8' + api_client.select_header_content_type(['APPLICATION/JSON', 'text/html']).should == 'APPLICATION/JSON' + api_client.select_header_content_type(['application/xml']).should == 'application/xml' + api_client.select_header_content_type(['text/plain', 'application/xml']).should == 'text/plain' + end + end + end diff --git a/samples/client/petstore/ruby/spec/configuration_spec.rb b/samples/client/petstore/ruby/spec/configuration_spec.rb index 9f86f5602b74..eb29b54c2a79 100644 --- a/samples/client/petstore/ruby/spec/configuration_spec.rb +++ b/samples/client/petstore/ruby/spec/configuration_spec.rb @@ -1,7 +1,7 @@ require 'spec_helper' describe Petstore::Configuration do - let(:config) { Petstore::Configuration.instance } + let(:config) { Petstore::Configuration.default } before(:each) do Petstore.configure do |c| diff --git a/samples/client/petstore/ruby/spec/spec_helper.rb b/samples/client/petstore/ruby/spec/spec_helper.rb index b8ba0f739756..26da98f9c422 100644 --- a/samples/client/petstore/ruby/spec/spec_helper.rb +++ b/samples/client/petstore/ruby/spec/spec_helper.rb @@ -36,7 +36,7 @@ end # help #end -API_CLIENT = Petstore::ApiClient.new +API_CLIENT = Petstore::ApiClient.new(Petstore::Configuration.new) # always delete and then re-create the pet object with 10002 def prepare_pet(pet_api) diff --git a/samples/client/petstore/swift/Cartfile b/samples/client/petstore/swift/Cartfile index 745e00376a80..5e4bd352eefc 100644 --- a/samples/client/petstore/swift/Cartfile +++ b/samples/client/petstore/swift/Cartfile @@ -1,2 +1,2 @@ -github "Alamofire/Alamofire" >= 3.0.0 +github "Alamofire/Alamofire" >= 3.1.0 github "mxcl/PromiseKit" >=1.5.3 diff --git a/samples/client/petstore/swift/PetstoreClient.podspec b/samples/client/petstore/swift/PetstoreClient.podspec index 3caf12083de0..ed41db4bfb13 100644 --- a/samples/client/petstore/swift/PetstoreClient.podspec +++ b/samples/client/petstore/swift/PetstoreClient.podspec @@ -7,5 +7,5 @@ Pod::Spec.new do |s| s.license = 'Apache License, Version 2.0' s.source_files = 'PetstoreClient/Classes/Swaggers/**/*.swift' s.dependency 'PromiseKit', '~> 2.1' - s.dependency 'Alamofire', '~> 3.0.0' + s.dependency 'Alamofire', '~> 3.1.0' end diff --git a/samples/server/petstore/sinatra/api/pet_api.rb b/samples/server/petstore/sinatra/api/pet_api.rb index 5f995c531d85..7ccad2056b92 100644 --- a/samples/server/petstore/sinatra/api/pet_api.rb +++ b/samples/server/petstore/sinatra/api/pet_api.rb @@ -1,7 +1,7 @@ require 'json' -MyApp.add_route('PUT', '/pet', { +MyApp.add_route('PUT', '/v2/pet', { "resourcePath" => "/Pet", "summary" => "Update an existing pet", "nickname" => "update_pet", @@ -28,7 +28,7 @@ MyApp.add_route('PUT', '/pet', { end -MyApp.add_route('POST', '/pet', { +MyApp.add_route('POST', '/v2/pet', { "resourcePath" => "/Pet", "summary" => "Add a new pet to the store", "nickname" => "add_pet", @@ -55,7 +55,7 @@ MyApp.add_route('POST', '/pet', { end -MyApp.add_route('GET', '/pet/findByStatus', { +MyApp.add_route('GET', '/v2/pet/findByStatus', { "resourcePath" => "/Pet", "summary" => "Finds Pets by status", "nickname" => "find_pets_by_status", @@ -85,7 +85,7 @@ MyApp.add_route('GET', '/pet/findByStatus', { end -MyApp.add_route('GET', '/pet/findByTags', { +MyApp.add_route('GET', '/v2/pet/findByTags', { "resourcePath" => "/Pet", "summary" => "Finds Pets by tags", "nickname" => "find_pets_by_tags", @@ -115,7 +115,7 @@ MyApp.add_route('GET', '/pet/findByTags', { end -MyApp.add_route('GET', '/pet/{petId}', { +MyApp.add_route('GET', '/v2/pet/{petId}', { "resourcePath" => "/Pet", "summary" => "Find pet by ID", "nickname" => "get_pet_by_id", @@ -142,7 +142,7 @@ MyApp.add_route('GET', '/pet/{petId}', { end -MyApp.add_route('POST', '/pet/{petId}', { +MyApp.add_route('POST', '/v2/pet/{petId}', { "resourcePath" => "/Pet", "summary" => "Updates a pet in the store with form data", "nickname" => "update_pet_with_form", @@ -169,7 +169,7 @@ MyApp.add_route('POST', '/pet/{petId}', { end -MyApp.add_route('DELETE', '/pet/{petId}', { +MyApp.add_route('DELETE', '/v2/pet/{petId}', { "resourcePath" => "/Pet", "summary" => "Deletes a pet", "nickname" => "delete_pet", @@ -203,7 +203,7 @@ MyApp.add_route('DELETE', '/pet/{petId}', { end -MyApp.add_route('POST', '/pet/{petId}/uploadImage', { +MyApp.add_route('POST', '/v2/pet/{petId}/uploadImage', { "resourcePath" => "/Pet", "summary" => "uploads an image", "nickname" => "upload_file", diff --git a/samples/server/petstore/sinatra/api/store_api.rb b/samples/server/petstore/sinatra/api/store_api.rb index 244983874127..37938b304db1 100644 --- a/samples/server/petstore/sinatra/api/store_api.rb +++ b/samples/server/petstore/sinatra/api/store_api.rb @@ -1,7 +1,7 @@ require 'json' -MyApp.add_route('GET', '/store/inventory', { +MyApp.add_route('GET', '/v2/store/inventory', { "resourcePath" => "/Store", "summary" => "Returns pet inventories by status", "nickname" => "get_inventory", @@ -21,7 +21,7 @@ MyApp.add_route('GET', '/store/inventory', { end -MyApp.add_route('POST', '/store/order', { +MyApp.add_route('POST', '/v2/store/order', { "resourcePath" => "/Store", "summary" => "Place an order for a pet", "nickname" => "place_order", @@ -48,7 +48,7 @@ MyApp.add_route('POST', '/store/order', { end -MyApp.add_route('GET', '/store/order/{orderId}', { +MyApp.add_route('GET', '/v2/store/order/{orderId}', { "resourcePath" => "/Store", "summary" => "Find purchase order by ID", "nickname" => "get_order_by_id", @@ -75,7 +75,7 @@ MyApp.add_route('GET', '/store/order/{orderId}', { end -MyApp.add_route('DELETE', '/store/order/{orderId}', { +MyApp.add_route('DELETE', '/v2/store/order/{orderId}', { "resourcePath" => "/Store", "summary" => "Delete purchase order by ID", "nickname" => "delete_order", diff --git a/samples/server/petstore/sinatra/api/user_api.rb b/samples/server/petstore/sinatra/api/user_api.rb index 98f50549ba11..7b890004891d 100644 --- a/samples/server/petstore/sinatra/api/user_api.rb +++ b/samples/server/petstore/sinatra/api/user_api.rb @@ -1,7 +1,7 @@ require 'json' -MyApp.add_route('POST', '/user', { +MyApp.add_route('POST', '/v2/user', { "resourcePath" => "/User", "summary" => "Create user", "nickname" => "create_user", @@ -28,7 +28,7 @@ MyApp.add_route('POST', '/user', { end -MyApp.add_route('POST', '/user/createWithArray', { +MyApp.add_route('POST', '/v2/user/createWithArray', { "resourcePath" => "/User", "summary" => "Creates list of users with given input array", "nickname" => "create_users_with_array_input", @@ -55,7 +55,7 @@ MyApp.add_route('POST', '/user/createWithArray', { end -MyApp.add_route('POST', '/user/createWithList', { +MyApp.add_route('POST', '/v2/user/createWithList', { "resourcePath" => "/User", "summary" => "Creates list of users with given input array", "nickname" => "create_users_with_list_input", @@ -82,7 +82,7 @@ MyApp.add_route('POST', '/user/createWithList', { end -MyApp.add_route('GET', '/user/login', { +MyApp.add_route('GET', '/v2/user/login', { "resourcePath" => "/User", "summary" => "Logs user into the system", "nickname" => "login_user", @@ -122,7 +122,7 @@ MyApp.add_route('GET', '/user/login', { end -MyApp.add_route('GET', '/user/logout', { +MyApp.add_route('GET', '/v2/user/logout', { "resourcePath" => "/User", "summary" => "Logs out current logged in user session", "nickname" => "logout_user", @@ -142,7 +142,7 @@ MyApp.add_route('GET', '/user/logout', { end -MyApp.add_route('GET', '/user/{username}', { +MyApp.add_route('GET', '/v2/user/{username}', { "resourcePath" => "/User", "summary" => "Get user by user name", "nickname" => "get_user_by_name", @@ -154,7 +154,7 @@ MyApp.add_route('GET', '/user/{username}', { { "name" => "username", - "description" => "The name that needs to be fetched. Use user1 for testing. ", + "description" => "The name that needs to be fetched. Use user1 for testing.", "dataType" => "string", "paramType" => "path", }, @@ -169,7 +169,7 @@ MyApp.add_route('GET', '/user/{username}', { end -MyApp.add_route('PUT', '/user/{username}', { +MyApp.add_route('PUT', '/v2/user/{username}', { "resourcePath" => "/User", "summary" => "Updated user", "nickname" => "update_user", @@ -203,7 +203,7 @@ MyApp.add_route('PUT', '/user/{username}', { end -MyApp.add_route('DELETE', '/user/{username}', { +MyApp.add_route('DELETE', '/v2/user/{username}', { "resourcePath" => "/User", "summary" => "Delete user", "nickname" => "delete_user", diff --git a/samples/server/petstore/sinatra/lib/swaggering.rb b/samples/server/petstore/sinatra/lib/swaggering.rb index 79aca1da2c92..1357bb19134b 100644 --- a/samples/server/petstore/sinatra/lib/swaggering.rb +++ b/samples/server/petstore/sinatra/lib/swaggering.rb @@ -26,14 +26,22 @@ class Swaggering < Sinatra::Base cross_origin Swaggering.to_resource_listing } + + # for swagger.yaml + get("/swagger.yaml") { + cross_origin + File.read("./swagger.yaml"); + } + @@configuration ||= Configuration.new yield(@@configuration) if block_given? end def self.add_route(method, path, swag={}, opts={}, &block) - fullPath = swag["resourcePath"].to_s + @@configuration.format_specifier + path + #fullPath = swag["resourcePath"].to_s + @@configuration.format_specifier + path + fullPath = path.gsub(/{(.*)}/, ':\1') - accepted = case method + accepted = case method.to_s.downcase when 'get' get(fullPath, opts, &block) true @@ -47,6 +55,7 @@ class Swaggering < Sinatra::Base put(fullPath, opts, &block) true else + puts "Error adding route: #{method} #{fullPath}" false end diff --git a/samples/server/petstore/sinatra/my_app.rb b/samples/server/petstore/sinatra/my_app.rb index 9f4d991d0f1d..33376ef311d9 100644 --- a/samples/server/petstore/sinatra/my_app.rb +++ b/samples/server/petstore/sinatra/my_app.rb @@ -7,3 +7,7 @@ class MyApp < Swaggering end end +# include the api files +Dir["./api/*.rb"].each { |file| + require file +} diff --git a/samples/server/petstore/sinatra/swagger.yaml b/samples/server/petstore/sinatra/swagger.yaml new file mode 100644 index 000000000000..49a3405de09a --- /dev/null +++ b/samples/server/petstore/sinatra/swagger.yaml @@ -0,0 +1,667 @@ +--- +swagger: "2.0" +info: + description: "This is a sample server Petstore server. You can find out more about\ + \ Swagger at http://swagger.io or on irc.freenode.net,\ + \ #swagger. For this sample, you can use the api key \"special-key\" to test\ + \ the authorization filters" + version: "1.0.0" + title: "Swagger Petstore" + termsOfService: "http://swagger.io/terms/" + contact: + email: "apiteam@swagger.io" + license: + name: "Apache 2.0" + url: "http://www.apache.org/licenses/LICENSE-2.0.html" +host: "petstore.swagger.io" +basePath: "/v2" +schemes: +- "http" +paths: + /pet: + post: + tags: + - "pet" + summary: "Add a new pet to the store" + description: "" + operationId: "addPet" + consumes: + - "application/json" + - "application/xml" + produces: + - "application/json" + - "application/xml" + parameters: + - in: "body" + name: "body" + description: "Pet object that needs to be added to the store" + required: false + schema: + $ref: "#/definitions/Pet" + responses: + 405: + description: "Invalid input" + security: + - petstore_auth: + - "write:pets" + - "read:pets" + put: + tags: + - "pet" + summary: "Update an existing pet" + description: "" + operationId: "updatePet" + consumes: + - "application/json" + - "application/xml" + produces: + - "application/json" + - "application/xml" + parameters: + - in: "body" + name: "body" + description: "Pet object that needs to be added to the store" + required: false + schema: + $ref: "#/definitions/Pet" + responses: + 400: + description: "Invalid ID supplied" + 404: + description: "Pet not found" + 405: + description: "Validation exception" + security: + - petstore_auth: + - "write:pets" + - "read:pets" + /pet/findByStatus: + get: + tags: + - "pet" + summary: "Finds Pets by status" + description: "Multiple status values can be provided with comma seperated strings" + operationId: "findPetsByStatus" + produces: + - "application/json" + - "application/xml" + parameters: + - name: "status" + in: "query" + description: "Status values that need to be considered for filter" + required: false + type: "array" + items: + type: "string" + collectionFormat: "multi" + default: "available" + responses: + 200: + description: "successful operation" + schema: + type: "array" + items: + $ref: "#/definitions/Pet" + 400: + description: "Invalid status value" + security: + - petstore_auth: + - "write:pets" + - "read:pets" + /pet/findByTags: + get: + tags: + - "pet" + summary: "Finds Pets by tags" + description: "Muliple tags can be provided with comma seperated strings. Use\ + \ tag1, tag2, tag3 for testing." + operationId: "findPetsByTags" + produces: + - "application/json" + - "application/xml" + parameters: + - name: "tags" + in: "query" + description: "Tags to filter by" + required: false + type: "array" + items: + type: "string" + collectionFormat: "multi" + responses: + 200: + description: "successful operation" + schema: + type: "array" + items: + $ref: "#/definitions/Pet" + 400: + description: "Invalid tag value" + security: + - petstore_auth: + - "write:pets" + - "read:pets" + /pet/{petId}: + get: + tags: + - "pet" + summary: "Find pet by ID" + description: "Returns a pet when ID < 10. ID > 10 or nonintegers will simulate\ + \ API error conditions" + operationId: "getPetById" + produces: + - "application/json" + - "application/xml" + parameters: + - name: "petId" + in: "path" + description: "ID of pet that needs to be fetched" + required: true + type: "integer" + format: "int64" + responses: + 200: + description: "successful operation" + schema: + $ref: "#/definitions/Pet" + 400: + description: "Invalid ID supplied" + 404: + description: "Pet not found" + security: + - api_key: [] + - petstore_auth: + - "write:pets" + - "read:pets" + post: + tags: + - "pet" + summary: "Updates a pet in the store with form data" + description: "" + operationId: "updatePetWithForm" + consumes: + - "application/x-www-form-urlencoded" + produces: + - "application/json" + - "application/xml" + parameters: + - name: "petId" + in: "path" + description: "ID of pet that needs to be updated" + required: true + type: "string" + - name: "name" + in: "formData" + description: "Updated name of the pet" + required: false + type: "string" + - name: "status" + in: "formData" + description: "Updated status of the pet" + required: false + type: "string" + responses: + 405: + description: "Invalid input" + security: + - petstore_auth: + - "write:pets" + - "read:pets" + delete: + tags: + - "pet" + summary: "Deletes a pet" + description: "" + operationId: "deletePet" + produces: + - "application/json" + - "application/xml" + parameters: + - name: "api_key" + in: "header" + description: "" + required: false + type: "string" + - name: "petId" + in: "path" + description: "Pet id to delete" + required: true + type: "integer" + format: "int64" + responses: + 400: + description: "Invalid pet value" + security: + - petstore_auth: + - "write:pets" + - "read:pets" + /pet/{petId}/uploadImage: + post: + tags: + - "pet" + summary: "uploads an image" + description: "" + operationId: "uploadFile" + consumes: + - "multipart/form-data" + produces: + - "application/json" + - "application/xml" + parameters: + - name: "petId" + in: "path" + description: "ID of pet to update" + required: true + type: "integer" + format: "int64" + - name: "additionalMetadata" + in: "formData" + description: "Additional data to pass to server" + required: false + type: "string" + - name: "file" + in: "formData" + description: "file to upload" + required: false + type: "file" + responses: + default: + description: "successful operation" + security: + - petstore_auth: + - "write:pets" + - "read:pets" + /store/inventory: + get: + tags: + - "store" + summary: "Returns pet inventories by status" + description: "Returns a map of status codes to quantities" + operationId: "getInventory" + produces: + - "application/json" + - "application/xml" + parameters: [] + responses: + 200: + description: "successful operation" + schema: + type: "object" + additionalProperties: + type: "integer" + format: "int32" + security: + - api_key: [] + /store/order: + post: + tags: + - "store" + summary: "Place an order for a pet" + description: "" + operationId: "placeOrder" + produces: + - "application/json" + - "application/xml" + parameters: + - in: "body" + name: "body" + description: "order placed for purchasing the pet" + required: false + schema: + $ref: "#/definitions/Order" + responses: + 200: + description: "successful operation" + schema: + $ref: "#/definitions/Order" + 400: + description: "Invalid Order" + /store/order/{orderId}: + get: + tags: + - "store" + summary: "Find purchase order by ID" + description: "For valid response try integer IDs with value <= 5 or > 10. Other\ + \ values will generated exceptions" + operationId: "getOrderById" + produces: + - "application/json" + - "application/xml" + parameters: + - name: "orderId" + in: "path" + description: "ID of pet that needs to be fetched" + required: true + type: "string" + responses: + 200: + description: "successful operation" + schema: + $ref: "#/definitions/Order" + 400: + description: "Invalid ID supplied" + 404: + description: "Order not found" + delete: + tags: + - "store" + summary: "Delete purchase order by ID" + description: "For valid response try integer IDs with value < 1000. Anything\ + \ above 1000 or nonintegers will generate API errors" + operationId: "deleteOrder" + produces: + - "application/json" + - "application/xml" + parameters: + - name: "orderId" + in: "path" + description: "ID of the order that needs to be deleted" + required: true + type: "string" + responses: + 400: + description: "Invalid ID supplied" + 404: + description: "Order not found" + /user: + post: + tags: + - "user" + summary: "Create user" + description: "This can only be done by the logged in user." + operationId: "createUser" + produces: + - "application/json" + - "application/xml" + parameters: + - in: "body" + name: "body" + description: "Created user object" + required: false + schema: + $ref: "#/definitions/User" + responses: + default: + description: "successful operation" + /user/createWithArray: + post: + tags: + - "user" + summary: "Creates list of users with given input array" + description: "" + operationId: "createUsersWithArrayInput" + produces: + - "application/json" + - "application/xml" + parameters: + - in: "body" + name: "body" + description: "List of user object" + required: false + schema: + type: "array" + items: + $ref: "#/definitions/User" + responses: + default: + description: "successful operation" + /user/createWithList: + post: + tags: + - "user" + summary: "Creates list of users with given input array" + description: "" + operationId: "createUsersWithListInput" + produces: + - "application/json" + - "application/xml" + parameters: + - in: "body" + name: "body" + description: "List of user object" + required: false + schema: + type: "array" + items: + $ref: "#/definitions/User" + responses: + default: + description: "successful operation" + /user/login: + get: + tags: + - "user" + summary: "Logs user into the system" + description: "" + operationId: "loginUser" + produces: + - "application/json" + - "application/xml" + parameters: + - name: "username" + in: "query" + description: "The user name for login" + required: false + type: "string" + - name: "password" + in: "query" + description: "The password for login in clear text" + required: false + type: "string" + responses: + 200: + description: "successful operation" + schema: + type: "string" + 400: + description: "Invalid username/password supplied" + /user/logout: + get: + tags: + - "user" + summary: "Logs out current logged in user session" + description: "" + operationId: "logoutUser" + produces: + - "application/json" + - "application/xml" + parameters: [] + responses: + default: + description: "successful operation" + /user/{username}: + get: + tags: + - "user" + summary: "Get user by user name" + description: "" + operationId: "getUserByName" + produces: + - "application/json" + - "application/xml" + parameters: + - name: "username" + in: "path" + description: "The name that needs to be fetched. Use user1 for testing. " + required: true + type: "string" + responses: + 200: + description: "successful operation" + schema: + $ref: "#/definitions/User" + examples: + application/json: + id: 1 + username: "johnp" + firstName: "John" + lastName: "Public" + email: "johnp@swagger.io" + password: "-secret-" + phone: "0123456789" + userStatus: 0 + 400: + description: "Invalid username supplied" + 404: + description: "User not found" + put: + tags: + - "user" + summary: "Updated user" + description: "This can only be done by the logged in user." + operationId: "updateUser" + produces: + - "application/json" + - "application/xml" + parameters: + - name: "username" + in: "path" + description: "name that need to be deleted" + required: true + type: "string" + - in: "body" + name: "body" + description: "Updated user object" + required: false + schema: + $ref: "#/definitions/User" + responses: + 400: + description: "Invalid user supplied" + 404: + description: "User not found" + delete: + tags: + - "user" + summary: "Delete user" + description: "This can only be done by the logged in user." + operationId: "deleteUser" + produces: + - "application/json" + - "application/xml" + parameters: + - name: "username" + in: "path" + description: "The name that needs to be deleted" + required: true + type: "string" + responses: + 400: + description: "Invalid username supplied" + 404: + description: "User not found" +securityDefinitions: + api_key: + type: "apiKey" + name: "api_key" + in: "header" + petstore_auth: + type: "oauth2" + authorizationUrl: "http://petstore.swagger.io/api/oauth/dialog" + flow: "implicit" + scopes: + write:pets: "modify pets in your account" + read:pets: "read your pets" +definitions: + User: + properties: + id: + type: "integer" + format: "int64" + username: + type: "string" + firstName: + type: "string" + lastName: + type: "string" + email: + type: "string" + password: + type: "string" + phone: + type: "string" + userStatus: + type: "integer" + format: "int32" + description: "User Status" + xml: + name: "User" + Category: + properties: + id: + type: "integer" + format: "int64" + name: + type: "string" + xml: + name: "Category" + Pet: + required: + - "name" + - "photoUrls" + properties: + id: + type: "integer" + format: "int64" + category: + $ref: "#/definitions/Category" + name: + type: "string" + example: "doggie" + photoUrls: + type: "array" + xml: + name: "photoUrl" + wrapped: true + items: + type: "string" + tags: + type: "array" + xml: + name: "tag" + wrapped: true + items: + $ref: "#/definitions/Tag" + status: + type: "string" + description: "pet status in the store" + enum: + - "available" + - "pending" + - "sold" + xml: + name: "Pet" + Tag: + properties: + id: + type: "integer" + format: "int64" + name: + type: "string" + xml: + name: "Tag" + Order: + properties: + id: + type: "integer" + format: "int64" + petId: + type: "integer" + format: "int64" + quantity: + type: "integer" + format: "int32" + shipDate: + type: "string" + format: "date-time" + status: + type: "string" + description: "Order Status" + enum: + - "placed" + - "approved" + - "delivered" + complete: + type: "boolean" + xml: + name: "Order"